title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How to resize an array in Java?
An array cannot be resized dynamically in Java. One approach is to use java.util.ArrayList(or java.util.Vector) instead of a native array. Another approach is to re-allocate an array with a different size and copy the contents of the old array to the new array. class ResizableArray { public static void main (String[] args) { int[] a = {1, 2, 3}; a = (int[])resizeArray(a, 5); a[3] = 4; a[4] = 5; for (int i=0; i<a.length; i++) System.out.println(a[i]); } private static Object resizeArray (Object oldArray, int newSize) { int oldSize = java.lang.reflect.Array.getLength(oldArray); Class elementType = oldArray.getClass().getComponentType(); Object newArray = java.lang.reflect.Array.newInstance(elementType, newSize); int preserveLength = Math.min(oldSize, newSize); if (preserveLength > 0) System.arraycopy(oldArray, 0, newArray, 0, preserveLength); return newArray; } } 1 2 3 4 5
[ { "code": null, "e": 1111, "s": 1062, "text": "An array cannot be resized dynamically in Java. " }, { "code": null, "e": 1202, "s": 1111, "text": "One approach is to use java.util.ArrayList(or java.util.Vector) instead of a native array." }, { "code": null, "e": 1325, "s": 1202, "text": "Another approach is to re-allocate an array with a different size and copy the contents of the old array to the new array." }, { "code": null, "e": 2105, "s": 1325, "text": "class ResizableArray {\n public static void main (String[] args) {\n int[] a = {1, 2, 3};\n a = (int[])resizeArray(a, 5);\n a[3] = 4;\n a[4] = 5;\n for (int i=0; i<a.length; i++)\n System.out.println(a[i]);\n }\n private static Object resizeArray (Object oldArray, int newSize) {\n int oldSize = java.lang.reflect.Array.getLength(oldArray);\n Class elementType = oldArray.getClass().getComponentType();\n Object newArray = java.lang.reflect.Array.newInstance(elementType, newSize);\n int preserveLength = Math.min(oldSize, newSize);\n if (preserveLength > 0)\n System.arraycopy(oldArray, 0, newArray, 0, preserveLength);\n return newArray;\n }\n}\n" }, { "code": null, "e": 2115, "s": 2105, "text": "1\n2\n3\n4\n5" } ]
How do I adjust (offset) the colorbar title in Matplotlib?
To adjust (offset) the colorbar title in matplotlib, we can take the following steps − Create a random data of 4×4 dimension. Create a random data of 4×4 dimension. Use imshow() method to display the data as an imgage. Use imshow() method to display the data as an imgage. Create a colorbar for a scalar mappable instance using colorbar() method, with im mappable instance. Create a colorbar for a scalar mappable instance using colorbar() method, with im mappable instance. Now, adjust (offset) the colorbar title in matplotlib, with labelpad=-1. You can assign different values to labelpad to see how it affects the colorbar title. Now, adjust (offset) the colorbar title in matplotlib, with labelpad=-1. You can assign different values to labelpad to see how it affects the colorbar title. To display the figure, use show() method. To display the figure, use show() method. import numpy as np from matplotlib import pyplot as plt, cm plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True data = np.random.rand(4, 4) im = plt.imshow(data, cmap=cm.jet) cb = plt.colorbar(im) cb.set_label('Image Colorbar', labelpad=-1) plt.show()
[ { "code": null, "e": 1149, "s": 1062, "text": "To adjust (offset) the colorbar title in matplotlib, we can take the following steps −" }, { "code": null, "e": 1188, "s": 1149, "text": "Create a random data of 4×4 dimension." }, { "code": null, "e": 1227, "s": 1188, "text": "Create a random data of 4×4 dimension." }, { "code": null, "e": 1281, "s": 1227, "text": "Use imshow() method to display the data as an imgage." }, { "code": null, "e": 1335, "s": 1281, "text": "Use imshow() method to display the data as an imgage." }, { "code": null, "e": 1436, "s": 1335, "text": "Create a colorbar for a scalar mappable instance using colorbar() method, with im mappable instance." }, { "code": null, "e": 1537, "s": 1436, "text": "Create a colorbar for a scalar mappable instance using colorbar() method, with im mappable instance." }, { "code": null, "e": 1696, "s": 1537, "text": "Now, adjust (offset) the colorbar title in matplotlib, with labelpad=-1. You can assign different values to labelpad to see how it affects the colorbar title." }, { "code": null, "e": 1855, "s": 1696, "text": "Now, adjust (offset) the colorbar title in matplotlib, with labelpad=-1. You can assign different values to labelpad to see how it affects the colorbar title." }, { "code": null, "e": 1897, "s": 1855, "text": "To display the figure, use show() method." }, { "code": null, "e": 1939, "s": 1897, "text": "To display the figure, use show() method." }, { "code": null, "e": 2226, "s": 1939, "text": "import numpy as np\nfrom matplotlib import pyplot as plt, cm\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\ndata = np.random.rand(4, 4)\nim = plt.imshow(data, cmap=cm.jet)\ncb = plt.colorbar(im)\ncb.set_label('Image Colorbar', labelpad=-1)\nplt.show()" } ]
Implementing a Linked List in Java using Class - GeeksforGeeks
19 Feb, 2021 Pre-requisite: Linked List Data Structure Like arrays, Linked List is a linear data structure. Unlike arrays, linked list elements are not stored at the contiguous location, the elements are linked using pointers as shown below. In Java, LinkedList can be represented as a class and a Node as a separate class. The LinkedList class contains a reference of Node class type. Java class LinkedList { Node head; // head of list /* Linked list Node*/ class Node { int data; Node next; // Constructor to create a new node // Next is by default initialized // as null Node(int d) { data = d; } }} Creation and Insertion In this article, insertion in the list is done at the end, that is the new node is added after the last node of the given Linked List. For example, if the given Linked List is 5->10->15->20->25 and 30 is to be inserted, then the Linked List becomes 5->10->15->20->25->30. Since a Linked List is typically represented by the head pointer of it, it is required to traverse the list till the last node and then change the next to last node to the new node. Java import java.io.*; // Java program to implement// a Singly Linked Listpublic class LinkedList { Node head; // head of list // Linked list Node. // This inner class is made static // so that main() can access it static class Node { int data; Node next; // Constructor Node(int d) { data = d; next = null; } } // Method to insert a new node public static LinkedList insert(LinkedList list, int data) { // Create a new node with given data Node new_node = new Node(data); new_node.next = null; // If the Linked List is empty, // then make the new node as head if (list.head == null) { list.head = new_node; } else { // Else traverse till the last node // and insert the new_node there Node last = list.head; while (last.next != null) { last = last.next; } // Insert the new_node at last node last.next = new_node; } // Return the list by head return list; } // Method to print the LinkedList. public static void printList(LinkedList list) { Node currNode = list.head; System.out.print("LinkedList: "); // Traverse through the LinkedList while (currNode != null) { // Print the data at current node System.out.print(currNode.data + " "); // Go to next node currNode = currNode.next; } } // Driver code public static void main(String[] args) { /* Start with the empty list. */ LinkedList list = new LinkedList(); // // ******INSERTION****** // // Insert the values list = insert(list, 1); list = insert(list, 2); list = insert(list, 3); list = insert(list, 4); list = insert(list, 5); list = insert(list, 6); list = insert(list, 7); list = insert(list, 8); // Print the LinkedList printList(list); }} LinkedList: 1 2 3 4 5 6 7 8 Traversal For traversal, below is a general-purpose function printList() that prints any given list by traversing the list from head node to the last. Java import java.io.*; // Java program to implement// a Singly Linked Listpublic class LinkedList { Node head; // head of list // Linked list Node. // Node is a static nested class // so main() can access it static class Node { int data; Node next; // Constructor Node(int d) { data = d; next = null; } } // Method to insert a new node public static LinkedList insert(LinkedList list, int data) { // Create a new node with given data Node new_node = new Node(data); new_node.next = null; // If the Linked List is empty, // then make the new node as head if (list.head == null) { list.head = new_node; } else { // Else traverse till the last node // and insert the new_node there Node last = list.head; while (last.next != null) { last = last.next; } // Insert the new_node at last node last.next = new_node; } // Return the list by head return list; } // Method to print the LinkedList. public static void printList(LinkedList list) { Node currNode = list.head; System.out.print("LinkedList: "); // Traverse through the LinkedList while (currNode != null) { // Print the data at current node System.out.print(currNode.data + " "); // Go to next node currNode = currNode.next; } } // **************MAIN METHOD************** // method to create a Singly linked list with n nodes public static void main(String[] args) { /* Start with the empty list. */ LinkedList list = new LinkedList(); // // ******INSERTION****** // // Insert the values list = insert(list, 1); list = insert(list, 2); list = insert(list, 3); list = insert(list, 4); list = insert(list, 5); list = insert(list, 6); list = insert(list, 7); list = insert(list, 8); // Print the LinkedList printList(list); }} LinkedList: 1 2 3 4 5 6 7 8 Deletion By KEY The deletion process can be understood as follows: To be done: Given a ‘key’, delete the first occurrence of this key in the linked list. How to do it: To delete a node from the linked list, do following steps. Search the key for its first occurrence in the listNow, Any of the 3 conditions can be there: Case 1: The key is found at the head In this case, Change the head of the node to the next node of the current head. Free the memory of the replaced head node.Case 2: The key is found in the middle or last, except at the head In this case, Find the previous node of the node to be deleted. Change the next the previous node to the next node of the current node.Free the memory of the replaced node.Case 3: The key is not found in the list In this case, No operation needs to be done. Search the key for its first occurrence in the list Now, Any of the 3 conditions can be there: Case 1: The key is found at the head In this case, Change the head of the node to the next node of the current head. Free the memory of the replaced head node.Case 2: The key is found in the middle or last, except at the head In this case, Find the previous node of the node to be deleted. Change the next the previous node to the next node of the current node.Free the memory of the replaced node.Case 3: The key is not found in the list In this case, No operation needs to be done. Case 1: The key is found at the head In this case, Change the head of the node to the next node of the current head. Free the memory of the replaced head node. In this case, Change the head of the node to the next node of the current head. Free the memory of the replaced head node. In this case, Change the head of the node to the next node of the current head. Free the memory of the replaced head node. Case 2: The key is found in the middle or last, except at the head In this case, Find the previous node of the node to be deleted. Change the next the previous node to the next node of the current node.Free the memory of the replaced node. In this case, Find the previous node of the node to be deleted. Change the next the previous node to the next node of the current node.Free the memory of the replaced node. In this case, Find the previous node of the node to be deleted. Change the next the previous node to the next node of the current node. Free the memory of the replaced node. Case 3: The key is not found in the list In this case, No operation needs to be done. In this case, No operation needs to be done. In this case, No operation needs to be done. Java import java.io.*; // Java program to implement// a Singly Linked Listpublic class LinkedList { Node head; // head of list // Linked list Node. // Node is a static nested class // so main() can access it static class Node { int data; Node next; // Constructor Node(int d) { data = d; next = null; } } // Method to insert a new node public static LinkedList insert(LinkedList list, int data) { // Create a new node with given data Node new_node = new Node(data); new_node.next = null; // If the Linked List is empty, // then make the new node as head if (list.head == null) { list.head = new_node; } else { // Else traverse till the last node // and insert the new_node there Node last = list.head; while (last.next != null) { last = last.next; } // Insert the new_node at last node last.next = new_node; } // Return the list by head return list; } // Method to print the LinkedList. public static void printList(LinkedList list) { Node currNode = list.head; System.out.print("LinkedList: "); // Traverse through the LinkedList while (currNode != null) { // Print the data at current node System.out.print(currNode.data + " "); // Go to next node currNode = currNode.next; } System.out.println(); } // **************DELETION BY KEY************** // Method to delete a node in the LinkedList by KEY public static LinkedList deleteByKey(LinkedList list, int key) { // Store head node Node currNode = list.head, prev = null; // // CASE 1: // If head node itself holds the key to be deleted if (currNode != null && currNode.data == key) { list.head = currNode.next; // Changed head // Display the message System.out.println(key + " found and deleted"); // Return the updated List return list; } // // CASE 2: // If the key is somewhere other than at head // // Search for the key to be deleted, // keep track of the previous node // as it is needed to change currNode.next while (currNode != null && currNode.data != key) { // If currNode does not hold key // continue to next node prev = currNode; currNode = currNode.next; } // If the key was present, it should be at currNode // Therefore the currNode shall not be null if (currNode != null) { // Since the key is at currNode // Unlink currNode from linked list prev.next = currNode.next; // Display the message System.out.println(key + " found and deleted"); } // // CASE 3: The key is not present // // If key was not present in linked list // currNode should be null if (currNode == null) { // Display the message System.out.println(key + " not found"); } // return the List return list; } // **************MAIN METHOD************** // method to create a Singly linked list with n nodes public static void main(String[] args) { /* Start with the empty list. */ LinkedList list = new LinkedList(); // // ******INSERTION****** // // Insert the values list = insert(list, 1); list = insert(list, 2); list = insert(list, 3); list = insert(list, 4); list = insert(list, 5); list = insert(list, 6); list = insert(list, 7); list = insert(list, 8); // Print the LinkedList printList(list); // // ******DELETION BY KEY****** // // Delete node with value 1 // In this case the key is ***at head*** deleteByKey(list, 1); // Print the LinkedList printList(list); // Delete node with value 4 // In this case the key is present ***in the // middle*** deleteByKey(list, 4); // Print the LinkedList printList(list); // Delete node with value 10 // In this case the key is ***not present*** deleteByKey(list, 10); // Print the LinkedList printList(list); }} LinkedList: 1 2 3 4 5 6 7 8 1 found and deleted LinkedList: 2 3 4 5 6 7 8 4 found and deleted LinkedList: 2 3 5 6 7 8 10 not found LinkedList: 2 3 5 6 7 8 Deletion At Position This deletion process can be understood as follows:To be done: Given a ‘position’, delete the node at this position from the linked list.How to do it: The steps to do it are as follows: Traverse the list by counting the index of the nodesFor each index, match the index to be same as positionNow, Any of the 3 conditions can be there: Case 1: The position is 0, i.e. the head is to be deleted In this case, Change the head of the node to the next node of current head. Free the memory of replaced head node.Case 2: The position is greater than 0 but less than the size of the list, i.e. in the middle or last, except at head In this case, Find previous node of the node to be deleted. Change the next of previous node to the next node of current node.Free the memory of replaced node.Case 3: The position is greater than the size of the list, i.e. position not found in the list In this case, No operation needs to be done. Traverse the list by counting the index of the nodes For each index, match the index to be same as position Now, Any of the 3 conditions can be there: Case 1: The position is 0, i.e. the head is to be deleted In this case, Change the head of the node to the next node of current head. Free the memory of replaced head node.Case 2: The position is greater than 0 but less than the size of the list, i.e. in the middle or last, except at head In this case, Find previous node of the node to be deleted. Change the next of previous node to the next node of current node.Free the memory of replaced node.Case 3: The position is greater than the size of the list, i.e. position not found in the list In this case, No operation needs to be done. Case 1: The position is 0, i.e. the head is to be deleted In this case, Change the head of the node to the next node of current head. Free the memory of replaced head node. In this case, Change the head of the node to the next node of current head. Free the memory of replaced head node. In this case, Change the head of the node to the next node of current head. Free the memory of replaced head node. Case 2: The position is greater than 0 but less than the size of the list, i.e. in the middle or last, except at head In this case, Find previous node of the node to be deleted. Change the next of previous node to the next node of current node.Free the memory of replaced node. In this case, Find previous node of the node to be deleted. Change the next of previous node to the next node of current node.Free the memory of replaced node. In this case, Find previous node of the node to be deleted. Change the next of previous node to the next node of current node. Free the memory of replaced node. Case 3: The position is greater than the size of the list, i.e. position not found in the list In this case, No operation needs to be done. In this case, No operation needs to be done. In this case, No operation needs to be done. Java import java.io.*; // Java program to implement// a Singly Linked Listpublic class LinkedList { Node head; // head of list // Linked list Node. // Node is a static nested class // so main() can access it static class Node { int data; Node next; // Constructor Node(int d) { data = d; next = null; } } // Method to insert a new node public static LinkedList insert(LinkedList list, int data) { // Create a new node with given data Node new_node = new Node(data); new_node.next = null; // If the Linked List is empty, // then make the new node as head if (list.head == null) { list.head = new_node; } else { // Else traverse till the last node // and insert the new_node there Node last = list.head; while (last.next != null) { last = last.next; } // Insert the new_node at last node last.next = new_node; } // Return the list by head return list; } // Method to print the LinkedList. public static void printList(LinkedList list) { Node currNode = list.head; System.out.print("LinkedList: "); // Traverse through the LinkedList while (currNode != null) { // Print the data at current node System.out.print(currNode.data + " "); // Go to next node currNode = currNode.next; } System.out.println(); } // Method to delete a node in the LinkedList by POSITION public static LinkedList deleteAtPosition(LinkedList list, int index) { // Store head node Node currNode = list.head, prev = null; // // CASE 1: // If index is 0, then head node itself is to be // deleted if (index == 0 && currNode != null) { list.head = currNode.next; // Changed head // Display the message System.out.println( index + " position element deleted"); // Return the updated List return list; } // // CASE 2: // If the index is greater than 0 but less than the // size of LinkedList // // The counter int counter = 0; // Count for the index to be deleted, // keep track of the previous node // as it is needed to change currNode.next while (currNode != null) { if (counter == index) { // Since the currNode is the required // position Unlink currNode from linked list prev.next = currNode.next; // Display the message System.out.println( index + " position element deleted"); break; } else { // If current position is not the index // continue to next node prev = currNode; currNode = currNode.next; counter++; } } // If the position element was found, it should be // at currNode Therefore the currNode shall not be // null // // CASE 3: The index is greater than the size of the // LinkedList // // In this case, the currNode should be null if (currNode == null) { // Display the message System.out.println( index + " position element not found"); } // return the List return list; } // **************MAIN METHOD************** // method to create a Singly linked list with n nodes public static void main(String[] args) { /* Start with the empty list. */ LinkedList list = new LinkedList(); // // ******INSERTION****** // // Insert the values list = insert(list, 1); list = insert(list, 2); list = insert(list, 3); list = insert(list, 4); list = insert(list, 5); list = insert(list, 6); list = insert(list, 7); list = insert(list, 8); // Print the LinkedList printList(list); // // ******DELETION AT POSITION****** // // Delete node at position 0 // In this case the key is ***at head*** deleteAtPosition(list, 0); // Print the LinkedList printList(list); // Delete node at position 2 // In this case the key is present ***in the // middle*** deleteAtPosition(list, 2); // Print the LinkedList printList(list); // Delete node at position 10 // In this case the key is ***not present*** deleteAtPosition(list, 10); // Print the LinkedList printList(list); }} LinkedList: 1 2 3 4 5 6 7 8 0 position element deleted LinkedList: 2 3 4 5 6 7 8 2 position element deleted LinkedList: 2 3 5 6 7 8 10 position element not found LinkedList: 2 3 5 6 7 8 All Operations Below is the complete program that applies each operation together: Java import java.io.*; // Java program to implement// a Singly Linked Listpublic class LinkedList { Node head; // head of list // Linked list Node. // Node is a static nested class // so main() can access it static class Node { int data; Node next; // Constructor Node(int d) { data = d; next = null; } } // **************INSERTION************** // Method to insert a new node public static LinkedList insert(LinkedList list, int data) { // Create a new node with given data Node new_node = new Node(data); new_node.next = null; // If the Linked List is empty, // then make the new node as head if (list.head == null) { list.head = new_node; } else { // Else traverse till the last node // and insert the new_node there Node last = list.head; while (last.next != null) { last = last.next; } // Insert the new_node at last node last.next = new_node; } // Return the list by head return list; } // **************TRAVERSAL************** // Method to print the LinkedList. public static void printList(LinkedList list) { Node currNode = list.head; System.out.print("\nLinkedList: "); // Traverse through the LinkedList while (currNode != null) { // Print the data at current node System.out.print(currNode.data + " "); // Go to next node currNode = currNode.next; } System.out.println("\n"); } // **************DELETION BY KEY************** // Method to delete a node in the LinkedList by KEY public static LinkedList deleteByKey(LinkedList list, int key) { // Store head node Node currNode = list.head, prev = null; // // CASE 1: // If head node itself holds the key to be deleted if (currNode != null && currNode.data == key) { list.head = currNode.next; // Changed head // Display the message System.out.println(key + " found and deleted"); // Return the updated List return list; } // // CASE 2: // If the key is somewhere other than at head // // Search for the key to be deleted, // keep track of the previous node // as it is needed to change currNode.next while (currNode != null && currNode.data != key) { // If currNode does not hold key // continue to next node prev = currNode; currNode = currNode.next; } // If the key was present, it should be at currNode // Therefore the currNode shall not be null if (currNode != null) { // Since the key is at currNode // Unlink currNode from linked list prev.next = currNode.next; // Display the message System.out.println(key + " found and deleted"); } // // CASE 3: The key is not present // // If key was not present in linked list // currNode should be null if (currNode == null) { // Display the message System.out.println(key + " not found"); } // return the List return list; } // **************DELETION AT A POSITION************** // Method to delete a node in the LinkedList by POSITION public static LinkedList deleteAtPosition(LinkedList list, int index) { // Store head node Node currNode = list.head, prev = null; // // CASE 1: // If index is 0, then head node itself is to be // deleted if (index == 0 && currNode != null) { list.head = currNode.next; // Changed head // Display the message System.out.println( index + " position element deleted"); // Return the updated List return list; } // // CASE 2: // If the index is greater than 0 but less than the // size of LinkedList // // The counter int counter = 0; // Count for the index to be deleted, // keep track of the previous node // as it is needed to change currNode.next while (currNode != null) { if (counter == index) { // Since the currNode is the required // position Unlink currNode from linked list prev.next = currNode.next; // Display the message System.out.println( index + " position element deleted"); break; } else { // If current position is not the index // continue to next node prev = currNode; currNode = currNode.next; counter++; } } // If the position element was found, it should be // at currNode Therefore the currNode shall not be // null // // CASE 3: The index is greater than the size of the // LinkedList // // In this case, the currNode should be null if (currNode == null) { // Display the message System.out.println( index + " position element not found"); } // return the List return list; } // **************MAIN METHOD************** // method to create a Singly linked list with n nodes public static void main(String[] args) { /* Start with the empty list. */ LinkedList list = new LinkedList(); // // ******INSERTION****** // // Insert the values list = insert(list, 1); list = insert(list, 2); list = insert(list, 3); list = insert(list, 4); list = insert(list, 5); list = insert(list, 6); list = insert(list, 7); list = insert(list, 8); // Print the LinkedList printList(list); // // ******DELETION BY KEY****** // // Delete node with value 1 // In this case the key is ***at head*** deleteByKey(list, 1); // Print the LinkedList printList(list); // Delete node with value 4 // In this case the key is present ***in the // middle*** deleteByKey(list, 4); // Print the LinkedList printList(list); // Delete node with value 10 // In this case the key is ***not present*** deleteByKey(list, 10); // Print the LinkedList printList(list); // // ******DELETION AT POSITION****** // // Delete node at position 0 // In this case the key is ***at head*** deleteAtPosition(list, 0); // Print the LinkedList printList(list); // Delete node at position 2 // In this case the key is present ***in the // middle*** deleteAtPosition(list, 2); // Print the LinkedList printList(list); // Delete node at position 10 // In this case the key is ***not present*** deleteAtPosition(list, 10); // Print the LinkedList printList(list); }} LinkedList: 1 2 3 4 5 6 7 8 1 found and deleted LinkedList: 2 3 4 5 6 7 8 4 found and deleted LinkedList: 2 3 5 6 7 8 10 not found LinkedList: 2 3 5 6 7 8 0 position element deleted LinkedList: 3 5 6 7 8 2 position element deleted LinkedList: 3 5 7 8 10 position element not found LinkedList: 3 5 7 8 shakibuddinbhuiyan Java-Class and Object Java-List-Programs Data Structures Java Java Programs Linked List Data Structures Java-Class and Object Linked List Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments SDE SHEET - A Complete Guide for SDE Preparation Insertion and Deletion in Heaps DSA Sheet by Love Babbar Comparison between Adjacency List and Adjacency Matrix representation of Graph Introduction to Algorithms Arrays in Java Split() String method in Java with examples Arrays.sort() in Java with examples For-each loop in Java Initialize an ArrayList in Java
[ { "code": null, "e": 24243, "s": 24215, "text": "\n19 Feb, 2021" }, { "code": null, "e": 24285, "s": 24243, "text": "Pre-requisite: Linked List Data Structure" }, { "code": null, "e": 24473, "s": 24285, "text": "Like arrays, Linked List is a linear data structure. Unlike arrays, linked list elements are not stored at the contiguous location, the elements are linked using pointers as shown below. " }, { "code": null, "e": 24618, "s": 24473, "text": "In Java, LinkedList can be represented as a class and a Node as a separate class. The LinkedList class contains a reference of Node class type. " }, { "code": null, "e": 24623, "s": 24618, "text": "Java" }, { "code": "class LinkedList { Node head; // head of list /* Linked list Node*/ class Node { int data; Node next; // Constructor to create a new node // Next is by default initialized // as null Node(int d) { data = d; } }}", "e": 24891, "s": 24623, "text": null }, { "code": null, "e": 24916, "s": 24893, "text": "Creation and Insertion" }, { "code": null, "e": 25370, "s": 24916, "text": "In this article, insertion in the list is done at the end, that is the new node is added after the last node of the given Linked List. For example, if the given Linked List is 5->10->15->20->25 and 30 is to be inserted, then the Linked List becomes 5->10->15->20->25->30. Since a Linked List is typically represented by the head pointer of it, it is required to traverse the list till the last node and then change the next to last node to the new node." }, { "code": null, "e": 25375, "s": 25370, "text": "Java" }, { "code": "import java.io.*; // Java program to implement// a Singly Linked Listpublic class LinkedList { Node head; // head of list // Linked list Node. // This inner class is made static // so that main() can access it static class Node { int data; Node next; // Constructor Node(int d) { data = d; next = null; } } // Method to insert a new node public static LinkedList insert(LinkedList list, int data) { // Create a new node with given data Node new_node = new Node(data); new_node.next = null; // If the Linked List is empty, // then make the new node as head if (list.head == null) { list.head = new_node; } else { // Else traverse till the last node // and insert the new_node there Node last = list.head; while (last.next != null) { last = last.next; } // Insert the new_node at last node last.next = new_node; } // Return the list by head return list; } // Method to print the LinkedList. public static void printList(LinkedList list) { Node currNode = list.head; System.out.print(\"LinkedList: \"); // Traverse through the LinkedList while (currNode != null) { // Print the data at current node System.out.print(currNode.data + \" \"); // Go to next node currNode = currNode.next; } } // Driver code public static void main(String[] args) { /* Start with the empty list. */ LinkedList list = new LinkedList(); // // ******INSERTION****** // // Insert the values list = insert(list, 1); list = insert(list, 2); list = insert(list, 3); list = insert(list, 4); list = insert(list, 5); list = insert(list, 6); list = insert(list, 7); list = insert(list, 8); // Print the LinkedList printList(list); }}", "e": 27513, "s": 25375, "text": null }, { "code": null, "e": 27542, "s": 27513, "text": "LinkedList: 1 2 3 4 5 6 7 8 " }, { "code": null, "e": 27552, "s": 27542, "text": "Traversal" }, { "code": null, "e": 27693, "s": 27552, "text": "For traversal, below is a general-purpose function printList() that prints any given list by traversing the list from head node to the last." }, { "code": null, "e": 27698, "s": 27693, "text": "Java" }, { "code": "import java.io.*; // Java program to implement// a Singly Linked Listpublic class LinkedList { Node head; // head of list // Linked list Node. // Node is a static nested class // so main() can access it static class Node { int data; Node next; // Constructor Node(int d) { data = d; next = null; } } // Method to insert a new node public static LinkedList insert(LinkedList list, int data) { // Create a new node with given data Node new_node = new Node(data); new_node.next = null; // If the Linked List is empty, // then make the new node as head if (list.head == null) { list.head = new_node; } else { // Else traverse till the last node // and insert the new_node there Node last = list.head; while (last.next != null) { last = last.next; } // Insert the new_node at last node last.next = new_node; } // Return the list by head return list; } // Method to print the LinkedList. public static void printList(LinkedList list) { Node currNode = list.head; System.out.print(\"LinkedList: \"); // Traverse through the LinkedList while (currNode != null) { // Print the data at current node System.out.print(currNode.data + \" \"); // Go to next node currNode = currNode.next; } } // **************MAIN METHOD************** // method to create a Singly linked list with n nodes public static void main(String[] args) { /* Start with the empty list. */ LinkedList list = new LinkedList(); // // ******INSERTION****** // // Insert the values list = insert(list, 1); list = insert(list, 2); list = insert(list, 3); list = insert(list, 4); list = insert(list, 5); list = insert(list, 6); list = insert(list, 7); list = insert(list, 8); // Print the LinkedList printList(list); }}", "e": 29912, "s": 27698, "text": null }, { "code": null, "e": 29941, "s": 29912, "text": "LinkedList: 1 2 3 4 5 6 7 8 " }, { "code": null, "e": 29957, "s": 29941, "text": "Deletion By KEY" }, { "code": null, "e": 30008, "s": 29957, "text": "The deletion process can be understood as follows:" }, { "code": null, "e": 30021, "s": 30008, "text": "To be done: " }, { "code": null, "e": 30096, "s": 30021, "text": "Given a ‘key’, delete the first occurrence of this key in the linked list." }, { "code": null, "e": 30111, "s": 30096, "text": "How to do it: " }, { "code": null, "e": 30172, "s": 30111, "text": "To delete a node from the linked list, do following steps. " }, { "code": null, "e": 30754, "s": 30172, "text": "Search the key for its first occurrence in the listNow, Any of the 3 conditions can be there: Case 1: The key is found at the head In this case, Change the head of the node to the next node of the current head. Free the memory of the replaced head node.Case 2: The key is found in the middle or last, except at the head In this case, Find the previous node of the node to be deleted. Change the next the previous node to the next node of the current node.Free the memory of the replaced node.Case 3: The key is not found in the list In this case, No operation needs to be done. " }, { "code": null, "e": 30806, "s": 30754, "text": "Search the key for its first occurrence in the list" }, { "code": null, "e": 31337, "s": 30806, "text": "Now, Any of the 3 conditions can be there: Case 1: The key is found at the head In this case, Change the head of the node to the next node of the current head. Free the memory of the replaced head node.Case 2: The key is found in the middle or last, except at the head In this case, Find the previous node of the node to be deleted. Change the next the previous node to the next node of the current node.Free the memory of the replaced node.Case 3: The key is not found in the list In this case, No operation needs to be done. " }, { "code": null, "e": 31498, "s": 31337, "text": "Case 1: The key is found at the head In this case, Change the head of the node to the next node of the current head. Free the memory of the replaced head node." }, { "code": null, "e": 31622, "s": 31498, "text": "In this case, Change the head of the node to the next node of the current head. Free the memory of the replaced head node." }, { "code": null, "e": 31704, "s": 31622, "text": "In this case, Change the head of the node to the next node of the current head. " }, { "code": null, "e": 31747, "s": 31704, "text": "Free the memory of the replaced head node." }, { "code": null, "e": 31988, "s": 31747, "text": "Case 2: The key is found in the middle or last, except at the head In this case, Find the previous node of the node to be deleted. Change the next the previous node to the next node of the current node.Free the memory of the replaced node." }, { "code": null, "e": 32162, "s": 31988, "text": "In this case, Find the previous node of the node to be deleted. Change the next the previous node to the next node of the current node.Free the memory of the replaced node." }, { "code": null, "e": 32228, "s": 32162, "text": "In this case, Find the previous node of the node to be deleted. " }, { "code": null, "e": 32300, "s": 32228, "text": "Change the next the previous node to the next node of the current node." }, { "code": null, "e": 32338, "s": 32300, "text": "Free the memory of the replaced node." }, { "code": null, "e": 32426, "s": 32338, "text": "Case 3: The key is not found in the list In this case, No operation needs to be done. " }, { "code": null, "e": 32473, "s": 32426, "text": "In this case, No operation needs to be done. " }, { "code": null, "e": 32520, "s": 32473, "text": "In this case, No operation needs to be done. " }, { "code": null, "e": 32529, "s": 32524, "text": "Java" }, { "code": "import java.io.*; // Java program to implement// a Singly Linked Listpublic class LinkedList { Node head; // head of list // Linked list Node. // Node is a static nested class // so main() can access it static class Node { int data; Node next; // Constructor Node(int d) { data = d; next = null; } } // Method to insert a new node public static LinkedList insert(LinkedList list, int data) { // Create a new node with given data Node new_node = new Node(data); new_node.next = null; // If the Linked List is empty, // then make the new node as head if (list.head == null) { list.head = new_node; } else { // Else traverse till the last node // and insert the new_node there Node last = list.head; while (last.next != null) { last = last.next; } // Insert the new_node at last node last.next = new_node; } // Return the list by head return list; } // Method to print the LinkedList. public static void printList(LinkedList list) { Node currNode = list.head; System.out.print(\"LinkedList: \"); // Traverse through the LinkedList while (currNode != null) { // Print the data at current node System.out.print(currNode.data + \" \"); // Go to next node currNode = currNode.next; } System.out.println(); } // **************DELETION BY KEY************** // Method to delete a node in the LinkedList by KEY public static LinkedList deleteByKey(LinkedList list, int key) { // Store head node Node currNode = list.head, prev = null; // // CASE 1: // If head node itself holds the key to be deleted if (currNode != null && currNode.data == key) { list.head = currNode.next; // Changed head // Display the message System.out.println(key + \" found and deleted\"); // Return the updated List return list; } // // CASE 2: // If the key is somewhere other than at head // // Search for the key to be deleted, // keep track of the previous node // as it is needed to change currNode.next while (currNode != null && currNode.data != key) { // If currNode does not hold key // continue to next node prev = currNode; currNode = currNode.next; } // If the key was present, it should be at currNode // Therefore the currNode shall not be null if (currNode != null) { // Since the key is at currNode // Unlink currNode from linked list prev.next = currNode.next; // Display the message System.out.println(key + \" found and deleted\"); } // // CASE 3: The key is not present // // If key was not present in linked list // currNode should be null if (currNode == null) { // Display the message System.out.println(key + \" not found\"); } // return the List return list; } // **************MAIN METHOD************** // method to create a Singly linked list with n nodes public static void main(String[] args) { /* Start with the empty list. */ LinkedList list = new LinkedList(); // // ******INSERTION****** // // Insert the values list = insert(list, 1); list = insert(list, 2); list = insert(list, 3); list = insert(list, 4); list = insert(list, 5); list = insert(list, 6); list = insert(list, 7); list = insert(list, 8); // Print the LinkedList printList(list); // // ******DELETION BY KEY****** // // Delete node with value 1 // In this case the key is ***at head*** deleteByKey(list, 1); // Print the LinkedList printList(list); // Delete node with value 4 // In this case the key is present ***in the // middle*** deleteByKey(list, 4); // Print the LinkedList printList(list); // Delete node with value 10 // In this case the key is ***not present*** deleteByKey(list, 10); // Print the LinkedList printList(list); }}", "e": 37159, "s": 32529, "text": null }, { "code": null, "e": 37319, "s": 37159, "text": "LinkedList: 1 2 3 4 5 6 7 8 \n1 found and deleted\nLinkedList: 2 3 4 5 6 7 8 \n4 found and deleted\nLinkedList: 2 3 5 6 7 8 \n10 not found\nLinkedList: 2 3 5 6 7 8 \n" }, { "code": null, "e": 37340, "s": 37319, "text": "Deletion At Position" }, { "code": null, "e": 37528, "s": 37340, "text": "This deletion process can be understood as follows:To be done: Given a ‘position’, delete the node at this position from the linked list.How to do it: The steps to do it are as follows: " }, { "code": null, "e": 38270, "s": 37528, "text": "Traverse the list by counting the index of the nodesFor each index, match the index to be same as positionNow, Any of the 3 conditions can be there: Case 1: The position is 0, i.e. the head is to be deleted In this case, Change the head of the node to the next node of current head. Free the memory of replaced head node.Case 2: The position is greater than 0 but less than the size of the list, i.e. in the middle or last, except at head In this case, Find previous node of the node to be deleted. Change the next of previous node to the next node of current node.Free the memory of replaced node.Case 3: The position is greater than the size of the list, i.e. position not found in the list In this case, No operation needs to be done. " }, { "code": null, "e": 38323, "s": 38270, "text": "Traverse the list by counting the index of the nodes" }, { "code": null, "e": 38378, "s": 38323, "text": "For each index, match the index to be same as position" }, { "code": null, "e": 39014, "s": 38378, "text": "Now, Any of the 3 conditions can be there: Case 1: The position is 0, i.e. the head is to be deleted In this case, Change the head of the node to the next node of current head. Free the memory of replaced head node.Case 2: The position is greater than 0 but less than the size of the list, i.e. in the middle or last, except at head In this case, Find previous node of the node to be deleted. Change the next of previous node to the next node of current node.Free the memory of replaced node.Case 3: The position is greater than the size of the list, i.e. position not found in the list In this case, No operation needs to be done. " }, { "code": null, "e": 39188, "s": 39014, "text": "Case 1: The position is 0, i.e. the head is to be deleted In this case, Change the head of the node to the next node of current head. Free the memory of replaced head node." }, { "code": null, "e": 39304, "s": 39188, "text": "In this case, Change the head of the node to the next node of current head. Free the memory of replaced head node." }, { "code": null, "e": 39382, "s": 39304, "text": "In this case, Change the head of the node to the next node of current head. " }, { "code": null, "e": 39421, "s": 39382, "text": "Free the memory of replaced head node." }, { "code": null, "e": 39700, "s": 39421, "text": "Case 2: The position is greater than 0 but less than the size of the list, i.e. in the middle or last, except at head In this case, Find previous node of the node to be deleted. Change the next of previous node to the next node of current node.Free the memory of replaced node." }, { "code": null, "e": 39861, "s": 39700, "text": "In this case, Find previous node of the node to be deleted. Change the next of previous node to the next node of current node.Free the memory of replaced node." }, { "code": null, "e": 39923, "s": 39861, "text": "In this case, Find previous node of the node to be deleted. " }, { "code": null, "e": 39990, "s": 39923, "text": "Change the next of previous node to the next node of current node." }, { "code": null, "e": 40024, "s": 39990, "text": "Free the memory of replaced node." }, { "code": null, "e": 40166, "s": 40024, "text": "Case 3: The position is greater than the size of the list, i.e. position not found in the list In this case, No operation needs to be done. " }, { "code": null, "e": 40213, "s": 40166, "text": "In this case, No operation needs to be done. " }, { "code": null, "e": 40260, "s": 40213, "text": "In this case, No operation needs to be done. " }, { "code": null, "e": 40269, "s": 40264, "text": "Java" }, { "code": "import java.io.*; // Java program to implement// a Singly Linked Listpublic class LinkedList { Node head; // head of list // Linked list Node. // Node is a static nested class // so main() can access it static class Node { int data; Node next; // Constructor Node(int d) { data = d; next = null; } } // Method to insert a new node public static LinkedList insert(LinkedList list, int data) { // Create a new node with given data Node new_node = new Node(data); new_node.next = null; // If the Linked List is empty, // then make the new node as head if (list.head == null) { list.head = new_node; } else { // Else traverse till the last node // and insert the new_node there Node last = list.head; while (last.next != null) { last = last.next; } // Insert the new_node at last node last.next = new_node; } // Return the list by head return list; } // Method to print the LinkedList. public static void printList(LinkedList list) { Node currNode = list.head; System.out.print(\"LinkedList: \"); // Traverse through the LinkedList while (currNode != null) { // Print the data at current node System.out.print(currNode.data + \" \"); // Go to next node currNode = currNode.next; } System.out.println(); } // Method to delete a node in the LinkedList by POSITION public static LinkedList deleteAtPosition(LinkedList list, int index) { // Store head node Node currNode = list.head, prev = null; // // CASE 1: // If index is 0, then head node itself is to be // deleted if (index == 0 && currNode != null) { list.head = currNode.next; // Changed head // Display the message System.out.println( index + \" position element deleted\"); // Return the updated List return list; } // // CASE 2: // If the index is greater than 0 but less than the // size of LinkedList // // The counter int counter = 0; // Count for the index to be deleted, // keep track of the previous node // as it is needed to change currNode.next while (currNode != null) { if (counter == index) { // Since the currNode is the required // position Unlink currNode from linked list prev.next = currNode.next; // Display the message System.out.println( index + \" position element deleted\"); break; } else { // If current position is not the index // continue to next node prev = currNode; currNode = currNode.next; counter++; } } // If the position element was found, it should be // at currNode Therefore the currNode shall not be // null // // CASE 3: The index is greater than the size of the // LinkedList // // In this case, the currNode should be null if (currNode == null) { // Display the message System.out.println( index + \" position element not found\"); } // return the List return list; } // **************MAIN METHOD************** // method to create a Singly linked list with n nodes public static void main(String[] args) { /* Start with the empty list. */ LinkedList list = new LinkedList(); // // ******INSERTION****** // // Insert the values list = insert(list, 1); list = insert(list, 2); list = insert(list, 3); list = insert(list, 4); list = insert(list, 5); list = insert(list, 6); list = insert(list, 7); list = insert(list, 8); // Print the LinkedList printList(list); // // ******DELETION AT POSITION****** // // Delete node at position 0 // In this case the key is ***at head*** deleteAtPosition(list, 0); // Print the LinkedList printList(list); // Delete node at position 2 // In this case the key is present ***in the // middle*** deleteAtPosition(list, 2); // Print the LinkedList printList(list); // Delete node at position 10 // In this case the key is ***not present*** deleteAtPosition(list, 10); // Print the LinkedList printList(list); }}", "e": 45174, "s": 40269, "text": null }, { "code": null, "e": 45365, "s": 45174, "text": "LinkedList: 1 2 3 4 5 6 7 8 \n0 position element deleted\nLinkedList: 2 3 4 5 6 7 8 \n2 position element deleted\nLinkedList: 2 3 5 6 7 8 \n10 position element not found\nLinkedList: 2 3 5 6 7 8 \n" }, { "code": null, "e": 45380, "s": 45365, "text": "All Operations" }, { "code": null, "e": 45448, "s": 45380, "text": "Below is the complete program that applies each operation together:" }, { "code": null, "e": 45453, "s": 45448, "text": "Java" }, { "code": "import java.io.*; // Java program to implement// a Singly Linked Listpublic class LinkedList { Node head; // head of list // Linked list Node. // Node is a static nested class // so main() can access it static class Node { int data; Node next; // Constructor Node(int d) { data = d; next = null; } } // **************INSERTION************** // Method to insert a new node public static LinkedList insert(LinkedList list, int data) { // Create a new node with given data Node new_node = new Node(data); new_node.next = null; // If the Linked List is empty, // then make the new node as head if (list.head == null) { list.head = new_node; } else { // Else traverse till the last node // and insert the new_node there Node last = list.head; while (last.next != null) { last = last.next; } // Insert the new_node at last node last.next = new_node; } // Return the list by head return list; } // **************TRAVERSAL************** // Method to print the LinkedList. public static void printList(LinkedList list) { Node currNode = list.head; System.out.print(\"\\nLinkedList: \"); // Traverse through the LinkedList while (currNode != null) { // Print the data at current node System.out.print(currNode.data + \" \"); // Go to next node currNode = currNode.next; } System.out.println(\"\\n\"); } // **************DELETION BY KEY************** // Method to delete a node in the LinkedList by KEY public static LinkedList deleteByKey(LinkedList list, int key) { // Store head node Node currNode = list.head, prev = null; // // CASE 1: // If head node itself holds the key to be deleted if (currNode != null && currNode.data == key) { list.head = currNode.next; // Changed head // Display the message System.out.println(key + \" found and deleted\"); // Return the updated List return list; } // // CASE 2: // If the key is somewhere other than at head // // Search for the key to be deleted, // keep track of the previous node // as it is needed to change currNode.next while (currNode != null && currNode.data != key) { // If currNode does not hold key // continue to next node prev = currNode; currNode = currNode.next; } // If the key was present, it should be at currNode // Therefore the currNode shall not be null if (currNode != null) { // Since the key is at currNode // Unlink currNode from linked list prev.next = currNode.next; // Display the message System.out.println(key + \" found and deleted\"); } // // CASE 3: The key is not present // // If key was not present in linked list // currNode should be null if (currNode == null) { // Display the message System.out.println(key + \" not found\"); } // return the List return list; } // **************DELETION AT A POSITION************** // Method to delete a node in the LinkedList by POSITION public static LinkedList deleteAtPosition(LinkedList list, int index) { // Store head node Node currNode = list.head, prev = null; // // CASE 1: // If index is 0, then head node itself is to be // deleted if (index == 0 && currNode != null) { list.head = currNode.next; // Changed head // Display the message System.out.println( index + \" position element deleted\"); // Return the updated List return list; } // // CASE 2: // If the index is greater than 0 but less than the // size of LinkedList // // The counter int counter = 0; // Count for the index to be deleted, // keep track of the previous node // as it is needed to change currNode.next while (currNode != null) { if (counter == index) { // Since the currNode is the required // position Unlink currNode from linked list prev.next = currNode.next; // Display the message System.out.println( index + \" position element deleted\"); break; } else { // If current position is not the index // continue to next node prev = currNode; currNode = currNode.next; counter++; } } // If the position element was found, it should be // at currNode Therefore the currNode shall not be // null // // CASE 3: The index is greater than the size of the // LinkedList // // In this case, the currNode should be null if (currNode == null) { // Display the message System.out.println( index + \" position element not found\"); } // return the List return list; } // **************MAIN METHOD************** // method to create a Singly linked list with n nodes public static void main(String[] args) { /* Start with the empty list. */ LinkedList list = new LinkedList(); // // ******INSERTION****** // // Insert the values list = insert(list, 1); list = insert(list, 2); list = insert(list, 3); list = insert(list, 4); list = insert(list, 5); list = insert(list, 6); list = insert(list, 7); list = insert(list, 8); // Print the LinkedList printList(list); // // ******DELETION BY KEY****** // // Delete node with value 1 // In this case the key is ***at head*** deleteByKey(list, 1); // Print the LinkedList printList(list); // Delete node with value 4 // In this case the key is present ***in the // middle*** deleteByKey(list, 4); // Print the LinkedList printList(list); // Delete node with value 10 // In this case the key is ***not present*** deleteByKey(list, 10); // Print the LinkedList printList(list); // // ******DELETION AT POSITION****** // // Delete node at position 0 // In this case the key is ***at head*** deleteAtPosition(list, 0); // Print the LinkedList printList(list); // Delete node at position 2 // In this case the key is present ***in the // middle*** deleteAtPosition(list, 2); // Print the LinkedList printList(list); // Delete node at position 10 // In this case the key is ***not present*** deleteAtPosition(list, 10); // Print the LinkedList printList(list); }}", "e": 52897, "s": 45453, "text": null }, { "code": null, "e": 53219, "s": 52897, "text": "LinkedList: 1 2 3 4 5 6 7 8 \n\n1 found and deleted\n\nLinkedList: 2 3 4 5 6 7 8 \n\n4 found and deleted\n\nLinkedList: 2 3 5 6 7 8 \n\n10 not found\n\nLinkedList: 2 3 5 6 7 8 \n\n0 position element deleted\n\nLinkedList: 3 5 6 7 8 \n\n2 position element deleted\n\nLinkedList: 3 5 7 8 \n\n10 position element not found\n\nLinkedList: 3 5 7 8 \n\n" }, { "code": null, "e": 53238, "s": 53219, "text": "shakibuddinbhuiyan" }, { "code": null, "e": 53260, "s": 53238, "text": "Java-Class and Object" }, { "code": null, "e": 53279, "s": 53260, "text": "Java-List-Programs" }, { "code": null, "e": 53295, "s": 53279, "text": "Data Structures" }, { "code": null, "e": 53300, "s": 53295, "text": "Java" }, { "code": null, "e": 53314, "s": 53300, "text": "Java Programs" }, { "code": null, "e": 53326, "s": 53314, "text": "Linked List" }, { "code": null, "e": 53342, "s": 53326, "text": "Data Structures" }, { "code": null, "e": 53364, "s": 53342, "text": "Java-Class and Object" }, { "code": null, "e": 53376, "s": 53364, "text": "Linked List" }, { "code": null, "e": 53381, "s": 53376, "text": "Java" }, { "code": null, "e": 53479, "s": 53381, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 53488, "s": 53479, "text": "Comments" }, { "code": null, "e": 53501, "s": 53488, "text": "Old Comments" }, { "code": null, "e": 53550, "s": 53501, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 53582, "s": 53550, "text": "Insertion and Deletion in Heaps" }, { "code": null, "e": 53607, "s": 53582, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 53686, "s": 53607, "text": "Comparison between Adjacency List and Adjacency Matrix representation of Graph" }, { "code": null, "e": 53713, "s": 53686, "text": "Introduction to Algorithms" }, { "code": null, "e": 53728, "s": 53713, "text": "Arrays in Java" }, { "code": null, "e": 53772, "s": 53728, "text": "Split() String method in Java with examples" }, { "code": null, "e": 53808, "s": 53772, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 53830, "s": 53808, "text": "For-each loop in Java" } ]
Delete a File Using Java - GeeksforGeeks
24 Jan, 2022 Java provides methods to delete files using java programs. On the contrary to normal delete operations in any operating system, files being deleted using the java program are deleted permanently without being moved to the trash/recycle bin. 1. Using java.io.File.delete() function: Deletes the file or directory denoted by this abstract pathname. Syntax: public boolean delete() Returns: It returns true if and only if the file or the directory is successfully deleted; false otherwise Java // Java program to delete a fileimport java.io.*; public class Test { public static void main(String[] args) { File file = new File("C:\\Users\\Mayank\\Desktop\\1.txt"); if (file.delete()) { System.out.println("File deleted successfully"); } else { System.out.println("Failed to delete the file"); } }} Output: File deleted successfully 2. Using java.nio.file.files.deleteifexists(Path p) method defined in Files package: This method deletes a file if it exists. It also deletes a directory mentioned in the path only if the directory is not empty. Syntax: public static boolean deleteIfExists(Path path) throws IOException Parameters: path – the path to the file to delete Returns: It returns true if the file was deleted by this method; false if it could not be deleted because it did not exist. Throws: DirectoryNotEmptyException – if the file is a directory and could not otherwise be deleted because the directory is not empty (optional specific exception) IOException – if an I/O error occurs. Java // Java program to demonstrate delete using Files class import java.io.IOException;import java.nio.file.*; public class Test { public static void main(String[] args) { try { Files.deleteIfExists( Paths.get("C:\\Users\\Mayank\\Desktop\\ 445.txt")); } catch (NoSuchFileException e) { System.out.println( "No such file/directory exists"); } catch (DirectoryNotEmptyException e) { System.out.println("Directory is not empty."); } catch (IOException e) { System.out.println("Invalid permissions."); } System.out.println("Deletion successful."); }} Output: Deletion successful. This article is contributed by Mayank Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nishkarshgandhi java-file-handling Java-I/O Java-Library Java School Programming Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Split() String method in Java with examples Reverse a string in Java Arrays.sort() in Java with examples Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Python Dictionary Arrays in C/C++ Reverse a string in Java Inheritance in C++ C++ Classes and Objects
[ { "code": null, "e": 27485, "s": 27457, "text": "\n24 Jan, 2022" }, { "code": null, "e": 27727, "s": 27485, "text": "Java provides methods to delete files using java programs. On the contrary to normal delete operations in any operating system, files being deleted using the java program are deleted permanently without being moved to the trash/recycle bin. " }, { "code": null, "e": 27834, "s": 27727, "text": "1. Using java.io.File.delete() function: Deletes the file or directory denoted by this abstract pathname. " }, { "code": null, "e": 27843, "s": 27834, "text": "Syntax: " }, { "code": null, "e": 27867, "s": 27843, "text": "public boolean delete()" }, { "code": null, "e": 27974, "s": 27867, "text": "Returns: It returns true if and only if the file or the directory is successfully deleted; false otherwise" }, { "code": null, "e": 27979, "s": 27974, "text": "Java" }, { "code": "// Java program to delete a fileimport java.io.*; public class Test { public static void main(String[] args) { File file = new File(\"C:\\\\Users\\\\Mayank\\\\Desktop\\\\1.txt\"); if (file.delete()) { System.out.println(\"File deleted successfully\"); } else { System.out.println(\"Failed to delete the file\"); } }}", "e": 28360, "s": 27979, "text": null }, { "code": null, "e": 28369, "s": 28360, "text": "Output: " }, { "code": null, "e": 28395, "s": 28369, "text": "File deleted successfully" }, { "code": null, "e": 28608, "s": 28395, "text": "2. Using java.nio.file.files.deleteifexists(Path p) method defined in Files package: This method deletes a file if it exists. It also deletes a directory mentioned in the path only if the directory is not empty. " }, { "code": null, "e": 28616, "s": 28608, "text": "Syntax:" }, { "code": null, "e": 28683, "s": 28616, "text": "public static boolean deleteIfExists(Path path) throws IOException" }, { "code": null, "e": 28733, "s": 28683, "text": "Parameters: path – the path to the file to delete" }, { "code": null, "e": 28857, "s": 28733, "text": "Returns: It returns true if the file was deleted by this method; false if it could not be deleted because it did not exist." }, { "code": null, "e": 28866, "s": 28857, "text": "Throws: " }, { "code": null, "e": 29022, "s": 28866, "text": "DirectoryNotEmptyException – if the file is a directory and could not otherwise be deleted because the directory is not empty (optional specific exception)" }, { "code": null, "e": 29060, "s": 29022, "text": "IOException – if an I/O error occurs." }, { "code": null, "e": 29065, "s": 29060, "text": "Java" }, { "code": "// Java program to demonstrate delete using Files class import java.io.IOException;import java.nio.file.*; public class Test { public static void main(String[] args) { try { Files.deleteIfExists( Paths.get(\"C:\\\\Users\\\\Mayank\\\\Desktop\\\\ 445.txt\")); } catch (NoSuchFileException e) { System.out.println( \"No such file/directory exists\"); } catch (DirectoryNotEmptyException e) { System.out.println(\"Directory is not empty.\"); } catch (IOException e) { System.out.println(\"Invalid permissions.\"); } System.out.println(\"Deletion successful.\"); }}", "e": 29766, "s": 29065, "text": null }, { "code": null, "e": 29775, "s": 29766, "text": "Output: " }, { "code": null, "e": 29796, "s": 29775, "text": "Deletion successful." }, { "code": null, "e": 30217, "s": 29796, "text": "This article is contributed by Mayank Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 30233, "s": 30217, "text": "nishkarshgandhi" }, { "code": null, "e": 30252, "s": 30233, "text": "java-file-handling" }, { "code": null, "e": 30261, "s": 30252, "text": "Java-I/O" }, { "code": null, "e": 30274, "s": 30261, "text": "Java-Library" }, { "code": null, "e": 30279, "s": 30274, "text": "Java" }, { "code": null, "e": 30298, "s": 30279, "text": "School Programming" }, { "code": null, "e": 30303, "s": 30298, "text": "Java" }, { "code": null, "e": 30401, "s": 30303, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30410, "s": 30401, "text": "Comments" }, { "code": null, "e": 30423, "s": 30410, "text": "Old Comments" }, { "code": null, "e": 30467, "s": 30423, "text": "Split() String method in Java with examples" }, { "code": null, "e": 30492, "s": 30467, "text": "Reverse a string in Java" }, { "code": null, "e": 30528, "s": 30492, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 30579, "s": 30528, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 30610, "s": 30579, "text": "How to iterate any Map in Java" }, { "code": null, "e": 30628, "s": 30610, "text": "Python Dictionary" }, { "code": null, "e": 30644, "s": 30628, "text": "Arrays in C/C++" }, { "code": null, "e": 30669, "s": 30644, "text": "Reverse a string in Java" }, { "code": null, "e": 30688, "s": 30669, "text": "Inheritance in C++" } ]
BNF Notation in Compiler Design - GeeksforGeeks
20 Jul, 2021 BNF stands for Backus Naur Form notation. It is a formal method for describing the syntax of programming language which is understood as Backus Naur Formas introduced by John Bakus and Peter Naur in 1960. BNF and CFG (Context Free Grammar) were nearly identical. BNF may be a meta-language (a language that cannot describe another language) for primary languages. For human consumption, a proper notation for encoding grammars intended and called Backus Naur Form (BNF). Different languages have different description and rules but the general structure of BNF is given below – name ::= expansion The symbol ::= means “may expand into” and “may get replaced with.” In some texts, a reputation is additionally called a non-terminal symbol. Every name in Backus-Naur form is surrounded by angle brackets, < >, whether it appears on the left- or right-hand side of the rule. An expansion is an expression containing terminal symbols and non-terminal symbols, joined together by sequencing and selection. A terminal symbol may be a literal like (“+” or “function”) or a category of literals (like integer). Simply juxtaposing expressions indicates sequencing. A vertical bar | indicates choice. Examples : Examples : <expr> ::= <term> "+" <expr> | <term> <term> ::= <factor> "*" <term> | <factor> <factor> ::= "(" <expr> ")" | <const> <const> ::= integer Rules For making BNF : Naturally, we will define a grammar for rules in BNF – rule → name ::= expansion name → < identifier > expansion → expansion expansion expansion → expansion | expansion expansion → name expansion → terminal We might define identifiers as using the regular expression [-A-Za-z_0-9]+. A terminal could be a quoted literal (like “+”, “switch” or ” “<<=”) or the name of a category of literals (like integer). The name of a category of literals is typically defined by other means, like a daily expression or maybe prose. It is common to seek out regular-expression-like operations inside grammars. as an example, the Python lexical specification uses them. In these grammars: It is common to seek out regular-expression-like operations inside grammars. as an example, the Python lexical specification uses them. In these grammars: postfix * means "repeated 0 or more times" postfix + means "repeated 1 or more times" postfix ? means "0 or 1 times" The definition of floating-point literals in Python may be an exemplar of mixing several notations – floatnumber ::= pointfloat | exponentfloat pointfloat ::= [intpart] fraction | intpart "." exponentfloat ::= (intpart | pointfloat) exponent intpart ::= digit+ fraction ::= "." digit+ exponent ::= ("e" | "E") ["+" | "-"] digit+ It does not use angle brackets around names (like many EBNF notations and ABNF), yet does use ::= (like BNF). It mixes regular operations like + for non-empty repetition with EBNF conventions like [ ] for option. The grammar for the whole Python language uses a rather different (but still regular) notation. adnanirshad158 Compiler Design Theory of Computation & Automata Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Directed Acyclic graph in Compiler Design (with examples) Difference between Top down parsing and Bottom up parsing Loop Optimization in Compiler Design S - attributed and L - attributed SDTs in Syntax directed translation Why FIRST and FOLLOW in Compiler Design? Regular Expressions, Regular Grammar and Regular Languages Difference between DFA and NFA Introduction of Finite Automata Difference between Mealy machine and Moore machine Pumping Lemma in Theory of Computation
[ { "code": null, "e": 24446, "s": 24418, "text": "\n20 Jul, 2021" }, { "code": null, "e": 24811, "s": 24446, "text": "BNF stands for Backus Naur Form notation. It is a formal method for describing the syntax of programming language which is understood as Backus Naur Formas introduced by John Bakus and Peter Naur in 1960. BNF and CFG (Context Free Grammar) were nearly identical. BNF may be a meta-language (a language that cannot describe another language) for primary languages. " }, { "code": null, "e": 25026, "s": 24811, "text": "For human consumption, a proper notation for encoding grammars intended and called Backus Naur Form (BNF). Different languages have different description and rules but the general structure of BNF is given below – " }, { "code": null, "e": 25047, "s": 25028, "text": "name ::= expansion" }, { "code": null, "e": 25190, "s": 25047, "text": "The symbol ::= means “may expand into” and “may get replaced with.” In some texts, a reputation is additionally called a non-terminal symbol. " }, { "code": null, "e": 25327, "s": 25192, "text": "Every name in Backus-Naur form is surrounded by angle brackets, < >, whether it appears on the left- or right-hand side of the rule. " }, { "code": null, "e": 25460, "s": 25329, "text": "An expansion is an expression containing terminal symbols and non-terminal symbols, joined together by sequencing and selection. " }, { "code": null, "e": 25566, "s": 25462, "text": "A terminal symbol may be a literal like (“+” or “function”) or a category of literals (like integer). " }, { "code": null, "e": 25623, "s": 25568, "text": "Simply juxtaposing expressions indicates sequencing. " }, { "code": null, "e": 25673, "s": 25625, "text": "A vertical bar | indicates choice. Examples : " }, { "code": null, "e": 25686, "s": 25673, "text": "Examples : " }, { "code": null, "e": 25856, "s": 25686, "text": "<expr> ::= <term> \"+\" <expr>\n | <term>\n\n<term> ::= <factor> \"*\" <term>\n | <factor>\n\n<factor> ::= \"(\" <expr> \")\"\n | <const>\n\n<const> ::= integer" }, { "code": null, "e": 25936, "s": 25856, "text": "Rules For making BNF : Naturally, we will define a grammar for rules in BNF – " }, { "code": null, "e": 26088, "s": 25936, "text": "rule → name ::= expansion\nname → < identifier >\nexpansion → expansion expansion\nexpansion → expansion | expansion\nexpansion → name\nexpansion → terminal" }, { "code": null, "e": 26166, "s": 26088, "text": "We might define identifiers as using the regular expression [-A-Za-z_0-9]+. " }, { "code": null, "e": 26293, "s": 26168, "text": "A terminal could be a quoted literal (like “+”, “switch” or ” “<<=”) or the name of a category of literals (like integer). " }, { "code": null, "e": 26564, "s": 26295, "text": "The name of a category of literals is typically defined by other means, like a daily expression or maybe prose. It is common to seek out regular-expression-like operations inside grammars. as an example, the Python lexical specification uses them. In these grammars: " }, { "code": null, "e": 26721, "s": 26564, "text": "It is common to seek out regular-expression-like operations inside grammars. as an example, the Python lexical specification uses them. In these grammars: " }, { "code": null, "e": 26838, "s": 26721, "text": "postfix * means \"repeated 0 or more times\"\npostfix + means \"repeated 1 or more times\"\npostfix ? means \"0 or 1 times\"" }, { "code": null, "e": 26940, "s": 26838, "text": "The definition of floating-point literals in Python may be an exemplar of mixing several notations – " }, { "code": null, "e": 27197, "s": 26942, "text": "floatnumber ::= pointfloat | exponentfloat\npointfloat ::= [intpart] fraction | intpart \".\"\nexponentfloat ::= (intpart | pointfloat) exponent\nintpart ::= digit+\nfraction ::= \".\" digit+\nexponent ::= (\"e\" | \"E\") [\"+\" | \"-\"] digit+" }, { "code": null, "e": 27507, "s": 27197, "text": "It does not use angle brackets around names (like many EBNF notations and ABNF), yet does use ::= (like BNF). It mixes regular operations like + for non-empty repetition with EBNF conventions like [ ] for option. The grammar for the whole Python language uses a rather different (but still regular) notation. " }, { "code": null, "e": 27522, "s": 27507, "text": "adnanirshad158" }, { "code": null, "e": 27538, "s": 27522, "text": "Compiler Design" }, { "code": null, "e": 27571, "s": 27538, "text": "Theory of Computation & Automata" }, { "code": null, "e": 27669, "s": 27571, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27727, "s": 27669, "text": "Directed Acyclic graph in Compiler Design (with examples)" }, { "code": null, "e": 27785, "s": 27727, "text": "Difference between Top down parsing and Bottom up parsing" }, { "code": null, "e": 27822, "s": 27785, "text": "Loop Optimization in Compiler Design" }, { "code": null, "e": 27892, "s": 27822, "text": "S - attributed and L - attributed SDTs in Syntax directed translation" }, { "code": null, "e": 27933, "s": 27892, "text": "Why FIRST and FOLLOW in Compiler Design?" }, { "code": null, "e": 27992, "s": 27933, "text": "Regular Expressions, Regular Grammar and Regular Languages" }, { "code": null, "e": 28023, "s": 27992, "text": "Difference between DFA and NFA" }, { "code": null, "e": 28055, "s": 28023, "text": "Introduction of Finite Automata" }, { "code": null, "e": 28106, "s": 28055, "text": "Difference between Mealy machine and Moore machine" } ]
AngularJS | ng-model Directive - GeeksforGeeks
23 May, 2019 ngModel is a directive which binds input, select and textarea, and stores the required user value in a variable and we can use that variable whenever we require that value.It also is used during validations in a form. We can use ngModel with: inputtextcheckboxradionumberemailurldatedatetime-localtimemonthweekselecttextarea inputtextcheckboxradionumberemailurldatedatetime-localtimemonthweek text checkbox radio number email url date datetime-local time month week select textarea Example: <!DOCTYPE html><html><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script><style> .column { float: left; text-align: left; width: 49%; } .row { content: ""; display: table; }</style> <body ng-app="myApp" ng-controller="myController"> <h4>Input Box-</h4> <div class="row"> <div class="column"> Name- <input type="text" ng-model="name"> <pre> {{ name }} </pre> Checkbox- <input type="checkbox" ng-model="check"> <pre> {{ check }} </pre> Radiobox- <input type="radio" ng-model="choice"> <pre> {{ choice }} </pre> Number- <input type="number" ng-model="num"> <pre> {{ num }} </pre> Email- <input type="email" ng-model="mail"> <pre> {{ mail }} </pre> Url- <input type="url" ng-model="url"> <pre> {{ url }} </pre> </div> <div class="column"> Date: <input type="date" ng-model="date1" (change)="log(date1)"> <pre> Todays date:{{ date1+1 }}</pre> Datetime-local- <input type="datetime-local" ng-model="date2"> <pre> {{ date2+1 }} </pre> Time- <input type="time" ng-model="time1"> <pre> {{ time1+1 }} </pre> Month- <input type="month" ng-model="mon"> <pre> {{ mon+1 }} </pre> Week- <input type="week" ng-model="we"> <pre> {{ we+1 }} </pre> </div> </div></body><script> var app = angular.module('myApp', []); app.controller('myController', function($scope) { $scope.name = "Hello Geeks!"; $scope.check = ""; $scope.rad = ""; $scope.num = ""; $scope.mail = ""; $scope.url = ""; $scope.date1 = ""; $scope.date2 = ""; $scope.time1 = ""; $scope.mon = ""; $scope.we = ""; $scope.choice = ""; $scope.c = function() { $scope.choice = true; }; });</script> </html> In order to make url and email print, we have to write a valid email/url only then it would get printed. In case of printing of date, time using ngmodel we have to fill in all the fields in the input box. The radio button once selected won’t get deselected since in the function of “c” we are setting the value of choice as true. Ngmodel using forms:We can define ngModel in this way also, Write the below code in app.component.html <div class="form-group"> <label for="phone">mobile</label> <form> <input type="text" id="phone" ngModel name="phone" #phone="ngModel" placeholder="Mobile"></form><pre>{{ phone.value }}</pre></div> ngModel stores a variable by reference, not value. Usually in binding inputs to models that are objects (e.g. Date) or collections (e.g. arrays). The phone object created has many fields which are used for validation purpose. We can add the following classes for validation purpose. We are listing only the important ones. ng-touchedng-untouchedng-validng-invalidng-dirtyng-pendingng-pristine ng-touched ng-untouched ng-valid ng-invalid ng-dirty ng-pending ng-pristine Binding ngModel with getter and setter:Whenever a function is called with zero arguments then it returns a representation of the model. And when called with a parameter it sets the value. Since ngModel refers to address that is why it does not save the changed value in the object itself rather it saves it in some internal state (variable-name.value). It will be useful if we keep a practice of using getter and setter for models when there is an internal representation as the getter and setter function gets more often called as compared to rest of the parts of the code. Syntax: ng-model-options="{ getterSetter: true }" Add this to the input tab. Example: <html><head><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script></head><body ng-app="myApp"> <div ng-controller="myController"> <form> Name:<input type="text" name="Name" ng-model="user.name" ng-model-options="{ getterSetter: true }" /> <pre>user.name = <span ng-bind="user.name()"></span></pre> Name1:<input type="text" name="Name1" ng-model="user.name1" ng-model-options="{ getterSetter: true }" /> <pre>user.name = <span ng-bind="user.name1()"></span></pre> </form> </div><script>angular.module('myApp', []) .controller('myController', ['$scope', function($scope) { name = 'GeeksforGeeks'; name1 = ""; $scope.user = { name: function(Name) { return arguments.length ? (name = Name) : name; }, name1: function(Name1) { return arguments.length ? (name1 = Name1) : name1; } }; }]);</script></body></html> Here, we have initialized name by the string Geeksforgeeks and name1 by an empty string. References:https://docs.angularjs.org/api/ng/directive/ngModel AngularJS-Directives Picked AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 10 Angular Libraries For Web Developers Angular File Upload Angular | keyup event Auth Guards in Angular 9/10/11 What is AOT and JIT Compiler in Angular ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 28271, "s": 28243, "text": "\n23 May, 2019" }, { "code": null, "e": 28489, "s": 28271, "text": "ngModel is a directive which binds input, select and textarea, and stores the required user value in a variable and we can use that variable whenever we require that value.It also is used during validations in a form." }, { "code": null, "e": 28514, "s": 28489, "text": "We can use ngModel with:" }, { "code": null, "e": 28596, "s": 28514, "text": "inputtextcheckboxradionumberemailurldatedatetime-localtimemonthweekselecttextarea" }, { "code": null, "e": 28664, "s": 28596, "text": "inputtextcheckboxradionumberemailurldatedatetime-localtimemonthweek" }, { "code": null, "e": 28669, "s": 28664, "text": "text" }, { "code": null, "e": 28678, "s": 28669, "text": "checkbox" }, { "code": null, "e": 28684, "s": 28678, "text": "radio" }, { "code": null, "e": 28691, "s": 28684, "text": "number" }, { "code": null, "e": 28697, "s": 28691, "text": "email" }, { "code": null, "e": 28701, "s": 28697, "text": "url" }, { "code": null, "e": 28706, "s": 28701, "text": "date" }, { "code": null, "e": 28721, "s": 28706, "text": "datetime-local" }, { "code": null, "e": 28726, "s": 28721, "text": "time" }, { "code": null, "e": 28732, "s": 28726, "text": "month" }, { "code": null, "e": 28737, "s": 28732, "text": "week" }, { "code": null, "e": 28744, "s": 28737, "text": "select" }, { "code": null, "e": 28753, "s": 28744, "text": "textarea" }, { "code": null, "e": 28762, "s": 28753, "text": "Example:" }, { "code": "<!DOCTYPE html><html><script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"></script><style> .column { float: left; text-align: left; width: 49%; } .row { content: \"\"; display: table; }</style> <body ng-app=\"myApp\" ng-controller=\"myController\"> <h4>Input Box-</h4> <div class=\"row\"> <div class=\"column\"> Name- <input type=\"text\" ng-model=\"name\"> <pre> {{ name }} </pre> Checkbox- <input type=\"checkbox\" ng-model=\"check\"> <pre> {{ check }} </pre> Radiobox- <input type=\"radio\" ng-model=\"choice\"> <pre> {{ choice }} </pre> Number- <input type=\"number\" ng-model=\"num\"> <pre> {{ num }} </pre> Email- <input type=\"email\" ng-model=\"mail\"> <pre> {{ mail }} </pre> Url- <input type=\"url\" ng-model=\"url\"> <pre> {{ url }} </pre> </div> <div class=\"column\"> Date: <input type=\"date\" ng-model=\"date1\" (change)=\"log(date1)\"> <pre> Todays date:{{ date1+1 }}</pre> Datetime-local- <input type=\"datetime-local\" ng-model=\"date2\"> <pre> {{ date2+1 }} </pre> Time- <input type=\"time\" ng-model=\"time1\"> <pre> {{ time1+1 }} </pre> Month- <input type=\"month\" ng-model=\"mon\"> <pre> {{ mon+1 }} </pre> Week- <input type=\"week\" ng-model=\"we\"> <pre> {{ we+1 }} </pre> </div> </div></body><script> var app = angular.module('myApp', []); app.controller('myController', function($scope) { $scope.name = \"Hello Geeks!\"; $scope.check = \"\"; $scope.rad = \"\"; $scope.num = \"\"; $scope.mail = \"\"; $scope.url = \"\"; $scope.date1 = \"\"; $scope.date2 = \"\"; $scope.time1 = \"\"; $scope.mon = \"\"; $scope.we = \"\"; $scope.choice = \"\"; $scope.c = function() { $scope.choice = true; }; });</script> </html>", "e": 30938, "s": 28762, "text": null }, { "code": null, "e": 31268, "s": 30938, "text": "In order to make url and email print, we have to write a valid email/url only then it would get printed. In case of printing of date, time using ngmodel we have to fill in all the fields in the input box. The radio button once selected won’t get deselected since in the function of “c” we are setting the value of choice as true." }, { "code": null, "e": 31328, "s": 31268, "text": "Ngmodel using forms:We can define ngModel in this way also," }, { "code": null, "e": 31371, "s": 31328, "text": "Write the below code in app.component.html" }, { "code": "<div class=\"form-group\"> <label for=\"phone\">mobile</label> <form> <input type=\"text\" id=\"phone\" ngModel name=\"phone\" #phone=\"ngModel\" placeholder=\"Mobile\"></form><pre>{{ phone.value }}</pre></div>", "e": 31629, "s": 31371, "text": null }, { "code": null, "e": 31775, "s": 31629, "text": "ngModel stores a variable by reference, not value. Usually in binding inputs to models that are objects (e.g. Date) or collections (e.g. arrays)." }, { "code": null, "e": 31952, "s": 31775, "text": "The phone object created has many fields which are used for validation purpose. We can add the following classes for validation purpose. We are listing only the important ones." }, { "code": null, "e": 32022, "s": 31952, "text": "ng-touchedng-untouchedng-validng-invalidng-dirtyng-pendingng-pristine" }, { "code": null, "e": 32033, "s": 32022, "text": "ng-touched" }, { "code": null, "e": 32046, "s": 32033, "text": "ng-untouched" }, { "code": null, "e": 32055, "s": 32046, "text": "ng-valid" }, { "code": null, "e": 32066, "s": 32055, "text": "ng-invalid" }, { "code": null, "e": 32075, "s": 32066, "text": "ng-dirty" }, { "code": null, "e": 32086, "s": 32075, "text": "ng-pending" }, { "code": null, "e": 32098, "s": 32086, "text": "ng-pristine" }, { "code": null, "e": 32673, "s": 32098, "text": "Binding ngModel with getter and setter:Whenever a function is called with zero arguments then it returns a representation of the model. And when called with a parameter it sets the value. Since ngModel refers to address that is why it does not save the changed value in the object itself rather it saves it in some internal state (variable-name.value). It will be useful if we keep a practice of using getter and setter for models when there is an internal representation as the getter and setter function gets more often called as compared to rest of the parts of the code." }, { "code": null, "e": 32681, "s": 32673, "text": "Syntax:" }, { "code": null, "e": 32723, "s": 32681, "text": "ng-model-options=\"{ getterSetter: true }\"" }, { "code": null, "e": 32750, "s": 32723, "text": "Add this to the input tab." }, { "code": null, "e": 32759, "s": 32750, "text": "Example:" }, { "code": "<html><head><script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"></script></head><body ng-app=\"myApp\"> <div ng-controller=\"myController\"> <form> Name:<input type=\"text\" name=\"Name\" ng-model=\"user.name\" ng-model-options=\"{ getterSetter: true }\" /> <pre>user.name = <span ng-bind=\"user.name()\"></span></pre> Name1:<input type=\"text\" name=\"Name1\" ng-model=\"user.name1\" ng-model-options=\"{ getterSetter: true }\" /> <pre>user.name = <span ng-bind=\"user.name1()\"></span></pre> </form> </div><script>angular.module('myApp', []) .controller('myController', ['$scope', function($scope) { name = 'GeeksforGeeks'; name1 = \"\"; $scope.user = { name: function(Name) { return arguments.length ? (name = Name) : name; }, name1: function(Name1) { return arguments.length ? (name1 = Name1) : name1; } }; }]);</script></body></html>", "e": 33703, "s": 32759, "text": null }, { "code": null, "e": 33792, "s": 33703, "text": "Here, we have initialized name by the string Geeksforgeeks and name1 by an empty string." }, { "code": null, "e": 33855, "s": 33792, "text": "References:https://docs.angularjs.org/api/ng/directive/ngModel" }, { "code": null, "e": 33876, "s": 33855, "text": "AngularJS-Directives" }, { "code": null, "e": 33883, "s": 33876, "text": "Picked" }, { "code": null, "e": 33893, "s": 33883, "text": "AngularJS" }, { "code": null, "e": 33910, "s": 33893, "text": "Web Technologies" }, { "code": null, "e": 34008, "s": 33910, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34052, "s": 34008, "text": "Top 10 Angular Libraries For Web Developers" }, { "code": null, "e": 34072, "s": 34052, "text": "Angular File Upload" }, { "code": null, "e": 34094, "s": 34072, "text": "Angular | keyup event" }, { "code": null, "e": 34125, "s": 34094, "text": "Auth Guards in Angular 9/10/11" }, { "code": null, "e": 34167, "s": 34125, "text": "What is AOT and JIT Compiler in Angular ?" }, { "code": null, "e": 34209, "s": 34167, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 34242, "s": 34209, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 34285, "s": 34242, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 34335, "s": 34285, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
fstatat() - Unix, Linux System Call
Unix - Home Unix - Getting Started Unix - File Management Unix - Directories Unix - File Permission Unix - Environment Unix - Basic Utilities Unix - Pipes & Filters Unix - Processes Unix - Communication Unix - The vi Editor Unix - What is Shell? Unix - Using Variables Unix - Special Variables Unix - Using Arrays Unix - Basic Operators Unix - Decision Making Unix - Shell Loops Unix - Loop Control Unix - Shell Substitutions Unix - Quoting Mechanisms Unix - IO Redirections Unix - Shell Functions Unix - Manpage Help Unix - Regular Expressions Unix - File System Basics Unix - User Administration Unix - System Performance Unix - System Logging Unix - Signals and Traps Unix - Useful Commands Unix - Quick Guide Unix - Builtin Functions Unix - System Calls Unix - Commands List Unix Useful Resources Computer Glossary Who is Who Copyright © 2014 by tutorialspoint fstatat - get file status relative to a directory file descriptor #include <sys/stat.h> int fstatat(int dirfd, const char *path, struct stat * buf ", int " flags ); int fstatat(int dirfd, const char *path, struct stat * buf ", int " flags ); The fstatat() system call operates in exactly the same way as stat(2), except for the differences described in this manual page. If the pathname given in path is relative, then it is interpreted relative to the directory referred to by the file descriptor dirfd (rather than relative to the current working directory of the calling process, as is done by stat(2) for a relative pathname). If the pathname given in path is relative and dirfd is the special value AT_FDCWD, then path is interpreted relative to the current working directory of the calling process (like stat(2)). If the pathname given in path is absolute, then dirfd is ignored. flags can either be 0, or include the following flag: On success, fstatat() returns 0. On error, -1 is returned and errno is set to indicate the error. The same errors that occur for stat(2) can also occur for fstatat(). The following additional errors can occur for fstatat(): See openat(2) for an explanation of the need for fstatat(). This system call is non-standard but is proposed for inclusion in a future revision of POSIX.1. A similar system call exists on Solaris. fstatat() was added to Linux in kernel 2.6.16. openat (2) openat (2) path_resolution (2) path_resolution (2) stat (2) stat (2) Advertisements 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 1466, "s": 1454, "text": "Unix - Home" }, { "code": null, "e": 1489, "s": 1466, "text": "Unix - Getting Started" }, { "code": null, "e": 1512, "s": 1489, "text": "Unix - File Management" }, { "code": null, "e": 1531, "s": 1512, "text": "Unix - Directories" }, { "code": null, "e": 1554, "s": 1531, "text": "Unix - File Permission" }, { "code": null, "e": 1573, "s": 1554, "text": "Unix - Environment" }, { "code": null, "e": 1596, "s": 1573, "text": "Unix - Basic Utilities" }, { "code": null, "e": 1619, "s": 1596, "text": "Unix - Pipes & Filters" }, { "code": null, "e": 1636, "s": 1619, "text": "Unix - Processes" }, { "code": null, "e": 1657, "s": 1636, "text": "Unix - Communication" }, { "code": null, "e": 1678, "s": 1657, "text": "Unix - The vi Editor" }, { "code": null, "e": 1700, "s": 1678, "text": "Unix - What is Shell?" }, { "code": null, "e": 1723, "s": 1700, "text": "Unix - Using Variables" }, { "code": null, "e": 1748, "s": 1723, "text": "Unix - Special Variables" }, { "code": null, "e": 1768, "s": 1748, "text": "Unix - Using Arrays" }, { "code": null, "e": 1791, "s": 1768, "text": "Unix - Basic Operators" }, { "code": null, "e": 1814, "s": 1791, "text": "Unix - Decision Making" }, { "code": null, "e": 1833, "s": 1814, "text": "Unix - Shell Loops" }, { "code": null, "e": 1853, "s": 1833, "text": "Unix - Loop Control" }, { "code": null, "e": 1880, "s": 1853, "text": "Unix - Shell Substitutions" }, { "code": null, "e": 1906, "s": 1880, "text": "Unix - Quoting Mechanisms" }, { "code": null, "e": 1929, "s": 1906, "text": "Unix - IO Redirections" }, { "code": null, "e": 1952, "s": 1929, "text": "Unix - Shell Functions" }, { "code": null, "e": 1972, "s": 1952, "text": "Unix - Manpage Help" }, { "code": null, "e": 1999, "s": 1972, "text": "Unix - Regular Expressions" }, { "code": null, "e": 2025, "s": 1999, "text": "Unix - File System Basics" }, { "code": null, "e": 2052, "s": 2025, "text": "Unix - User Administration" }, { "code": null, "e": 2078, "s": 2052, "text": "Unix - System Performance" }, { "code": null, "e": 2100, "s": 2078, "text": "Unix - System Logging" }, { "code": null, "e": 2125, "s": 2100, "text": "Unix - Signals and Traps" }, { "code": null, "e": 2148, "s": 2125, "text": "Unix - Useful Commands" }, { "code": null, "e": 2167, "s": 2148, "text": "Unix - Quick Guide" }, { "code": null, "e": 2192, "s": 2167, "text": "Unix - Builtin Functions" }, { "code": null, "e": 2212, "s": 2192, "text": "Unix - System Calls" }, { "code": null, "e": 2233, "s": 2212, "text": "Unix - Commands List" }, { "code": null, "e": 2255, "s": 2233, "text": "Unix Useful Resources" }, { "code": null, "e": 2273, "s": 2255, "text": "Computer Glossary" }, { "code": null, "e": 2284, "s": 2273, "text": "Who is Who" }, { "code": null, "e": 2319, "s": 2284, "text": "Copyright © 2014 by tutorialspoint" }, { "code": null, "e": 2385, "s": 2319, "text": "fstatat - get file status relative to a directory file descriptor" }, { "code": null, "e": 2488, "s": 2385, "text": "#include <sys/stat.h> \n\nint fstatat(int dirfd, const char *path, struct stat * \nbuf \", int \" flags );\n" }, { "code": null, "e": 2568, "s": 2488, "text": "\nint fstatat(int dirfd, const char *path, struct stat * \nbuf \", int \" flags );\n" }, { "code": null, "e": 2697, "s": 2568, "text": "The fstatat() system call operates in exactly the same way as\nstat(2), except for the differences described in this manual page." }, { "code": null, "e": 2957, "s": 2697, "text": "If the pathname given in\npath is relative, then it is interpreted relative to the directory\nreferred to by the file descriptor\ndirfd (rather than relative to the current working directory of\nthe calling process, as is done by\nstat(2)\nfor a relative pathname)." }, { "code": null, "e": 3146, "s": 2957, "text": "If the pathname given in\npath is relative and\ndirfd is the special value\nAT_FDCWD, then\npath is interpreted relative to the current working\ndirectory of the calling process (like\nstat(2))." }, { "code": null, "e": 3212, "s": 3146, "text": "If the pathname given in\npath is absolute, then\ndirfd is ignored." }, { "code": null, "e": 3266, "s": 3212, "text": "flags can either be 0, or include the following flag:" }, { "code": null, "e": 3365, "s": 3266, "text": "On success,\nfstatat() returns 0. \nOn error, -1 is returned and\nerrno is set to indicate the error." }, { "code": null, "e": 3492, "s": 3365, "text": "The same errors that occur for\nstat(2)\ncan also occur for\nfstatat(). The following additional errors can occur for\nfstatat(): " }, { "code": null, "e": 3552, "s": 3492, "text": "See openat(2)\nfor an explanation of the need for\nfstatat()." }, { "code": null, "e": 3689, "s": 3552, "text": "This system call is non-standard but is proposed for inclusion in a future revision of POSIX.1. A similar system call exists on Solaris." }, { "code": null, "e": 3736, "s": 3689, "text": "fstatat() was added to Linux in kernel 2.6.16." }, { "code": null, "e": 3747, "s": 3736, "text": "openat (2)" }, { "code": null, "e": 3758, "s": 3747, "text": "openat (2)" }, { "code": null, "e": 3778, "s": 3758, "text": "path_resolution (2)" }, { "code": null, "e": 3798, "s": 3778, "text": "path_resolution (2)" }, { "code": null, "e": 3807, "s": 3798, "text": "stat (2)" }, { "code": null, "e": 3816, "s": 3807, "text": "stat (2)" }, { "code": null, "e": 3833, "s": 3816, "text": "\nAdvertisements\n" }, { "code": null, "e": 3868, "s": 3833, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 3896, "s": 3868, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3930, "s": 3896, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3947, "s": 3930, "text": " Frahaan Hussain" }, { "code": null, "e": 3980, "s": 3947, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 3991, "s": 3980, "text": " Pradeep D" }, { "code": null, "e": 4026, "s": 3991, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4042, "s": 4026, "text": " Musab Zayadneh" }, { "code": null, "e": 4075, "s": 4042, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 4087, "s": 4075, "text": " GUHARAJANM" }, { "code": null, "e": 4119, "s": 4087, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 4127, "s": 4119, "text": " Uplatz" }, { "code": null, "e": 4134, "s": 4127, "text": " Print" }, { "code": null, "e": 4145, "s": 4134, "text": " Add Notes" } ]
How to insert an array of values in a MySQL table with a single INSERT?
Let us first create a table − mysql> create table DemoTable ( ClientId int, ClientName varchar(50) ); Query OK, 0 rows affected (0.62 sec) Insert some records in the table using insert command. Here, we are inserting multiple values using only a single INSERT − mysql> insert into DemoTable values(101,'Adam'),(102,'Chris'),(103,'Robert'),(104,'Sam'),(105,'Mike'); Query OK, 5 rows affected (0.16 sec) Records: 5 Duplicates: 0 Warnings: 0 Display all records from the table using select statement − mysql> select *from DemoTable; This will produce the following output − +----------+------------+ | ClientId | ClientName | +----------+------------+ | 101 | Adam | | 102 | Chris | | 103 | Robert | | 104 | Sam | | 105 | Mike | +----------+------------+ 5 rows in set (0.00 sec)
[ { "code": null, "e": 1092, "s": 1062, "text": "Let us first create a table −" }, { "code": null, "e": 1207, "s": 1092, "text": "mysql> create table DemoTable\n(\n ClientId int,\n ClientName varchar(50)\n);\nQuery OK, 0 rows affected (0.62 sec)" }, { "code": null, "e": 1330, "s": 1207, "text": "Insert some records in the table using insert command. Here, we are inserting multiple values using only a single INSERT −" }, { "code": null, "e": 1507, "s": 1330, "text": "mysql> insert into DemoTable values(101,'Adam'),(102,'Chris'),(103,'Robert'),(104,'Sam'),(105,'Mike');\nQuery OK, 5 rows affected (0.16 sec)\nRecords: 5 Duplicates: 0 Warnings: 0" }, { "code": null, "e": 1567, "s": 1507, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1598, "s": 1567, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 1639, "s": 1598, "text": "This will produce the following output −" }, { "code": null, "e": 1898, "s": 1639, "text": "+----------+------------+\n| ClientId | ClientName |\n+----------+------------+\n| 101 | Adam |\n| 102 | Chris |\n| 103 | Robert |\n| 104 | Sam |\n| 105 | Mike |\n+----------+------------+\n5 rows in set (0.00 sec)" } ]
Type Erasure in Java
To support generic programming, as well as perform a stricter type check, Java implements type erasure. All type parameters in generic types are replaced with the bound (if unbounded) or object type. This way, the bytecode will only contain classes, methods, and interfaces. All type parameters in generic types are replaced with the bound (if unbounded) or object type. This way, the bytecode will only contain classes, methods, and interfaces. Type casts to preserve the type. Type casts to preserve the type. Bridge methods are generated so as to preserve the polymorphism concept in extended generic types. Bridge methods are generated so as to preserve the polymorphism concept in extended generic types. Live Demo import java.io.PrintStream; import java.util.*; public class Demo{ public Demo(){ } public static void main(String args[]){ List my_list = new ArrayList(); my_list.add("Hi there"); String my_str; for (Iterator iter = my_list.iterator(); iter.hasNext(); System.out.println(my_str)) my_str = (String)iter.next(); } } Hi there A class named Demo contains a constructor that basically has no body defined inside it. In the main function, a new array list is created, and elements are added into it using the ‘add’ function. An iterator is defined, and a string is defined. An iterator iterates over the elements in the string using the ‘hasNext’ function that checks if there is an element and then moves over to it. The output is printed on the screen.
[ { "code": null, "e": 1166, "s": 1062, "text": "To support generic programming, as well as perform a stricter type check, Java implements type\nerasure." }, { "code": null, "e": 1337, "s": 1166, "text": "All type parameters in generic types are replaced with the bound (if unbounded) or object\ntype. This way, the bytecode will only contain classes, methods, and interfaces." }, { "code": null, "e": 1508, "s": 1337, "text": "All type parameters in generic types are replaced with the bound (if unbounded) or object\ntype. This way, the bytecode will only contain classes, methods, and interfaces." }, { "code": null, "e": 1541, "s": 1508, "text": "Type casts to preserve the type." }, { "code": null, "e": 1574, "s": 1541, "text": "Type casts to preserve the type." }, { "code": null, "e": 1673, "s": 1574, "text": "Bridge methods are generated so as to preserve the polymorphism concept in extended\ngeneric types." }, { "code": null, "e": 1772, "s": 1673, "text": "Bridge methods are generated so as to preserve the polymorphism concept in extended\ngeneric types." }, { "code": null, "e": 1783, "s": 1772, "text": " Live Demo" }, { "code": null, "e": 2149, "s": 1783, "text": "import java.io.PrintStream;\nimport java.util.*;\npublic class Demo{\n public Demo(){\n }\n public static void main(String args[]){\n List my_list = new ArrayList();\n my_list.add(\"Hi there\");\n String my_str;\n for (Iterator iter = my_list.iterator(); iter.hasNext();\n System.out.println(my_str))\n my_str = (String)iter.next();\n }\n}" }, { "code": null, "e": 2158, "s": 2149, "text": "Hi there" }, { "code": null, "e": 2584, "s": 2158, "text": "A class named Demo contains a constructor that basically has no body defined inside it. In the main\nfunction, a new array list is created, and elements are added into it using the ‘add’ function. An\niterator is defined, and a string is defined. An iterator iterates over the elements in the string using\nthe ‘hasNext’ function that checks if there is an element and then moves over to it. The output is\nprinted on the screen." } ]
Python | Pandas Series.get() - GeeksforGeeks
13 Feb, 2019 Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.get() function get item from object for given key (DataFrame column, Panel slice, etc.). Returns default value if not found. Syntax: Series.get(key, default=None) Parameter :key : object Returns : value : same type as items contained in object Example #1: Use Series.get() function to get the value for the passed index label in the given series object. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', None, 'Rio']) # Create the Indexindex_ = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5'] # set the indexsr.index = index_ # Print the seriesprint(sr) Output :Now we will use Series.get() function to return the value for the passed index label in the given series object. # return the value corresponding to# the passe index labelresult = sr.get(key = 'City 3') # Print the resultprint(result) Output :As we can see in the output, the Series.get() function has returned the value corresponding to the passed index label. Example #2 : Use Series.get() function to get the value for the passed index label in the given series object. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([11, 21, 8, 18, 65, 84, 32, 10, 5, 24, 32]) # Create the Indexindex_ = pd.date_range('2010-10-09', periods = 11, freq ='M') # set the indexsr.index = index_ # Print the seriesprint(sr) Output : Now we will use Series.get() function to return the value for the passed index label in the given series object. # return the value corresponding to# the passe index labelresult = sr.get(key = '2011-03-31') # Print the resultprint(result) Output :As we can see in the output, the Series.get() function has returned the value corresponding to the passed index label. Python pandas-series Python pandas-series-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Create a Pandas DataFrame from Lists Reading and Writing to text files in Python
[ { "code": null, "e": 24930, "s": 24902, "text": "\n13 Feb, 2019" }, { "code": null, "e": 25187, "s": 24930, "text": "Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index." }, { "code": null, "e": 25326, "s": 25187, "text": "Pandas Series.get() function get item from object for given key (DataFrame column, Panel slice, etc.). Returns default value if not found." }, { "code": null, "e": 25364, "s": 25326, "text": "Syntax: Series.get(key, default=None)" }, { "code": null, "e": 25388, "s": 25364, "text": "Parameter :key : object" }, { "code": null, "e": 25445, "s": 25388, "text": "Returns : value : same type as items contained in object" }, { "code": null, "e": 25555, "s": 25445, "text": "Example #1: Use Series.get() function to get the value for the passed index label in the given series object." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', None, 'Rio']) # Create the Indexindex_ = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5'] # set the indexsr.index = index_ # Print the seriesprint(sr)", "e": 25828, "s": 25555, "text": null }, { "code": null, "e": 25949, "s": 25828, "text": "Output :Now we will use Series.get() function to return the value for the passed index label in the given series object." }, { "code": "# return the value corresponding to# the passe index labelresult = sr.get(key = 'City 3') # Print the resultprint(result)", "e": 26072, "s": 25949, "text": null }, { "code": null, "e": 26310, "s": 26072, "text": "Output :As we can see in the output, the Series.get() function has returned the value corresponding to the passed index label. Example #2 : Use Series.get() function to get the value for the passed index label in the given series object." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([11, 21, 8, 18, 65, 84, 32, 10, 5, 24, 32]) # Create the Indexindex_ = pd.date_range('2010-10-09', periods = 11, freq ='M') # set the indexsr.index = index_ # Print the seriesprint(sr)", "e": 26579, "s": 26310, "text": null }, { "code": null, "e": 26588, "s": 26579, "text": "Output :" }, { "code": null, "e": 26701, "s": 26588, "text": "Now we will use Series.get() function to return the value for the passed index label in the given series object." }, { "code": "# return the value corresponding to# the passe index labelresult = sr.get(key = '2011-03-31') # Print the resultprint(result)", "e": 26828, "s": 26701, "text": null }, { "code": null, "e": 26955, "s": 26828, "text": "Output :As we can see in the output, the Series.get() function has returned the value corresponding to the passed index label." }, { "code": null, "e": 26976, "s": 26955, "text": "Python pandas-series" }, { "code": null, "e": 27005, "s": 26976, "text": "Python pandas-series-methods" }, { "code": null, "e": 27019, "s": 27005, "text": "Python-pandas" }, { "code": null, "e": 27026, "s": 27019, "text": "Python" }, { "code": null, "e": 27124, "s": 27026, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27133, "s": 27124, "text": "Comments" }, { "code": null, "e": 27146, "s": 27133, "text": "Old Comments" }, { "code": null, "e": 27164, "s": 27146, "text": "Python Dictionary" }, { "code": null, "e": 27199, "s": 27164, "text": "Read a file line by line in Python" }, { "code": null, "e": 27221, "s": 27199, "text": "Enumerate() in Python" }, { "code": null, "e": 27253, "s": 27221, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27283, "s": 27253, "text": "Iterate over a list in Python" }, { "code": null, "e": 27325, "s": 27283, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27351, "s": 27325, "text": "Python String | replace()" }, { "code": null, "e": 27394, "s": 27351, "text": "Python program to convert a list to string" }, { "code": null, "e": 27431, "s": 27394, "text": "Create a Pandas DataFrame from Lists" } ]
.NET Core - Create .NET Standard Library
A class library defines the types and methods that can be called from any application. A class library developed using .NET Core supports the .NET Standard Library, which allows your library to be called by any .NET platform that supports that version of the .NET Standard Library. A class library developed using .NET Core supports the .NET Standard Library, which allows your library to be called by any .NET platform that supports that version of the .NET Standard Library. When you finish your class library, you can decide whether you want to distribute it as a third-party component, or whether you want to include it as a component that is bundled with one or more applications. When you finish your class library, you can decide whether you want to distribute it as a third-party component, or whether you want to include it as a component that is bundled with one or more applications. Let us start by adding a class library project in our Console application; right-click on the src folder in Solution Explorer and select Add → New Project... In the Add New Project dialog box, choose the .NET Core node, then choose the Class Library (.NET Core) project template. In the Name text box, enter "UtilityLibrary" as the name of the project, as the following figure shows. Click OK to create the class library project. Once the project is created, let us add a new class. Right-click on project in Solution Explorer and select Add → Class... Select class in the middle pane and enter StringLib.cs in the name and field and then click Add. Once the class is added, then replace the following code in StringLib.cs file. using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace UtilityLibrary { public static class StringLib { public static bool StartsWithUpper(this String str) { if (String.IsNullOrWhiteSpace(str)) return false; Char ch = str[0]; return Char.IsUpper(ch); } public static bool StartsWithLower(this String str) { if (String.IsNullOrWhiteSpace(str)) return false; Char ch = str[0]; return Char.IsLower(ch); } public static bool StartsWithNumber(this String str) { if (String.IsNullOrWhiteSpace(str)) return false; Char ch = str[0]; return Char.IsNumber(ch); } } } The class library, UtilityLibrary.StringLib, contains some methods like, StartsWithUpper, StartsWithLower, and StartsWithNumber which returns a Boolean value that indicates whether the current string instance begins with an uppercase, lowercase and number respectively. The class library, UtilityLibrary.StringLib, contains some methods like, StartsWithUpper, StartsWithLower, and StartsWithNumber which returns a Boolean value that indicates whether the current string instance begins with an uppercase, lowercase and number respectively. In .NET Core, the Char.IsUpper method returns true if a character is in uppercase, the Char.IsLower method returns true if a character is in lowercase, and similarly the Char.IsNumber method returns true if a character is a numeric. In .NET Core, the Char.IsUpper method returns true if a character is in uppercase, the Char.IsLower method returns true if a character is in lowercase, and similarly the Char.IsNumber method returns true if a character is a numeric. On the menu bar, choose Build, Build Solution. The project should compile without error. On the menu bar, choose Build, Build Solution. The project should compile without error. Our .NET Core console project doesn't have access to our class library. Our .NET Core console project doesn't have access to our class library. Now to consume this class library we need to add reference of this class library in our console project. Now to consume this class library we need to add reference of this class library in our console project. To do so, expand FirstApp and right-click on References and select Add Reference... In the Reference Manager dialog box, select UtilityLibrary, our class library project, and then click OK. Let us now open the Program.cs file of the console project and replace all of the code with the following code. using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using UtilityLibrary; namespace FirstApp { public class Program { public static void Main(string[] args) { int rows = Console.WindowHeight; Console.Clear(); do { if (Console.CursorTop >= rows || Console.CursorTop == 0) { Console.Clear(); Console.WriteLine("\nPress <Enter> only to exit; otherwise, enter a string and press <Enter>:\n"); } string input = Console.ReadLine(); if (String.IsNullOrEmpty(input)) break; Console.WriteLine("Input: {0} {1,30}: {2}\n", input, "Begins with uppercase? ", input.StartsWithUpper() ? "Yes" : "No"); } while (true); } } } Let us now run your application and you will see the following output. For better understanding, let us make use of the other extension methods of your class library in your project. Print Add Notes Bookmark this page
[ { "code": null, "e": 2473, "s": 2386, "text": "A class library defines the types and methods that can be called from any application." }, { "code": null, "e": 2668, "s": 2473, "text": "A class library developed using .NET Core supports the .NET Standard Library, which allows your library to be called by any .NET platform that supports that version of the .NET Standard Library." }, { "code": null, "e": 2863, "s": 2668, "text": "A class library developed using .NET Core supports the .NET Standard Library, which allows your library to be called by any .NET platform that supports that version of the .NET Standard Library." }, { "code": null, "e": 3072, "s": 2863, "text": "When you finish your class library, you can decide whether you want to distribute it as a third-party component, or whether you want to include it as a component that is bundled with one or more applications." }, { "code": null, "e": 3281, "s": 3072, "text": "When you finish your class library, you can decide whether you want to distribute it as a third-party component, or whether you want to include it as a component that is bundled with one or more applications." }, { "code": null, "e": 3439, "s": 3281, "text": "Let us start by adding a class library project in our Console application; right-click on the src folder in Solution Explorer and select Add → New Project..." }, { "code": null, "e": 3561, "s": 3439, "text": "In the Add New Project dialog box, choose the .NET Core node, then choose the Class Library (.NET Core) project template." }, { "code": null, "e": 3665, "s": 3561, "text": "In the Name text box, enter \"UtilityLibrary\" as the name of the project, as the following figure shows." }, { "code": null, "e": 3834, "s": 3665, "text": "Click OK to create the class library project. Once the project is created, let us add a new class. Right-click on project in Solution Explorer and select Add → Class..." }, { "code": null, "e": 4010, "s": 3834, "text": "Select class in the middle pane and enter StringLib.cs in the name and field and then click Add. Once the class is added, then replace the following code in StringLib.cs file." }, { "code": null, "e": 4799, "s": 4010, "text": "using System; \nusing System.Collections.Generic; \nusing System.Linq; \nusing System.Threading.Tasks; \n \nnamespace UtilityLibrary { \n public static class StringLib { \n public static bool StartsWithUpper(this String str) { \n if (String.IsNullOrWhiteSpace(str)) \n return false; \n Char ch = str[0]; \n return Char.IsUpper(ch); \n } \n public static bool StartsWithLower(this String str) { \n if (String.IsNullOrWhiteSpace(str)) \n return false; \n Char ch = str[0]; \n return Char.IsLower(ch); \n } \n public static bool StartsWithNumber(this String str) { \n if (String.IsNullOrWhiteSpace(str)) \n return false; \n Char ch = str[0]; \n return Char.IsNumber(ch); \n } \n } \n} " }, { "code": null, "e": 5069, "s": 4799, "text": "The class library, UtilityLibrary.StringLib, contains some methods like, StartsWithUpper, StartsWithLower, and StartsWithNumber which returns a Boolean value that indicates whether the current string instance begins with an uppercase, lowercase and number respectively." }, { "code": null, "e": 5339, "s": 5069, "text": "The class library, UtilityLibrary.StringLib, contains some methods like, StartsWithUpper, StartsWithLower, and StartsWithNumber which returns a Boolean value that indicates whether the current string instance begins with an uppercase, lowercase and number respectively." }, { "code": null, "e": 5572, "s": 5339, "text": "In .NET Core, the Char.IsUpper method returns true if a character is in uppercase, the Char.IsLower method returns true if a character is in lowercase, and similarly the Char.IsNumber method returns true if a character is a numeric." }, { "code": null, "e": 5805, "s": 5572, "text": "In .NET Core, the Char.IsUpper method returns true if a character is in uppercase, the Char.IsLower method returns true if a character is in lowercase, and similarly the Char.IsNumber method returns true if a character is a numeric." }, { "code": null, "e": 5894, "s": 5805, "text": "On the menu bar, choose Build, Build Solution. The project should compile without error." }, { "code": null, "e": 5983, "s": 5894, "text": "On the menu bar, choose Build, Build Solution. The project should compile without error." }, { "code": null, "e": 6055, "s": 5983, "text": "Our .NET Core console project doesn't have access to our class library." }, { "code": null, "e": 6127, "s": 6055, "text": "Our .NET Core console project doesn't have access to our class library." }, { "code": null, "e": 6232, "s": 6127, "text": "Now to consume this class library we need to add reference of this class library in our console project." }, { "code": null, "e": 6337, "s": 6232, "text": "Now to consume this class library we need to add reference of this class library in our console project." }, { "code": null, "e": 6421, "s": 6337, "text": "To do so, expand FirstApp and right-click on References and select Add Reference..." }, { "code": null, "e": 6527, "s": 6421, "text": "In the Reference Manager dialog box, select UtilityLibrary, our class library project, and then click OK." }, { "code": null, "e": 6639, "s": 6527, "text": "Let us now open the Program.cs file of the console project and replace all of the code with the following code." }, { "code": null, "e": 7486, "s": 6639, "text": "using System; \nusing System.Collections.Generic; \nusing System.Linq; \nusing System.Threading.Tasks; \nusing UtilityLibrary; \n\nnamespace FirstApp { \n public class Program { \n public static void Main(string[] args) { \n int rows = Console.WindowHeight; \n Console.Clear(); \n do { \n if (Console.CursorTop >= rows || Console.CursorTop == 0) { \n Console.Clear(); \n Console.WriteLine(\"\\nPress <Enter> only to exit; otherwise, enter a string and press <Enter>:\\n\"); \n } \n string input = Console.ReadLine(); \n \n if (String.IsNullOrEmpty(input)) break; \n Console.WriteLine(\"Input: {0} {1,30}: {2}\\n\", input, \"Begins with uppercase? \", \n input.StartsWithUpper() ? \"Yes\" : \"No\"); \n } while (true); \n } \n } \n} " }, { "code": null, "e": 7557, "s": 7486, "text": "Let us now run your application and you will see the following output." }, { "code": null, "e": 7669, "s": 7557, "text": "For better understanding, let us make use of the other extension methods of your class library in your project." }, { "code": null, "e": 7676, "s": 7669, "text": " Print" }, { "code": null, "e": 7687, "s": 7676, "text": " Add Notes" } ]
chpasswd command in Linux with examples - GeeksforGeeks
15 May, 2019 chpasswd command is used to change password although passwd command can also do same. But it changes the password of one user at a time so for multiple users chpasswd is used. Below figure shows the use of passwd command. Using passwd we are changing the password of the guest user. Here first you have to enter the password of the currently signed user and then you change the password of any other user. One must have administrator privileges. chpasswd command reads a number of username and password which are separated by colon using standard input or file, and then encrypt as per the options. Syntax: $chpasswd user1:user1_password user2:user2_password user3:user3_password Note: After completion please press ctrl+d to exit from the command. As soon as ctrl + d is pressed password gets changed. A simple text file can also be used to store username and password and then use them to change the password. $cat > pass.txt user1:user1_password user2:user2_password user3:user3_password Then provide this to chpasswd command. $chpasswd < file_name.txt Options: -c, –crypt-method Method_Name : This command option is used for the crypt method. The method can be DES, MD5, SHA256, SHA512 or NONE. -e, –encrypted : It is used to supply the encrypted passwords. -h, –help : Used to display the command options and messages. -m, –md5 : It is used to encrypt the clear text password using the MD5 algorithm. -s, –sha-no_of_rounds : Here you can give the number of rounds for the SHA crypt algorithm. Example: The encryption algorithm can also be applied to the password. $chpasswd -c SHA512 user1:user1_password user2:user2_password user3:user3_password or $chpasswd --md5 user1:user1_password user2:user2_password user3:user3_password Note: Both are a different type of encryption algorithm linux-command Linux-system-commands Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C ZIP command in Linux with examples tar command in Linux with examples SORT command in Linux/Unix with examples curl command in Linux with Examples 'crontab' in Linux with Examples UDP Server-Client implementation in C diff command in Linux with examples Conditional Statements | Shell Script Cat command in Linux with examples
[ { "code": null, "e": 24625, "s": 24597, "text": "\n15 May, 2019" }, { "code": null, "e": 25071, "s": 24625, "text": "chpasswd command is used to change password although passwd command can also do same. But it changes the password of one user at a time so for multiple users chpasswd is used. Below figure shows the use of passwd command. Using passwd we are changing the password of the guest user. Here first you have to enter the password of the currently signed user and then you change the password of any other user. One must have administrator privileges." }, { "code": null, "e": 25224, "s": 25071, "text": "chpasswd command reads a number of username and password which are separated by colon using standard input or file, and then encrypt as per the options." }, { "code": null, "e": 25232, "s": 25224, "text": "Syntax:" }, { "code": null, "e": 25306, "s": 25232, "text": "$chpasswd\nuser1:user1_password\nuser2:user2_password\nuser3:user3_password\n" }, { "code": null, "e": 25429, "s": 25306, "text": "Note: After completion please press ctrl+d to exit from the command. As soon as ctrl + d is pressed password gets changed." }, { "code": null, "e": 25538, "s": 25429, "text": "A simple text file can also be used to store username and password and then use them to change the password." }, { "code": null, "e": 25618, "s": 25538, "text": "$cat > pass.txt\nuser1:user1_password\nuser2:user2_password\nuser3:user3_password\n" }, { "code": null, "e": 25657, "s": 25618, "text": "Then provide this to chpasswd command." }, { "code": null, "e": 25684, "s": 25657, "text": "$chpasswd < file_name.txt\n" }, { "code": null, "e": 25693, "s": 25684, "text": "Options:" }, { "code": null, "e": 25827, "s": 25693, "text": "-c, –crypt-method Method_Name : This command option is used for the crypt method. The method can be DES, MD5, SHA256, SHA512 or NONE." }, { "code": null, "e": 25890, "s": 25827, "text": "-e, –encrypted : It is used to supply the encrypted passwords." }, { "code": null, "e": 25952, "s": 25890, "text": "-h, –help : Used to display the command options and messages." }, { "code": null, "e": 26034, "s": 25952, "text": "-m, –md5 : It is used to encrypt the clear text password using the MD5 algorithm." }, { "code": null, "e": 26126, "s": 26034, "text": "-s, –sha-no_of_rounds : Here you can give the number of rounds for the SHA crypt algorithm." }, { "code": null, "e": 26197, "s": 26126, "text": "Example: The encryption algorithm can also be applied to the password." }, { "code": null, "e": 26365, "s": 26197, "text": "$chpasswd -c SHA512\nuser1:user1_password\nuser2:user2_password\nuser3:user3_password\n\nor\n\n$chpasswd --md5\nuser1:user1_password\nuser2:user2_password\nuser3:user3_password\n" }, { "code": null, "e": 26421, "s": 26365, "text": "Note: Both are a different type of encryption algorithm" }, { "code": null, "e": 26435, "s": 26421, "text": "linux-command" }, { "code": null, "e": 26457, "s": 26435, "text": "Linux-system-commands" }, { "code": null, "e": 26464, "s": 26457, "text": "Picked" }, { "code": null, "e": 26475, "s": 26464, "text": "Linux-Unix" }, { "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": 26611, "s": 26573, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 26646, "s": 26611, "text": "ZIP command in Linux with examples" }, { "code": null, "e": 26681, "s": 26646, "text": "tar command in Linux with examples" }, { "code": null, "e": 26722, "s": 26681, "text": "SORT command in Linux/Unix with examples" }, { "code": null, "e": 26758, "s": 26722, "text": "curl command in Linux with Examples" }, { "code": null, "e": 26791, "s": 26758, "text": "'crontab' in Linux with Examples" }, { "code": null, "e": 26829, "s": 26791, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 26865, "s": 26829, "text": "diff command in Linux with examples" }, { "code": null, "e": 26903, "s": 26865, "text": "Conditional Statements | Shell Script" } ]
Construct a DFA which accept the language L = {w | w ∈ {a,b}* and Na(w) mod 3 = Nb (w) mod 3} - GeeksforGeeks
02 Jul, 2019 Problem: Construct a deterministic finite automata (DFA) for accepting the language L = {w | w ∈ {a,b}* and Na(w) mod 3 = Nb (w) mod 3}. Language L={w | Na(w) = Nb(w)mod 3} which means all string contain modulus of count of a’s equal to modulus of count of b’s by 3. Examples: Input: a a b b bOutput: NOT ACCEPTED// n = 2, m=3 (2 mod 3! = 3 mod 3) Input: a a b bOutput: ACCEPTED// n = 2, m = 2 (2 mod 3 = 2 mod 3) Input: b b bOutput: NOT ACCEPTED// n = 0, m = 3 ((0 mod 3 = 3 mod 3) <=> (0=0)) Approaches: Construct FA for {w | w {a, b}} and Na = 0 mod 3 means having a’s as a multiple of 3.Construct FA for {w | w {a, b}} and Nb = 0 mod 3 means having b’s as a multiple of 3.Concatenate the two FA and make single DFA using Concatenation process in DFA.Making state as final state which accepts the equal modulus count for a’s and b’s.DFA State Transition Diagram:States 00, 11 and 22 leads to the acceptance of the string.Whereas states 01, 02, 10, 12, 20 and 21 leads to the rejection of the string.Let’s see code for the demonstration:C/C++JavaPython 3C#C/C++// C/C++ Program to construct a DFA which accept the language// L = { w | w is in {a, b}* and Na(w) mod 3 = Nb(w) mod 3}#include <stdio.h>#include <string.h> // dfa tells the number associated// string end in which state.int dfa = 0; // This function is for// the starting state (00)of DFAvoid start(char c){ if (c == 'a') { dfa = 10; } else if (c == 'b') { dfa = 1; } // -1 is used to check for any invalid symbol else { dfa = -1; }} // This function is for the first state (01) of DFAvoid state01(char c){ if (c == 'a') { dfa = 11; } else if (c == 'b') { dfa = 2; } else { dfa = -1; }} // This function is for the second state (02) of DFAvoid state02(char c){ if (c == 'b') { dfa = 0; } else if (c == 'a') { dfa = 12; } else { dfa = -1; }} // This function is for the third state (10)of DFAvoid state10(char c){ if (c == 'b') { dfa = 11; } else if (c == 'a') { dfa = 20; } else { dfa = -1; }} // This function is for the forth state (11)of DFAvoid state11(char c){ if (c == 'b') { dfa = 12; } else if (c == 'a') { dfa = 21; } else { dfa = -1; }} void state12(char c){ if (c == 'b') { dfa = 10; } else if (c == 'a') { dfa = 22; } else { dfa = -1; }} void state20(char c){ if (c == 'b') { dfa = 21; } else if (c == 'a') { dfa = 0; } else { dfa = -1; }} void state21(char c){ if (c == 'b') { dfa = 22; } else if (c == 'a') { dfa = 1; } else { dfa = -1; }} void state22(char c){ if (c == 'b') { dfa = 20; } else if (c == 'a') { dfa = 2; } else { dfa = -1; }} int isAccepted(char str[]){ // store length of string int i, len = strlen(str); for (i = 0; i < len; i++) { if (dfa == 0) start(str[i]); else if (dfa == 1) state01(str[i]); else if (dfa == 2) state02(str[i]); else if (dfa == 10) state10(str[i]); else if (dfa == 11) state11(str[i]); else if (dfa == 12) state12(str[i]); else if (dfa == 20) state20(str[i]); else if (dfa == 21) state21(str[i]); else if (dfa == 22) state22(str[i]); else return 0; } if (dfa == 0 || dfa == 11 || dfa == 22) return 1; else return 0;} // driver codeint main(){ char str[] = "aaaabbbb"; if (isAccepted(str)) printf("ACCEPTED"); else printf("NOT ACCEPTED"); return 0;} // This code is contributed by SHUBHAMSINGH10.Java// Java Program to construct a DFA which accept the language// L = { w | w is in {a, b}* and Na(w) mod 3 = Nb(w) mod 3}class GFG{// dfa tells the number associated// string end in which state.static int dfa = 0; // This function is for// the starting state (00)of DFAstatic void start(char c){ if (c == 'a') { dfa = 10; } else if (c == 'b') { dfa = 1; } // -1 is used to check for any invalid symbol else { dfa = -1; }} // This function is for the first state (01) of DFAstatic void state01(char c){ if (c == 'a') { dfa = 11; } else if (c == 'b') { dfa = 2; } else { dfa = -1; }} // This function is for the second state (02) of DFAstatic void state02(char c){ if (c == 'b') { dfa = 0; } else if (c == 'a') { dfa = 12; } else { dfa = -1; }} // This function is for the third state (10)of DFAstatic void state10(char c){ if (c == 'b') { dfa = 11; } else if (c == 'a') { dfa = 20; } else { dfa = -1; }} // This function is for the forth state (11)of DFAstatic void state11(char c){ if (c == 'b') { dfa = 12; } else if (c == 'a') { dfa = 21; } else { dfa = -1; }} static void state12(char c){ if (c == 'b') { dfa = 10; } else if (c == 'a') { dfa = 22; } else { dfa = -1; }} static void state20(char c){ if (c == 'b') { dfa = 21; } else if (c == 'a') { dfa = 0; } else { dfa = -1; }} static void state21(char c){ if (c == 'b') { dfa = 22; } else if (c == 'a') { dfa = 1; } else { dfa = -1; }} static void state22(char c){ if (c == 'b') { dfa = 20; } else if (c == 'a') { dfa = 2; } else { dfa = -1; }} static boolean isAccepted(String st){ // store length of string int i, len = st.length(); char[] str = st.toCharArray(); for (i = 0; i < len; i++) { if (dfa == 0) start(str[i]); else if (dfa == 1) state01(str[i]); else if (dfa == 2) state02(str[i]); else if (dfa == 10) state10(str[i]); else if (dfa == 11) state11(str[i]); else if (dfa == 12) state12(str[i]); else if (dfa == 20) state20(str[i]); else if (dfa == 21) state21(str[i]); else if (dfa == 22) state22(str[i]); else return false; } if (dfa == 0 || dfa == 11 || dfa == 22) return true; else return false;} // driver codepublic static void main(String []args) { String str = "aaaabbbb"; if (isAccepted(str)) System.out.println("ACCEPTED"); else System.out.println("NOT ACCEPTED"); }} // This code contributed by Rajput-JiPython 3"""Python Program to construct a DFA which accept the language L = {w | w belongs to {a, b}*}and Na(w)mod3 = Nb(w)mod 3""" # This function is for # the starting state (00)of DFA def start( c): if (c == 'a'): dfa = 10 elif (c == 'b') : dfa = 1 #-1 is used to check for any invalid symbol else: dfa = -1 return dfa # This function is for the first state (01) of DFA def state01( c): if (c == 'a'): dfa = 11 elif (c == 'b') : dfa = 2 else: dfa = -1 return dfa # This function is for the second state (02) of DFA def state02( c): if (c == 'b') : dfa = 0 elif(c =='a'): dfa = 12 else: dfa = -1 return dfa # This function is for the third state (10)of DFA def state10( c): if (c == 'b') : dfa = 11 elif(c =='a'): dfa = 20 else: dfa = -1 return dfa # This function is for the forth state (11)of DFA def state11( c): if (c == 'b') : dfa = 12 elif(c =='a'): dfa = 21 else: dfa = -1 return dfa def state12( c): if (c == 'b') : dfa = 10 elif(c =='a'): dfa = 22 else: dfa = -1 return dfa def state20( c): if (c == 'b') : dfa = 21 elif(c =='a'): dfa = 0 else: dfa = -1 return dfa def state21( c): if (c == 'b') : dfa = 22 elif(c =='a'): dfa = 1 else: dfa = -1 return dfa def state22( c): if (c == 'b') : dfa = 20 elif(c =='a'): dfa = 2 else: dfa = -1 return dfa def isAccepted(str): # store length of string l = len(str) # dfa tells the number associated # with the present dfa = state dfa = 0 for i in range(l): if (dfa == 0) : start(str[i]) elif (dfa == 1): state01(str[i]) elif (dfa == 2) : state02(str[i]) elif (dfa == 10) : state10(str[i]) elif (dfa == 11) : state11(str[i]) elif (dfa == 12) : state12(str[i]) elif (dfa == 20) : state20(str[i]) elif (dfa == 21) : state21(str[i]) elif (dfa == 22) : state22(str[i]) else: return 0 if (dfa == 0 or dfa == 11 or dfa == 22) : return 1 else: return 0 # Driver code if __name__ == "__main__" : string = "aaaabbbb" if (isAccepted(string)) : print("ACCEPTED") else: print("NOT ACCEPTED") # This code is contributed by SHUBHAMSINGH10.C#// C# Program to construct a DFA which accept the language // L = { w | w is in {a, b}* and Na(w) mod 3 = Nb(w) mod 3} using System; class GFG{ // DFA tells the number associated // string end in which state. static int dfa = 0; // This function is for // the starting state (00)of DFA static void start(char c) { if (c == 'a') { dfa = 10; } else if (c == 'b') { dfa = 1; } // -1 is used to check for any invalid symbol else { dfa = -1; } } // This function is for the first state (01) of DFA static void state01(char c) { if (c == 'a') { dfa = 11; } else if (c == 'b') { dfa = 2; } else { dfa = -1; } } // This function is for the second state (02) of DFA static void state02(char c) { if (c == 'b') { dfa = 0; } else if (c == 'a') { dfa = 12; } else { dfa = -1; } } // This function is for the third state (10)of DFA static void state10(char c) { if (c == 'b') { dfa = 11; } else if (c == 'a') { dfa = 20; } else { dfa = -1; } } // This function is for the forth state (11)of DFA static void state11(char c) { if (c == 'b') { dfa = 12; } else if (c == 'a') { dfa = 21; } else { dfa = -1; } } static void state12(char c) { if (c == 'b') { dfa = 10; } else if (c == 'a') { dfa = 22; } else { dfa = -1; } } static void state20(char c) { if (c == 'b') { dfa = 21; } else if (c == 'a') { dfa = 0; } else { dfa = -1; } } static void state21(char c) { if (c == 'b') { dfa = 22; } else if (c == 'a') { dfa = 1; } else { dfa = -1; } } static void state22(char c) { if (c == 'b') { dfa = 20; } else if (c == 'a') { dfa = 2; } else { dfa = -1; } } static Boolean isAccepted(String st) { // store length of string int i, len = st.Length; char[] str = st.ToCharArray(); for (i = 0; i < len; i++) { if (dfa == 0) start(str[i]); else if (dfa == 1) state01(str[i]); else if (dfa == 2) state02(str[i]); else if (dfa == 10) state10(str[i]); else if (dfa == 11) state11(str[i]); else if (dfa == 12) state12(str[i]); else if (dfa == 20) state20(str[i]); else if (dfa == 21) state21(str[i]); else if (dfa == 22) state22(str[i]); else return false; } if (dfa == 0 || dfa == 11 || dfa == 22) return true; else return false; } // Driver code public static void Main(String []args) { String str = "aaaabbbb"; if (isAccepted(str)) Console.WriteLine("ACCEPTED"); else Console.WriteLine("NOT ACCEPTED"); } } // This code is contributed by 29AjayKumarOutput:ACCEPTEDMy Personal Notes arrow_drop_upSave Construct FA for {w | w {a, b}} and Na = 0 mod 3 means having a’s as a multiple of 3. Construct FA for {w | w {a, b}} and Nb = 0 mod 3 means having b’s as a multiple of 3. Concatenate the two FA and make single DFA using Concatenation process in DFA. Making state as final state which accepts the equal modulus count for a’s and b’s.DFA State Transition Diagram:States 00, 11 and 22 leads to the acceptance of the string.Whereas states 01, 02, 10, 12, 20 and 21 leads to the rejection of the string.Let’s see code for the demonstration:C/C++JavaPython 3C#C/C++// C/C++ Program to construct a DFA which accept the language// L = { w | w is in {a, b}* and Na(w) mod 3 = Nb(w) mod 3}#include <stdio.h>#include <string.h> // dfa tells the number associated// string end in which state.int dfa = 0; // This function is for// the starting state (00)of DFAvoid start(char c){ if (c == 'a') { dfa = 10; } else if (c == 'b') { dfa = 1; } // -1 is used to check for any invalid symbol else { dfa = -1; }} // This function is for the first state (01) of DFAvoid state01(char c){ if (c == 'a') { dfa = 11; } else if (c == 'b') { dfa = 2; } else { dfa = -1; }} // This function is for the second state (02) of DFAvoid state02(char c){ if (c == 'b') { dfa = 0; } else if (c == 'a') { dfa = 12; } else { dfa = -1; }} // This function is for the third state (10)of DFAvoid state10(char c){ if (c == 'b') { dfa = 11; } else if (c == 'a') { dfa = 20; } else { dfa = -1; }} // This function is for the forth state (11)of DFAvoid state11(char c){ if (c == 'b') { dfa = 12; } else if (c == 'a') { dfa = 21; } else { dfa = -1; }} void state12(char c){ if (c == 'b') { dfa = 10; } else if (c == 'a') { dfa = 22; } else { dfa = -1; }} void state20(char c){ if (c == 'b') { dfa = 21; } else if (c == 'a') { dfa = 0; } else { dfa = -1; }} void state21(char c){ if (c == 'b') { dfa = 22; } else if (c == 'a') { dfa = 1; } else { dfa = -1; }} void state22(char c){ if (c == 'b') { dfa = 20; } else if (c == 'a') { dfa = 2; } else { dfa = -1; }} int isAccepted(char str[]){ // store length of string int i, len = strlen(str); for (i = 0; i < len; i++) { if (dfa == 0) start(str[i]); else if (dfa == 1) state01(str[i]); else if (dfa == 2) state02(str[i]); else if (dfa == 10) state10(str[i]); else if (dfa == 11) state11(str[i]); else if (dfa == 12) state12(str[i]); else if (dfa == 20) state20(str[i]); else if (dfa == 21) state21(str[i]); else if (dfa == 22) state22(str[i]); else return 0; } if (dfa == 0 || dfa == 11 || dfa == 22) return 1; else return 0;} // driver codeint main(){ char str[] = "aaaabbbb"; if (isAccepted(str)) printf("ACCEPTED"); else printf("NOT ACCEPTED"); return 0;} // This code is contributed by SHUBHAMSINGH10.Java// Java Program to construct a DFA which accept the language// L = { w | w is in {a, b}* and Na(w) mod 3 = Nb(w) mod 3}class GFG{// dfa tells the number associated// string end in which state.static int dfa = 0; // This function is for// the starting state (00)of DFAstatic void start(char c){ if (c == 'a') { dfa = 10; } else if (c == 'b') { dfa = 1; } // -1 is used to check for any invalid symbol else { dfa = -1; }} // This function is for the first state (01) of DFAstatic void state01(char c){ if (c == 'a') { dfa = 11; } else if (c == 'b') { dfa = 2; } else { dfa = -1; }} // This function is for the second state (02) of DFAstatic void state02(char c){ if (c == 'b') { dfa = 0; } else if (c == 'a') { dfa = 12; } else { dfa = -1; }} // This function is for the third state (10)of DFAstatic void state10(char c){ if (c == 'b') { dfa = 11; } else if (c == 'a') { dfa = 20; } else { dfa = -1; }} // This function is for the forth state (11)of DFAstatic void state11(char c){ if (c == 'b') { dfa = 12; } else if (c == 'a') { dfa = 21; } else { dfa = -1; }} static void state12(char c){ if (c == 'b') { dfa = 10; } else if (c == 'a') { dfa = 22; } else { dfa = -1; }} static void state20(char c){ if (c == 'b') { dfa = 21; } else if (c == 'a') { dfa = 0; } else { dfa = -1; }} static void state21(char c){ if (c == 'b') { dfa = 22; } else if (c == 'a') { dfa = 1; } else { dfa = -1; }} static void state22(char c){ if (c == 'b') { dfa = 20; } else if (c == 'a') { dfa = 2; } else { dfa = -1; }} static boolean isAccepted(String st){ // store length of string int i, len = st.length(); char[] str = st.toCharArray(); for (i = 0; i < len; i++) { if (dfa == 0) start(str[i]); else if (dfa == 1) state01(str[i]); else if (dfa == 2) state02(str[i]); else if (dfa == 10) state10(str[i]); else if (dfa == 11) state11(str[i]); else if (dfa == 12) state12(str[i]); else if (dfa == 20) state20(str[i]); else if (dfa == 21) state21(str[i]); else if (dfa == 22) state22(str[i]); else return false; } if (dfa == 0 || dfa == 11 || dfa == 22) return true; else return false;} // driver codepublic static void main(String []args) { String str = "aaaabbbb"; if (isAccepted(str)) System.out.println("ACCEPTED"); else System.out.println("NOT ACCEPTED"); }} // This code contributed by Rajput-JiPython 3"""Python Program to construct a DFA which accept the language L = {w | w belongs to {a, b}*}and Na(w)mod3 = Nb(w)mod 3""" # This function is for # the starting state (00)of DFA def start( c): if (c == 'a'): dfa = 10 elif (c == 'b') : dfa = 1 #-1 is used to check for any invalid symbol else: dfa = -1 return dfa # This function is for the first state (01) of DFA def state01( c): if (c == 'a'): dfa = 11 elif (c == 'b') : dfa = 2 else: dfa = -1 return dfa # This function is for the second state (02) of DFA def state02( c): if (c == 'b') : dfa = 0 elif(c =='a'): dfa = 12 else: dfa = -1 return dfa # This function is for the third state (10)of DFA def state10( c): if (c == 'b') : dfa = 11 elif(c =='a'): dfa = 20 else: dfa = -1 return dfa # This function is for the forth state (11)of DFA def state11( c): if (c == 'b') : dfa = 12 elif(c =='a'): dfa = 21 else: dfa = -1 return dfa def state12( c): if (c == 'b') : dfa = 10 elif(c =='a'): dfa = 22 else: dfa = -1 return dfa def state20( c): if (c == 'b') : dfa = 21 elif(c =='a'): dfa = 0 else: dfa = -1 return dfa def state21( c): if (c == 'b') : dfa = 22 elif(c =='a'): dfa = 1 else: dfa = -1 return dfa def state22( c): if (c == 'b') : dfa = 20 elif(c =='a'): dfa = 2 else: dfa = -1 return dfa def isAccepted(str): # store length of string l = len(str) # dfa tells the number associated # with the present dfa = state dfa = 0 for i in range(l): if (dfa == 0) : start(str[i]) elif (dfa == 1): state01(str[i]) elif (dfa == 2) : state02(str[i]) elif (dfa == 10) : state10(str[i]) elif (dfa == 11) : state11(str[i]) elif (dfa == 12) : state12(str[i]) elif (dfa == 20) : state20(str[i]) elif (dfa == 21) : state21(str[i]) elif (dfa == 22) : state22(str[i]) else: return 0 if (dfa == 0 or dfa == 11 or dfa == 22) : return 1 else: return 0 # Driver code if __name__ == "__main__" : string = "aaaabbbb" if (isAccepted(string)) : print("ACCEPTED") else: print("NOT ACCEPTED") # This code is contributed by SHUBHAMSINGH10.C#// C# Program to construct a DFA which accept the language // L = { w | w is in {a, b}* and Na(w) mod 3 = Nb(w) mod 3} using System; class GFG{ // DFA tells the number associated // string end in which state. static int dfa = 0; // This function is for // the starting state (00)of DFA static void start(char c) { if (c == 'a') { dfa = 10; } else if (c == 'b') { dfa = 1; } // -1 is used to check for any invalid symbol else { dfa = -1; } } // This function is for the first state (01) of DFA static void state01(char c) { if (c == 'a') { dfa = 11; } else if (c == 'b') { dfa = 2; } else { dfa = -1; } } // This function is for the second state (02) of DFA static void state02(char c) { if (c == 'b') { dfa = 0; } else if (c == 'a') { dfa = 12; } else { dfa = -1; } } // This function is for the third state (10)of DFA static void state10(char c) { if (c == 'b') { dfa = 11; } else if (c == 'a') { dfa = 20; } else { dfa = -1; } } // This function is for the forth state (11)of DFA static void state11(char c) { if (c == 'b') { dfa = 12; } else if (c == 'a') { dfa = 21; } else { dfa = -1; } } static void state12(char c) { if (c == 'b') { dfa = 10; } else if (c == 'a') { dfa = 22; } else { dfa = -1; } } static void state20(char c) { if (c == 'b') { dfa = 21; } else if (c == 'a') { dfa = 0; } else { dfa = -1; } } static void state21(char c) { if (c == 'b') { dfa = 22; } else if (c == 'a') { dfa = 1; } else { dfa = -1; } } static void state22(char c) { if (c == 'b') { dfa = 20; } else if (c == 'a') { dfa = 2; } else { dfa = -1; } } static Boolean isAccepted(String st) { // store length of string int i, len = st.Length; char[] str = st.ToCharArray(); for (i = 0; i < len; i++) { if (dfa == 0) start(str[i]); else if (dfa == 1) state01(str[i]); else if (dfa == 2) state02(str[i]); else if (dfa == 10) state10(str[i]); else if (dfa == 11) state11(str[i]); else if (dfa == 12) state12(str[i]); else if (dfa == 20) state20(str[i]); else if (dfa == 21) state21(str[i]); else if (dfa == 22) state22(str[i]); else return false; } if (dfa == 0 || dfa == 11 || dfa == 22) return true; else return false; } // Driver code public static void Main(String []args) { String str = "aaaabbbb"; if (isAccepted(str)) Console.WriteLine("ACCEPTED"); else Console.WriteLine("NOT ACCEPTED"); } } // This code is contributed by 29AjayKumarOutput:ACCEPTEDMy Personal Notes arrow_drop_upSave DFA State Transition Diagram:States 00, 11 and 22 leads to the acceptance of the string.Whereas states 01, 02, 10, 12, 20 and 21 leads to the rejection of the string.Let’s see code for the demonstration:C/C++JavaPython 3C#C/C++// C/C++ Program to construct a DFA which accept the language// L = { w | w is in {a, b}* and Na(w) mod 3 = Nb(w) mod 3}#include <stdio.h>#include <string.h> // dfa tells the number associated// string end in which state.int dfa = 0; // This function is for// the starting state (00)of DFAvoid start(char c){ if (c == 'a') { dfa = 10; } else if (c == 'b') { dfa = 1; } // -1 is used to check for any invalid symbol else { dfa = -1; }} // This function is for the first state (01) of DFAvoid state01(char c){ if (c == 'a') { dfa = 11; } else if (c == 'b') { dfa = 2; } else { dfa = -1; }} // This function is for the second state (02) of DFAvoid state02(char c){ if (c == 'b') { dfa = 0; } else if (c == 'a') { dfa = 12; } else { dfa = -1; }} // This function is for the third state (10)of DFAvoid state10(char c){ if (c == 'b') { dfa = 11; } else if (c == 'a') { dfa = 20; } else { dfa = -1; }} // This function is for the forth state (11)of DFAvoid state11(char c){ if (c == 'b') { dfa = 12; } else if (c == 'a') { dfa = 21; } else { dfa = -1; }} void state12(char c){ if (c == 'b') { dfa = 10; } else if (c == 'a') { dfa = 22; } else { dfa = -1; }} void state20(char c){ if (c == 'b') { dfa = 21; } else if (c == 'a') { dfa = 0; } else { dfa = -1; }} void state21(char c){ if (c == 'b') { dfa = 22; } else if (c == 'a') { dfa = 1; } else { dfa = -1; }} void state22(char c){ if (c == 'b') { dfa = 20; } else if (c == 'a') { dfa = 2; } else { dfa = -1; }} int isAccepted(char str[]){ // store length of string int i, len = strlen(str); for (i = 0; i < len; i++) { if (dfa == 0) start(str[i]); else if (dfa == 1) state01(str[i]); else if (dfa == 2) state02(str[i]); else if (dfa == 10) state10(str[i]); else if (dfa == 11) state11(str[i]); else if (dfa == 12) state12(str[i]); else if (dfa == 20) state20(str[i]); else if (dfa == 21) state21(str[i]); else if (dfa == 22) state22(str[i]); else return 0; } if (dfa == 0 || dfa == 11 || dfa == 22) return 1; else return 0;} // driver codeint main(){ char str[] = "aaaabbbb"; if (isAccepted(str)) printf("ACCEPTED"); else printf("NOT ACCEPTED"); return 0;} // This code is contributed by SHUBHAMSINGH10.Java// Java Program to construct a DFA which accept the language// L = { w | w is in {a, b}* and Na(w) mod 3 = Nb(w) mod 3}class GFG{// dfa tells the number associated// string end in which state.static int dfa = 0; // This function is for// the starting state (00)of DFAstatic void start(char c){ if (c == 'a') { dfa = 10; } else if (c == 'b') { dfa = 1; } // -1 is used to check for any invalid symbol else { dfa = -1; }} // This function is for the first state (01) of DFAstatic void state01(char c){ if (c == 'a') { dfa = 11; } else if (c == 'b') { dfa = 2; } else { dfa = -1; }} // This function is for the second state (02) of DFAstatic void state02(char c){ if (c == 'b') { dfa = 0; } else if (c == 'a') { dfa = 12; } else { dfa = -1; }} // This function is for the third state (10)of DFAstatic void state10(char c){ if (c == 'b') { dfa = 11; } else if (c == 'a') { dfa = 20; } else { dfa = -1; }} // This function is for the forth state (11)of DFAstatic void state11(char c){ if (c == 'b') { dfa = 12; } else if (c == 'a') { dfa = 21; } else { dfa = -1; }} static void state12(char c){ if (c == 'b') { dfa = 10; } else if (c == 'a') { dfa = 22; } else { dfa = -1; }} static void state20(char c){ if (c == 'b') { dfa = 21; } else if (c == 'a') { dfa = 0; } else { dfa = -1; }} static void state21(char c){ if (c == 'b') { dfa = 22; } else if (c == 'a') { dfa = 1; } else { dfa = -1; }} static void state22(char c){ if (c == 'b') { dfa = 20; } else if (c == 'a') { dfa = 2; } else { dfa = -1; }} static boolean isAccepted(String st){ // store length of string int i, len = st.length(); char[] str = st.toCharArray(); for (i = 0; i < len; i++) { if (dfa == 0) start(str[i]); else if (dfa == 1) state01(str[i]); else if (dfa == 2) state02(str[i]); else if (dfa == 10) state10(str[i]); else if (dfa == 11) state11(str[i]); else if (dfa == 12) state12(str[i]); else if (dfa == 20) state20(str[i]); else if (dfa == 21) state21(str[i]); else if (dfa == 22) state22(str[i]); else return false; } if (dfa == 0 || dfa == 11 || dfa == 22) return true; else return false;} // driver codepublic static void main(String []args) { String str = "aaaabbbb"; if (isAccepted(str)) System.out.println("ACCEPTED"); else System.out.println("NOT ACCEPTED"); }} // This code contributed by Rajput-JiPython 3"""Python Program to construct a DFA which accept the language L = {w | w belongs to {a, b}*}and Na(w)mod3 = Nb(w)mod 3""" # This function is for # the starting state (00)of DFA def start( c): if (c == 'a'): dfa = 10 elif (c == 'b') : dfa = 1 #-1 is used to check for any invalid symbol else: dfa = -1 return dfa # This function is for the first state (01) of DFA def state01( c): if (c == 'a'): dfa = 11 elif (c == 'b') : dfa = 2 else: dfa = -1 return dfa # This function is for the second state (02) of DFA def state02( c): if (c == 'b') : dfa = 0 elif(c =='a'): dfa = 12 else: dfa = -1 return dfa # This function is for the third state (10)of DFA def state10( c): if (c == 'b') : dfa = 11 elif(c =='a'): dfa = 20 else: dfa = -1 return dfa # This function is for the forth state (11)of DFA def state11( c): if (c == 'b') : dfa = 12 elif(c =='a'): dfa = 21 else: dfa = -1 return dfa def state12( c): if (c == 'b') : dfa = 10 elif(c =='a'): dfa = 22 else: dfa = -1 return dfa def state20( c): if (c == 'b') : dfa = 21 elif(c =='a'): dfa = 0 else: dfa = -1 return dfa def state21( c): if (c == 'b') : dfa = 22 elif(c =='a'): dfa = 1 else: dfa = -1 return dfa def state22( c): if (c == 'b') : dfa = 20 elif(c =='a'): dfa = 2 else: dfa = -1 return dfa def isAccepted(str): # store length of string l = len(str) # dfa tells the number associated # with the present dfa = state dfa = 0 for i in range(l): if (dfa == 0) : start(str[i]) elif (dfa == 1): state01(str[i]) elif (dfa == 2) : state02(str[i]) elif (dfa == 10) : state10(str[i]) elif (dfa == 11) : state11(str[i]) elif (dfa == 12) : state12(str[i]) elif (dfa == 20) : state20(str[i]) elif (dfa == 21) : state21(str[i]) elif (dfa == 22) : state22(str[i]) else: return 0 if (dfa == 0 or dfa == 11 or dfa == 22) : return 1 else: return 0 # Driver code if __name__ == "__main__" : string = "aaaabbbb" if (isAccepted(string)) : print("ACCEPTED") else: print("NOT ACCEPTED") # This code is contributed by SHUBHAMSINGH10.C#// C# Program to construct a DFA which accept the language // L = { w | w is in {a, b}* and Na(w) mod 3 = Nb(w) mod 3} using System; class GFG{ // DFA tells the number associated // string end in which state. static int dfa = 0; // This function is for // the starting state (00)of DFA static void start(char c) { if (c == 'a') { dfa = 10; } else if (c == 'b') { dfa = 1; } // -1 is used to check for any invalid symbol else { dfa = -1; } } // This function is for the first state (01) of DFA static void state01(char c) { if (c == 'a') { dfa = 11; } else if (c == 'b') { dfa = 2; } else { dfa = -1; } } // This function is for the second state (02) of DFA static void state02(char c) { if (c == 'b') { dfa = 0; } else if (c == 'a') { dfa = 12; } else { dfa = -1; } } // This function is for the third state (10)of DFA static void state10(char c) { if (c == 'b') { dfa = 11; } else if (c == 'a') { dfa = 20; } else { dfa = -1; } } // This function is for the forth state (11)of DFA static void state11(char c) { if (c == 'b') { dfa = 12; } else if (c == 'a') { dfa = 21; } else { dfa = -1; } } static void state12(char c) { if (c == 'b') { dfa = 10; } else if (c == 'a') { dfa = 22; } else { dfa = -1; } } static void state20(char c) { if (c == 'b') { dfa = 21; } else if (c == 'a') { dfa = 0; } else { dfa = -1; } } static void state21(char c) { if (c == 'b') { dfa = 22; } else if (c == 'a') { dfa = 1; } else { dfa = -1; } } static void state22(char c) { if (c == 'b') { dfa = 20; } else if (c == 'a') { dfa = 2; } else { dfa = -1; } } static Boolean isAccepted(String st) { // store length of string int i, len = st.Length; char[] str = st.ToCharArray(); for (i = 0; i < len; i++) { if (dfa == 0) start(str[i]); else if (dfa == 1) state01(str[i]); else if (dfa == 2) state02(str[i]); else if (dfa == 10) state10(str[i]); else if (dfa == 11) state11(str[i]); else if (dfa == 12) state12(str[i]); else if (dfa == 20) state20(str[i]); else if (dfa == 21) state21(str[i]); else if (dfa == 22) state22(str[i]); else return false; } if (dfa == 0 || dfa == 11 || dfa == 22) return true; else return false; } // Driver code public static void Main(String []args) { String str = "aaaabbbb"; if (isAccepted(str)) Console.WriteLine("ACCEPTED"); else Console.WriteLine("NOT ACCEPTED"); } } // This code is contributed by 29AjayKumarOutput:ACCEPTEDMy Personal Notes arrow_drop_upSave DFA State Transition Diagram: States 00, 11 and 22 leads to the acceptance of the string.Whereas states 01, 02, 10, 12, 20 and 21 leads to the rejection of the string. Let’s see code for the demonstration: C/C++ Java Python 3 C# // C/C++ Program to construct a DFA which accept the language// L = { w | w is in {a, b}* and Na(w) mod 3 = Nb(w) mod 3}#include <stdio.h>#include <string.h> // dfa tells the number associated// string end in which state.int dfa = 0; // This function is for// the starting state (00)of DFAvoid start(char c){ if (c == 'a') { dfa = 10; } else if (c == 'b') { dfa = 1; } // -1 is used to check for any invalid symbol else { dfa = -1; }} // This function is for the first state (01) of DFAvoid state01(char c){ if (c == 'a') { dfa = 11; } else if (c == 'b') { dfa = 2; } else { dfa = -1; }} // This function is for the second state (02) of DFAvoid state02(char c){ if (c == 'b') { dfa = 0; } else if (c == 'a') { dfa = 12; } else { dfa = -1; }} // This function is for the third state (10)of DFAvoid state10(char c){ if (c == 'b') { dfa = 11; } else if (c == 'a') { dfa = 20; } else { dfa = -1; }} // This function is for the forth state (11)of DFAvoid state11(char c){ if (c == 'b') { dfa = 12; } else if (c == 'a') { dfa = 21; } else { dfa = -1; }} void state12(char c){ if (c == 'b') { dfa = 10; } else if (c == 'a') { dfa = 22; } else { dfa = -1; }} void state20(char c){ if (c == 'b') { dfa = 21; } else if (c == 'a') { dfa = 0; } else { dfa = -1; }} void state21(char c){ if (c == 'b') { dfa = 22; } else if (c == 'a') { dfa = 1; } else { dfa = -1; }} void state22(char c){ if (c == 'b') { dfa = 20; } else if (c == 'a') { dfa = 2; } else { dfa = -1; }} int isAccepted(char str[]){ // store length of string int i, len = strlen(str); for (i = 0; i < len; i++) { if (dfa == 0) start(str[i]); else if (dfa == 1) state01(str[i]); else if (dfa == 2) state02(str[i]); else if (dfa == 10) state10(str[i]); else if (dfa == 11) state11(str[i]); else if (dfa == 12) state12(str[i]); else if (dfa == 20) state20(str[i]); else if (dfa == 21) state21(str[i]); else if (dfa == 22) state22(str[i]); else return 0; } if (dfa == 0 || dfa == 11 || dfa == 22) return 1; else return 0;} // driver codeint main(){ char str[] = "aaaabbbb"; if (isAccepted(str)) printf("ACCEPTED"); else printf("NOT ACCEPTED"); return 0;} // This code is contributed by SHUBHAMSINGH10. // Java Program to construct a DFA which accept the language// L = { w | w is in {a, b}* and Na(w) mod 3 = Nb(w) mod 3}class GFG{// dfa tells the number associated// string end in which state.static int dfa = 0; // This function is for// the starting state (00)of DFAstatic void start(char c){ if (c == 'a') { dfa = 10; } else if (c == 'b') { dfa = 1; } // -1 is used to check for any invalid symbol else { dfa = -1; }} // This function is for the first state (01) of DFAstatic void state01(char c){ if (c == 'a') { dfa = 11; } else if (c == 'b') { dfa = 2; } else { dfa = -1; }} // This function is for the second state (02) of DFAstatic void state02(char c){ if (c == 'b') { dfa = 0; } else if (c == 'a') { dfa = 12; } else { dfa = -1; }} // This function is for the third state (10)of DFAstatic void state10(char c){ if (c == 'b') { dfa = 11; } else if (c == 'a') { dfa = 20; } else { dfa = -1; }} // This function is for the forth state (11)of DFAstatic void state11(char c){ if (c == 'b') { dfa = 12; } else if (c == 'a') { dfa = 21; } else { dfa = -1; }} static void state12(char c){ if (c == 'b') { dfa = 10; } else if (c == 'a') { dfa = 22; } else { dfa = -1; }} static void state20(char c){ if (c == 'b') { dfa = 21; } else if (c == 'a') { dfa = 0; } else { dfa = -1; }} static void state21(char c){ if (c == 'b') { dfa = 22; } else if (c == 'a') { dfa = 1; } else { dfa = -1; }} static void state22(char c){ if (c == 'b') { dfa = 20; } else if (c == 'a') { dfa = 2; } else { dfa = -1; }} static boolean isAccepted(String st){ // store length of string int i, len = st.length(); char[] str = st.toCharArray(); for (i = 0; i < len; i++) { if (dfa == 0) start(str[i]); else if (dfa == 1) state01(str[i]); else if (dfa == 2) state02(str[i]); else if (dfa == 10) state10(str[i]); else if (dfa == 11) state11(str[i]); else if (dfa == 12) state12(str[i]); else if (dfa == 20) state20(str[i]); else if (dfa == 21) state21(str[i]); else if (dfa == 22) state22(str[i]); else return false; } if (dfa == 0 || dfa == 11 || dfa == 22) return true; else return false;} // driver codepublic static void main(String []args) { String str = "aaaabbbb"; if (isAccepted(str)) System.out.println("ACCEPTED"); else System.out.println("NOT ACCEPTED"); }} // This code contributed by Rajput-Ji """Python Program to construct a DFA which accept the language L = {w | w belongs to {a, b}*}and Na(w)mod3 = Nb(w)mod 3""" # This function is for # the starting state (00)of DFA def start( c): if (c == 'a'): dfa = 10 elif (c == 'b') : dfa = 1 #-1 is used to check for any invalid symbol else: dfa = -1 return dfa # This function is for the first state (01) of DFA def state01( c): if (c == 'a'): dfa = 11 elif (c == 'b') : dfa = 2 else: dfa = -1 return dfa # This function is for the second state (02) of DFA def state02( c): if (c == 'b') : dfa = 0 elif(c =='a'): dfa = 12 else: dfa = -1 return dfa # This function is for the third state (10)of DFA def state10( c): if (c == 'b') : dfa = 11 elif(c =='a'): dfa = 20 else: dfa = -1 return dfa # This function is for the forth state (11)of DFA def state11( c): if (c == 'b') : dfa = 12 elif(c =='a'): dfa = 21 else: dfa = -1 return dfa def state12( c): if (c == 'b') : dfa = 10 elif(c =='a'): dfa = 22 else: dfa = -1 return dfa def state20( c): if (c == 'b') : dfa = 21 elif(c =='a'): dfa = 0 else: dfa = -1 return dfa def state21( c): if (c == 'b') : dfa = 22 elif(c =='a'): dfa = 1 else: dfa = -1 return dfa def state22( c): if (c == 'b') : dfa = 20 elif(c =='a'): dfa = 2 else: dfa = -1 return dfa def isAccepted(str): # store length of string l = len(str) # dfa tells the number associated # with the present dfa = state dfa = 0 for i in range(l): if (dfa == 0) : start(str[i]) elif (dfa == 1): state01(str[i]) elif (dfa == 2) : state02(str[i]) elif (dfa == 10) : state10(str[i]) elif (dfa == 11) : state11(str[i]) elif (dfa == 12) : state12(str[i]) elif (dfa == 20) : state20(str[i]) elif (dfa == 21) : state21(str[i]) elif (dfa == 22) : state22(str[i]) else: return 0 if (dfa == 0 or dfa == 11 or dfa == 22) : return 1 else: return 0 # Driver code if __name__ == "__main__" : string = "aaaabbbb" if (isAccepted(string)) : print("ACCEPTED") else: print("NOT ACCEPTED") # This code is contributed by SHUBHAMSINGH10. // C# Program to construct a DFA which accept the language // L = { w | w is in {a, b}* and Na(w) mod 3 = Nb(w) mod 3} using System; class GFG{ // DFA tells the number associated // string end in which state. static int dfa = 0; // This function is for // the starting state (00)of DFA static void start(char c) { if (c == 'a') { dfa = 10; } else if (c == 'b') { dfa = 1; } // -1 is used to check for any invalid symbol else { dfa = -1; } } // This function is for the first state (01) of DFA static void state01(char c) { if (c == 'a') { dfa = 11; } else if (c == 'b') { dfa = 2; } else { dfa = -1; } } // This function is for the second state (02) of DFA static void state02(char c) { if (c == 'b') { dfa = 0; } else if (c == 'a') { dfa = 12; } else { dfa = -1; } } // This function is for the third state (10)of DFA static void state10(char c) { if (c == 'b') { dfa = 11; } else if (c == 'a') { dfa = 20; } else { dfa = -1; } } // This function is for the forth state (11)of DFA static void state11(char c) { if (c == 'b') { dfa = 12; } else if (c == 'a') { dfa = 21; } else { dfa = -1; } } static void state12(char c) { if (c == 'b') { dfa = 10; } else if (c == 'a') { dfa = 22; } else { dfa = -1; } } static void state20(char c) { if (c == 'b') { dfa = 21; } else if (c == 'a') { dfa = 0; } else { dfa = -1; } } static void state21(char c) { if (c == 'b') { dfa = 22; } else if (c == 'a') { dfa = 1; } else { dfa = -1; } } static void state22(char c) { if (c == 'b') { dfa = 20; } else if (c == 'a') { dfa = 2; } else { dfa = -1; } } static Boolean isAccepted(String st) { // store length of string int i, len = st.Length; char[] str = st.ToCharArray(); for (i = 0; i < len; i++) { if (dfa == 0) start(str[i]); else if (dfa == 1) state01(str[i]); else if (dfa == 2) state02(str[i]); else if (dfa == 10) state10(str[i]); else if (dfa == 11) state11(str[i]); else if (dfa == 12) state12(str[i]); else if (dfa == 20) state20(str[i]); else if (dfa == 21) state21(str[i]); else if (dfa == 22) state22(str[i]); else return false; } if (dfa == 0 || dfa == 11 || dfa == 22) return true; else return false; } // Driver code public static void Main(String []args) { String str = "aaaabbbb"; if (isAccepted(str)) Console.WriteLine("ACCEPTED"); else Console.WriteLine("NOT ACCEPTED"); } } // This code is contributed by 29AjayKumar Output: ACCEPTED Rajput-Ji 29AjayKumar GATE CS Theory of Computation & Automata Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Page Replacement Algorithms in Operating Systems Differences between TCP and UDP Semaphores in Process Synchronization Caesar Cipher in Cryptography Difference between Process and Thread Difference between DFA and NFA Difference between Mealy machine and Moore machine Turing Machine in TOC Conversion from NFA to DFA Converting Context Free Grammar to Chomsky Normal Form
[ { "code": null, "e": 24582, "s": 24554, "text": "\n02 Jul, 2019" }, { "code": null, "e": 24719, "s": 24582, "text": "Problem: Construct a deterministic finite automata (DFA) for accepting the language L = {w | w ∈ {a,b}* and Na(w) mod 3 = Nb (w) mod 3}." }, { "code": null, "e": 24849, "s": 24719, "text": "Language L={w | Na(w) = Nb(w)mod 3} which means all string contain modulus of count of a’s equal to modulus of count of b’s by 3." }, { "code": null, "e": 24859, "s": 24849, "text": "Examples:" }, { "code": null, "e": 24930, "s": 24859, "text": "Input: a a b b bOutput: NOT ACCEPTED// n = 2, m=3 (2 mod 3! = 3 mod 3)" }, { "code": null, "e": 24996, "s": 24930, "text": "Input: a a b bOutput: ACCEPTED// n = 2, m = 2 (2 mod 3 = 2 mod 3)" }, { "code": null, "e": 25076, "s": 24996, "text": "Input: b b bOutput: NOT ACCEPTED// n = 0, m = 3 ((0 mod 3 = 3 mod 3) <=> (0=0))" }, { "code": null, "e": 25088, "s": 25076, "text": "Approaches:" }, { "code": null, "e": 37457, "s": 25088, "text": "Construct FA for {w | w {a, b}} and Na = 0 mod 3 means having a’s as a multiple of 3.Construct FA for {w | w {a, b}} and Nb = 0 mod 3 means having b’s as a multiple of 3.Concatenate the two FA and make single DFA using Concatenation process in DFA.Making state as final state which accepts the equal modulus count for a’s and b’s.DFA State Transition Diagram:States 00, 11 and 22 leads to the acceptance of the string.Whereas states 01, 02, 10, 12, 20 and 21 leads to the rejection of the string.Let’s see code for the demonstration:C/C++JavaPython 3C#C/C++// C/C++ Program to construct a DFA which accept the language// L = { w | w is in {a, b}* and Na(w) mod 3 = Nb(w) mod 3}#include <stdio.h>#include <string.h> // dfa tells the number associated// string end in which state.int dfa = 0; // This function is for// the starting state (00)of DFAvoid start(char c){ if (c == 'a') { dfa = 10; } else if (c == 'b') { dfa = 1; } // -1 is used to check for any invalid symbol else { dfa = -1; }} // This function is for the first state (01) of DFAvoid state01(char c){ if (c == 'a') { dfa = 11; } else if (c == 'b') { dfa = 2; } else { dfa = -1; }} // This function is for the second state (02) of DFAvoid state02(char c){ if (c == 'b') { dfa = 0; } else if (c == 'a') { dfa = 12; } else { dfa = -1; }} // This function is for the third state (10)of DFAvoid state10(char c){ if (c == 'b') { dfa = 11; } else if (c == 'a') { dfa = 20; } else { dfa = -1; }} // This function is for the forth state (11)of DFAvoid state11(char c){ if (c == 'b') { dfa = 12; } else if (c == 'a') { dfa = 21; } else { dfa = -1; }} void state12(char c){ if (c == 'b') { dfa = 10; } else if (c == 'a') { dfa = 22; } else { dfa = -1; }} void state20(char c){ if (c == 'b') { dfa = 21; } else if (c == 'a') { dfa = 0; } else { dfa = -1; }} void state21(char c){ if (c == 'b') { dfa = 22; } else if (c == 'a') { dfa = 1; } else { dfa = -1; }} void state22(char c){ if (c == 'b') { dfa = 20; } else if (c == 'a') { dfa = 2; } else { dfa = -1; }} int isAccepted(char str[]){ // store length of string int i, len = strlen(str); for (i = 0; i < len; i++) { if (dfa == 0) start(str[i]); else if (dfa == 1) state01(str[i]); else if (dfa == 2) state02(str[i]); else if (dfa == 10) state10(str[i]); else if (dfa == 11) state11(str[i]); else if (dfa == 12) state12(str[i]); else if (dfa == 20) state20(str[i]); else if (dfa == 21) state21(str[i]); else if (dfa == 22) state22(str[i]); else return 0; } if (dfa == 0 || dfa == 11 || dfa == 22) return 1; else return 0;} // driver codeint main(){ char str[] = \"aaaabbbb\"; if (isAccepted(str)) printf(\"ACCEPTED\"); else printf(\"NOT ACCEPTED\"); return 0;} // This code is contributed by SHUBHAMSINGH10.Java// Java Program to construct a DFA which accept the language// L = { w | w is in {a, b}* and Na(w) mod 3 = Nb(w) mod 3}class GFG{// dfa tells the number associated// string end in which state.static int dfa = 0; // This function is for// the starting state (00)of DFAstatic void start(char c){ if (c == 'a') { dfa = 10; } else if (c == 'b') { dfa = 1; } // -1 is used to check for any invalid symbol else { dfa = -1; }} // This function is for the first state (01) of DFAstatic void state01(char c){ if (c == 'a') { dfa = 11; } else if (c == 'b') { dfa = 2; } else { dfa = -1; }} // This function is for the second state (02) of DFAstatic void state02(char c){ if (c == 'b') { dfa = 0; } else if (c == 'a') { dfa = 12; } else { dfa = -1; }} // This function is for the third state (10)of DFAstatic void state10(char c){ if (c == 'b') { dfa = 11; } else if (c == 'a') { dfa = 20; } else { dfa = -1; }} // This function is for the forth state (11)of DFAstatic void state11(char c){ if (c == 'b') { dfa = 12; } else if (c == 'a') { dfa = 21; } else { dfa = -1; }} static void state12(char c){ if (c == 'b') { dfa = 10; } else if (c == 'a') { dfa = 22; } else { dfa = -1; }} static void state20(char c){ if (c == 'b') { dfa = 21; } else if (c == 'a') { dfa = 0; } else { dfa = -1; }} static void state21(char c){ if (c == 'b') { dfa = 22; } else if (c == 'a') { dfa = 1; } else { dfa = -1; }} static void state22(char c){ if (c == 'b') { dfa = 20; } else if (c == 'a') { dfa = 2; } else { dfa = -1; }} static boolean isAccepted(String st){ // store length of string int i, len = st.length(); char[] str = st.toCharArray(); for (i = 0; i < len; i++) { if (dfa == 0) start(str[i]); else if (dfa == 1) state01(str[i]); else if (dfa == 2) state02(str[i]); else if (dfa == 10) state10(str[i]); else if (dfa == 11) state11(str[i]); else if (dfa == 12) state12(str[i]); else if (dfa == 20) state20(str[i]); else if (dfa == 21) state21(str[i]); else if (dfa == 22) state22(str[i]); else return false; } if (dfa == 0 || dfa == 11 || dfa == 22) return true; else return false;} // driver codepublic static void main(String []args) { String str = \"aaaabbbb\"; if (isAccepted(str)) System.out.println(\"ACCEPTED\"); else System.out.println(\"NOT ACCEPTED\"); }} // This code contributed by Rajput-JiPython 3\"\"\"Python Program to construct a DFA which accept the language L = {w | w belongs to {a, b}*}and Na(w)mod3 = Nb(w)mod 3\"\"\" # This function is for # the starting state (00)of DFA def start( c): if (c == 'a'): dfa = 10 elif (c == 'b') : dfa = 1 #-1 is used to check for any invalid symbol else: dfa = -1 return dfa # This function is for the first state (01) of DFA def state01( c): if (c == 'a'): dfa = 11 elif (c == 'b') : dfa = 2 else: dfa = -1 return dfa # This function is for the second state (02) of DFA def state02( c): if (c == 'b') : dfa = 0 elif(c =='a'): dfa = 12 else: dfa = -1 return dfa # This function is for the third state (10)of DFA def state10( c): if (c == 'b') : dfa = 11 elif(c =='a'): dfa = 20 else: dfa = -1 return dfa # This function is for the forth state (11)of DFA def state11( c): if (c == 'b') : dfa = 12 elif(c =='a'): dfa = 21 else: dfa = -1 return dfa def state12( c): if (c == 'b') : dfa = 10 elif(c =='a'): dfa = 22 else: dfa = -1 return dfa def state20( c): if (c == 'b') : dfa = 21 elif(c =='a'): dfa = 0 else: dfa = -1 return dfa def state21( c): if (c == 'b') : dfa = 22 elif(c =='a'): dfa = 1 else: dfa = -1 return dfa def state22( c): if (c == 'b') : dfa = 20 elif(c =='a'): dfa = 2 else: dfa = -1 return dfa def isAccepted(str): # store length of string l = len(str) # dfa tells the number associated # with the present dfa = state dfa = 0 for i in range(l): if (dfa == 0) : start(str[i]) elif (dfa == 1): state01(str[i]) elif (dfa == 2) : state02(str[i]) elif (dfa == 10) : state10(str[i]) elif (dfa == 11) : state11(str[i]) elif (dfa == 12) : state12(str[i]) elif (dfa == 20) : state20(str[i]) elif (dfa == 21) : state21(str[i]) elif (dfa == 22) : state22(str[i]) else: return 0 if (dfa == 0 or dfa == 11 or dfa == 22) : return 1 else: return 0 # Driver code if __name__ == \"__main__\" : string = \"aaaabbbb\" if (isAccepted(string)) : print(\"ACCEPTED\") else: print(\"NOT ACCEPTED\") # This code is contributed by SHUBHAMSINGH10.C#// C# Program to construct a DFA which accept the language // L = { w | w is in {a, b}* and Na(w) mod 3 = Nb(w) mod 3} using System; class GFG{ // DFA tells the number associated // string end in which state. static int dfa = 0; // This function is for // the starting state (00)of DFA static void start(char c) { if (c == 'a') { dfa = 10; } else if (c == 'b') { dfa = 1; } // -1 is used to check for any invalid symbol else { dfa = -1; } } // This function is for the first state (01) of DFA static void state01(char c) { if (c == 'a') { dfa = 11; } else if (c == 'b') { dfa = 2; } else { dfa = -1; } } // This function is for the second state (02) of DFA static void state02(char c) { if (c == 'b') { dfa = 0; } else if (c == 'a') { dfa = 12; } else { dfa = -1; } } // This function is for the third state (10)of DFA static void state10(char c) { if (c == 'b') { dfa = 11; } else if (c == 'a') { dfa = 20; } else { dfa = -1; } } // This function is for the forth state (11)of DFA static void state11(char c) { if (c == 'b') { dfa = 12; } else if (c == 'a') { dfa = 21; } else { dfa = -1; } } static void state12(char c) { if (c == 'b') { dfa = 10; } else if (c == 'a') { dfa = 22; } else { dfa = -1; } } static void state20(char c) { if (c == 'b') { dfa = 21; } else if (c == 'a') { dfa = 0; } else { dfa = -1; } } static void state21(char c) { if (c == 'b') { dfa = 22; } else if (c == 'a') { dfa = 1; } else { dfa = -1; } } static void state22(char c) { if (c == 'b') { dfa = 20; } else if (c == 'a') { dfa = 2; } else { dfa = -1; } } static Boolean isAccepted(String st) { // store length of string int i, len = st.Length; char[] str = st.ToCharArray(); for (i = 0; i < len; i++) { if (dfa == 0) start(str[i]); else if (dfa == 1) state01(str[i]); else if (dfa == 2) state02(str[i]); else if (dfa == 10) state10(str[i]); else if (dfa == 11) state11(str[i]); else if (dfa == 12) state12(str[i]); else if (dfa == 20) state20(str[i]); else if (dfa == 21) state21(str[i]); else if (dfa == 22) state22(str[i]); else return false; } if (dfa == 0 || dfa == 11 || dfa == 22) return true; else return false; } // Driver code public static void Main(String []args) { String str = \"aaaabbbb\"; if (isAccepted(str)) Console.WriteLine(\"ACCEPTED\"); else Console.WriteLine(\"NOT ACCEPTED\"); } } // This code is contributed by 29AjayKumarOutput:ACCEPTEDMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 37544, "s": 37457, "text": "Construct FA for {w | w {a, b}} and Na = 0 mod 3 means having a’s as a multiple of 3." }, { "code": null, "e": 37631, "s": 37544, "text": "Construct FA for {w | w {a, b}} and Nb = 0 mod 3 means having b’s as a multiple of 3." }, { "code": null, "e": 37710, "s": 37631, "text": "Concatenate the two FA and make single DFA using Concatenation process in DFA." }, { "code": null, "e": 49829, "s": 37710, "text": "Making state as final state which accepts the equal modulus count for a’s and b’s.DFA State Transition Diagram:States 00, 11 and 22 leads to the acceptance of the string.Whereas states 01, 02, 10, 12, 20 and 21 leads to the rejection of the string.Let’s see code for the demonstration:C/C++JavaPython 3C#C/C++// C/C++ Program to construct a DFA which accept the language// L = { w | w is in {a, b}* and Na(w) mod 3 = Nb(w) mod 3}#include <stdio.h>#include <string.h> // dfa tells the number associated// string end in which state.int dfa = 0; // This function is for// the starting state (00)of DFAvoid start(char c){ if (c == 'a') { dfa = 10; } else if (c == 'b') { dfa = 1; } // -1 is used to check for any invalid symbol else { dfa = -1; }} // This function is for the first state (01) of DFAvoid state01(char c){ if (c == 'a') { dfa = 11; } else if (c == 'b') { dfa = 2; } else { dfa = -1; }} // This function is for the second state (02) of DFAvoid state02(char c){ if (c == 'b') { dfa = 0; } else if (c == 'a') { dfa = 12; } else { dfa = -1; }} // This function is for the third state (10)of DFAvoid state10(char c){ if (c == 'b') { dfa = 11; } else if (c == 'a') { dfa = 20; } else { dfa = -1; }} // This function is for the forth state (11)of DFAvoid state11(char c){ if (c == 'b') { dfa = 12; } else if (c == 'a') { dfa = 21; } else { dfa = -1; }} void state12(char c){ if (c == 'b') { dfa = 10; } else if (c == 'a') { dfa = 22; } else { dfa = -1; }} void state20(char c){ if (c == 'b') { dfa = 21; } else if (c == 'a') { dfa = 0; } else { dfa = -1; }} void state21(char c){ if (c == 'b') { dfa = 22; } else if (c == 'a') { dfa = 1; } else { dfa = -1; }} void state22(char c){ if (c == 'b') { dfa = 20; } else if (c == 'a') { dfa = 2; } else { dfa = -1; }} int isAccepted(char str[]){ // store length of string int i, len = strlen(str); for (i = 0; i < len; i++) { if (dfa == 0) start(str[i]); else if (dfa == 1) state01(str[i]); else if (dfa == 2) state02(str[i]); else if (dfa == 10) state10(str[i]); else if (dfa == 11) state11(str[i]); else if (dfa == 12) state12(str[i]); else if (dfa == 20) state20(str[i]); else if (dfa == 21) state21(str[i]); else if (dfa == 22) state22(str[i]); else return 0; } if (dfa == 0 || dfa == 11 || dfa == 22) return 1; else return 0;} // driver codeint main(){ char str[] = \"aaaabbbb\"; if (isAccepted(str)) printf(\"ACCEPTED\"); else printf(\"NOT ACCEPTED\"); return 0;} // This code is contributed by SHUBHAMSINGH10.Java// Java Program to construct a DFA which accept the language// L = { w | w is in {a, b}* and Na(w) mod 3 = Nb(w) mod 3}class GFG{// dfa tells the number associated// string end in which state.static int dfa = 0; // This function is for// the starting state (00)of DFAstatic void start(char c){ if (c == 'a') { dfa = 10; } else if (c == 'b') { dfa = 1; } // -1 is used to check for any invalid symbol else { dfa = -1; }} // This function is for the first state (01) of DFAstatic void state01(char c){ if (c == 'a') { dfa = 11; } else if (c == 'b') { dfa = 2; } else { dfa = -1; }} // This function is for the second state (02) of DFAstatic void state02(char c){ if (c == 'b') { dfa = 0; } else if (c == 'a') { dfa = 12; } else { dfa = -1; }} // This function is for the third state (10)of DFAstatic void state10(char c){ if (c == 'b') { dfa = 11; } else if (c == 'a') { dfa = 20; } else { dfa = -1; }} // This function is for the forth state (11)of DFAstatic void state11(char c){ if (c == 'b') { dfa = 12; } else if (c == 'a') { dfa = 21; } else { dfa = -1; }} static void state12(char c){ if (c == 'b') { dfa = 10; } else if (c == 'a') { dfa = 22; } else { dfa = -1; }} static void state20(char c){ if (c == 'b') { dfa = 21; } else if (c == 'a') { dfa = 0; } else { dfa = -1; }} static void state21(char c){ if (c == 'b') { dfa = 22; } else if (c == 'a') { dfa = 1; } else { dfa = -1; }} static void state22(char c){ if (c == 'b') { dfa = 20; } else if (c == 'a') { dfa = 2; } else { dfa = -1; }} static boolean isAccepted(String st){ // store length of string int i, len = st.length(); char[] str = st.toCharArray(); for (i = 0; i < len; i++) { if (dfa == 0) start(str[i]); else if (dfa == 1) state01(str[i]); else if (dfa == 2) state02(str[i]); else if (dfa == 10) state10(str[i]); else if (dfa == 11) state11(str[i]); else if (dfa == 12) state12(str[i]); else if (dfa == 20) state20(str[i]); else if (dfa == 21) state21(str[i]); else if (dfa == 22) state22(str[i]); else return false; } if (dfa == 0 || dfa == 11 || dfa == 22) return true; else return false;} // driver codepublic static void main(String []args) { String str = \"aaaabbbb\"; if (isAccepted(str)) System.out.println(\"ACCEPTED\"); else System.out.println(\"NOT ACCEPTED\"); }} // This code contributed by Rajput-JiPython 3\"\"\"Python Program to construct a DFA which accept the language L = {w | w belongs to {a, b}*}and Na(w)mod3 = Nb(w)mod 3\"\"\" # This function is for # the starting state (00)of DFA def start( c): if (c == 'a'): dfa = 10 elif (c == 'b') : dfa = 1 #-1 is used to check for any invalid symbol else: dfa = -1 return dfa # This function is for the first state (01) of DFA def state01( c): if (c == 'a'): dfa = 11 elif (c == 'b') : dfa = 2 else: dfa = -1 return dfa # This function is for the second state (02) of DFA def state02( c): if (c == 'b') : dfa = 0 elif(c =='a'): dfa = 12 else: dfa = -1 return dfa # This function is for the third state (10)of DFA def state10( c): if (c == 'b') : dfa = 11 elif(c =='a'): dfa = 20 else: dfa = -1 return dfa # This function is for the forth state (11)of DFA def state11( c): if (c == 'b') : dfa = 12 elif(c =='a'): dfa = 21 else: dfa = -1 return dfa def state12( c): if (c == 'b') : dfa = 10 elif(c =='a'): dfa = 22 else: dfa = -1 return dfa def state20( c): if (c == 'b') : dfa = 21 elif(c =='a'): dfa = 0 else: dfa = -1 return dfa def state21( c): if (c == 'b') : dfa = 22 elif(c =='a'): dfa = 1 else: dfa = -1 return dfa def state22( c): if (c == 'b') : dfa = 20 elif(c =='a'): dfa = 2 else: dfa = -1 return dfa def isAccepted(str): # store length of string l = len(str) # dfa tells the number associated # with the present dfa = state dfa = 0 for i in range(l): if (dfa == 0) : start(str[i]) elif (dfa == 1): state01(str[i]) elif (dfa == 2) : state02(str[i]) elif (dfa == 10) : state10(str[i]) elif (dfa == 11) : state11(str[i]) elif (dfa == 12) : state12(str[i]) elif (dfa == 20) : state20(str[i]) elif (dfa == 21) : state21(str[i]) elif (dfa == 22) : state22(str[i]) else: return 0 if (dfa == 0 or dfa == 11 or dfa == 22) : return 1 else: return 0 # Driver code if __name__ == \"__main__\" : string = \"aaaabbbb\" if (isAccepted(string)) : print(\"ACCEPTED\") else: print(\"NOT ACCEPTED\") # This code is contributed by SHUBHAMSINGH10.C#// C# Program to construct a DFA which accept the language // L = { w | w is in {a, b}* and Na(w) mod 3 = Nb(w) mod 3} using System; class GFG{ // DFA tells the number associated // string end in which state. static int dfa = 0; // This function is for // the starting state (00)of DFA static void start(char c) { if (c == 'a') { dfa = 10; } else if (c == 'b') { dfa = 1; } // -1 is used to check for any invalid symbol else { dfa = -1; } } // This function is for the first state (01) of DFA static void state01(char c) { if (c == 'a') { dfa = 11; } else if (c == 'b') { dfa = 2; } else { dfa = -1; } } // This function is for the second state (02) of DFA static void state02(char c) { if (c == 'b') { dfa = 0; } else if (c == 'a') { dfa = 12; } else { dfa = -1; } } // This function is for the third state (10)of DFA static void state10(char c) { if (c == 'b') { dfa = 11; } else if (c == 'a') { dfa = 20; } else { dfa = -1; } } // This function is for the forth state (11)of DFA static void state11(char c) { if (c == 'b') { dfa = 12; } else if (c == 'a') { dfa = 21; } else { dfa = -1; } } static void state12(char c) { if (c == 'b') { dfa = 10; } else if (c == 'a') { dfa = 22; } else { dfa = -1; } } static void state20(char c) { if (c == 'b') { dfa = 21; } else if (c == 'a') { dfa = 0; } else { dfa = -1; } } static void state21(char c) { if (c == 'b') { dfa = 22; } else if (c == 'a') { dfa = 1; } else { dfa = -1; } } static void state22(char c) { if (c == 'b') { dfa = 20; } else if (c == 'a') { dfa = 2; } else { dfa = -1; } } static Boolean isAccepted(String st) { // store length of string int i, len = st.Length; char[] str = st.ToCharArray(); for (i = 0; i < len; i++) { if (dfa == 0) start(str[i]); else if (dfa == 1) state01(str[i]); else if (dfa == 2) state02(str[i]); else if (dfa == 10) state10(str[i]); else if (dfa == 11) state11(str[i]); else if (dfa == 12) state12(str[i]); else if (dfa == 20) state20(str[i]); else if (dfa == 21) state21(str[i]); else if (dfa == 22) state22(str[i]); else return false; } if (dfa == 0 || dfa == 11 || dfa == 22) return true; else return false; } // Driver code public static void Main(String []args) { String str = \"aaaabbbb\"; if (isAccepted(str)) Console.WriteLine(\"ACCEPTED\"); else Console.WriteLine(\"NOT ACCEPTED\"); } } // This code is contributed by 29AjayKumarOutput:ACCEPTEDMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 61866, "s": 49829, "text": "DFA State Transition Diagram:States 00, 11 and 22 leads to the acceptance of the string.Whereas states 01, 02, 10, 12, 20 and 21 leads to the rejection of the string.Let’s see code for the demonstration:C/C++JavaPython 3C#C/C++// C/C++ Program to construct a DFA which accept the language// L = { w | w is in {a, b}* and Na(w) mod 3 = Nb(w) mod 3}#include <stdio.h>#include <string.h> // dfa tells the number associated// string end in which state.int dfa = 0; // This function is for// the starting state (00)of DFAvoid start(char c){ if (c == 'a') { dfa = 10; } else if (c == 'b') { dfa = 1; } // -1 is used to check for any invalid symbol else { dfa = -1; }} // This function is for the first state (01) of DFAvoid state01(char c){ if (c == 'a') { dfa = 11; } else if (c == 'b') { dfa = 2; } else { dfa = -1; }} // This function is for the second state (02) of DFAvoid state02(char c){ if (c == 'b') { dfa = 0; } else if (c == 'a') { dfa = 12; } else { dfa = -1; }} // This function is for the third state (10)of DFAvoid state10(char c){ if (c == 'b') { dfa = 11; } else if (c == 'a') { dfa = 20; } else { dfa = -1; }} // This function is for the forth state (11)of DFAvoid state11(char c){ if (c == 'b') { dfa = 12; } else if (c == 'a') { dfa = 21; } else { dfa = -1; }} void state12(char c){ if (c == 'b') { dfa = 10; } else if (c == 'a') { dfa = 22; } else { dfa = -1; }} void state20(char c){ if (c == 'b') { dfa = 21; } else if (c == 'a') { dfa = 0; } else { dfa = -1; }} void state21(char c){ if (c == 'b') { dfa = 22; } else if (c == 'a') { dfa = 1; } else { dfa = -1; }} void state22(char c){ if (c == 'b') { dfa = 20; } else if (c == 'a') { dfa = 2; } else { dfa = -1; }} int isAccepted(char str[]){ // store length of string int i, len = strlen(str); for (i = 0; i < len; i++) { if (dfa == 0) start(str[i]); else if (dfa == 1) state01(str[i]); else if (dfa == 2) state02(str[i]); else if (dfa == 10) state10(str[i]); else if (dfa == 11) state11(str[i]); else if (dfa == 12) state12(str[i]); else if (dfa == 20) state20(str[i]); else if (dfa == 21) state21(str[i]); else if (dfa == 22) state22(str[i]); else return 0; } if (dfa == 0 || dfa == 11 || dfa == 22) return 1; else return 0;} // driver codeint main(){ char str[] = \"aaaabbbb\"; if (isAccepted(str)) printf(\"ACCEPTED\"); else printf(\"NOT ACCEPTED\"); return 0;} // This code is contributed by SHUBHAMSINGH10.Java// Java Program to construct a DFA which accept the language// L = { w | w is in {a, b}* and Na(w) mod 3 = Nb(w) mod 3}class GFG{// dfa tells the number associated// string end in which state.static int dfa = 0; // This function is for// the starting state (00)of DFAstatic void start(char c){ if (c == 'a') { dfa = 10; } else if (c == 'b') { dfa = 1; } // -1 is used to check for any invalid symbol else { dfa = -1; }} // This function is for the first state (01) of DFAstatic void state01(char c){ if (c == 'a') { dfa = 11; } else if (c == 'b') { dfa = 2; } else { dfa = -1; }} // This function is for the second state (02) of DFAstatic void state02(char c){ if (c == 'b') { dfa = 0; } else if (c == 'a') { dfa = 12; } else { dfa = -1; }} // This function is for the third state (10)of DFAstatic void state10(char c){ if (c == 'b') { dfa = 11; } else if (c == 'a') { dfa = 20; } else { dfa = -1; }} // This function is for the forth state (11)of DFAstatic void state11(char c){ if (c == 'b') { dfa = 12; } else if (c == 'a') { dfa = 21; } else { dfa = -1; }} static void state12(char c){ if (c == 'b') { dfa = 10; } else if (c == 'a') { dfa = 22; } else { dfa = -1; }} static void state20(char c){ if (c == 'b') { dfa = 21; } else if (c == 'a') { dfa = 0; } else { dfa = -1; }} static void state21(char c){ if (c == 'b') { dfa = 22; } else if (c == 'a') { dfa = 1; } else { dfa = -1; }} static void state22(char c){ if (c == 'b') { dfa = 20; } else if (c == 'a') { dfa = 2; } else { dfa = -1; }} static boolean isAccepted(String st){ // store length of string int i, len = st.length(); char[] str = st.toCharArray(); for (i = 0; i < len; i++) { if (dfa == 0) start(str[i]); else if (dfa == 1) state01(str[i]); else if (dfa == 2) state02(str[i]); else if (dfa == 10) state10(str[i]); else if (dfa == 11) state11(str[i]); else if (dfa == 12) state12(str[i]); else if (dfa == 20) state20(str[i]); else if (dfa == 21) state21(str[i]); else if (dfa == 22) state22(str[i]); else return false; } if (dfa == 0 || dfa == 11 || dfa == 22) return true; else return false;} // driver codepublic static void main(String []args) { String str = \"aaaabbbb\"; if (isAccepted(str)) System.out.println(\"ACCEPTED\"); else System.out.println(\"NOT ACCEPTED\"); }} // This code contributed by Rajput-JiPython 3\"\"\"Python Program to construct a DFA which accept the language L = {w | w belongs to {a, b}*}and Na(w)mod3 = Nb(w)mod 3\"\"\" # This function is for # the starting state (00)of DFA def start( c): if (c == 'a'): dfa = 10 elif (c == 'b') : dfa = 1 #-1 is used to check for any invalid symbol else: dfa = -1 return dfa # This function is for the first state (01) of DFA def state01( c): if (c == 'a'): dfa = 11 elif (c == 'b') : dfa = 2 else: dfa = -1 return dfa # This function is for the second state (02) of DFA def state02( c): if (c == 'b') : dfa = 0 elif(c =='a'): dfa = 12 else: dfa = -1 return dfa # This function is for the third state (10)of DFA def state10( c): if (c == 'b') : dfa = 11 elif(c =='a'): dfa = 20 else: dfa = -1 return dfa # This function is for the forth state (11)of DFA def state11( c): if (c == 'b') : dfa = 12 elif(c =='a'): dfa = 21 else: dfa = -1 return dfa def state12( c): if (c == 'b') : dfa = 10 elif(c =='a'): dfa = 22 else: dfa = -1 return dfa def state20( c): if (c == 'b') : dfa = 21 elif(c =='a'): dfa = 0 else: dfa = -1 return dfa def state21( c): if (c == 'b') : dfa = 22 elif(c =='a'): dfa = 1 else: dfa = -1 return dfa def state22( c): if (c == 'b') : dfa = 20 elif(c =='a'): dfa = 2 else: dfa = -1 return dfa def isAccepted(str): # store length of string l = len(str) # dfa tells the number associated # with the present dfa = state dfa = 0 for i in range(l): if (dfa == 0) : start(str[i]) elif (dfa == 1): state01(str[i]) elif (dfa == 2) : state02(str[i]) elif (dfa == 10) : state10(str[i]) elif (dfa == 11) : state11(str[i]) elif (dfa == 12) : state12(str[i]) elif (dfa == 20) : state20(str[i]) elif (dfa == 21) : state21(str[i]) elif (dfa == 22) : state22(str[i]) else: return 0 if (dfa == 0 or dfa == 11 or dfa == 22) : return 1 else: return 0 # Driver code if __name__ == \"__main__\" : string = \"aaaabbbb\" if (isAccepted(string)) : print(\"ACCEPTED\") else: print(\"NOT ACCEPTED\") # This code is contributed by SHUBHAMSINGH10.C#// C# Program to construct a DFA which accept the language // L = { w | w is in {a, b}* and Na(w) mod 3 = Nb(w) mod 3} using System; class GFG{ // DFA tells the number associated // string end in which state. static int dfa = 0; // This function is for // the starting state (00)of DFA static void start(char c) { if (c == 'a') { dfa = 10; } else if (c == 'b') { dfa = 1; } // -1 is used to check for any invalid symbol else { dfa = -1; } } // This function is for the first state (01) of DFA static void state01(char c) { if (c == 'a') { dfa = 11; } else if (c == 'b') { dfa = 2; } else { dfa = -1; } } // This function is for the second state (02) of DFA static void state02(char c) { if (c == 'b') { dfa = 0; } else if (c == 'a') { dfa = 12; } else { dfa = -1; } } // This function is for the third state (10)of DFA static void state10(char c) { if (c == 'b') { dfa = 11; } else if (c == 'a') { dfa = 20; } else { dfa = -1; } } // This function is for the forth state (11)of DFA static void state11(char c) { if (c == 'b') { dfa = 12; } else if (c == 'a') { dfa = 21; } else { dfa = -1; } } static void state12(char c) { if (c == 'b') { dfa = 10; } else if (c == 'a') { dfa = 22; } else { dfa = -1; } } static void state20(char c) { if (c == 'b') { dfa = 21; } else if (c == 'a') { dfa = 0; } else { dfa = -1; } } static void state21(char c) { if (c == 'b') { dfa = 22; } else if (c == 'a') { dfa = 1; } else { dfa = -1; } } static void state22(char c) { if (c == 'b') { dfa = 20; } else if (c == 'a') { dfa = 2; } else { dfa = -1; } } static Boolean isAccepted(String st) { // store length of string int i, len = st.Length; char[] str = st.ToCharArray(); for (i = 0; i < len; i++) { if (dfa == 0) start(str[i]); else if (dfa == 1) state01(str[i]); else if (dfa == 2) state02(str[i]); else if (dfa == 10) state10(str[i]); else if (dfa == 11) state11(str[i]); else if (dfa == 12) state12(str[i]); else if (dfa == 20) state20(str[i]); else if (dfa == 21) state21(str[i]); else if (dfa == 22) state22(str[i]); else return false; } if (dfa == 0 || dfa == 11 || dfa == 22) return true; else return false; } // Driver code public static void Main(String []args) { String str = \"aaaabbbb\"; if (isAccepted(str)) Console.WriteLine(\"ACCEPTED\"); else Console.WriteLine(\"NOT ACCEPTED\"); } } // This code is contributed by 29AjayKumarOutput:ACCEPTEDMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 61896, "s": 61866, "text": "DFA State Transition Diagram:" }, { "code": null, "e": 62034, "s": 61896, "text": "States 00, 11 and 22 leads to the acceptance of the string.Whereas states 01, 02, 10, 12, 20 and 21 leads to the rejection of the string." }, { "code": null, "e": 62072, "s": 62034, "text": "Let’s see code for the demonstration:" }, { "code": null, "e": 62078, "s": 62072, "text": "C/C++" }, { "code": null, "e": 62083, "s": 62078, "text": "Java" }, { "code": null, "e": 62092, "s": 62083, "text": "Python 3" }, { "code": null, "e": 62095, "s": 62092, "text": "C#" }, { "code": "// C/C++ Program to construct a DFA which accept the language// L = { w | w is in {a, b}* and Na(w) mod 3 = Nb(w) mod 3}#include <stdio.h>#include <string.h> // dfa tells the number associated// string end in which state.int dfa = 0; // This function is for// the starting state (00)of DFAvoid start(char c){ if (c == 'a') { dfa = 10; } else if (c == 'b') { dfa = 1; } // -1 is used to check for any invalid symbol else { dfa = -1; }} // This function is for the first state (01) of DFAvoid state01(char c){ if (c == 'a') { dfa = 11; } else if (c == 'b') { dfa = 2; } else { dfa = -1; }} // This function is for the second state (02) of DFAvoid state02(char c){ if (c == 'b') { dfa = 0; } else if (c == 'a') { dfa = 12; } else { dfa = -1; }} // This function is for the third state (10)of DFAvoid state10(char c){ if (c == 'b') { dfa = 11; } else if (c == 'a') { dfa = 20; } else { dfa = -1; }} // This function is for the forth state (11)of DFAvoid state11(char c){ if (c == 'b') { dfa = 12; } else if (c == 'a') { dfa = 21; } else { dfa = -1; }} void state12(char c){ if (c == 'b') { dfa = 10; } else if (c == 'a') { dfa = 22; } else { dfa = -1; }} void state20(char c){ if (c == 'b') { dfa = 21; } else if (c == 'a') { dfa = 0; } else { dfa = -1; }} void state21(char c){ if (c == 'b') { dfa = 22; } else if (c == 'a') { dfa = 1; } else { dfa = -1; }} void state22(char c){ if (c == 'b') { dfa = 20; } else if (c == 'a') { dfa = 2; } else { dfa = -1; }} int isAccepted(char str[]){ // store length of string int i, len = strlen(str); for (i = 0; i < len; i++) { if (dfa == 0) start(str[i]); else if (dfa == 1) state01(str[i]); else if (dfa == 2) state02(str[i]); else if (dfa == 10) state10(str[i]); else if (dfa == 11) state11(str[i]); else if (dfa == 12) state12(str[i]); else if (dfa == 20) state20(str[i]); else if (dfa == 21) state21(str[i]); else if (dfa == 22) state22(str[i]); else return 0; } if (dfa == 0 || dfa == 11 || dfa == 22) return 1; else return 0;} // driver codeint main(){ char str[] = \"aaaabbbb\"; if (isAccepted(str)) printf(\"ACCEPTED\"); else printf(\"NOT ACCEPTED\"); return 0;} // This code is contributed by SHUBHAMSINGH10.", "e": 64872, "s": 62095, "text": null }, { "code": "// Java Program to construct a DFA which accept the language// L = { w | w is in {a, b}* and Na(w) mod 3 = Nb(w) mod 3}class GFG{// dfa tells the number associated// string end in which state.static int dfa = 0; // This function is for// the starting state (00)of DFAstatic void start(char c){ if (c == 'a') { dfa = 10; } else if (c == 'b') { dfa = 1; } // -1 is used to check for any invalid symbol else { dfa = -1; }} // This function is for the first state (01) of DFAstatic void state01(char c){ if (c == 'a') { dfa = 11; } else if (c == 'b') { dfa = 2; } else { dfa = -1; }} // This function is for the second state (02) of DFAstatic void state02(char c){ if (c == 'b') { dfa = 0; } else if (c == 'a') { dfa = 12; } else { dfa = -1; }} // This function is for the third state (10)of DFAstatic void state10(char c){ if (c == 'b') { dfa = 11; } else if (c == 'a') { dfa = 20; } else { dfa = -1; }} // This function is for the forth state (11)of DFAstatic void state11(char c){ if (c == 'b') { dfa = 12; } else if (c == 'a') { dfa = 21; } else { dfa = -1; }} static void state12(char c){ if (c == 'b') { dfa = 10; } else if (c == 'a') { dfa = 22; } else { dfa = -1; }} static void state20(char c){ if (c == 'b') { dfa = 21; } else if (c == 'a') { dfa = 0; } else { dfa = -1; }} static void state21(char c){ if (c == 'b') { dfa = 22; } else if (c == 'a') { dfa = 1; } else { dfa = -1; }} static void state22(char c){ if (c == 'b') { dfa = 20; } else if (c == 'a') { dfa = 2; } else { dfa = -1; }} static boolean isAccepted(String st){ // store length of string int i, len = st.length(); char[] str = st.toCharArray(); for (i = 0; i < len; i++) { if (dfa == 0) start(str[i]); else if (dfa == 1) state01(str[i]); else if (dfa == 2) state02(str[i]); else if (dfa == 10) state10(str[i]); else if (dfa == 11) state11(str[i]); else if (dfa == 12) state12(str[i]); else if (dfa == 20) state20(str[i]); else if (dfa == 21) state21(str[i]); else if (dfa == 22) state22(str[i]); else return false; } if (dfa == 0 || dfa == 11 || dfa == 22) return true; else return false;} // driver codepublic static void main(String []args) { String str = \"aaaabbbb\"; if (isAccepted(str)) System.out.println(\"ACCEPTED\"); else System.out.println(\"NOT ACCEPTED\"); }} // This code contributed by Rajput-Ji", "e": 67803, "s": 64872, "text": null }, { "code": "\"\"\"Python Program to construct a DFA which accept the language L = {w | w belongs to {a, b}*}and Na(w)mod3 = Nb(w)mod 3\"\"\" # This function is for # the starting state (00)of DFA def start( c): if (c == 'a'): dfa = 10 elif (c == 'b') : dfa = 1 #-1 is used to check for any invalid symbol else: dfa = -1 return dfa # This function is for the first state (01) of DFA def state01( c): if (c == 'a'): dfa = 11 elif (c == 'b') : dfa = 2 else: dfa = -1 return dfa # This function is for the second state (02) of DFA def state02( c): if (c == 'b') : dfa = 0 elif(c =='a'): dfa = 12 else: dfa = -1 return dfa # This function is for the third state (10)of DFA def state10( c): if (c == 'b') : dfa = 11 elif(c =='a'): dfa = 20 else: dfa = -1 return dfa # This function is for the forth state (11)of DFA def state11( c): if (c == 'b') : dfa = 12 elif(c =='a'): dfa = 21 else: dfa = -1 return dfa def state12( c): if (c == 'b') : dfa = 10 elif(c =='a'): dfa = 22 else: dfa = -1 return dfa def state20( c): if (c == 'b') : dfa = 21 elif(c =='a'): dfa = 0 else: dfa = -1 return dfa def state21( c): if (c == 'b') : dfa = 22 elif(c =='a'): dfa = 1 else: dfa = -1 return dfa def state22( c): if (c == 'b') : dfa = 20 elif(c =='a'): dfa = 2 else: dfa = -1 return dfa def isAccepted(str): # store length of string l = len(str) # dfa tells the number associated # with the present dfa = state dfa = 0 for i in range(l): if (dfa == 0) : start(str[i]) elif (dfa == 1): state01(str[i]) elif (dfa == 2) : state02(str[i]) elif (dfa == 10) : state10(str[i]) elif (dfa == 11) : state11(str[i]) elif (dfa == 12) : state12(str[i]) elif (dfa == 20) : state20(str[i]) elif (dfa == 21) : state21(str[i]) elif (dfa == 22) : state22(str[i]) else: return 0 if (dfa == 0 or dfa == 11 or dfa == 22) : return 1 else: return 0 # Driver code if __name__ == \"__main__\" : string = \"aaaabbbb\" if (isAccepted(string)) : print(\"ACCEPTED\") else: print(\"NOT ACCEPTED\") # This code is contributed by SHUBHAMSINGH10.", "e": 70767, "s": 67803, "text": null }, { "code": "// C# Program to construct a DFA which accept the language // L = { w | w is in {a, b}* and Na(w) mod 3 = Nb(w) mod 3} using System; class GFG{ // DFA tells the number associated // string end in which state. static int dfa = 0; // This function is for // the starting state (00)of DFA static void start(char c) { if (c == 'a') { dfa = 10; } else if (c == 'b') { dfa = 1; } // -1 is used to check for any invalid symbol else { dfa = -1; } } // This function is for the first state (01) of DFA static void state01(char c) { if (c == 'a') { dfa = 11; } else if (c == 'b') { dfa = 2; } else { dfa = -1; } } // This function is for the second state (02) of DFA static void state02(char c) { if (c == 'b') { dfa = 0; } else if (c == 'a') { dfa = 12; } else { dfa = -1; } } // This function is for the third state (10)of DFA static void state10(char c) { if (c == 'b') { dfa = 11; } else if (c == 'a') { dfa = 20; } else { dfa = -1; } } // This function is for the forth state (11)of DFA static void state11(char c) { if (c == 'b') { dfa = 12; } else if (c == 'a') { dfa = 21; } else { dfa = -1; } } static void state12(char c) { if (c == 'b') { dfa = 10; } else if (c == 'a') { dfa = 22; } else { dfa = -1; } } static void state20(char c) { if (c == 'b') { dfa = 21; } else if (c == 'a') { dfa = 0; } else { dfa = -1; } } static void state21(char c) { if (c == 'b') { dfa = 22; } else if (c == 'a') { dfa = 1; } else { dfa = -1; } } static void state22(char c) { if (c == 'b') { dfa = 20; } else if (c == 'a') { dfa = 2; } else { dfa = -1; } } static Boolean isAccepted(String st) { // store length of string int i, len = st.Length; char[] str = st.ToCharArray(); for (i = 0; i < len; i++) { if (dfa == 0) start(str[i]); else if (dfa == 1) state01(str[i]); else if (dfa == 2) state02(str[i]); else if (dfa == 10) state10(str[i]); else if (dfa == 11) state11(str[i]); else if (dfa == 12) state12(str[i]); else if (dfa == 20) state20(str[i]); else if (dfa == 21) state21(str[i]); else if (dfa == 22) state22(str[i]); else return false; } if (dfa == 0 || dfa == 11 || dfa == 22) return true; else return false; } // Driver code public static void Main(String []args) { String str = \"aaaabbbb\"; if (isAccepted(str)) Console.WriteLine(\"ACCEPTED\"); else Console.WriteLine(\"NOT ACCEPTED\"); } } // This code is contributed by 29AjayKumar", "e": 73844, "s": 70767, "text": null }, { "code": null, "e": 73852, "s": 73844, "text": "Output:" }, { "code": null, "e": 73861, "s": 73852, "text": "ACCEPTED" }, { "code": null, "e": 73871, "s": 73861, "text": "Rajput-Ji" }, { "code": null, "e": 73883, "s": 73871, "text": "29AjayKumar" }, { "code": null, "e": 73891, "s": 73883, "text": "GATE CS" }, { "code": null, "e": 73924, "s": 73891, "text": "Theory of Computation & Automata" }, { "code": null, "e": 74022, "s": 73924, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 74071, "s": 74022, "text": "Page Replacement Algorithms in Operating Systems" }, { "code": null, "e": 74103, "s": 74071, "text": "Differences between TCP and UDP" }, { "code": null, "e": 74141, "s": 74103, "text": "Semaphores in Process Synchronization" }, { "code": null, "e": 74171, "s": 74141, "text": "Caesar Cipher in Cryptography" }, { "code": null, "e": 74209, "s": 74171, "text": "Difference between Process and Thread" }, { "code": null, "e": 74240, "s": 74209, "text": "Difference between DFA and NFA" }, { "code": null, "e": 74291, "s": 74240, "text": "Difference between Mealy machine and Moore machine" }, { "code": null, "e": 74313, "s": 74291, "text": "Turing Machine in TOC" }, { "code": null, "e": 74340, "s": 74313, "text": "Conversion from NFA to DFA" } ]
Spring Boot Basic Authentication 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 this tutorials, we are going show you how to use Spring Boot Basic Authentication. We can provide the basic authentication for a Spring Boot application by simply adding the below dependency in pom.xml. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> Spring Boot 2.0.0.RELEASE Spring Security Java 8 Project Structure : pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.onlinetutorialspoint</groupId> <artifactId>SpringBoot_Basic_Authentication</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>SpringBoot_Basic_Authentication</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.0.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> Create Simple Rest Controller : HelloController.java package com.onlinetutorialspoint; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @RequestMapping("/hello") @ResponseBody public String sayHello(){ return "<h2>Greetings.. !</h2>"; } } Application.java package com.onlinetutorialspoint; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } mvn clean install mvn spring-boot:run [INFO] --- spring-boot-maven-plugin:2.0.0.RELEASE:run (default-cli) @ SpringBoot_Basic_Authentication --- . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.0.0.RELEASE) 2018-03-11 21:30:37.225 INFO 2356 --- [ main] com.onlinetutorialspoint.Application : Starting Application on DESKTOP-RN4SMHT with PID 2356 (E:\work\SpringBoot_Basic_Au thentication\target\classes started by Lenovo in E:\work\SpringBoot_Basic_Authentication) 2018-03-11 21:30:37.241 INFO 2356 --- [ main] com.onlinetutorialspoint.Application : No active profile set, falling back to default profiles: default 2018-03-11 21:30:37.350 INFO 2356 --- [ main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWeb ServerApplicationContext@563670cc: startup date [Sun Mar 11 21:30:37 IST 2018]; root of context hierarchy 2018-03-11 21:30:40.886 INFO 2356 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http) 2018-03-11 21:30:40.949 INFO 2356 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2018-03-11 21:30:40.949 INFO 2356 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.28 2018-03-11 21:30:40.980 INFO 2356 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener : The APR based Apache Tomcat Native library which allows optimal performance in pro duction environments was not found on the java.library.path: [C:\Program Files\Java\jdk1.8.0_161\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\ProgramData\Oracle\Java \javapath;C:\oraclexe\app\oracle\product.2.0\server\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\ MySQL\MySQL Server 5.5\bin;C:\php;C:\Apache24;C:\Apache24\bin;C:\Program Files\Java\jdk1.8.0_161\bin;D:\Softwares\apache-maven-3.5.2\bin;C:\Program Files\Git\cmd;C:\Program Files\Git \mingw64\bin;C:\Program Files\Git\usr\bin;D:\Softwares\apache-ant-1.10.2\bin;C:\Users\Lenovo\AppData\Local\Microsoft\WindowsApps;C:\Users\Lenovo\AppData\Local\atom\bin;%USERPROFILE%\ AppData\Local\Microsoft\WindowsApps;;.] 2018-03-11 21:30:41.574 INFO 2356 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2018-03-11 21:30:41.589 INFO 2356 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 4239 ms 2018-03-11 21:30:42.131 INFO 2356 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*] 2018-03-11 21:30:42.146 INFO 2356 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*] 2018-03-11 21:30:42.146 INFO 2356 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*] 2018-03-11 21:30:42.146 INFO 2356 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*] 2018-03-11 21:30:42.146 INFO 2356 --- [ost-startStop-1] .s.DelegatingFilterProxyRegistrationBean : Mapping filter: 'springSecurityFilterChain' to: [/*] 2018-03-11 21:30:42.146 INFO 2356 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/] 2018-03-11 21:30:43.193 INFO 2356 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.web.servlet.context.Annota tionConfigServletWebServerApplicationContext@563670cc: startup date [Sun Mar 11 21:30:37 IST 2018]; root of context hierarchy 2018-03-11 21:30:43.397 INFO 2356 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/hello]}" onto public java.lang.String com.onlinetutorialspoint.HelloCon troller.sayHello() 2018-03-11 21:30:43.428 INFO 2356 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util. Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest) 2018-03-11 21:30:43.428 INFO 2356 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servl et.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse) 2018-03-11 21:30:43.522 INFO 2356 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web. servlet.resource.ResourceHttpRequestHandler] 2018-03-11 21:30:43.522 INFO 2356 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet. resource.ResourceHttpRequestHandler] 2018-03-11 21:30:43.647 INFO 2356 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework. web.servlet.resource.ResourceHttpRequestHandler] 2018-03-11 21:30:44.287 INFO 2356 --- [ main] .s.s.UserDetailsServiceAutoConfiguration : Using generated security password: ef4512ac-aebc-40f8-b589-37cd3b1fc460 2018-03-11 21:30:44.853 INFO 2356 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: org.springframework.security.web.util.matcher.AnyRequestMat cher@1, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@203364d6, org.springframework.security.web.context.SecurityContextPersistenceFilter@6 f53f03a, org.springframework.security.web.header.HeaderWriterFilter@7e765142, org.springframework.security.web.csrf.CsrfFilter@396c3d2f, org.springframework.security.web.authenticati on.logout.LogoutFilter@4e980e94, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@12e2d748, org.springframework.security.web.authentication.ui.Def aultLoginPageGeneratingFilter@28c3e342, org.springframework.security.web.authentication.www.BasicAuthenticationFilter@aaeec51, org.springframework.security.web.savedrequest.RequestCa cheAwareFilter@7c7fca3e, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@6d51bf8a, org.springframework.security.web.authentication.AnonymousAuthen ticationFilter@5f832ac6, org.springframework.security.web.session.SessionManagementFilter@6250c19a, org.springframework.security.web.access.ExceptionTranslationFilter@6835f9de, org.s pringframework.security.web.access.intercept.FilterSecurityInterceptor@24b65d7d] 2018-03-11 21:30:45.119 INFO 2356 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup 2018-03-11 21:30:45.353 INFO 2356 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path '' 2018-03-11 21:30:45.353 INFO 2356 --- [ main] com.onlinetutorialspoint.Application : Started Application in 9.346 seconds (JVM running for 26.637) On the above console output, we can see the default authentication password. We can use this password to access the application. User Name : user Password : ef4512ac-aebc-40f8-b589-37cd3b1fc460 The above password is only for one time, for each time while running the applicaiton, we should get the different password. Happy Learning 🙂 How to use Spring Boot Random Port Spring Boot How to change the Tomcat to Jetty Server Spring Boot In Memory Basic Authentication Security How to set Spring Boot SetTimeZone How to Create own Spring Boot Error Page Spring Boot Environment Properties reading based on activeprofile How to change Spring Boot Tomcat Port Number How To Change Spring Boot Context Path MicroServices Spring Boot Eureka Server Example How to Get All Spring Beans Details Loaded in ICO Spring Boot Apache ActiveMq In Memory Example How to set Spring boot favicon image Spring Boot Security MySQL Database Integration Example Spring Boot MongoDB + Spring Data Example Spring Boot JPA Integration Example How to use Spring Boot Random Port Spring Boot How to change the Tomcat to Jetty Server Spring Boot In Memory Basic Authentication Security How to set Spring Boot SetTimeZone How to Create own Spring Boot Error Page Spring Boot Environment Properties reading based on activeprofile How to change Spring Boot Tomcat Port Number How To Change Spring Boot Context Path MicroServices Spring Boot Eureka Server Example How to Get All Spring Beans Details Loaded in ICO Spring Boot Apache ActiveMq In Memory Example How to set Spring boot favicon image Spring Boot Security MySQL Database Integration Example Spring Boot MongoDB + Spring Data Example Spring Boot JPA Integration Example Δ Spring Boot – Hello World Spring Boot – MVC Example Spring Boot- Change Context Path Spring Boot – Change Tomcat Port Number Spring Boot – Change Tomcat to Jetty Server Spring Boot – Tomcat session timeout Spring Boot – Enable Random Port Spring Boot – Properties File Spring Boot – Beans Lazy Loading Spring Boot – Set Favicon image Spring Boot – Set Custom Banner Spring Boot – Set Application TimeZone Spring Boot – Send Mail Spring Boot – FileUpload Ajax Spring Boot – Actuator Spring Boot – Actuator Database Health Check Spring Boot – Swagger Spring Boot – Enable CORS Spring Boot – External Apache ActiveMQ Setup Spring Boot – Inmemory Apache ActiveMq Spring Boot – Scheduler Job Spring Boot – Exception Handling Spring Boot – Hibernate CRUD Spring Boot – JPA Integration CRUD Spring Boot – JPA DataRest CRUD Spring Boot – JdbcTemplate CRUD Spring Boot – Multiple Data Sources Config Spring Boot – JNDI Configuration Spring Boot – H2 Database CRUD Spring Boot – MongoDB CRUD Spring Boot – Redis Data CRUD Spring Boot – MVC Login Form Validation Spring Boot – Custom Error Pages Spring Boot – iText PDF Spring Boot – Enable SSL (HTTPs) Spring Boot – Basic Authentication Spring Boot – In Memory Basic Authentication Spring Boot – Security MySQL Database Integration Spring Boot – Redis Cache – Redis Server Spring Boot – Hazelcast Cache Spring Boot – EhCache Spring Boot – Kafka Producer Spring Boot – Kafka Consumer Spring Boot – Kafka JSON Message to Kafka Topic Spring Boot – RabbitMQ Publisher Spring Boot – RabbitMQ Consumer Spring Boot – SOAP Consumer Spring Boot – Soap WebServices Spring Boot – Batch Csv to Database Spring Boot – Eureka Server Spring Boot – MockMvc JUnit Spring Boot – Docker Deployment
[ { "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": 484, "s": 398, "text": "In this tutorials, we are going show you how to use Spring Boot Basic Authentication." }, { "code": null, "e": 604, "s": 484, "text": "We can provide the basic authentication for a Spring Boot application by simply adding the below dependency in pom.xml." }, { "code": null, "e": 735, "s": 604, "text": "<dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-security</artifactId>\n</dependency>" }, { "code": null, "e": 761, "s": 735, "text": "Spring Boot 2.0.0.RELEASE" }, { "code": null, "e": 777, "s": 761, "text": "Spring Security" }, { "code": null, "e": 784, "s": 777, "text": "Java 8" }, { "code": null, "e": 804, "s": 784, "text": "Project Structure :" }, { "code": null, "e": 812, "s": 804, "text": "pom.xml" }, { "code": null, "e": 2338, "s": 812, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n\n <groupId>com.onlinetutorialspoint</groupId>\n <artifactId>SpringBoot_Basic_Authentication</artifactId>\n <version>0.0.1-SNAPSHOT</version>\n <packaging>jar</packaging>\n\n <name>SpringBoot_Basic_Authentication</name>\n <description>Demo project for Spring Boot</description>\n\n <parent>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-parent</artifactId>\n <version>2.0.0.RELEASE</version>\n <relativePath/> <!-- lookup parent from repository -->\n </parent>\n <properties>\n <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>\n <java.version>1.8</java.version>\n </properties>\n\n <dependencies>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-security</artifactId>\n </dependency>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-web</artifactId>\n </dependency>\n </dependencies>\n <build>\n <plugins>\n <plugin>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-maven-plugin</artifactId>\n </plugin>\n </plugins>\n </build>\n</project>\n" }, { "code": null, "e": 2370, "s": 2338, "text": "Create Simple Rest Controller :" }, { "code": null, "e": 2391, "s": 2370, "text": "HelloController.java" }, { "code": null, "e": 2789, "s": 2391, "text": "package com.onlinetutorialspoint;\n\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.ResponseBody;\nimport org.springframework.web.bind.annotation.RestController;\n\n@RestController\npublic class HelloController {\n @RequestMapping(\"/hello\")\n @ResponseBody\n public String sayHello(){\n return \"<h2>Greetings.. !</h2>\";\n }\n}\n" }, { "code": null, "e": 2806, "s": 2789, "text": "Application.java" }, { "code": null, "e": 3115, "s": 2806, "text": "package com.onlinetutorialspoint;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\n@SpringBootApplication\npublic class Application {\n\n public static void main(String[] args) {\n SpringApplication.run(Application.class, args);\n }\n}\n" }, { "code": null, "e": 10767, "s": 3115, "text": "mvn clean install\nmvn spring-boot:run\n\n[INFO] --- spring-boot-maven-plugin:2.0.0.RELEASE:run (default-cli) @ SpringBoot_Basic_Authentication ---\n\n . ____ _ __ _ _\n /\\\\ / ___'_ __ _ _(_)_ __ __ _ \\ \\ \\ \\\n( ( )\\___ | '_ | '_| | '_ \\/ _` | \\ \\ \\ \\\n \\\\/ ___)| |_)| | | | | || (_| | ) ) ) )\n ' |____| .__|_| |_|_| |_\\__, | / / / /\n =========|_|==============|___/=/_/_/_/\n :: Spring Boot :: (v2.0.0.RELEASE)\n\n2018-03-11 21:30:37.225 INFO 2356 --- [ main] com.onlinetutorialspoint.Application : Starting Application on DESKTOP-RN4SMHT with PID 2356 (E:\\work\\SpringBoot_Basic_Au\nthentication\\target\\classes started by Lenovo in E:\\work\\SpringBoot_Basic_Authentication)\n2018-03-11 21:30:37.241 INFO 2356 --- [ main] com.onlinetutorialspoint.Application : No active profile set, falling back to default profiles: default\n2018-03-11 21:30:37.350 INFO 2356 --- [ main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWeb\nServerApplicationContext@563670cc: startup date [Sun Mar 11 21:30:37 IST 2018]; root of context hierarchy\n2018-03-11 21:30:40.886 INFO 2356 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)\n2018-03-11 21:30:40.949 INFO 2356 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]\n2018-03-11 21:30:40.949 INFO 2356 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.28\n2018-03-11 21:30:40.980 INFO 2356 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener : The APR based Apache Tomcat Native library which allows optimal performance in pro\nduction environments was not found on the java.library.path: [C:\\Program Files\\Java\\jdk1.8.0_161\\bin;C:\\WINDOWS\\Sun\\Java\\bin;C:\\WINDOWS\\system32;C:\\WINDOWS;C:\\ProgramData\\Oracle\\Java\n\\javapath;C:\\oraclexe\\app\\oracle\\product.2.0\\server\\bin;C:\\WINDOWS\\system32;C:\\WINDOWS;C:\\WINDOWS\\System32\\Wbem;C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\;C:\\Program Files (x86)\\\nMySQL\\MySQL Server 5.5\\bin;C:\\php;C:\\Apache24;C:\\Apache24\\bin;C:\\Program Files\\Java\\jdk1.8.0_161\\bin;D:\\Softwares\\apache-maven-3.5.2\\bin;C:\\Program Files\\Git\\cmd;C:\\Program Files\\Git\n\\mingw64\\bin;C:\\Program Files\\Git\\usr\\bin;D:\\Softwares\\apache-ant-1.10.2\\bin;C:\\Users\\Lenovo\\AppData\\Local\\Microsoft\\WindowsApps;C:\\Users\\Lenovo\\AppData\\Local\\atom\\bin;%USERPROFILE%\\\nAppData\\Local\\Microsoft\\WindowsApps;;.]\n2018-03-11 21:30:41.574 INFO 2356 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext\n2018-03-11 21:30:41.589 INFO 2356 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 4239 ms\n2018-03-11 21:30:42.131 INFO 2356 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]\n2018-03-11 21:30:42.146 INFO 2356 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]\n2018-03-11 21:30:42.146 INFO 2356 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]\n2018-03-11 21:30:42.146 INFO 2356 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]\n2018-03-11 21:30:42.146 INFO 2356 --- [ost-startStop-1] .s.DelegatingFilterProxyRegistrationBean : Mapping filter: 'springSecurityFilterChain' to: [/*]\n2018-03-11 21:30:42.146 INFO 2356 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/]\n2018-03-11 21:30:43.193 INFO 2356 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.web.servlet.context.Annota\ntionConfigServletWebServerApplicationContext@563670cc: startup date [Sun Mar 11 21:30:37 IST 2018]; root of context hierarchy\n2018-03-11 21:30:43.397 INFO 2356 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped \"{[/hello]}\" onto public java.lang.String com.onlinetutorialspoint.HelloCon\ntroller.sayHello()\n2018-03-11 21:30:43.428 INFO 2356 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped \"{[/error]}\" onto public org.springframework.http.ResponseEntity<java.util.\nMap<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)\n2018-03-11 21:30:43.428 INFO 2356 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped \"{[/error],produces=[text/html]}\" onto public org.springframework.web.servl\net.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)\n2018-03-11 21:30:43.522 INFO 2356 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.\nservlet.resource.ResourceHttpRequestHandler]\n2018-03-11 21:30:43.522 INFO 2356 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.\nresource.ResourceHttpRequestHandler]\n2018-03-11 21:30:43.647 INFO 2356 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.\nweb.servlet.resource.ResourceHttpRequestHandler]\n2018-03-11 21:30:44.287 INFO 2356 --- [ main] .s.s.UserDetailsServiceAutoConfiguration :\n\nUsing generated security password: ef4512ac-aebc-40f8-b589-37cd3b1fc460\n\n2018-03-11 21:30:44.853 INFO 2356 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: org.springframework.security.web.util.matcher.AnyRequestMat\ncher@1, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@203364d6, org.springframework.security.web.context.SecurityContextPersistenceFilter@6\nf53f03a, org.springframework.security.web.header.HeaderWriterFilter@7e765142, org.springframework.security.web.csrf.CsrfFilter@396c3d2f, org.springframework.security.web.authenticati\non.logout.LogoutFilter@4e980e94, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@12e2d748, org.springframework.security.web.authentication.ui.Def\naultLoginPageGeneratingFilter@28c3e342, org.springframework.security.web.authentication.www.BasicAuthenticationFilter@aaeec51, org.springframework.security.web.savedrequest.RequestCa\ncheAwareFilter@7c7fca3e, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@6d51bf8a, org.springframework.security.web.authentication.AnonymousAuthen\nticationFilter@5f832ac6, org.springframework.security.web.session.SessionManagementFilter@6250c19a, org.springframework.security.web.access.ExceptionTranslationFilter@6835f9de, org.s\npringframework.security.web.access.intercept.FilterSecurityInterceptor@24b65d7d]\n2018-03-11 21:30:45.119 INFO 2356 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup\n2018-03-11 21:30:45.353 INFO 2356 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''\n2018-03-11 21:30:45.353 INFO 2356 --- [ main] com.onlinetutorialspoint.Application : Started Application in 9.346 seconds (JVM running for 26.637)\n" }, { "code": null, "e": 10896, "s": 10767, "text": "On the above console output, we can see the default authentication password. We can use this password to access the application." }, { "code": null, "e": 10913, "s": 10896, "text": "User Name : user" }, { "code": null, "e": 10961, "s": 10913, "text": "Password : ef4512ac-aebc-40f8-b589-37cd3b1fc460" }, { "code": null, "e": 11085, "s": 10961, "text": "The above password is only for one time, for each time while running the applicaiton, we should get the different password." }, { "code": null, "e": 11102, "s": 11085, "text": "Happy Learning 🙂" }, { "code": null, "e": 11785, "s": 11102, "text": "\nHow to use Spring Boot Random Port\nSpring Boot How to change the Tomcat to Jetty Server\nSpring Boot In Memory Basic Authentication Security\nHow to set Spring Boot SetTimeZone\nHow to Create own Spring Boot Error Page\nSpring Boot Environment Properties reading based on activeprofile\nHow to change Spring Boot Tomcat Port Number\nHow To Change Spring Boot Context Path\nMicroServices Spring Boot Eureka Server Example\nHow to Get All Spring Beans Details Loaded in ICO\nSpring Boot Apache ActiveMq In Memory Example\nHow to set Spring boot favicon image\nSpring Boot Security MySQL Database Integration Example\nSpring Boot MongoDB + Spring Data Example\nSpring Boot JPA Integration Example\n" }, { "code": null, "e": 11820, "s": 11785, "text": "How to use Spring Boot Random Port" }, { "code": null, "e": 11873, "s": 11820, "text": "Spring Boot How to change the Tomcat to Jetty Server" }, { "code": null, "e": 11925, "s": 11873, "text": "Spring Boot In Memory Basic Authentication Security" }, { "code": null, "e": 11960, "s": 11925, "text": "How to set Spring Boot SetTimeZone" }, { "code": null, "e": 12001, "s": 11960, "text": "How to Create own Spring Boot Error Page" }, { "code": null, "e": 12067, "s": 12001, "text": "Spring Boot Environment Properties reading based on activeprofile" }, { "code": null, "e": 12112, "s": 12067, "text": "How to change Spring Boot Tomcat Port Number" }, { "code": null, "e": 12151, "s": 12112, "text": "How To Change Spring Boot Context Path" }, { "code": null, "e": 12199, "s": 12151, "text": "MicroServices Spring Boot Eureka Server Example" }, { "code": null, "e": 12249, "s": 12199, "text": "How to Get All Spring Beans Details Loaded in ICO" }, { "code": null, "e": 12295, "s": 12249, "text": "Spring Boot Apache ActiveMq In Memory Example" }, { "code": null, "e": 12332, "s": 12295, "text": "How to set Spring boot favicon image" }, { "code": null, "e": 12388, "s": 12332, "text": "Spring Boot Security MySQL Database Integration Example" }, { "code": null, "e": 12430, "s": 12388, "text": "Spring Boot MongoDB + Spring Data Example" }, { "code": null, "e": 12466, "s": 12430, "text": "Spring Boot JPA Integration Example" }, { "code": null, "e": 12472, "s": 12470, "text": "Δ" }, { "code": null, "e": 12499, "s": 12472, "text": " Spring Boot – Hello World" }, { "code": null, "e": 12526, "s": 12499, "text": " Spring Boot – MVC Example" }, { "code": null, "e": 12560, "s": 12526, "text": " Spring Boot- Change Context Path" }, { "code": null, "e": 12601, "s": 12560, "text": " Spring Boot – Change Tomcat Port Number" }, { "code": null, "e": 12646, "s": 12601, "text": " Spring Boot – Change Tomcat to Jetty Server" }, { "code": null, "e": 12684, "s": 12646, "text": " Spring Boot – Tomcat session timeout" }, { "code": null, "e": 12718, "s": 12684, "text": " Spring Boot – Enable Random Port" }, { "code": null, "e": 12749, "s": 12718, "text": " Spring Boot – Properties File" }, { "code": null, "e": 12783, "s": 12749, "text": " Spring Boot – Beans Lazy Loading" }, { "code": null, "e": 12816, "s": 12783, "text": " Spring Boot – Set Favicon image" }, { "code": null, "e": 12849, "s": 12816, "text": " Spring Boot – Set Custom Banner" }, { "code": null, "e": 12889, "s": 12849, "text": " Spring Boot – Set Application TimeZone" }, { "code": null, "e": 12914, "s": 12889, "text": " Spring Boot – Send Mail" }, { "code": null, "e": 12945, "s": 12914, "text": " Spring Boot – FileUpload Ajax" }, { "code": null, "e": 12969, "s": 12945, "text": " Spring Boot – Actuator" }, { "code": null, "e": 13015, "s": 12969, "text": " Spring Boot – Actuator Database Health Check" }, { "code": null, "e": 13038, "s": 13015, "text": " Spring Boot – Swagger" }, { "code": null, "e": 13065, "s": 13038, "text": " Spring Boot – Enable CORS" }, { "code": null, "e": 13111, "s": 13065, "text": " Spring Boot – External Apache ActiveMQ Setup" }, { "code": null, "e": 13151, "s": 13111, "text": " Spring Boot – Inmemory Apache ActiveMq" }, { "code": null, "e": 13180, "s": 13151, "text": " Spring Boot – Scheduler Job" }, { "code": null, "e": 13214, "s": 13180, "text": " Spring Boot – Exception Handling" }, { "code": null, "e": 13244, "s": 13214, "text": " Spring Boot – Hibernate CRUD" }, { "code": null, "e": 13280, "s": 13244, "text": " Spring Boot – JPA Integration CRUD" }, { "code": null, "e": 13313, "s": 13280, "text": " Spring Boot – JPA DataRest CRUD" }, { "code": null, "e": 13346, "s": 13313, "text": " Spring Boot – JdbcTemplate CRUD" }, { "code": null, "e": 13390, "s": 13346, "text": " Spring Boot – Multiple Data Sources Config" }, { "code": null, "e": 13424, "s": 13390, "text": " Spring Boot – JNDI Configuration" }, { "code": null, "e": 13456, "s": 13424, "text": " Spring Boot – H2 Database CRUD" }, { "code": null, "e": 13484, "s": 13456, "text": " Spring Boot – MongoDB CRUD" }, { "code": null, "e": 13515, "s": 13484, "text": " Spring Boot – Redis Data CRUD" }, { "code": null, "e": 13556, "s": 13515, "text": " Spring Boot – MVC Login Form Validation" }, { "code": null, "e": 13590, "s": 13556, "text": " Spring Boot – Custom Error Pages" }, { "code": null, "e": 13615, "s": 13590, "text": " Spring Boot – iText PDF" }, { "code": null, "e": 13649, "s": 13615, "text": " Spring Boot – Enable SSL (HTTPs)" }, { "code": null, "e": 13685, "s": 13649, "text": " Spring Boot – Basic Authentication" }, { "code": null, "e": 13731, "s": 13685, "text": " Spring Boot – In Memory Basic Authentication" }, { "code": null, "e": 13782, "s": 13731, "text": " Spring Boot – Security MySQL Database Integration" }, { "code": null, "e": 13824, "s": 13782, "text": " Spring Boot – Redis Cache – Redis Server" }, { "code": null, "e": 13855, "s": 13824, "text": " Spring Boot – Hazelcast Cache" }, { "code": null, "e": 13878, "s": 13855, "text": " Spring Boot – EhCache" }, { "code": null, "e": 13908, "s": 13878, "text": " Spring Boot – Kafka Producer" }, { "code": null, "e": 13938, "s": 13908, "text": " Spring Boot – Kafka Consumer" }, { "code": null, "e": 13987, "s": 13938, "text": " Spring Boot – Kafka JSON Message to Kafka Topic" }, { "code": null, "e": 14021, "s": 13987, "text": " Spring Boot – RabbitMQ Publisher" }, { "code": null, "e": 14054, "s": 14021, "text": " Spring Boot – RabbitMQ Consumer" }, { "code": null, "e": 14083, "s": 14054, "text": " Spring Boot – SOAP Consumer" }, { "code": null, "e": 14115, "s": 14083, "text": " Spring Boot – Soap WebServices" }, { "code": null, "e": 14152, "s": 14115, "text": " Spring Boot – Batch Csv to Database" }, { "code": null, "e": 14181, "s": 14152, "text": " Spring Boot – Eureka Server" }, { "code": null, "e": 14210, "s": 14181, "text": " Spring Boot – MockMvc JUnit" } ]
How regular expression anchors work in Python?
Anchors are regex tokens that don't match any characters but that say or assert something about the string or the matching process. Anchors inform us that the engine's current position in the string matches a determined location: for example, the beginning of the string/line, or the end of a string/line. This type of assertion is useful for many reasons. First, it lets you specify that you want to match alphabets/digits at the beginning/end of a string/line, but not anywhere else. Second, when you tell the engine that you want to find a pattern at a certain location, it need not find that pattern at any other locations. This is why it is recommended to use anchors whenever possible. ^ and $ are two examples of anchor tokens in regex. The following code shows the use of anchors ^ and $ import re s = 'Princess Diana was a beauty icon' result = re.search(r'^\w+', s) print result.group() result2 = re.search(r'\w+$', s) print result2.group() This gives the output Princess icon
[ { "code": null, "e": 1368, "s": 1062, "text": "Anchors are regex tokens that don't match any characters but that say or assert something about the string or the matching process. Anchors inform us that the engine's current position in the string matches a determined location: for example, the beginning of the string/line, or the end of a string/line." }, { "code": null, "e": 1757, "s": 1368, "text": "This type of assertion is useful for many reasons. First, it lets you specify that you want to match alphabets/digits at the beginning/end of a string/line, but not anywhere else. Second, when you tell the engine that you want to find a pattern at a certain location, it need not find that pattern at any other locations. This is why it is recommended to use anchors whenever possible." }, { "code": null, "e": 1810, "s": 1757, "text": "^ and $ are two examples of anchor tokens in regex." }, { "code": null, "e": 1862, "s": 1810, "text": "The following code shows the use of anchors ^ and $" }, { "code": null, "e": 2017, "s": 1862, "text": "import re\ns = 'Princess Diana was a beauty icon'\nresult = re.search(r'^\\w+', s)\nprint result.group()\nresult2 = re.search(r'\\w+$', s)\nprint result2.group()" }, { "code": null, "e": 2039, "s": 2017, "text": "This gives the output" }, { "code": null, "e": 2053, "s": 2039, "text": "Princess\nicon" } ]
How to use Android ViewPager?
Before getting into the example, we should know what is view pager in android. View pager found in Support Library in Android, using view pager we can switch the fragments. This example demonstrates how to use android view pager. 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 in build.gradle. apply plugin: 'com.android.application' android { compileSdkVersion 28 defaultConfig { applicationId "com.example.andy.myapplication" minSdkVersion 19 targetSdkVersion 28 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.android.support:appcompat-v7:28.0.0' implementation 'com.android.support:design:28.0.0' implementation 'com.android.support.constraint:constraint-layout:1.1.3' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' } Step 3 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <android.support.design.widget.CoordinatorLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:app = "http://schemas.android.com/apk/res-auto" android:layout_width = "match_parent" android:layout_height = "match_parent"> <android.support.design.widget.AppBarLayout android:layout_width = "match_parent" android:layout_height = "wrap_content" android:theme = "@style/ThemeOverlay.AppCompat.Dark.ActionBar"> <android.support.v7.widget.Toolbar android:id = "@+id/toolbar" android:layout_width = "match_parent" android:layout_height = "?attr/actionBarSize" android:background = "?attr/colorPrimary" app:layout_scrollFlags = "scroll|enterAlways" app:popupTheme = "@style/ThemeOverlay.AppCompat.Light" /> <android.support.design.widget.TabLayout android:id = "@+id/tabs" android:layout_width = "match_parent" android:layout_height = "wrap_content" app:tabMode = "fixed" app:tabGravity = "fill"/> </android.support.design.widget.AppBarLayout> <android.support.v4.view.ViewPager android:id = "@+id/viewpager" android:layout_width = "match_parent" android:layout_height = "match_parent" app:layout_behavior = "@string/appbar_scrolling_view_behavior" /> </android.support.design.widget.CoordinatorLayout> Step 4 − Add the following code to src/MainActivity.java package com.example.andy.myapplication; import android.annotation.TargetApi; import android.os.Build; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private ViewPager viewPager; private Toolbar toolbar; private TabLayout tabLayout; @TargetApi(Build.VERSION_CODES.O) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); tabLayout = findViewById(R.id.tabs); viewPager = findViewById(R.id.viewpager); ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager()); adapter.addFragment(new OneFragment(), "ONE"); adapter.addFragment(new TwoFragment(), "TWO"); viewPager.setAdapter(adapter); tabLayout.setupWithViewPager(viewPager); } class ViewPagerAdapter extends FragmentPagerAdapter { private final List<Fragment> mList = new ArrayList<>(); private final List<String> mTitleList = new ArrayList<>(); public ViewPagerAdapter(FragmentManager supportFragmentManager) { super(supportFragmentManager); } @Override public Fragment getItem(int i) { return mList.get(i); } @Override public int getCount() { return mList.size(); } public void addFragment(Fragment fragment, String title) { mList.add(fragment); mTitleList.add(title); } @Override public CharSequence getPageTitle(int position) { return mTitleList.get(position); } } } Step 5 − Add the following code to src/OneFragment.java package com.example.andy.myapplication; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class OneFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){ View v= inflater.inflate(R.layout.fragment_one, container, false); TextView textView=v.findViewById(R.id.text); textView.setText("First Fragment"); return v; } } Step 6 − Add the following code to src/TwoFragment.java package com.example.andy.myapplication; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class TwoFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){ View v= inflater.inflate(R.layout.fragment_one, container, false); TextView textView=v.findViewById(R.id.text); textView.setText("Second Fragment"); return v; } } Step 7 − Add the following code to res/layout/fragment_one.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/text" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:textSize="20sp" /> </LinearLayout> Step 8 − Add the following code to styles.xml. <resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> <!-- Customize your theme here. --> <item name = "windowNoTitle">true</item> <item name = "windowActionBar">false</item> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style> </resources> 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": 1235, "s": 1062, "text": "Before getting into the example, we should know what is view pager in android. View pager found in Support Library in Android, using view pager we can switch the fragments." }, { "code": null, "e": 1292, "s": 1235, "text": "This example demonstrates how to use android view pager." }, { "code": null, "e": 1421, "s": 1292, "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": 1470, "s": 1421, "text": "Step 2 − Add the following code in build.gradle." }, { "code": null, "e": 2424, "s": 1470, "text": "apply plugin: 'com.android.application'\nandroid {\n compileSdkVersion 28\n defaultConfig {\n applicationId \"com.example.andy.myapplication\"\n minSdkVersion 19\n targetSdkVersion 28\n versionCode 1\n versionName \"1.0\"\n testInstrumentationRunner \"android.support.test.runner.AndroidJUnitRunner\"\n }\n buildTypes {\n release {\n minifyEnabled false\n proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\n }\n }\n}\ndependencies {\n implementation fileTree(dir: 'libs', include: ['*.jar'])\n implementation 'com.android.support:appcompat-v7:28.0.0'\n implementation 'com.android.support:design:28.0.0'\n implementation 'com.android.support.constraint:constraint-layout:1.1.3'\n testImplementation 'junit:junit:4.12'\n androidTestImplementation 'com.android.support.test:runner:1.0.2'\n androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'\n}" }, { "code": null, "e": 2489, "s": 2424, "text": "Step 3 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 3922, "s": 2489, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<android.support.design.widget.CoordinatorLayout\n xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\">\n <android.support.design.widget.AppBarLayout\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:theme = \"@style/ThemeOverlay.AppCompat.Dark.ActionBar\">\n <android.support.v7.widget.Toolbar\n android:id = \"@+id/toolbar\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"?attr/actionBarSize\"\n android:background = \"?attr/colorPrimary\"\n app:layout_scrollFlags = \"scroll|enterAlways\"\n app:popupTheme = \"@style/ThemeOverlay.AppCompat.Light\" />\n <android.support.design.widget.TabLayout\n android:id = \"@+id/tabs\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n app:tabMode = \"fixed\"\n app:tabGravity = \"fill\"/>\n </android.support.design.widget.AppBarLayout>\n <android.support.v4.view.ViewPager\n android:id = \"@+id/viewpager\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n app:layout_behavior = \"@string/appbar_scrolling_view_behavior\" />\n</android.support.design.widget.CoordinatorLayout>" }, { "code": null, "e": 3979, "s": 3922, "text": "Step 4 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 6083, "s": 3979, "text": "package com.example.andy.myapplication;\nimport android.annotation.TargetApi;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.design.widget.TabLayout;\nimport android.support.v4.app.Fragment;\nimport android.support.v4.app.FragmentManager;\nimport android.support.v4.app.FragmentPagerAdapter;\nimport android.support.v4.view.ViewPager;\nimport android.support.v7.app.AppCompatActivity;\nimport android.support.v7.widget.Toolbar;\nimport java.util.ArrayList;\nimport java.util.List;\npublic class MainActivity extends AppCompatActivity {\n private ViewPager viewPager;\n private Toolbar toolbar;\n private TabLayout tabLayout;\n @TargetApi(Build.VERSION_CODES.O)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n toolbar = (Toolbar) findViewById(R.id.toolbar);\n setSupportActionBar(toolbar);\n getSupportActionBar().setDisplayHomeAsUpEnabled(true);\n tabLayout = findViewById(R.id.tabs);\n viewPager = findViewById(R.id.viewpager);\n ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());\n adapter.addFragment(new OneFragment(), \"ONE\");\n adapter.addFragment(new TwoFragment(), \"TWO\");\n viewPager.setAdapter(adapter);\n tabLayout.setupWithViewPager(viewPager);\n }\n class ViewPagerAdapter extends FragmentPagerAdapter {\n private final List<Fragment> mList = new ArrayList<>();\n private final List<String> mTitleList = new ArrayList<>();\n public ViewPagerAdapter(FragmentManager supportFragmentManager) {\n super(supportFragmentManager);\n }\n @Override\n public Fragment getItem(int i) {\n return mList.get(i);\n }\n @Override\n public int getCount() {\n return mList.size();\n }\n public void addFragment(Fragment fragment, String title) {\n mList.add(fragment);\n mTitleList.add(title);\n }\n @Override\n public CharSequence getPageTitle(int position) {\n return mTitleList.get(position);\n }\n }\n}" }, { "code": null, "e": 6139, "s": 6083, "text": "Step 5 − Add the following code to src/OneFragment.java" }, { "code": null, "e": 6718, "s": 6139, "text": "package com.example.andy.myapplication;\nimport android.os.Bundle;\nimport android.support.v4.app.Fragment;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.TextView;\npublic class OneFragment extends Fragment {\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){\n View v= inflater.inflate(R.layout.fragment_one, container, false);\n TextView textView=v.findViewById(R.id.text);\n textView.setText(\"First Fragment\");\n return v;\n }\n}" }, { "code": null, "e": 6774, "s": 6718, "text": "Step 6 − Add the following code to src/TwoFragment.java" }, { "code": null, "e": 7354, "s": 6774, "text": "package com.example.andy.myapplication;\nimport android.os.Bundle;\nimport android.support.v4.app.Fragment;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.TextView;\npublic class TwoFragment extends Fragment {\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){\n View v= inflater.inflate(R.layout.fragment_one, container, false);\n TextView textView=v.findViewById(R.id.text);\n textView.setText(\"Second Fragment\");\n return v;\n }\n}" }, { "code": null, "e": 7418, "s": 7354, "text": "Step 7 − Add the following code to res/layout/fragment_one.xml." }, { "code": null, "e": 7793, "s": 7418, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout\nxmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\"\nandroid:layout_height=\"match_parent\">\n<TextView\n android:id=\"@+id/text\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:gravity=\"center\"\n android:textSize=\"20sp\"\n/>\n</LinearLayout>" }, { "code": null, "e": 7840, "s": 7793, "text": "Step 8 − Add the following code to styles.xml." }, { "code": null, "e": 8307, "s": 7840, "text": "<resources>\n <!-- Base application theme. -->\n <style name=\"AppTheme\" parent=\"Theme.AppCompat.Light.DarkActionBar\">\n <!-- Customize your theme here. -->\n <item name = \"windowNoTitle\">true</item>\n <item name = \"windowActionBar\">false</item>\n <item name=\"colorPrimary\">@color/colorPrimary</item>\n <item name=\"colorPrimaryDark\">@color/colorPrimaryDark</item>\n <item name=\"colorAccent\">@color/colorAccent</item>\n </style>\n</resources>" }, { "code": null, "e": 8654, "s": 8307, "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": 8696, "s": 8656, "text": "Click here to download the project code" } ]
Remove duplicates from a List in C#
Use the Distinct() method to remove duplicates from a list in C#. Firstly, add a new list − List<int> arr1 = new List<int>(); arr1.Add(10); arr1.Add(20); arr1.Add(30); arr1.Add(40); arr1.Add(50); arr1.Add(30); arr1.Add(40); arr1.Add(50); To remove duplicate elements, use the Distinct() method as shown below − List<int> distinct = arr1.Distinct().ToList(); Here is the complete code − Live Demo using System; using System.Collections.Generic; using System.Linq; public class Demo { public static void Main() { List<int> arr1 = new List<int>(); arr1.Add(10); arr1.Add(20); arr1.Add(30); arr1.Add(40); arr1.Add(50); arr1.Add(30); arr1.Add(40); arr1.Add(50); Console.WriteLine("Initial List ..."); foreach (int i in arr1) { Console.WriteLine(i); } // Removing duplicate elements List<int> distinct = arr1.Distinct().ToList(); Console.WriteLine("List after removing duplicate elements ..."); foreach (int res in distinct) { Console.WriteLine("{0}", res); } } } Initial List ... 10 20 30 40 50 30 40 50 List after removing duplicate elements ... 10 20 30 40 50
[ { "code": null, "e": 1128, "s": 1062, "text": "Use the Distinct() method to remove duplicates from a list in C#." }, { "code": null, "e": 1154, "s": 1128, "text": "Firstly, add a new list −" }, { "code": null, "e": 1300, "s": 1154, "text": "List<int> arr1 = new List<int>();\narr1.Add(10);\narr1.Add(20);\narr1.Add(30);\narr1.Add(40);\narr1.Add(50);\narr1.Add(30);\narr1.Add(40);\narr1.Add(50);" }, { "code": null, "e": 1373, "s": 1300, "text": "To remove duplicate elements, use the Distinct() method as shown below −" }, { "code": null, "e": 1420, "s": 1373, "text": "List<int> distinct = arr1.Distinct().ToList();" }, { "code": null, "e": 1448, "s": 1420, "text": "Here is the complete code −" }, { "code": null, "e": 1459, "s": 1448, "text": " Live Demo" }, { "code": null, "e": 2147, "s": 1459, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\npublic class Demo {\n public static void Main() {\n List<int> arr1 = new List<int>();\n arr1.Add(10);\n arr1.Add(20);\n arr1.Add(30);\n arr1.Add(40);\n arr1.Add(50);\n arr1.Add(30);\n arr1.Add(40);\n arr1.Add(50);\n Console.WriteLine(\"Initial List ...\");\n foreach (int i in arr1) {\n Console.WriteLine(i);\n }\n // Removing duplicate elements\n List<int> distinct = arr1.Distinct().ToList();\n Console.WriteLine(\"List after removing duplicate elements ...\");\n foreach (int res in distinct) {\n Console.WriteLine(\"{0}\", res);\n }\n }\n}" }, { "code": null, "e": 2246, "s": 2147, "text": "Initial List ...\n10\n20\n30\n40\n50\n30\n40\n50\nList after removing duplicate elements ...\n10\n20\n30\n40\n50" } ]
How to show/hide dropdown menu on mouse hover using CSS ?
06 Jun, 2022 The approach of this article is to show and hide the dropdown menu on mouse hover using CSS. The task can be done by using the display property and :hover selector. Example: HTML <!DOCTYPE html><html lang="en"><head> <title> How to Show Hide Dropdown Using CSS </title> <style> ul { padding: 0; list-style: none; background: #f2f2f2; width: 500px; } ul li { display: block; position: relative; line-height: 21px; text-align: left; } ul li a { display: block; padding: 8px 25px; color: #333; text-decoration: none; } ul li a:hover { color: #fff; background: #939393; } ul li ul.dropdown { min-width: 100%; /* Set width of the dropdown */ background: #f2f2f2; display: none; position: absolute; z-index: 999; left: 0; } ul li:hover ul.dropdown { display: block; /* Display the dropdown */ } </style></head> <body> <h1> GeeksForGeeks </h1> <h2> How to show and hide dropdown menu on mouse hover using CSS? </h2> <ul> <li> <a href="#">Programming languages</a> <ul class="dropdown"> <li><a href="#">C++</a></li> <li><a href="#">JAVA</a></li> <li><a href="#">PHP</a></li> </ul> </li> </ul> </body> </html> Output: Supported Browsers are listed below: Google Chrome Internet Explorer Firefox Opera Safari HTML is the foundation of web pages and is used for webpage development by structuring websites and web apps. You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples. CSS is the foundation of web pages and is used for webpage development by styling websites and web apps. You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples. sanjyotpanure CSS-Misc HTML-Misc CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Jun, 2022" }, { "code": null, "e": 193, "s": 28, "text": "The approach of this article is to show and hide the dropdown menu on mouse hover using CSS. The task can be done by using the display property and :hover selector." }, { "code": null, "e": 204, "s": 193, "text": "Example: " }, { "code": null, "e": 209, "s": 204, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <title> How to Show Hide Dropdown Using CSS </title> <style> ul { padding: 0; list-style: none; background: #f2f2f2; width: 500px; } ul li { display: block; position: relative; line-height: 21px; text-align: left; } ul li a { display: block; padding: 8px 25px; color: #333; text-decoration: none; } ul li a:hover { color: #fff; background: #939393; } ul li ul.dropdown { min-width: 100%; /* Set width of the dropdown */ background: #f2f2f2; display: none; position: absolute; z-index: 999; left: 0; } ul li:hover ul.dropdown { display: block; /* Display the dropdown */ } </style></head> <body> <h1> GeeksForGeeks </h1> <h2> How to show and hide dropdown menu on mouse hover using CSS? </h2> <ul> <li> <a href=\"#\">Programming languages</a> <ul class=\"dropdown\"> <li><a href=\"#\">C++</a></li> <li><a href=\"#\">JAVA</a></li> <li><a href=\"#\">PHP</a></li> </ul> </li> </ul> </body> </html>", "e": 1622, "s": 209, "text": null }, { "code": null, "e": 1630, "s": 1622, "text": "Output:" }, { "code": null, "e": 1669, "s": 1632, "text": "Supported Browsers are listed below:" }, { "code": null, "e": 1683, "s": 1669, "text": "Google Chrome" }, { "code": null, "e": 1701, "s": 1683, "text": "Internet Explorer" }, { "code": null, "e": 1709, "s": 1701, "text": "Firefox" }, { "code": null, "e": 1715, "s": 1709, "text": "Opera" }, { "code": null, "e": 1722, "s": 1715, "text": "Safari" }, { "code": null, "e": 1921, "s": 1722, "text": "HTML is the foundation of web pages and is used for webpage development by structuring websites and web apps. You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples." }, { "code": null, "e": 2112, "s": 1921, "text": "CSS is the foundation of web pages and is used for webpage development by styling websites and web apps. You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples." }, { "code": null, "e": 2126, "s": 2112, "text": "sanjyotpanure" }, { "code": null, "e": 2135, "s": 2126, "text": "CSS-Misc" }, { "code": null, "e": 2145, "s": 2135, "text": "HTML-Misc" }, { "code": null, "e": 2149, "s": 2145, "text": "CSS" }, { "code": null, "e": 2154, "s": 2149, "text": "HTML" }, { "code": null, "e": 2171, "s": 2154, "text": "Web Technologies" }, { "code": null, "e": 2176, "s": 2171, "text": "HTML" } ]
Finding the maximum square sub-matrix with all equal elements
13 Jul, 2022 Given a N x N matrix, determine the maximum K such that K x K is a submatrix with all equal elements i.e., all the elements in this submatrix must be same. Constraints: 1 <= N <= 1000 0 <= Ai , j <= 109 Examples: Input : a[][] = {{2, 3, 3}, {2, 3, 3}, {2, 2, 2}} Output : 2 Explanation: A 2x2 matrix is formed from index A0,1 to A1,2 Input : a[][] = {{9, 9, 9, 8}, {9, 9, 9, 6}, {9, 9, 9, 3}, {2, 2, 2, 2} Output : 3 Explanation : A 3x3 matrix is formed from index A0,0 to A2,2 Method I ( Naive approach ):We can easily find all the square submatrices in O(n3) time and check whether each submatrix contains equal elements or not in O(n2) time Which makes the total running time of the algorithm as O(n5). Method II ( Dynamic Programming ):For each cell (i, j), we store the largest value of K such that K x K is a submatrix with all equal elements and position of (i, j) being the bottom-right most element.And DPi,j depends upon {DPi-1, j, DPi, j-1, DPi-1, j-1} If Ai, j is equal to {Ai-1, j, Ai, j-1, Ai-1, j-1}, all the three values: DPi, j = min(DPi-1, j, DPi, j-1, DPi-1, j-1) + 1 Else DPi, j = 1 // Matrix Size 1 The answer would be the maximum of all DPi, j's Below is the implementation of above steps. C++ Java C# Python 3 PHP Javascript // C++ program to find maximum K such that K x K// is a submatrix with equal elements.#include<bits/stdc++.h>#define Row 6#define Col 6using namespace std; // Returns size of the largest square sub-matrix// with all same elements.int largestKSubmatrix(int a[][Col]){ int dp[Row][Col]; memset(dp, sizeof(dp), 0); int result = 0; for (int i = 0 ; i < Row ; i++) { for (int j = 0 ; j < Col ; j++) { // If elements is at top row or first // column, it wont form a square // matrix's bottom-right if (i == 0 || j == 0) dp[i][j] = 1; else { // Check if adjacent elements are equal if (a[i][j] == a[i-1][j] && a[i][j] == a[i][j-1] && a[i][j] == a[i-1][j-1] ) dp[i][j] = min(min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1] ) + 1; // If not equal, then it will form a 1x1 // submatrix else dp[i][j] = 1; } // Update result at each (i,j) result = max(result, dp[i][j]); } } return result;} // Driven Programint main(){ int a[Row][Col] = { 2, 2, 3, 3, 4, 4, 5, 5, 7, 7, 7, 4, 1, 2, 7, 7, 7, 4, 4, 4, 7, 7, 7, 4, 5, 5, 5, 1, 2, 7, 8, 7, 9, 4, 4, 4 }; cout << largestKSubmatrix(a) << endl; return 0;} // Java program to find maximum// K such that K x K is a// submatrix with equal elements.class GFG{ static int Row = 6, Col = 6; // Returns size of the largest // square sub-matrix with // all same elements. static int largestKSubmatrix(int [][]a) { int [][]dp = new int [Row][Col]; int result = 0; for (int i = 0 ; i < Row ; i++) { for (int j = 0 ; j < Col ; j++) { // If elements is at top // row or first column, // it wont form a square // matrix's bottom-right if (i == 0 || j == 0) dp[i][j] = 1; else { // Check if adjacent // elements are equal if (a[i][j] == a[i - 1][j] && a[i][j] == a[i][j - 1] && a[i][j] == a[i - 1][j - 1]) { dp[i][j] = (dp[i - 1][j] > dp[i][j - 1] && dp[i - 1][j] > dp[i - 1][j - 1] + 1) ? dp[i - 1][j] : (dp[i][j - 1] > dp[i - 1][j] && dp[i][j - 1] > dp[i - 1][j - 1] + 1) ? dp[i][j - 1] : dp[i - 1][j - 1] + 1; } // If not equal, then it // will form a 1x1 submatrix else dp[i][j] = 1; } // Update result at each (i,j) result = result > dp[i][j] ? result : dp[i][j]; } } return result; } // Driver code public static void main(String[] args) { int [][]a = {{2, 2, 3, 3, 4, 4}, {5, 5, 7, 7, 7, 4}, {1, 2, 7, 7, 7, 4}, {4, 4, 7, 7, 7, 4}, {5, 5, 5, 1, 2, 7}, {8, 7, 9, 4, 4, 4}}; System.out.println(largestKSubmatrix(a)); }} // This code is contributed// by ChitraNayal // C# program to find maximum// K such that K x K is a// submatrix with equal elements.using System; class GFG{ static int Row = 6, Col = 6; // Returns size of the // largest square sub-matrix // with all same elements. static int largestKSubmatrix(int[,] a) { int[,] dp = new int [Row, Col]; int result = 0; for (int i = 0 ; i < Row ; i++) { for (int j = 0 ; j < Col ; j++) { // If elements is at top // row or first column, // it wont form a square // matrix's bottom-right if (i == 0 || j == 0) dp[i, j] = 1; else { // Check if adjacent // elements are equal if (a[i, j] == a[i - 1, j] && a[i, j] == a[i, j - 1] && a[i, j] == a[i - 1, j - 1]) { dp[i, j] = (dp[i - 1, j] > dp[i, j - 1] && dp[i - 1, j] > dp[i - 1, j - 1] + 1) ? dp[i - 1, j] : (dp[i, j - 1] > dp[i - 1, j] && dp[i, j - 1] > dp[i - 1, j - 1] + 1) ? dp[i, j - 1] : dp[i - 1, j - 1] + 1; } // If not equal, then // it will form a 1x1 // submatrix else dp[i, j] = 1; } // Update result at each (i,j) result = result > dp[i, j] ? result : dp[i, j]; } } return result; } // Driver Code public static void Main() { int[,] a = {{2, 2, 3, 3, 4, 4}, {5, 5, 7, 7, 7, 4}, {1, 2, 7, 7, 7, 4}, {4, 4, 7, 7, 7, 4}, {5, 5, 5, 1, 2, 7}, {8, 7, 9, 4, 4, 4}}; Console.Write(largestKSubmatrix(a)); }} // This code is contributed// by ChitraNayal # Python 3 program to find# maximum K such that K x K# is a submatrix with equal# elements.Row = 6Col = 6 # Returns size of the# largest square sub-matrix# with all same elements.def largestKSubmatrix(a): dp = [[0 for x in range(Row)] for y in range(Col)] result = 0 for i in range(Row ): for j in range(Col): # If elements is at top # row or first column, # it wont form a square # matrix's bottom-right if (i == 0 or j == 0): dp[i][j] = 1 else: # Check if adjacent # elements are equal if (a[i][j] == a[i - 1][j] and a[i][j] == a[i][j - 1] and a[i][j] == a[i - 1][j - 1]): dp[i][j] = min(min(dp[i - 1][j], dp[i][j - 1]), dp[i - 1][j - 1] ) + 1 # If not equal, then # it will form a 1x1 # submatrix else: dp[i][j] = 1 # Update result at each (i,j) result = max(result, dp[i][j]) return result # Driver Codea = [[ 2, 2, 3, 3, 4, 4], [ 5, 5, 7, 7, 7, 4], [ 1, 2, 7, 7, 7, 4], [ 4, 4, 7, 7, 7, 4], [ 5, 5, 5, 1, 2, 7], [ 8, 7, 9, 4, 4, 4]]; print(largestKSubmatrix(a)) # This code is contributed# by ChitraNayal <?php// Java program to find maximum// K such that K x K is a// submatrix with equal elements.$Row = 6;$Col = 6; // Returns size of the largest// square sub-matrix with// all same elements.function largestKSubmatrix(&$a){ global $Row, $Col; $result = 0; for ($i = 0 ; $i < $Row ; $i++) { for ($j = 0 ; $j < $Col ; $j++) { // If elements is at // top row or first // column, it wont form // a square matrix's // bottom-right if ($i == 0 || $j == 0) $dp[$i][$j] = 1; else { // Check if adjacent // elements are equal if ($a[$i][$j] == $a[$i - 1][$j] && $a[$i][$j] == $a[$i][$j - 1] && $a[$i][$j] == $a[$i - 1][$j - 1] ) $dp[$i][$j] = min(min($dp[$i - 1][$j], $dp[$i][$j - 1]), $dp[$i - 1][$j - 1] ) + 1; // If not equal, then it // will form a 1x1 submatrix else $dp[$i][$j] = 1; } // Update result at each (i,j) $result = max($result, $dp[$i][$j]); } } return $result;} // Driver Code$a = array(array(2, 2, 3, 3, 4, 4), array(5, 5, 7, 7, 7, 4), array(1, 2, 7, 7, 7, 4), array(4, 4, 7, 7, 7, 4), array(5, 5, 5, 1, 2, 7), array(8, 7, 9, 4, 4, 4)); echo largestKSubmatrix($a); // This code is contributed// by ChitraNayal?> <script> // Javascript program to find maximum// K such that K x K is a// submatrix with equal elements. let Row = 6, Col = 6; // Returns size of the largest // square sub-matrix with // all same elements. function largestKSubmatrix(a) { let dp = new Array(Row); for(let i = 0; i < Row; i++) { dp[i] = new Array(Col); for(let j = 0; j < Col; j++) { dp[i][j] = 0; } } let result = 0; for (let i = 0 ; i < Row ; i++) { for (let j = 0 ; j < Col ; j++) { // If elements is at top // row or first column, // it wont form a square // matrix's bottom-right if (i == 0 || j == 0) dp[i][j] = 1; else { // Check if adjacent // elements are equal if (a[i][j] == a[i - 1][j] && a[i][j] == a[i][j - 1] && a[i][j] == a[i - 1][j - 1]) { dp[i][j] = (dp[i - 1][j] > dp[i][j - 1] && dp[i - 1][j] > dp[i - 1][j - 1] + 1) ? dp[i - 1][j] : (dp[i][j - 1] > dp[i - 1][j] && dp[i][j - 1] > dp[i - 1][j - 1] + 1) ? dp[i][j - 1] : dp[i - 1][j - 1] + 1; } // If not equal, then it // will form a 1x1 submatrix else dp[i][j] = 1; } // Update result at each (i,j) result = result > dp[i][j] ? result : dp[i][j]; } } return result; } // Driver code let a = [[ 2, 2, 3, 3, 4, 4], [ 5, 5, 7, 7, 7, 4], [ 1, 2, 7, 7, 7, 4], [ 4, 4, 7, 7, 7, 4], [ 5, 5, 5, 1, 2, 7], [ 8, 7, 9, 4, 4, 4]]; document.write(largestKSubmatrix(a)); // This code is contributed by avanitrachhadiya2155</script> 3 Time Complexity : O(Row * Col) Auxiliary Space : O(Row * Col) This article is contributed by Shubham Gupta. 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. ukasp avanitrachhadiya2155 hardikkoriintern Directi Dynamic Programming Matrix Directi Dynamic Programming Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n13 Jul, 2022" }, { "code": null, "e": 211, "s": 54, "text": "Given a N x N matrix, determine the maximum K such that K x K is a submatrix with all equal elements i.e., all the elements in this submatrix must be same. " }, { "code": null, "e": 225, "s": 211, "text": "Constraints: " }, { "code": null, "e": 241, "s": 225, "text": "1 <= N <= 1000 " }, { "code": null, "e": 260, "s": 241, "text": "0 <= Ai , j <= 109" }, { "code": null, "e": 271, "s": 260, "text": "Examples: " }, { "code": null, "e": 628, "s": 271, "text": " \nInput : a[][] = {{2, 3, 3},\n {2, 3, 3},\n {2, 2, 2}}\nOutput : 2\nExplanation: A 2x2 matrix is formed from index\nA0,1 to A1,2\n\nInput : a[][] = {{9, 9, 9, 8},\n {9, 9, 9, 6},\n {9, 9, 9, 3},\n {2, 2, 2, 2}\nOutput : 3\nExplanation : A 3x3 matrix is formed from index\nA0,0 to A2,2" }, { "code": null, "e": 856, "s": 628, "text": "Method I ( Naive approach ):We can easily find all the square submatrices in O(n3) time and check whether each submatrix contains equal elements or not in O(n2) time Which makes the total running time of the algorithm as O(n5)." }, { "code": null, "e": 1114, "s": 856, "text": "Method II ( Dynamic Programming ):For each cell (i, j), we store the largest value of K such that K x K is a submatrix with all equal elements and position of (i, j) being the bottom-right most element.And DPi,j depends upon {DPi-1, j, DPi, j-1, DPi-1, j-1}" }, { "code": null, "e": 1333, "s": 1114, "text": "If Ai, j is equal to {Ai-1, j, Ai, j-1, Ai-1, j-1}, \n all the three values:\n DPi, j = min(DPi-1, j, DPi, j-1, DPi-1, j-1) + 1\nElse\n DPi, j = 1 // Matrix Size 1 \n\nThe answer would be the maximum of all DPi, j's" }, { "code": null, "e": 1379, "s": 1333, "text": "Below is the implementation of above steps. " }, { "code": null, "e": 1383, "s": 1379, "text": "C++" }, { "code": null, "e": 1388, "s": 1383, "text": "Java" }, { "code": null, "e": 1391, "s": 1388, "text": "C#" }, { "code": null, "e": 1400, "s": 1391, "text": "Python 3" }, { "code": null, "e": 1404, "s": 1400, "text": "PHP" }, { "code": null, "e": 1415, "s": 1404, "text": "Javascript" }, { "code": "// C++ program to find maximum K such that K x K// is a submatrix with equal elements.#include<bits/stdc++.h>#define Row 6#define Col 6using namespace std; // Returns size of the largest square sub-matrix// with all same elements.int largestKSubmatrix(int a[][Col]){ int dp[Row][Col]; memset(dp, sizeof(dp), 0); int result = 0; for (int i = 0 ; i < Row ; i++) { for (int j = 0 ; j < Col ; j++) { // If elements is at top row or first // column, it wont form a square // matrix's bottom-right if (i == 0 || j == 0) dp[i][j] = 1; else { // Check if adjacent elements are equal if (a[i][j] == a[i-1][j] && a[i][j] == a[i][j-1] && a[i][j] == a[i-1][j-1] ) dp[i][j] = min(min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1] ) + 1; // If not equal, then it will form a 1x1 // submatrix else dp[i][j] = 1; } // Update result at each (i,j) result = max(result, dp[i][j]); } } return result;} // Driven Programint main(){ int a[Row][Col] = { 2, 2, 3, 3, 4, 4, 5, 5, 7, 7, 7, 4, 1, 2, 7, 7, 7, 4, 4, 4, 7, 7, 7, 4, 5, 5, 5, 1, 2, 7, 8, 7, 9, 4, 4, 4 }; cout << largestKSubmatrix(a) << endl; return 0;}", "e": 2975, "s": 1415, "text": null }, { "code": "// Java program to find maximum// K such that K x K is a// submatrix with equal elements.class GFG{ static int Row = 6, Col = 6; // Returns size of the largest // square sub-matrix with // all same elements. static int largestKSubmatrix(int [][]a) { int [][]dp = new int [Row][Col]; int result = 0; for (int i = 0 ; i < Row ; i++) { for (int j = 0 ; j < Col ; j++) { // If elements is at top // row or first column, // it wont form a square // matrix's bottom-right if (i == 0 || j == 0) dp[i][j] = 1; else { // Check if adjacent // elements are equal if (a[i][j] == a[i - 1][j] && a[i][j] == a[i][j - 1] && a[i][j] == a[i - 1][j - 1]) { dp[i][j] = (dp[i - 1][j] > dp[i][j - 1] && dp[i - 1][j] > dp[i - 1][j - 1] + 1) ? dp[i - 1][j] : (dp[i][j - 1] > dp[i - 1][j] && dp[i][j - 1] > dp[i - 1][j - 1] + 1) ? dp[i][j - 1] : dp[i - 1][j - 1] + 1; } // If not equal, then it // will form a 1x1 submatrix else dp[i][j] = 1; } // Update result at each (i,j) result = result > dp[i][j] ? result : dp[i][j]; } } return result; } // Driver code public static void main(String[] args) { int [][]a = {{2, 2, 3, 3, 4, 4}, {5, 5, 7, 7, 7, 4}, {1, 2, 7, 7, 7, 4}, {4, 4, 7, 7, 7, 4}, {5, 5, 5, 1, 2, 7}, {8, 7, 9, 4, 4, 4}}; System.out.println(largestKSubmatrix(a)); }} // This code is contributed// by ChitraNayal", "e": 5240, "s": 2975, "text": null }, { "code": "// C# program to find maximum// K such that K x K is a// submatrix with equal elements.using System; class GFG{ static int Row = 6, Col = 6; // Returns size of the // largest square sub-matrix // with all same elements. static int largestKSubmatrix(int[,] a) { int[,] dp = new int [Row, Col]; int result = 0; for (int i = 0 ; i < Row ; i++) { for (int j = 0 ; j < Col ; j++) { // If elements is at top // row or first column, // it wont form a square // matrix's bottom-right if (i == 0 || j == 0) dp[i, j] = 1; else { // Check if adjacent // elements are equal if (a[i, j] == a[i - 1, j] && a[i, j] == a[i, j - 1] && a[i, j] == a[i - 1, j - 1]) { dp[i, j] = (dp[i - 1, j] > dp[i, j - 1] && dp[i - 1, j] > dp[i - 1, j - 1] + 1) ? dp[i - 1, j] : (dp[i, j - 1] > dp[i - 1, j] && dp[i, j - 1] > dp[i - 1, j - 1] + 1) ? dp[i, j - 1] : dp[i - 1, j - 1] + 1; } // If not equal, then // it will form a 1x1 // submatrix else dp[i, j] = 1; } // Update result at each (i,j) result = result > dp[i, j] ? result : dp[i, j]; } } return result; } // Driver Code public static void Main() { int[,] a = {{2, 2, 3, 3, 4, 4}, {5, 5, 7, 7, 7, 4}, {1, 2, 7, 7, 7, 4}, {4, 4, 7, 7, 7, 4}, {5, 5, 5, 1, 2, 7}, {8, 7, 9, 4, 4, 4}}; Console.Write(largestKSubmatrix(a)); }} // This code is contributed// by ChitraNayal", "e": 7506, "s": 5240, "text": null }, { "code": "# Python 3 program to find# maximum K such that K x K# is a submatrix with equal# elements.Row = 6Col = 6 # Returns size of the# largest square sub-matrix# with all same elements.def largestKSubmatrix(a): dp = [[0 for x in range(Row)] for y in range(Col)] result = 0 for i in range(Row ): for j in range(Col): # If elements is at top # row or first column, # it wont form a square # matrix's bottom-right if (i == 0 or j == 0): dp[i][j] = 1 else: # Check if adjacent # elements are equal if (a[i][j] == a[i - 1][j] and a[i][j] == a[i][j - 1] and a[i][j] == a[i - 1][j - 1]): dp[i][j] = min(min(dp[i - 1][j], dp[i][j - 1]), dp[i - 1][j - 1] ) + 1 # If not equal, then # it will form a 1x1 # submatrix else: dp[i][j] = 1 # Update result at each (i,j) result = max(result, dp[i][j]) return result # Driver Codea = [[ 2, 2, 3, 3, 4, 4], [ 5, 5, 7, 7, 7, 4], [ 1, 2, 7, 7, 7, 4], [ 4, 4, 7, 7, 7, 4], [ 5, 5, 5, 1, 2, 7], [ 8, 7, 9, 4, 4, 4]]; print(largestKSubmatrix(a)) # This code is contributed# by ChitraNayal", "e": 8996, "s": 7506, "text": null }, { "code": "<?php// Java program to find maximum// K such that K x K is a// submatrix with equal elements.$Row = 6;$Col = 6; // Returns size of the largest// square sub-matrix with// all same elements.function largestKSubmatrix(&$a){ global $Row, $Col; $result = 0; for ($i = 0 ; $i < $Row ; $i++) { for ($j = 0 ; $j < $Col ; $j++) { // If elements is at // top row or first // column, it wont form // a square matrix's // bottom-right if ($i == 0 || $j == 0) $dp[$i][$j] = 1; else { // Check if adjacent // elements are equal if ($a[$i][$j] == $a[$i - 1][$j] && $a[$i][$j] == $a[$i][$j - 1] && $a[$i][$j] == $a[$i - 1][$j - 1] ) $dp[$i][$j] = min(min($dp[$i - 1][$j], $dp[$i][$j - 1]), $dp[$i - 1][$j - 1] ) + 1; // If not equal, then it // will form a 1x1 submatrix else $dp[$i][$j] = 1; } // Update result at each (i,j) $result = max($result, $dp[$i][$j]); } } return $result;} // Driver Code$a = array(array(2, 2, 3, 3, 4, 4), array(5, 5, 7, 7, 7, 4), array(1, 2, 7, 7, 7, 4), array(4, 4, 7, 7, 7, 4), array(5, 5, 5, 1, 2, 7), array(8, 7, 9, 4, 4, 4)); echo largestKSubmatrix($a); // This code is contributed// by ChitraNayal?>", "e": 10620, "s": 8996, "text": null }, { "code": "<script> // Javascript program to find maximum// K such that K x K is a// submatrix with equal elements. let Row = 6, Col = 6; // Returns size of the largest // square sub-matrix with // all same elements. function largestKSubmatrix(a) { let dp = new Array(Row); for(let i = 0; i < Row; i++) { dp[i] = new Array(Col); for(let j = 0; j < Col; j++) { dp[i][j] = 0; } } let result = 0; for (let i = 0 ; i < Row ; i++) { for (let j = 0 ; j < Col ; j++) { // If elements is at top // row or first column, // it wont form a square // matrix's bottom-right if (i == 0 || j == 0) dp[i][j] = 1; else { // Check if adjacent // elements are equal if (a[i][j] == a[i - 1][j] && a[i][j] == a[i][j - 1] && a[i][j] == a[i - 1][j - 1]) { dp[i][j] = (dp[i - 1][j] > dp[i][j - 1] && dp[i - 1][j] > dp[i - 1][j - 1] + 1) ? dp[i - 1][j] : (dp[i][j - 1] > dp[i - 1][j] && dp[i][j - 1] > dp[i - 1][j - 1] + 1) ? dp[i][j - 1] : dp[i - 1][j - 1] + 1; } // If not equal, then it // will form a 1x1 submatrix else dp[i][j] = 1; } // Update result at each (i,j) result = result > dp[i][j] ? result : dp[i][j]; } } return result; } // Driver code let a = [[ 2, 2, 3, 3, 4, 4], [ 5, 5, 7, 7, 7, 4], [ 1, 2, 7, 7, 7, 4], [ 4, 4, 7, 7, 7, 4], [ 5, 5, 5, 1, 2, 7], [ 8, 7, 9, 4, 4, 4]]; document.write(largestKSubmatrix(a)); // This code is contributed by avanitrachhadiya2155</script>", "e": 12943, "s": 10620, "text": null }, { "code": null, "e": 12946, "s": 12943, "text": "3\n" }, { "code": null, "e": 13008, "s": 12946, "text": "Time Complexity : O(Row * Col) Auxiliary Space : O(Row * Col)" }, { "code": null, "e": 13306, "s": 13008, "text": "This article is contributed by Shubham Gupta. 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": 13312, "s": 13306, "text": "ukasp" }, { "code": null, "e": 13333, "s": 13312, "text": "avanitrachhadiya2155" }, { "code": null, "e": 13350, "s": 13333, "text": "hardikkoriintern" }, { "code": null, "e": 13358, "s": 13350, "text": "Directi" }, { "code": null, "e": 13378, "s": 13358, "text": "Dynamic Programming" }, { "code": null, "e": 13385, "s": 13378, "text": "Matrix" }, { "code": null, "e": 13393, "s": 13385, "text": "Directi" }, { "code": null, "e": 13413, "s": 13393, "text": "Dynamic Programming" }, { "code": null, "e": 13420, "s": 13413, "text": "Matrix" } ]
Creating an activate/deactivate button using PHP and MySQL
21 Jul, 2021 In this article, we will discuss how to create an Activate/Deactivate button using PHP. When a particular status is set, the same gets updated in the database. Approach: In order to illustrate the example, let’s say that there are a few courses that can be set as active or inactive and need to have appropriate colored buttons for the same. The implementation is done using HTML, PHP, and CSS. Requirements: MySQL database with a table containing at least course name and a boolean status value.PHP and HTML files.XAMPP (or any alternative) MySQL database with a table containing at least course name and a boolean status value. PHP and HTML files. XAMPP (or any alternative) Database creation: Open XAMPP control panel and start Apache and MySQL modules.click on the start buttons click on the start buttons Open “localhost/phpmyadmin” in your browser and click on the new button to create a new database. Give a name to your database and click create. In the SQL tab enter the following SQL code and click go. In order to achieve the desired result, let us create a database called “courses” and set up a few courses using the following SQL code. Table structure for table `courses` Course_name String and status boolean fields CREATE TABLE `courses` ( `Course_name` varchar(50) NOT NULL, `status` tinyint(1) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; Sample data for table `courses` INSERT INTO `courses` (`Course_name`, `status`) VALUES ('C++', 0), ('Java', 1), ('Data Structures', 1), ('SQL', 0); ALTER TABLE `courses` ADD `id` INT NOT NULL AUTO_INCREMENT FIRST, ADD PRIMARY KEY (`id`); In this table, we must know that status is an integer that represents inactive as 0 and active as 1. Web-page creation: Create a folder in htdocs called courses and store the following file as “course-page.php“. course-page.php <?php // Connect to database $con = mysqli_connect("localhost","root","","courses"); // Get all the courses from courses table // execute the query // Store the result $sql = "SELECT * FROM `courses`"; $Sql_query = mysqli_query($con,$sql); $All_courses = mysqli_fetch_all($Sql_query,MYSQLI_ASSOC);?> <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Using internal/embedded css --> <style> .btn{ background-color: red; border: none; color: white; padding: 5px 5px; text-align: center; text-decoration: none; display: inline-block; font-size: 20px; margin: 4px 2px; cursor: pointer; border-radius: 20px; } .green{ background-color: #199319; } .red{ background-color: red; } table,th{ border-style : solid; border-width : 1; text-align :center; } td{ text-align :center; } </style> </head> <body> <h2>Courses Table</h2> <table> <!-- TABLE TOP ROW HEADINGS--> <tr> <th>Course Name</th> <th>Course Status</th> <th>Toggle</th> </tr> <?php // Use foreach to access all the courses data foreach ($All_courses as $course) { ?> <tr> <td><?php echo $course['Course_name']; ?></td> <td><?php // Usage of if-else statement to translate the // tinyint status value into some common terms // 0-Inactive // 1-Active if($course['status']=="1") echo "Active"; else echo "Inactive"; ?> </td> <td> <?php if($course['status']=="1") // if a course is active i.e. status is 1 // the toggle button must be able to deactivate // we echo the hyperlink to the page "deactivate.php" // in order to make it look like a button // we use the appropriate css // red-deactivate // green- activate echo "<a href=deactivate.php?id=".$course['id']." class='btn red'>Deactivate</a>"; else echo "<a href=activate.php?id=".$course['id']." class='btn green'>Activate</a>"; ?> </tr> <?php } // End the foreach loop ?> </table></body> </html> Output: A decent looking table is created We are actually not using buttons, rather using hyperlinks that link to PHP files that perform the toggle of the status variable of the table “courses”. So we need to create these files too. activate.php <?php // Connect to database $con=mysqli_connect("localhost","root","","courses"); // Check if id is set or not if true toggle, // else simply go back to the page if (isset($_GET['id'])){ // Store the value from get to a // local variable "course_id" $course_id=$_GET['id']; // SQL query that sets the status // to 1 to indicate activation. $sql="UPDATE `courses` SET `status`=1 WHERE id='$course_id'"; // Execute the query mysqli_query($con,$sql); } // Go back to course-page.php header('location: course-page.php');?> deactivate.php <?php // Connect to database $con=mysqli_connect("localhost","root","","courses"); // Check if id is set or not, if true, // toggle else simply go back to the page if (isset($_GET['id'])){ // Store the value from get to // a local variable "course_id" $course_id=$_GET['id']; // SQL query that sets the status to // 0 to indicate deactivation. $sql="UPDATE `courses` SET `status`=0 WHERE id='$course_id'"; // Execute the query mysqli_query($con,$sql); } // Go back to course-page.php header('location: course-page.php');?> Output: We have created a page with clickable buttons and when we click on the buttons the status changes in the database. activate and deactivate HTML-Questions mysql PHP-function PHP-Questions HTML PHP SQL Web Technologies SQL HTML PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Jul, 2021" }, { "code": null, "e": 213, "s": 52, "text": "In this article, we will discuss how to create an Activate/Deactivate button using PHP. When a particular status is set, the same gets updated in the database. " }, { "code": null, "e": 448, "s": 213, "text": "Approach: In order to illustrate the example, let’s say that there are a few courses that can be set as active or inactive and need to have appropriate colored buttons for the same. The implementation is done using HTML, PHP, and CSS." }, { "code": null, "e": 462, "s": 448, "text": "Requirements:" }, { "code": null, "e": 595, "s": 462, "text": "MySQL database with a table containing at least course name and a boolean status value.PHP and HTML files.XAMPP (or any alternative)" }, { "code": null, "e": 683, "s": 595, "text": "MySQL database with a table containing at least course name and a boolean status value." }, { "code": null, "e": 703, "s": 683, "text": "PHP and HTML files." }, { "code": null, "e": 730, "s": 703, "text": "XAMPP (or any alternative)" }, { "code": null, "e": 751, "s": 732, "text": "Database creation:" }, { "code": null, "e": 838, "s": 751, "text": "Open XAMPP control panel and start Apache and MySQL modules.click on the start buttons" }, { "code": null, "e": 865, "s": 838, "text": "click on the start buttons" }, { "code": null, "e": 963, "s": 865, "text": "Open “localhost/phpmyadmin” in your browser and click on the new button to create a new database." }, { "code": null, "e": 1010, "s": 963, "text": "Give a name to your database and click create." }, { "code": null, "e": 1068, "s": 1010, "text": "In the SQL tab enter the following SQL code and click go." }, { "code": null, "e": 1205, "s": 1068, "text": "In order to achieve the desired result, let us create a database called “courses” and set up a few courses using the following SQL code." }, { "code": null, "e": 1668, "s": 1205, "text": "Table structure for table `courses`\nCourse_name String and status boolean fields\n\nCREATE TABLE `courses` (\n `Course_name` varchar(50) NOT NULL,\n `status` tinyint(1) NOT NULL\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;\n\n\nSample data for table `courses`\n\nINSERT INTO `courses` (`Course_name`, `status`) VALUES\n('C++', 0),\n('Java', 1),\n('Data Structures', 1),\n('SQL', 0);\n\nALTER TABLE `courses` ADD `id` INT NOT NULL AUTO_INCREMENT\n FIRST, ADD PRIMARY KEY (`id`);" }, { "code": null, "e": 1769, "s": 1668, "text": "In this table, we must know that status is an integer that represents inactive as 0 and active as 1." }, { "code": null, "e": 1880, "s": 1769, "text": "Web-page creation: Create a folder in htdocs called courses and store the following file as “course-page.php“." }, { "code": null, "e": 1896, "s": 1880, "text": "course-page.php" }, { "code": "<?php // Connect to database $con = mysqli_connect(\"localhost\",\"root\",\"\",\"courses\"); // Get all the courses from courses table // execute the query // Store the result $sql = \"SELECT * FROM `courses`\"; $Sql_query = mysqli_query($con,$sql); $All_courses = mysqli_fetch_all($Sql_query,MYSQLI_ASSOC);?> <!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <!-- Using internal/embedded css --> <style> .btn{ background-color: red; border: none; color: white; padding: 5px 5px; text-align: center; text-decoration: none; display: inline-block; font-size: 20px; margin: 4px 2px; cursor: pointer; border-radius: 20px; } .green{ background-color: #199319; } .red{ background-color: red; } table,th{ border-style : solid; border-width : 1; text-align :center; } td{ text-align :center; } </style> </head> <body> <h2>Courses Table</h2> <table> <!-- TABLE TOP ROW HEADINGS--> <tr> <th>Course Name</th> <th>Course Status</th> <th>Toggle</th> </tr> <?php // Use foreach to access all the courses data foreach ($All_courses as $course) { ?> <tr> <td><?php echo $course['Course_name']; ?></td> <td><?php // Usage of if-else statement to translate the // tinyint status value into some common terms // 0-Inactive // 1-Active if($course['status']==\"1\") echo \"Active\"; else echo \"Inactive\"; ?> </td> <td> <?php if($course['status']==\"1\") // if a course is active i.e. status is 1 // the toggle button must be able to deactivate // we echo the hyperlink to the page \"deactivate.php\" // in order to make it look like a button // we use the appropriate css // red-deactivate // green- activate echo \"<a href=deactivate.php?id=\".$course['id'].\" class='btn red'>Deactivate</a>\"; else echo \"<a href=activate.php?id=\".$course['id'].\" class='btn green'>Activate</a>\"; ?> </tr> <?php } // End the foreach loop ?> </table></body> </html>", "e": 4923, "s": 1896, "text": null }, { "code": null, "e": 4931, "s": 4923, "text": "Output:" }, { "code": null, "e": 4965, "s": 4931, "text": "A decent looking table is created" }, { "code": null, "e": 5156, "s": 4965, "text": "We are actually not using buttons, rather using hyperlinks that link to PHP files that perform the toggle of the status variable of the table “courses”. So we need to create these files too." }, { "code": null, "e": 5169, "s": 5156, "text": "activate.php" }, { "code": "<?php // Connect to database $con=mysqli_connect(\"localhost\",\"root\",\"\",\"courses\"); // Check if id is set or not if true toggle, // else simply go back to the page if (isset($_GET['id'])){ // Store the value from get to a // local variable \"course_id\" $course_id=$_GET['id']; // SQL query that sets the status // to 1 to indicate activation. $sql=\"UPDATE `courses` SET `status`=1 WHERE id='$course_id'\"; // Execute the query mysqli_query($con,$sql); } // Go back to course-page.php header('location: course-page.php');?>", "e": 5796, "s": 5169, "text": null }, { "code": null, "e": 5811, "s": 5796, "text": "deactivate.php" }, { "code": "<?php // Connect to database $con=mysqli_connect(\"localhost\",\"root\",\"\",\"courses\"); // Check if id is set or not, if true, // toggle else simply go back to the page if (isset($_GET['id'])){ // Store the value from get to // a local variable \"course_id\" $course_id=$_GET['id']; // SQL query that sets the status to // 0 to indicate deactivation. $sql=\"UPDATE `courses` SET `status`=0 WHERE id='$course_id'\"; // Execute the query mysqli_query($con,$sql); } // Go back to course-page.php header('location: course-page.php');?>", "e": 6440, "s": 5811, "text": null }, { "code": null, "e": 6563, "s": 6440, "text": "Output: We have created a page with clickable buttons and when we click on the buttons the status changes in the database." }, { "code": null, "e": 6587, "s": 6563, "text": "activate and deactivate" }, { "code": null, "e": 6602, "s": 6587, "text": "HTML-Questions" }, { "code": null, "e": 6608, "s": 6602, "text": "mysql" }, { "code": null, "e": 6621, "s": 6608, "text": "PHP-function" }, { "code": null, "e": 6635, "s": 6621, "text": "PHP-Questions" }, { "code": null, "e": 6640, "s": 6635, "text": "HTML" }, { "code": null, "e": 6644, "s": 6640, "text": "PHP" }, { "code": null, "e": 6648, "s": 6644, "text": "SQL" }, { "code": null, "e": 6665, "s": 6648, "text": "Web Technologies" }, { "code": null, "e": 6669, "s": 6665, "text": "SQL" }, { "code": null, "e": 6674, "s": 6669, "text": "HTML" }, { "code": null, "e": 6678, "s": 6674, "text": "PHP" } ]
Python | Pandas MultiIndex.sortlevel()
24 Dec, 2018 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas MultiIndex.sortlevel() function sort MultiIndex at the requested level. The result will respect the original ordering of the associated factor at that level. Syntax: MultiIndex.sortlevel(level=0, ascending=True, sort_remaining=True) Parameters :level : [list-like, int or str, default 0] If a string is given, must be a name of the level If list-like must be names or ints of levelsascending : False to sort in descending order Can also be a list to specify a directed orderingsort_remaining : sort by the remaining levels after level. Returns :sorted_index : Resulting indexindexer : Indices of output values in original index Example #1: Use MultiIndex.sortlevel() function to sort the 0th level of the MultiIndex in descending order. # importing pandas as pdimport pandas as pd # Create the MultiIndexmidx = pd.MultiIndex.from_arrays([['Networking', 'Cryptography', 'Anthropology', 'Science'], [88, 84, 98, 95]]) # Print the MultiIndexprint(midx) Output : Now let’s sort the 0th level of the MultiIndex in descending order. # sort the 0th level in descending order.midx.sortlevel(level = 0, ascending = False) Output :As we can see in the output, the function has returned a new object having the 0th level sorted in descending order. Example #2: Use MultiIndex.sortlevel() function to sort the 1st level of the MultiIndex in the increasing order. # importing pandas as pdimport pandas as pd # Create the MultiIndexmidx = pd.MultiIndex.from_arrays([['Networking', 'Cryptography', 'Anthropology', 'Science'], [88, 84, 98, 95]]) # Print the MultiIndexprint(midx) Output : Now let’s sort the 1st level of the MultiIndex in increasing order. # sort the 1st level of the MultiIndex in increasing order.midx.sortlevel(level = 1, ascending = True) Output :As we can see in the output, the function has returned a new object having the first level sorted in increasing order. Python pandas-multiIndex Python-pandas Python 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": 242, "s": 28, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 407, "s": 242, "text": "Pandas MultiIndex.sortlevel() function sort MultiIndex at the requested level. The result will respect the original ordering of the associated factor at that level." }, { "code": null, "e": 482, "s": 407, "text": "Syntax: MultiIndex.sortlevel(level=0, ascending=True, sort_remaining=True)" }, { "code": null, "e": 785, "s": 482, "text": "Parameters :level : [list-like, int or str, default 0] If a string is given, must be a name of the level If list-like must be names or ints of levelsascending : False to sort in descending order Can also be a list to specify a directed orderingsort_remaining : sort by the remaining levels after level." }, { "code": null, "e": 877, "s": 785, "text": "Returns :sorted_index : Resulting indexindexer : Indices of output values in original index" }, { "code": null, "e": 986, "s": 877, "text": "Example #1: Use MultiIndex.sortlevel() function to sort the 0th level of the MultiIndex in descending order." }, { "code": "# importing pandas as pdimport pandas as pd # Create the MultiIndexmidx = pd.MultiIndex.from_arrays([['Networking', 'Cryptography', 'Anthropology', 'Science'], [88, 84, 98, 95]]) # Print the MultiIndexprint(midx)", "e": 1282, "s": 986, "text": null }, { "code": null, "e": 1291, "s": 1282, "text": "Output :" }, { "code": null, "e": 1359, "s": 1291, "text": "Now let’s sort the 0th level of the MultiIndex in descending order." }, { "code": "# sort the 0th level in descending order.midx.sortlevel(level = 0, ascending = False)", "e": 1445, "s": 1359, "text": null }, { "code": null, "e": 1683, "s": 1445, "text": "Output :As we can see in the output, the function has returned a new object having the 0th level sorted in descending order. Example #2: Use MultiIndex.sortlevel() function to sort the 1st level of the MultiIndex in the increasing order." }, { "code": "# importing pandas as pdimport pandas as pd # Create the MultiIndexmidx = pd.MultiIndex.from_arrays([['Networking', 'Cryptography', 'Anthropology', 'Science'], [88, 84, 98, 95]]) # Print the MultiIndexprint(midx)", "e": 1980, "s": 1683, "text": null }, { "code": null, "e": 1989, "s": 1980, "text": "Output :" }, { "code": null, "e": 2057, "s": 1989, "text": "Now let’s sort the 1st level of the MultiIndex in increasing order." }, { "code": "# sort the 1st level of the MultiIndex in increasing order.midx.sortlevel(level = 1, ascending = True)", "e": 2160, "s": 2057, "text": null }, { "code": null, "e": 2287, "s": 2160, "text": "Output :As we can see in the output, the function has returned a new object having the first level sorted in increasing order." }, { "code": null, "e": 2312, "s": 2287, "text": "Python pandas-multiIndex" }, { "code": null, "e": 2326, "s": 2312, "text": "Python-pandas" }, { "code": null, "e": 2333, "s": 2326, "text": "Python" } ]
Functools module in Python
26 Mar, 2020 Functools module is for higher-order functions that work on other functions. It provides functions for working with other functions and callable objects to use or extend them without completely rewriting them. This module has two classes – partial and partialmethod. A partial function is an original function for particular argument values. They can be created in Python by using “partial” from the functools library. The __name__ and __doc__ attributes are to be created by the programmer as they are not created automatically. Objects created by partial() have three read-only attributes: Syntax: partial(func[, *args][, **keywords]) partial.func – It returns the name of parent function along with hexadecimal address. partial.args – It returns the positional arguments provided in partial function. partial.keywords – It returns the keyword arguments provided in partial function. Example: from functools import partial def power(a, b): return a**b # partial functionspow2 = partial(power, b = 2)pow4 = partial(power, b = 4)power_of_5 = partial(power, 5) print(power(2, 3))print(pow2(4))print(pow4(3))print(power_of_5(2)) print('Function used in partial function pow2 :', pow2.func)print('Default keywords for pow2 :', pow2.keywords)print('Default arguments for power_of_5 :', power_of_5.args) Output : 8168125Function used in partial function pow2 : <function power at 0x000001CCBBE8C7B8>Default keywords for pow2 : {‘b’: 2}Default arguments for power_of_5 : (5, ) It is a method definition of an already defined function for specific arguments like a partial function. However, it is not callable but is only a method descriptor. It returns a new partialmethod descriptor. Syntax: partialmethod(func, *args, **keywords) Example: from functools import partialmethod class Demo: def __init__(self): self.color = 'black' def _color(self, type): self.color = type set_red = partialmethod(_color, type ='red') set_blue = partialmethod(_color, type ='blue') set_green = partialmethod(_color, type ='green') obj = Demo()print(obj.color)obj.set_blue()print(obj.color) Output : black blue Cmp_to_keyIt converts a comparison function into a key function. The comparison function must return 1, -1 and 0 for different conditions. It can be used in key functions such as sorted(), min(), max().Syntax :function(iterable, key=cmp_to_key(cmp_function)) Example:from functools import cmp_to_key # function to sort according to last characterdef cmp_fun(a, b): if a[-1] > b[-1]: return 1 elif a[-1] < b[-1]: return -1 else: return 0 list1 = ['geeks', 'for', 'geeks']l = sorted(list1, key = cmp_to_key(cmp_fun))print('sorted list :', l)Output :sorted list : ['for', 'geeks', 'geeks'] It converts a comparison function into a key function. The comparison function must return 1, -1 and 0 for different conditions. It can be used in key functions such as sorted(), min(), max(). Syntax : function(iterable, key=cmp_to_key(cmp_function)) Example: from functools import cmp_to_key # function to sort according to last characterdef cmp_fun(a, b): if a[-1] > b[-1]: return 1 elif a[-1] < b[-1]: return -1 else: return 0 list1 = ['geeks', 'for', 'geeks']l = sorted(list1, key = cmp_to_key(cmp_fun))print('sorted list :', l) Output : sorted list : ['for', 'geeks', 'geeks'] ReduceIt applies a function of two arguments repeatedly on the elements of a sequence so as to reduce the sequence to a single value. For example, reduce(lambda x, y: x^y, [1, 2, 3, 4]) calculates (((1^2)^3)^4). If the initial is present, it is placed first in the calculation, and if the default result when the sequence is empty.Syntax :reduce(function, sequence[, initial]) -> value Example:from functools import reducelist1 = [2, 4, 7, 9, 1, 3]sum_of_list1 = reduce(lambda a, b:a + b, list1) list2 = ["abc", "xyz", "def"]max_of_list2 = reduce(lambda a, b:a if a>b else b, list2) print('Sum of list1 :', sum_of_list1)print('Maximum of list2 :', max_of_list2)Output :Sum of list1 : 26 Maximum of list2 : xyz It applies a function of two arguments repeatedly on the elements of a sequence so as to reduce the sequence to a single value. For example, reduce(lambda x, y: x^y, [1, 2, 3, 4]) calculates (((1^2)^3)^4). If the initial is present, it is placed first in the calculation, and if the default result when the sequence is empty.Syntax : reduce(function, sequence[, initial]) -> value Example: from functools import reducelist1 = [2, 4, 7, 9, 1, 3]sum_of_list1 = reduce(lambda a, b:a + b, list1) list2 = ["abc", "xyz", "def"]max_of_list2 = reduce(lambda a, b:a if a>b else b, list2) print('Sum of list1 :', sum_of_list1)print('Maximum of list2 :', max_of_list2) Output : Sum of list1 : 26 Maximum of list2 : xyz Total_orderingIt is a class decorator that fills in the missing comparison methods (__lt__, __gt__, __eq__, __le__, __ge__). If a class is given which defines one or more comparison methods, “@total_ordering” automatically supplies the rest as per the given definitions. However, the class must define one of __lt__(), __le__(), __gt__(), or __ge__() and additionally, the class should supply an __eq__() method.Example:from functools import total_ordering @total_orderingclass N: def __init__(self, value): self.value = value def __eq__(self, other): return self.value == other.value # Reverse the function of # '<' operator and accordingly # other rich comparison operators # due to total_ordering decorator def __lt__(self, other): return self.value > other.value print('6 > 2 :', N(6)>N(2))print('3 < 1 :', N(3)<N(1))print('2 <= 7 :', N(2)<= N(7))print('9 >= 10 :', N(9)>= N(10))print('5 == 5 :', N(5)== N(5))Output :6 > 2 : False 3 < 1 : True 2 = 10 : True 5 == 5 : True Example: from functools import total_ordering @total_orderingclass N: def __init__(self, value): self.value = value def __eq__(self, other): return self.value == other.value # Reverse the function of # '<' operator and accordingly # other rich comparison operators # due to total_ordering decorator def __lt__(self, other): return self.value > other.value print('6 > 2 :', N(6)>N(2))print('3 < 1 :', N(3)<N(1))print('2 <= 7 :', N(2)<= N(7))print('9 >= 10 :', N(9)>= N(10))print('5 == 5 :', N(5)== N(5)) Output : 6 > 2 : False 3 < 1 : True 2 = 10 : True 5 == 5 : True Update_wrapperIt updates a wrapper function to look like the wrapped function. For example, in case of partial functions, we can update partial function to look like its parent function by using update_wrapper(partial, parent). This will update the documentation(__doc__) and name(__name__) of the partial function to same as of the parent function.Syntax :update_wrapper(wrapper, wrapped[, assigned][, updated])Example:from functools import update_wrapper, partial def power(a, b): ''' a to the power b''' return a**b # partial functionpow2 = partial(power, b = 2)pow2.__doc__='''a to the power 2'''pow2.__name__ = 'pow2' print('Before wrapper update -')print('Documentation of pow2 :', pow2.__doc__)print('Name of pow2 :', pow2.__name__)print()update_wrapper(pow2, power)print('After wrapper update -')print('Documentation of pow2 :', pow2.__doc__)print('Name of pow2 :', pow2.__name__)Output :Before wrapper update - Documentation of pow2 : a to the power 2 Name of pow2 : pow2 After wrapper update - Documentation of pow2 : a to the power b Name of pow2 : power It updates a wrapper function to look like the wrapped function. For example, in case of partial functions, we can update partial function to look like its parent function by using update_wrapper(partial, parent). This will update the documentation(__doc__) and name(__name__) of the partial function to same as of the parent function. Syntax : update_wrapper(wrapper, wrapped[, assigned][, updated]) Example: from functools import update_wrapper, partial def power(a, b): ''' a to the power b''' return a**b # partial functionpow2 = partial(power, b = 2)pow2.__doc__='''a to the power 2'''pow2.__name__ = 'pow2' print('Before wrapper update -')print('Documentation of pow2 :', pow2.__doc__)print('Name of pow2 :', pow2.__name__)print()update_wrapper(pow2, power)print('After wrapper update -')print('Documentation of pow2 :', pow2.__doc__)print('Name of pow2 :', pow2.__name__) Output : Before wrapper update - Documentation of pow2 : a to the power 2 Name of pow2 : pow2 After wrapper update - Documentation of pow2 : a to the power b Name of pow2 : power WrapsIt is a function decorator which applies update_wrapper() to the decorated function. It is equivalent to partial(update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated).Example:from functools import wraps def decorator(f): @wraps(f) def decorated(*args, **kwargs): """Decorator's docstring""" return f(*args, **kwargs) print('Documentation of decorated :', decorated.__doc__) return decorated @decoratordef f(x): """f's Docstring""" return x print('f name :', f.__name__)print('Documentation of f :', f.__doc__)Output :Documentation of decorated : f's Docstring f name : f Documentation of f : f's Docstring Example: from functools import wraps def decorator(f): @wraps(f) def decorated(*args, **kwargs): """Decorator's docstring""" return f(*args, **kwargs) print('Documentation of decorated :', decorated.__doc__) return decorated @decoratordef f(x): """f's Docstring""" return x print('f name :', f.__name__)print('Documentation of f :', f.__doc__) Output : Documentation of decorated : f's Docstring f name : f Documentation of f : f's Docstring LRU_cacheLRU_cache is a function decorator used for saving up to the maxsize most recent calls of a function. This can save time and memory in case of repeated calls with the same arguments.If *maxsize* is set to None, the cache can grow without bound. If *typed* is True, arguments of different data types will be cached separately. For example, f(1.0) and f(1) will be memoized distinctly.Syntax :lru_cache(maxsize=128, typed=False)Example:from functools import lru_cache @lru_cache(maxsize = None)def factorial(n): if n<= 1: return 1 return n * factorial(n-1)print([factorial(n) for n in range(7)])print(factorial.cache_info())Output :[1, 1, 2, 6, 24, 120, 720] CacheInfo(hits=5, misses=7, maxsize=None, currsize=7) LRU_cache is a function decorator used for saving up to the maxsize most recent calls of a function. This can save time and memory in case of repeated calls with the same arguments.If *maxsize* is set to None, the cache can grow without bound. If *typed* is True, arguments of different data types will be cached separately. For example, f(1.0) and f(1) will be memoized distinctly. Syntax : lru_cache(maxsize=128, typed=False) Example: from functools import lru_cache @lru_cache(maxsize = None)def factorial(n): if n<= 1: return 1 return n * factorial(n-1)print([factorial(n) for n in range(7)])print(factorial.cache_info()) Output : [1, 1, 2, 6, 24, 120, 720] CacheInfo(hits=5, misses=7, maxsize=None, currsize=7) SingleDispatchIt is a function decorator. It transforms a function into a generic function so that it can have different behaviors depending upon the type of its first argument. It is used for function overloading, the overloaded implementations are registered using the register() attribute of theExample:from functools import singledispatch @singledispatchdef fun(s): print(s)@fun.register(int)def _(s): print(s * 2) fun('GeeksforGeeks')fun(10)Output :GeeksforGeeks 20 Example: from functools import singledispatch @singledispatchdef fun(s): print(s)@fun.register(int)def _(s): print(s * 2) fun('GeeksforGeeks')fun(10) Output : GeeksforGeeks 20 python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Mar, 2020" }, { "code": null, "e": 295, "s": 28, "text": "Functools module is for higher-order functions that work on other functions. It provides functions for working with other functions and callable objects to use or extend them without completely rewriting them. This module has two classes – partial and partialmethod." }, { "code": null, "e": 620, "s": 295, "text": "A partial function is an original function for particular argument values. They can be created in Python by using “partial” from the functools library. The __name__ and __doc__ attributes are to be created by the programmer as they are not created automatically. Objects created by partial() have three read-only attributes:" }, { "code": null, "e": 628, "s": 620, "text": "Syntax:" }, { "code": null, "e": 665, "s": 628, "text": "partial(func[, *args][, **keywords])" }, { "code": null, "e": 751, "s": 665, "text": "partial.func – It returns the name of parent function along with hexadecimal address." }, { "code": null, "e": 832, "s": 751, "text": "partial.args – It returns the positional arguments provided in partial function." }, { "code": null, "e": 914, "s": 832, "text": "partial.keywords – It returns the keyword arguments provided in partial function." }, { "code": null, "e": 923, "s": 914, "text": "Example:" }, { "code": "from functools import partial def power(a, b): return a**b # partial functionspow2 = partial(power, b = 2)pow4 = partial(power, b = 4)power_of_5 = partial(power, 5) print(power(2, 3))print(pow2(4))print(pow4(3))print(power_of_5(2)) print('Function used in partial function pow2 :', pow2.func)print('Default keywords for pow2 :', pow2.keywords)print('Default arguments for power_of_5 :', power_of_5.args)", "e": 1336, "s": 923, "text": null }, { "code": null, "e": 1345, "s": 1336, "text": "Output :" }, { "code": null, "e": 1508, "s": 1345, "text": "8168125Function used in partial function pow2 : <function power at 0x000001CCBBE8C7B8>Default keywords for pow2 : {‘b’: 2}Default arguments for power_of_5 : (5, )" }, { "code": null, "e": 1717, "s": 1508, "text": "It is a method definition of an already defined function for specific arguments like a partial function. However, it is not callable but is only a method descriptor. It returns a new partialmethod descriptor." }, { "code": null, "e": 1725, "s": 1717, "text": "Syntax:" }, { "code": null, "e": 1764, "s": 1725, "text": "partialmethod(func, *args, **keywords)" }, { "code": null, "e": 1773, "s": 1764, "text": "Example:" }, { "code": "from functools import partialmethod class Demo: def __init__(self): self.color = 'black' def _color(self, type): self.color = type set_red = partialmethod(_color, type ='red') set_blue = partialmethod(_color, type ='blue') set_green = partialmethod(_color, type ='green') obj = Demo()print(obj.color)obj.set_blue()print(obj.color)", "e": 2141, "s": 1773, "text": null }, { "code": null, "e": 2150, "s": 2141, "text": "Output :" }, { "code": null, "e": 2162, "s": 2150, "text": "black\nblue\n" }, { "code": null, "e": 2782, "s": 2162, "text": "Cmp_to_keyIt converts a comparison function into a key function. The comparison function must return 1, -1 and 0 for different conditions. It can be used in key functions such as sorted(), min(), max().Syntax :function(iterable, key=cmp_to_key(cmp_function)) Example:from functools import cmp_to_key # function to sort according to last characterdef cmp_fun(a, b): if a[-1] > b[-1]: return 1 elif a[-1] < b[-1]: return -1 else: return 0 list1 = ['geeks', 'for', 'geeks']l = sorted(list1, key = cmp_to_key(cmp_fun))print('sorted list :', l)Output :sorted list : ['for', 'geeks', 'geeks']\n" }, { "code": null, "e": 2975, "s": 2782, "text": "It converts a comparison function into a key function. The comparison function must return 1, -1 and 0 for different conditions. It can be used in key functions such as sorted(), min(), max()." }, { "code": null, "e": 2984, "s": 2975, "text": "Syntax :" }, { "code": null, "e": 3034, "s": 2984, "text": "function(iterable, key=cmp_to_key(cmp_function)) " }, { "code": null, "e": 3043, "s": 3034, "text": "Example:" }, { "code": "from functools import cmp_to_key # function to sort according to last characterdef cmp_fun(a, b): if a[-1] > b[-1]: return 1 elif a[-1] < b[-1]: return -1 else: return 0 list1 = ['geeks', 'for', 'geeks']l = sorted(list1, key = cmp_to_key(cmp_fun))print('sorted list :', l)", "e": 3348, "s": 3043, "text": null }, { "code": null, "e": 3357, "s": 3348, "text": "Output :" }, { "code": null, "e": 3398, "s": 3357, "text": "sorted list : ['for', 'geeks', 'geeks']\n" }, { "code": null, "e": 4112, "s": 3398, "text": "ReduceIt applies a function of two arguments repeatedly on the elements of a sequence so as to reduce the sequence to a single value. For example, reduce(lambda x, y: x^y, [1, 2, 3, 4]) calculates (((1^2)^3)^4). If the initial is present, it is placed first in the calculation, and if the default result when the sequence is empty.Syntax :reduce(function, sequence[, initial]) -> value Example:from functools import reducelist1 = [2, 4, 7, 9, 1, 3]sum_of_list1 = reduce(lambda a, b:a + b, list1) list2 = [\"abc\", \"xyz\", \"def\"]max_of_list2 = reduce(lambda a, b:a if a>b else b, list2) print('Sum of list1 :', sum_of_list1)print('Maximum of list2 :', max_of_list2)Output :Sum of list1 : 26\nMaximum of list2 : xyz\n" }, { "code": null, "e": 4446, "s": 4112, "text": "It applies a function of two arguments repeatedly on the elements of a sequence so as to reduce the sequence to a single value. For example, reduce(lambda x, y: x^y, [1, 2, 3, 4]) calculates (((1^2)^3)^4). If the initial is present, it is placed first in the calculation, and if the default result when the sequence is empty.Syntax :" }, { "code": null, "e": 4495, "s": 4446, "text": "reduce(function, sequence[, initial]) -> value " }, { "code": null, "e": 4504, "s": 4495, "text": "Example:" }, { "code": "from functools import reducelist1 = [2, 4, 7, 9, 1, 3]sum_of_list1 = reduce(lambda a, b:a + b, list1) list2 = [\"abc\", \"xyz\", \"def\"]max_of_list2 = reduce(lambda a, b:a if a>b else b, list2) print('Sum of list1 :', sum_of_list1)print('Maximum of list2 :', max_of_list2)", "e": 4774, "s": 4504, "text": null }, { "code": null, "e": 4783, "s": 4774, "text": "Output :" }, { "code": null, "e": 4825, "s": 4783, "text": "Sum of list1 : 26\nMaximum of list2 : xyz\n" }, { "code": null, "e": 5851, "s": 4825, "text": "Total_orderingIt is a class decorator that fills in the missing comparison methods (__lt__, __gt__, __eq__, __le__, __ge__). If a class is given which defines one or more comparison methods, “@total_ordering” automatically supplies the rest as per the given definitions. However, the class must define one of __lt__(), __le__(), __gt__(), or __ge__() and additionally, the class should supply an __eq__() method.Example:from functools import total_ordering @total_orderingclass N: def __init__(self, value): self.value = value def __eq__(self, other): return self.value == other.value # Reverse the function of # '<' operator and accordingly # other rich comparison operators # due to total_ordering decorator def __lt__(self, other): return self.value > other.value print('6 > 2 :', N(6)>N(2))print('3 < 1 :', N(3)<N(1))print('2 <= 7 :', N(2)<= N(7))print('9 >= 10 :', N(9)>= N(10))print('5 == 5 :', N(5)== N(5))Output :6 > 2 : False\n3 < 1 : True\n2 = 10 : True\n5 == 5 : True\n" }, { "code": null, "e": 5860, "s": 5851, "text": "Example:" }, { "code": "from functools import total_ordering @total_orderingclass N: def __init__(self, value): self.value = value def __eq__(self, other): return self.value == other.value # Reverse the function of # '<' operator and accordingly # other rich comparison operators # due to total_ordering decorator def __lt__(self, other): return self.value > other.value print('6 > 2 :', N(6)>N(2))print('3 < 1 :', N(3)<N(1))print('2 <= 7 :', N(2)<= N(7))print('9 >= 10 :', N(9)>= N(10))print('5 == 5 :', N(5)== N(5))", "e": 6403, "s": 5860, "text": null }, { "code": null, "e": 6412, "s": 6403, "text": "Output :" }, { "code": null, "e": 6468, "s": 6412, "text": "6 > 2 : False\n3 < 1 : True\n2 = 10 : True\n5 == 5 : True\n" }, { "code": null, "e": 7546, "s": 6468, "text": "Update_wrapperIt updates a wrapper function to look like the wrapped function. For example, in case of partial functions, we can update partial function to look like its parent function by using update_wrapper(partial, parent). This will update the documentation(__doc__) and name(__name__) of the partial function to same as of the parent function.Syntax :update_wrapper(wrapper, wrapped[, assigned][, updated])Example:from functools import update_wrapper, partial def power(a, b): ''' a to the power b''' return a**b # partial functionpow2 = partial(power, b = 2)pow2.__doc__='''a to the power 2'''pow2.__name__ = 'pow2' print('Before wrapper update -')print('Documentation of pow2 :', pow2.__doc__)print('Name of pow2 :', pow2.__name__)print()update_wrapper(pow2, power)print('After wrapper update -')print('Documentation of pow2 :', pow2.__doc__)print('Name of pow2 :', pow2.__name__)Output :Before wrapper update -\nDocumentation of pow2 : a to the power 2\nName of pow2 : pow2\n\nAfter wrapper update -\nDocumentation of pow2 : a to the power b\nName of pow2 : power\n" }, { "code": null, "e": 7882, "s": 7546, "text": "It updates a wrapper function to look like the wrapped function. For example, in case of partial functions, we can update partial function to look like its parent function by using update_wrapper(partial, parent). This will update the documentation(__doc__) and name(__name__) of the partial function to same as of the parent function." }, { "code": null, "e": 7891, "s": 7882, "text": "Syntax :" }, { "code": null, "e": 7947, "s": 7891, "text": "update_wrapper(wrapper, wrapped[, assigned][, updated])" }, { "code": null, "e": 7956, "s": 7947, "text": "Example:" }, { "code": "from functools import update_wrapper, partial def power(a, b): ''' a to the power b''' return a**b # partial functionpow2 = partial(power, b = 2)pow2.__doc__='''a to the power 2'''pow2.__name__ = 'pow2' print('Before wrapper update -')print('Documentation of pow2 :', pow2.__doc__)print('Name of pow2 :', pow2.__name__)print()update_wrapper(pow2, power)print('After wrapper update -')print('Documentation of pow2 :', pow2.__doc__)print('Name of pow2 :', pow2.__name__)", "e": 8434, "s": 7956, "text": null }, { "code": null, "e": 8443, "s": 8434, "text": "Output :" }, { "code": null, "e": 8616, "s": 8443, "text": "Before wrapper update -\nDocumentation of pow2 : a to the power 2\nName of pow2 : pow2\n\nAfter wrapper update -\nDocumentation of pow2 : a to the power b\nName of pow2 : power\n" }, { "code": null, "e": 9280, "s": 8616, "text": "WrapsIt is a function decorator which applies update_wrapper() to the decorated function. It is equivalent to partial(update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated).Example:from functools import wraps def decorator(f): @wraps(f) def decorated(*args, **kwargs): \"\"\"Decorator's docstring\"\"\" return f(*args, **kwargs) print('Documentation of decorated :', decorated.__doc__) return decorated @decoratordef f(x): \"\"\"f's Docstring\"\"\" return x print('f name :', f.__name__)print('Documentation of f :', f.__doc__)Output :Documentation of decorated : f's Docstring\nf name : f\nDocumentation of f : f's Docstring\n" }, { "code": null, "e": 9289, "s": 9280, "text": "Example:" }, { "code": "from functools import wraps def decorator(f): @wraps(f) def decorated(*args, **kwargs): \"\"\"Decorator's docstring\"\"\" return f(*args, **kwargs) print('Documentation of decorated :', decorated.__doc__) return decorated @decoratordef f(x): \"\"\"f's Docstring\"\"\" return x print('f name :', f.__name__)print('Documentation of f :', f.__doc__)", "e": 9661, "s": 9289, "text": null }, { "code": null, "e": 9670, "s": 9661, "text": "Output :" }, { "code": null, "e": 9760, "s": 9670, "text": "Documentation of decorated : f's Docstring\nf name : f\nDocumentation of f : f's Docstring\n" }, { "code": null, "e": 10494, "s": 9760, "text": "LRU_cacheLRU_cache is a function decorator used for saving up to the maxsize most recent calls of a function. This can save time and memory in case of repeated calls with the same arguments.If *maxsize* is set to None, the cache can grow without bound. If *typed* is True, arguments of different data types will be cached separately. For example, f(1.0) and f(1) will be memoized distinctly.Syntax :lru_cache(maxsize=128, typed=False)Example:from functools import lru_cache @lru_cache(maxsize = None)def factorial(n): if n<= 1: return 1 return n * factorial(n-1)print([factorial(n) for n in range(7)])print(factorial.cache_info())Output :[1, 1, 2, 6, 24, 120, 720]\nCacheInfo(hits=5, misses=7, maxsize=None, currsize=7)\n" }, { "code": null, "e": 10877, "s": 10494, "text": "LRU_cache is a function decorator used for saving up to the maxsize most recent calls of a function. This can save time and memory in case of repeated calls with the same arguments.If *maxsize* is set to None, the cache can grow without bound. If *typed* is True, arguments of different data types will be cached separately. For example, f(1.0) and f(1) will be memoized distinctly." }, { "code": null, "e": 10886, "s": 10877, "text": "Syntax :" }, { "code": null, "e": 10922, "s": 10886, "text": "lru_cache(maxsize=128, typed=False)" }, { "code": null, "e": 10931, "s": 10922, "text": "Example:" }, { "code": "from functools import lru_cache @lru_cache(maxsize = None)def factorial(n): if n<= 1: return 1 return n * factorial(n-1)print([factorial(n) for n in range(7)])print(factorial.cache_info())", "e": 11134, "s": 10931, "text": null }, { "code": null, "e": 11143, "s": 11134, "text": "Output :" }, { "code": null, "e": 11225, "s": 11143, "text": "[1, 1, 2, 6, 24, 120, 720]\nCacheInfo(hits=5, misses=7, maxsize=None, currsize=7)\n" }, { "code": null, "e": 11705, "s": 11225, "text": "SingleDispatchIt is a function decorator. It transforms a function into a generic function so that it can have different behaviors depending upon the type of its first argument. It is used for function overloading, the overloaded implementations are registered using the register() attribute of theExample:from functools import singledispatch @singledispatchdef fun(s): print(s)@fun.register(int)def _(s): print(s * 2) fun('GeeksforGeeks')fun(10)Output :GeeksforGeeks\n20\n" }, { "code": null, "e": 11714, "s": 11705, "text": "Example:" }, { "code": "from functools import singledispatch @singledispatchdef fun(s): print(s)@fun.register(int)def _(s): print(s * 2) fun('GeeksforGeeks')fun(10)", "e": 11863, "s": 11714, "text": null }, { "code": null, "e": 11872, "s": 11863, "text": "Output :" }, { "code": null, "e": 11890, "s": 11872, "text": "GeeksforGeeks\n20\n" }, { "code": null, "e": 11905, "s": 11890, "text": "python-modules" }, { "code": null, "e": 11912, "s": 11905, "text": "Python" } ]
Java Program for Longest Palindromic Subsequence | DP-12
13 Aug, 2021 Given a sequence, find the length of the longest palindromic subsequence in it. As another example, if the given sequence is “BBABCBCAB”, then the output should be 7 as “BABCBAB” is the longest palindromic subsequence in it. “BBBBB” and “BBCBB” are also palindromic subsequences of the given sequence, but not the longest ones. 1) Optimal Substructure: Let X[0..n-1] be the input sequence of length n and L(0, n-1) be the length of the longest palindromic subsequence of X[0..n-1]. If last and first characters of X are same, then L(0, n-1) = L(1, n-2) + 2. Else L(0, n-1) = MAX (L(1, n-1), L(0, n-2)). Following is a general recursive solution with all cases handled. Java // Java program of above approachclass GFG { // A utility function to get max of two integers static int max(int x, int y) { return (x > y) ? x : y; } // Returns the length of the longest palindromic subsequence in seq static int lps(char seq[], int i, int j) { // Base Case 1: If there is only 1 character if (i == j) { return 1; } // Base Case 2: If there are only 2 characters and both are same if (seq[i] == seq[j] && i + 1 == j) { return 2; } // If the first and last characters match if (seq[i] == seq[j]) { return lps(seq, i + 1, j - 1) + 2; } // If the first and last characters do not match return max(lps(seq, i, j - 1), lps(seq, i + 1, j)); } /* Driver program to test above function */ public static void main(String[] args) { String seq = "GEEKSFORGEEKS"; int n = seq.length(); System.out.printf("The length of the LPS is %d", lps(seq.toCharArray(), 0, n - 1)); }} The length of the LPS is 5 Dynamic Programming Solution Java // A Dynamic Programming based Java// Program for the Egg Dropping Puzzleclass LPS { // A utility function to get max of two integers static int max(int x, int y) { return (x > y) ? x : y; } // Returns the length of the longest // palindromic subsequence in seq static int lps(String seq) { int n = seq.length(); int i, j, cl; // Create a table to store results of subproblems int L[][] = new int[n][n]; // Strings of length 1 are palindrome of length 1 for (i = 0; i < n; i++) L[i][i] = 1; // Build the table. Note that the lower // diagonal values of table are // useless and not filled in the process. // The values are filled in a manner similar // to Matrix Chain Multiplication DP solution (See // https:// www.geeksforgeeks.org/matrix-chain-multiplication-dp-8/). // cl is length of substring for (cl = 2; cl <= n; cl++) { for (i = 0; i < n - cl + 1; i++) { j = i + cl - 1; if (seq.charAt(i) == seq.charAt(j) && cl == 2) L[i][j] = 2; else if (seq.charAt(i) == seq.charAt(j)) L[i][j] = L[i + 1][j - 1] + 2; else L[i][j] = max(L[i][j - 1], L[i + 1][j]); } } return L[0][n - 1]; } /* Driver program to test above functions */ public static void main(String args[]) { String seq = "GEEKSFORGEEKS"; int n = seq.length(); System.out.println("The length of the lps is " + lps(seq)); }}/* This code is contributed by Rajat Mishra */ The length of the lps is 5 Please refer complete article on Longest Palindromic Subsequence | DP-12 for more details! gulshankumarar231 singghakshay Java Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Aug, 2021" }, { "code": null, "e": 108, "s": 28, "text": "Given a sequence, find the length of the longest palindromic subsequence in it." }, { "code": null, "e": 357, "s": 108, "text": "As another example, if the given sequence is “BBABCBCAB”, then the output should be 7 as “BABCBAB” is the longest palindromic subsequence in it. “BBBBB” and “BBCBB” are also palindromic subsequences of the given sequence, but not the longest ones. " }, { "code": null, "e": 633, "s": 357, "text": "1) Optimal Substructure: Let X[0..n-1] be the input sequence of length n and L(0, n-1) be the length of the longest palindromic subsequence of X[0..n-1]. If last and first characters of X are same, then L(0, n-1) = L(1, n-2) + 2. Else L(0, n-1) = MAX (L(1, n-1), L(0, n-2)). " }, { "code": null, "e": 700, "s": 633, "text": "Following is a general recursive solution with all cases handled. " }, { "code": null, "e": 705, "s": 700, "text": "Java" }, { "code": "// Java program of above approachclass GFG { // A utility function to get max of two integers static int max(int x, int y) { return (x > y) ? x : y; } // Returns the length of the longest palindromic subsequence in seq static int lps(char seq[], int i, int j) { // Base Case 1: If there is only 1 character if (i == j) { return 1; } // Base Case 2: If there are only 2 characters and both are same if (seq[i] == seq[j] && i + 1 == j) { return 2; } // If the first and last characters match if (seq[i] == seq[j]) { return lps(seq, i + 1, j - 1) + 2; } // If the first and last characters do not match return max(lps(seq, i, j - 1), lps(seq, i + 1, j)); } /* Driver program to test above function */ public static void main(String[] args) { String seq = \"GEEKSFORGEEKS\"; int n = seq.length(); System.out.printf(\"The length of the LPS is %d\", lps(seq.toCharArray(), 0, n - 1)); }}", "e": 1785, "s": 705, "text": null }, { "code": null, "e": 1812, "s": 1785, "text": "The length of the LPS is 5" }, { "code": null, "e": 1844, "s": 1814, "text": "Dynamic Programming Solution " }, { "code": null, "e": 1849, "s": 1844, "text": "Java" }, { "code": "// A Dynamic Programming based Java// Program for the Egg Dropping Puzzleclass LPS { // A utility function to get max of two integers static int max(int x, int y) { return (x > y) ? x : y; } // Returns the length of the longest // palindromic subsequence in seq static int lps(String seq) { int n = seq.length(); int i, j, cl; // Create a table to store results of subproblems int L[][] = new int[n][n]; // Strings of length 1 are palindrome of length 1 for (i = 0; i < n; i++) L[i][i] = 1; // Build the table. Note that the lower // diagonal values of table are // useless and not filled in the process. // The values are filled in a manner similar // to Matrix Chain Multiplication DP solution (See // https:// www.geeksforgeeks.org/matrix-chain-multiplication-dp-8/). // cl is length of substring for (cl = 2; cl <= n; cl++) { for (i = 0; i < n - cl + 1; i++) { j = i + cl - 1; if (seq.charAt(i) == seq.charAt(j) && cl == 2) L[i][j] = 2; else if (seq.charAt(i) == seq.charAt(j)) L[i][j] = L[i + 1][j - 1] + 2; else L[i][j] = max(L[i][j - 1], L[i + 1][j]); } } return L[0][n - 1]; } /* Driver program to test above functions */ public static void main(String args[]) { String seq = \"GEEKSFORGEEKS\"; int n = seq.length(); System.out.println(\"The length of the lps is \" + lps(seq)); }}/* This code is contributed by Rajat Mishra */", "e": 3503, "s": 1849, "text": null }, { "code": null, "e": 3530, "s": 3503, "text": "The length of the lps is 5" }, { "code": null, "e": 3622, "s": 3530, "text": "Please refer complete article on Longest Palindromic Subsequence | DP-12 for more details! " }, { "code": null, "e": 3640, "s": 3622, "text": "gulshankumarar231" }, { "code": null, "e": 3653, "s": 3640, "text": "singghakshay" }, { "code": null, "e": 3667, "s": 3653, "text": "Java Programs" } ]
MySQL | LAST_DAY() Function
21 Mar, 2018 The LAST_DAY() function in MySQL can be used to know the last day of the month for a given date or a datetime. The LAST_DAY() function takes a date value as argument and returns the last day of month in that date. The date argument represents a valid date or datetime. Syntax: LAST_DAY( Date ); If the date or datetime value is invalid, the function returns NULL. Parameters Used:Date: The LAST_DAY() function takes a single argument Date. It is the date or datetime value for which you want to extract the last day of the month. Return Value:The LAST_DAY() function returns the last day of the month for a valid Date argument. If the argument Date is invalid or null, then the function will also return NULL. Below are some common examples or usages of the LAST_DAY() function: Extracting last day from a given date:To know the last date of the month December 2017,the LAST_DAY() function can be executed in the following way:Syntax :Output :'2017-12-31'Extracting the last day from a given datetime:To know the last date of the month December using datetime format,the LAST_DAY() function can be executed in the following way:Syntax :Output :'2017-12-31'Checking whether it is a leap year or not:To know whether the year is a leap year or not, we can use the LAST_DAY() function to check the last day of the month February of that year. If it is the 29th day then that year is leap otherwise not.Syntax :Output :'2016-02-29'Extracting the last day for the current month:To know the last date of the current month ,the LAST_DAY() function is combined with the NOW() or CURDATE() function and can be executed in the following way:Using the NOW() function: The NOW() function in MySQL returns the current date-time stamp.Syntax :Output :'2017-12-31'Using the CURDATE() function: The CURDATE() function in MySQL return the current date in Date format.Syntax :Output :'2017-12-31'Extracting the last day of the next month:To know the last date of the next month,the last_day() function can be executed in the following way:Syntax :Output :'2018-01-31' Extracting last day from a given date:To know the last date of the month December 2017,the LAST_DAY() function can be executed in the following way:Syntax :Output :'2017-12-31' '2017-12-31' Extracting the last day from a given datetime:To know the last date of the month December using datetime format,the LAST_DAY() function can be executed in the following way:Syntax :Output :'2017-12-31' '2017-12-31' Checking whether it is a leap year or not:To know whether the year is a leap year or not, we can use the LAST_DAY() function to check the last day of the month February of that year. If it is the 29th day then that year is leap otherwise not.Syntax :Output :'2016-02-29' '2016-02-29' Extracting the last day for the current month:To know the last date of the current month ,the LAST_DAY() function is combined with the NOW() or CURDATE() function and can be executed in the following way:Using the NOW() function: The NOW() function in MySQL returns the current date-time stamp.Syntax :Output :'2017-12-31' '2017-12-31' Using the CURDATE() function: The CURDATE() function in MySQL return the current date in Date format.Syntax :Output :'2017-12-31' '2017-12-31' Extracting the last day of the next month:To know the last date of the next month,the last_day() function can be executed in the following way:Syntax :Output :'2018-01-31' '2018-01-31' mysql SQL-Functions SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Mar, 2018" }, { "code": null, "e": 297, "s": 28, "text": "The LAST_DAY() function in MySQL can be used to know the last day of the month for a given date or a datetime. The LAST_DAY() function takes a date value as argument and returns the last day of month in that date. The date argument represents a valid date or datetime." }, { "code": null, "e": 305, "s": 297, "text": "Syntax:" }, { "code": null, "e": 324, "s": 305, "text": "LAST_DAY( Date );\n" }, { "code": null, "e": 393, "s": 324, "text": "If the date or datetime value is invalid, the function returns NULL." }, { "code": null, "e": 559, "s": 393, "text": "Parameters Used:Date: The LAST_DAY() function takes a single argument Date. It is the date or datetime value for which you want to extract the last day of the month." }, { "code": null, "e": 739, "s": 559, "text": "Return Value:The LAST_DAY() function returns the last day of the month for a valid Date argument. If the argument Date is invalid or null, then the function will also return NULL." }, { "code": null, "e": 808, "s": 739, "text": "Below are some common examples or usages of the LAST_DAY() function:" }, { "code": null, "e": 2078, "s": 808, "text": "Extracting last day from a given date:To know the last date of the month December 2017,the LAST_DAY() function can be executed in the following way:Syntax :Output :'2017-12-31'Extracting the last day from a given datetime:To know the last date of the month December using datetime format,the LAST_DAY() function can be executed in the following way:Syntax :Output :'2017-12-31'Checking whether it is a leap year or not:To know whether the year is a leap year or not, we can use the LAST_DAY() function to check the last day of the month February of that year. If it is the 29th day then that year is leap otherwise not.Syntax :Output :'2016-02-29'Extracting the last day for the current month:To know the last date of the current month ,the LAST_DAY() function is combined with the NOW() or CURDATE() function and can be executed in the following way:Using the NOW() function: The NOW() function in MySQL returns the current date-time stamp.Syntax :Output :'2017-12-31'Using the CURDATE() function: The CURDATE() function in MySQL return the current date in Date format.Syntax :Output :'2017-12-31'Extracting the last day of the next month:To know the last date of the next month,the last_day() function can be executed in the following way:Syntax :Output :'2018-01-31'" }, { "code": null, "e": 2255, "s": 2078, "text": "Extracting last day from a given date:To know the last date of the month December 2017,the LAST_DAY() function can be executed in the following way:Syntax :Output :'2017-12-31'" }, { "code": null, "e": 2268, "s": 2255, "text": "'2017-12-31'" }, { "code": null, "e": 2470, "s": 2268, "text": "Extracting the last day from a given datetime:To know the last date of the month December using datetime format,the LAST_DAY() function can be executed in the following way:Syntax :Output :'2017-12-31'" }, { "code": null, "e": 2483, "s": 2470, "text": "'2017-12-31'" }, { "code": null, "e": 2754, "s": 2483, "text": "Checking whether it is a leap year or not:To know whether the year is a leap year or not, we can use the LAST_DAY() function to check the last day of the month February of that year. If it is the 29th day then that year is leap otherwise not.Syntax :Output :'2016-02-29'" }, { "code": null, "e": 2767, "s": 2754, "text": "'2016-02-29'" }, { "code": null, "e": 3090, "s": 2767, "text": "Extracting the last day for the current month:To know the last date of the current month ,the LAST_DAY() function is combined with the NOW() or CURDATE() function and can be executed in the following way:Using the NOW() function: The NOW() function in MySQL returns the current date-time stamp.Syntax :Output :'2017-12-31'" }, { "code": null, "e": 3103, "s": 3090, "text": "'2017-12-31'" }, { "code": null, "e": 3233, "s": 3103, "text": "Using the CURDATE() function: The CURDATE() function in MySQL return the current date in Date format.Syntax :Output :'2017-12-31'" }, { "code": null, "e": 3246, "s": 3233, "text": "'2017-12-31'" }, { "code": null, "e": 3418, "s": 3246, "text": "Extracting the last day of the next month:To know the last date of the next month,the last_day() function can be executed in the following way:Syntax :Output :'2018-01-31'" }, { "code": null, "e": 3431, "s": 3418, "text": "'2018-01-31'" }, { "code": null, "e": 3437, "s": 3431, "text": "mysql" }, { "code": null, "e": 3451, "s": 3437, "text": "SQL-Functions" }, { "code": null, "e": 3455, "s": 3451, "text": "SQL" }, { "code": null, "e": 3459, "s": 3455, "text": "SQL" } ]
Python | Pandas Series.item()
12 Feb, 2019 Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.item() function return the first element of the underlying data of the given series object as a python scalar. Note : This function can only convert an array of size 1 to a Python scalar Syntax: Series.item() Parameter : None Returns : scalar Example #1: Use Series.item() function to return the first element of the given series object as a scalar. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([248]) # Create the Indexindex_ = ['Coca Cola'] # set the indexsr.index = index_ # Print the seriesprint(sr) Output : Now we will use Series.item() function to return the first element of the given series object as a scalar. # return a scalarresult = sr.item() # Print the resultprint(result) Output : As we can see in the output, the Series.item() function has successfully returned a scalar value. Example #2 : Use Series.item() function to iterate over all the elements in the given series object. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([11]) # Create the Indexindex_ = pd.date_range('2010-10-09', periods = 1, freq ='M') # set the indexsr.index = index_ # Print the seriesprint(sr) Output : Now we will use Series.item() function to return the first element of the given series object as a scalar. # return a scalarresult = sr.item() # Print the resultprint(result) Output : As we can see in the output, the Series.item() function has successfully returned a scalar value. Python pandas-series Python pandas-series-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Feb, 2019" }, { "code": null, "e": 285, "s": 28, "text": "Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index." }, { "code": null, "e": 410, "s": 285, "text": "Pandas Series.item() function return the first element of the underlying data of the given series object as a python scalar." }, { "code": null, "e": 486, "s": 410, "text": "Note : This function can only convert an array of size 1 to a Python scalar" }, { "code": null, "e": 508, "s": 486, "text": "Syntax: Series.item()" }, { "code": null, "e": 525, "s": 508, "text": "Parameter : None" }, { "code": null, "e": 542, "s": 525, "text": "Returns : scalar" }, { "code": null, "e": 649, "s": 542, "text": "Example #1: Use Series.item() function to return the first element of the given series object as a scalar." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([248]) # Create the Indexindex_ = ['Coca Cola'] # set the indexsr.index = index_ # Print the seriesprint(sr)", "e": 842, "s": 649, "text": null }, { "code": null, "e": 851, "s": 842, "text": "Output :" }, { "code": null, "e": 958, "s": 851, "text": "Now we will use Series.item() function to return the first element of the given series object as a scalar." }, { "code": "# return a scalarresult = sr.item() # Print the resultprint(result)", "e": 1027, "s": 958, "text": null }, { "code": null, "e": 1036, "s": 1027, "text": "Output :" }, { "code": null, "e": 1235, "s": 1036, "text": "As we can see in the output, the Series.item() function has successfully returned a scalar value. Example #2 : Use Series.item() function to iterate over all the elements in the given series object." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([11]) # Create the Indexindex_ = pd.date_range('2010-10-09', periods = 1, freq ='M') # set the indexsr.index = index_ # Print the seriesprint(sr)", "e": 1465, "s": 1235, "text": null }, { "code": null, "e": 1474, "s": 1465, "text": "Output :" }, { "code": null, "e": 1581, "s": 1474, "text": "Now we will use Series.item() function to return the first element of the given series object as a scalar." }, { "code": "# return a scalarresult = sr.item() # Print the resultprint(result)", "e": 1650, "s": 1581, "text": null }, { "code": null, "e": 1659, "s": 1650, "text": "Output :" }, { "code": null, "e": 1757, "s": 1659, "text": "As we can see in the output, the Series.item() function has successfully returned a scalar value." }, { "code": null, "e": 1778, "s": 1757, "text": "Python pandas-series" }, { "code": null, "e": 1807, "s": 1778, "text": "Python pandas-series-methods" }, { "code": null, "e": 1821, "s": 1807, "text": "Python-pandas" }, { "code": null, "e": 1828, "s": 1821, "text": "Python" } ]
React Native WebView Component
28 Apr, 2021 In this article, We are going to see how to create a WebView in react-native. WebView is used to display web content in an application. For this, we are going to use WebView Component. Syntax : <WebView source={} /> Props of WebView : source: It basically loads the URL in the web view. automaticallyAdjustContentInsets: It controls the content inset for web views. It’s default value is true. injectJavaScript: It injects JavaScript into the web view. injectedJavaScript: It also injects JavaScript into the web view, but it runs immediately as the view loaded, and it runs once only. mediaPlaybackRequiresUserAction: It determines whether the HTML5 audio and video require the user to tap them before they start playing. By default, it is true. nativeConfig: It overrides the native component which is used to render the web view. onError: It is a function that is invoked when web view load fails. onLoad: It is a function that is invoked when the web view is loaded. onLoadEnd: It is a function that is invoked when the web view load is ended. onLoadStart: It is a function that is invoked when the web view starts loading. onMessage : It is a function that is invoked when the WebView calls ‘window.postMessage‘. onNavigationStateChange: It is a function that is invoked when the WebView loading starts or ends. originWhitelist: It is a list of origin strings to allow being navigated to. The default origin lists are “http://*” and “https://*”. renderError: It is a function that returns a view to show if there’s an error. renderLoading: It is a function that returns a loading indicator. scalesPageToFit: It controls whether the content is scaled to fit the view or not. It’s default value is true. onShouldStartLoadWithRequest: It is a function that allows custom handling of any web view request. startInLoadingState: It basically forces the WebView to show the loading view on the first load. decelerationRate: It is a floating-point number that determines how quickly the scroll view decelerates. You can also use the shortcut i.e. normal and fast. domStorageEnabled: It controls whether the DOM storage is enabled or not. It is only for the android platform. javaScriptEnabled: It controls whether the JavaScript is enabled or not. It is only for the android platform and by default its value is true. mixedContentMode: It basically specifies the mixed content model. Its possible values are never, always, and compatible. thirdPartyCookiesEnabled: It enables the third-party cookies if true. Its default value is true. userAgent: It sets the user agent for the web view. allowsInlineMediaPlayback: It determines whether HTML5 videos play inline or use the native full-screen controller. It’s default value is false. bounces: It determines whether the web view bounces when it reaches the edge of the content. Its default value is true. contentInset: It is the amount by which the web view content is inset from the edges of the scroll view. dataDetectorTypes: It determines the types of data converted to clickable URLs in the web view’s content. It’s possible values are phoneNumber, link, address, calendar event, none and all. scrollEnabled: It determines whether the scrolling is enabled or not. By default, it is true. geolocationEnabled: It determines whether the geolocation enables or not in web view. By default, it is false. allowUniversalAccessFromFileURLs: It determines whether JavaScript running in the context of a file scheme URL should be allowed to access content from any origin. Its default value is false. allowFileAccess: It determines whether web view has system files access or not. By default, it is false. useWebKit: It is a deprecated prop. Use the source prop instead. html: It is also a deprecated prop. Use the source prop instead. Methods in WebView : goForward(): It takes you one page forward in the web view. goBack(): It takes you one page back in the web view. reload(): It reloads the current page in the web view. stopLoading() : It stops loading in web view. Now let’s start with the implementation: Step 1: Open your terminal and install expo-cli by the following command.npm install -g expo-cli Step 1: Open your terminal and install expo-cli by the following command. npm install -g expo-cli Step 2: Now create a project by the following command.expo init myapp Step 2: Now create a project by the following command. expo init myapp Step 3: Now go into your project folder i.e. myappcd myapp Step 3: Now go into your project folder i.e. myapp cd myapp Step 4: For WebView we have WebView component in react-native which helps us to display the web content in an application, but that component is now deprecated, So in substitute for this we are going to use an external package called react-native-webview. Install that package by using the following command.npm install react-native-webview Step 4: For WebView we have WebView component in react-native which helps us to display the web content in an application, but that component is now deprecated, So in substitute for this we are going to use an external package called react-native-webview. Install that package by using the following command. npm install react-native-webview Project Structure : Example: Now let’s implement the WebView. Here we are going to render the GeeksforGeeks website in our webview. App.js import React from 'react';import { WebView } from 'react-native-webview';export default function App() { return ( <WebView source={{ uri: 'https://geeksforgeeks.org/' }} /> );} Start the server by using the following command. npm run android Output: If your emulator did not open automatically then you need to do it manually. First, go to your android studio and run the emulator. Now start the server again. Reference: https://reactnative.dev/docs/0.61/webview Picked React-Native 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": "\n28 Apr, 2021" }, { "code": null, "e": 214, "s": 28, "text": "In this article, We are going to see how to create a WebView in react-native. WebView is used to display web content in an application. For this, we are going to use WebView Component. " }, { "code": null, "e": 224, "s": 214, "text": "Syntax : " }, { "code": null, "e": 250, "s": 224, "text": "<WebView\n source={}\n/>" }, { "code": null, "e": 270, "s": 250, "text": "Props of WebView : " }, { "code": null, "e": 322, "s": 270, "text": "source: It basically loads the URL in the web view." }, { "code": null, "e": 429, "s": 322, "text": "automaticallyAdjustContentInsets: It controls the content inset for web views. It’s default value is true." }, { "code": null, "e": 489, "s": 429, "text": " injectJavaScript: It injects JavaScript into the web view." }, { "code": null, "e": 622, "s": 489, "text": "injectedJavaScript: It also injects JavaScript into the web view, but it runs immediately as the view loaded, and it runs once only." }, { "code": null, "e": 783, "s": 622, "text": "mediaPlaybackRequiresUserAction: It determines whether the HTML5 audio and video require the user to tap them before they start playing. By default, it is true." }, { "code": null, "e": 869, "s": 783, "text": "nativeConfig: It overrides the native component which is used to render the web view." }, { "code": null, "e": 939, "s": 869, "text": "onError: It is a function that is invoked when web view load fails. " }, { "code": null, "e": 1009, "s": 939, "text": "onLoad: It is a function that is invoked when the web view is loaded." }, { "code": null, "e": 1086, "s": 1009, "text": "onLoadEnd: It is a function that is invoked when the web view load is ended." }, { "code": null, "e": 1166, "s": 1086, "text": "onLoadStart: It is a function that is invoked when the web view starts loading." }, { "code": null, "e": 1256, "s": 1166, "text": "onMessage : It is a function that is invoked when the WebView calls ‘window.postMessage‘." }, { "code": null, "e": 1355, "s": 1256, "text": "onNavigationStateChange: It is a function that is invoked when the WebView loading starts or ends." }, { "code": null, "e": 1489, "s": 1355, "text": "originWhitelist: It is a list of origin strings to allow being navigated to. The default origin lists are “http://*” and “https://*”." }, { "code": null, "e": 1568, "s": 1489, "text": "renderError: It is a function that returns a view to show if there’s an error." }, { "code": null, "e": 1634, "s": 1568, "text": "renderLoading: It is a function that returns a loading indicator." }, { "code": null, "e": 1745, "s": 1634, "text": "scalesPageToFit: It controls whether the content is scaled to fit the view or not. It’s default value is true." }, { "code": null, "e": 1845, "s": 1745, "text": "onShouldStartLoadWithRequest: It is a function that allows custom handling of any web view request." }, { "code": null, "e": 1942, "s": 1845, "text": "startInLoadingState: It basically forces the WebView to show the loading view on the first load." }, { "code": null, "e": 2099, "s": 1942, "text": "decelerationRate: It is a floating-point number that determines how quickly the scroll view decelerates. You can also use the shortcut i.e. normal and fast." }, { "code": null, "e": 2210, "s": 2099, "text": "domStorageEnabled: It controls whether the DOM storage is enabled or not. It is only for the android platform." }, { "code": null, "e": 2353, "s": 2210, "text": "javaScriptEnabled: It controls whether the JavaScript is enabled or not. It is only for the android platform and by default its value is true." }, { "code": null, "e": 2474, "s": 2353, "text": "mixedContentMode: It basically specifies the mixed content model. Its possible values are never, always, and compatible." }, { "code": null, "e": 2571, "s": 2474, "text": "thirdPartyCookiesEnabled: It enables the third-party cookies if true. Its default value is true." }, { "code": null, "e": 2623, "s": 2571, "text": "userAgent: It sets the user agent for the web view." }, { "code": null, "e": 2768, "s": 2623, "text": "allowsInlineMediaPlayback: It determines whether HTML5 videos play inline or use the native full-screen controller. It’s default value is false." }, { "code": null, "e": 2888, "s": 2768, "text": "bounces: It determines whether the web view bounces when it reaches the edge of the content. Its default value is true." }, { "code": null, "e": 2994, "s": 2888, "text": "contentInset: It is the amount by which the web view content is inset from the edges of the scroll view. " }, { "code": null, "e": 3183, "s": 2994, "text": "dataDetectorTypes: It determines the types of data converted to clickable URLs in the web view’s content. It’s possible values are phoneNumber, link, address, calendar event, none and all." }, { "code": null, "e": 3277, "s": 3183, "text": "scrollEnabled: It determines whether the scrolling is enabled or not. By default, it is true." }, { "code": null, "e": 3388, "s": 3277, "text": "geolocationEnabled: It determines whether the geolocation enables or not in web view. By default, it is false." }, { "code": null, "e": 3580, "s": 3388, "text": "allowUniversalAccessFromFileURLs: It determines whether JavaScript running in the context of a file scheme URL should be allowed to access content from any origin. Its default value is false." }, { "code": null, "e": 3685, "s": 3580, "text": "allowFileAccess: It determines whether web view has system files access or not. By default, it is false." }, { "code": null, "e": 3750, "s": 3685, "text": "useWebKit: It is a deprecated prop. Use the source prop instead." }, { "code": null, "e": 3815, "s": 3750, "text": "html: It is also a deprecated prop. Use the source prop instead." }, { "code": null, "e": 3837, "s": 3815, "text": "Methods in WebView : " }, { "code": null, "e": 3897, "s": 3837, "text": "goForward(): It takes you one page forward in the web view." }, { "code": null, "e": 3951, "s": 3897, "text": "goBack(): It takes you one page back in the web view." }, { "code": null, "e": 4006, "s": 3951, "text": "reload(): It reloads the current page in the web view." }, { "code": null, "e": 4052, "s": 4006, "text": "stopLoading() : It stops loading in web view." }, { "code": null, "e": 4093, "s": 4052, "text": "Now let’s start with the implementation:" }, { "code": null, "e": 4190, "s": 4093, "text": "Step 1: Open your terminal and install expo-cli by the following command.npm install -g expo-cli" }, { "code": null, "e": 4264, "s": 4190, "text": "Step 1: Open your terminal and install expo-cli by the following command." }, { "code": null, "e": 4288, "s": 4264, "text": "npm install -g expo-cli" }, { "code": null, "e": 4358, "s": 4288, "text": "Step 2: Now create a project by the following command.expo init myapp" }, { "code": null, "e": 4413, "s": 4358, "text": "Step 2: Now create a project by the following command." }, { "code": null, "e": 4429, "s": 4413, "text": "expo init myapp" }, { "code": null, "e": 4488, "s": 4429, "text": "Step 3: Now go into your project folder i.e. myappcd myapp" }, { "code": null, "e": 4539, "s": 4488, "text": "Step 3: Now go into your project folder i.e. myapp" }, { "code": null, "e": 4548, "s": 4539, "text": "cd myapp" }, { "code": null, "e": 4889, "s": 4548, "text": "Step 4: For WebView we have WebView component in react-native which helps us to display the web content in an application, but that component is now deprecated, So in substitute for this we are going to use an external package called react-native-webview. Install that package by using the following command.npm install react-native-webview" }, { "code": null, "e": 5198, "s": 4889, "text": "Step 4: For WebView we have WebView component in react-native which helps us to display the web content in an application, but that component is now deprecated, So in substitute for this we are going to use an external package called react-native-webview. Install that package by using the following command." }, { "code": null, "e": 5231, "s": 5198, "text": "npm install react-native-webview" }, { "code": null, "e": 5252, "s": 5231, "text": "Project Structure : " }, { "code": null, "e": 5364, "s": 5252, "text": "Example: Now let’s implement the WebView. Here we are going to render the GeeksforGeeks website in our webview." }, { "code": null, "e": 5371, "s": 5364, "text": "App.js" }, { "code": "import React from 'react';import { WebView } from 'react-native-webview';export default function App() { return ( <WebView source={{ uri: 'https://geeksforgeeks.org/' }} /> );}", "e": 5555, "s": 5371, "text": null }, { "code": null, "e": 5604, "s": 5555, "text": "Start the server by using the following command." }, { "code": null, "e": 5620, "s": 5604, "text": "npm run android" }, { "code": null, "e": 5789, "s": 5620, "text": "Output: If your emulator did not open automatically then you need to do it manually. First, go to your android studio and run the emulator. Now start the server again. " }, { "code": null, "e": 5842, "s": 5789, "text": "Reference: https://reactnative.dev/docs/0.61/webview" }, { "code": null, "e": 5849, "s": 5842, "text": "Picked" }, { "code": null, "e": 5862, "s": 5849, "text": "React-Native" }, { "code": null, "e": 5879, "s": 5862, "text": "Web Technologies" } ]
What are the uses of super keyword in java?
The super keyword in Java is a reference to the object of the parent/superclass. Using it, you can refer/call a field, a method or, a constructor of the immediate superclass. As mentioned above, you can refer to an instance filed/variable of the immediate superclass from an instance method or, a constructor of a subclass, using the "super" keyword. If a class extends another class, a copy of members of the parent class will be created in the subclass i.e. Using the object of the subclass you can access the members of both subclass and the superclass. If a class has a variable with name same as the variable of the superclass then, you can differentiate the superclass variable from the subclass variable using the super keyword. In the following Java example, we have two classes SuperClass and SubClass here, the SubClass extends the SuperClass and, both have the same variable "name". From a method of the class SubClass (display()), we are printing the value of the instance variable (name) of both classes using "super" and "this" keywords respectively − Live Demo class SuperClass{ String name = "Raju"; public void display() { System.out.println("This is a method of the superclass"); } } public class SubClass extends SuperClass{ String name = "Ramu"; public void display() { System.out.println("This is a method of the superclass"); System.out.println("Value of name in superclass: "+super.name); System.out.println("Value of name in subclass: "+this.name); } public static void main(String args[]) { new SubClass().display(); } } This is a method of the superclass Value of name in superclass: Raju Value of name in subclass: Ramu You can also refer/call a constructor of the superclass from the constructor of the child/subclass using the "super" keyword (explicitly). In the following Java example, we have two classes SuperClass and SubClass. Here, the SubClass extends the SuperClass and both classes have default constructors. We are trying to call the constructor of the superclass from the constructor of the subclass using the super keyword − Live Demo class SuperClass{ String name = "Raju"; public SuperClass() { System.out.println("This is the constructor of the superclass"); } } public class SubClass extends SuperClass{ String name = "Ramu"; public SubClass() { System.out.println("This is a constructor of the subclass"); } public static void main(String args[]) { new SubClass(); } } This is the constructor of the superclass This is a constructor of the subclass You can also use this to call an (instance) method of the superclass from the instance method of the subclass. In the following Java example, we have two classes SuperClass and SubClass. Here, the SubClass extends the SuperClass. Here, we are trying to invoke the display() method of the superclass using the super keyword from the subclass’s method named show. Live Demo class SuperClass{ String name = "Raju"; public void display() { System.out.println("This is a method of the superclass"); } } public class SubClass extends SuperClass{ String name = "Ramu"; public void show() { System.out.println("This is a method of the subclass"); super.display(); } public static void main(String args[]) { new SubClass().show(); } } This is the constructor of the superclass This is a constructor of the subclass
[ { "code": null, "e": 1237, "s": 1062, "text": "The super keyword in Java is a reference to the object of the parent/superclass. Using it, you can refer/call a field, a method or, a constructor of the immediate superclass." }, { "code": null, "e": 1413, "s": 1237, "text": "As mentioned above, you can refer to an instance filed/variable of the immediate superclass from an instance method or, a constructor of a subclass, using the \"super\" keyword." }, { "code": null, "e": 1619, "s": 1413, "text": "If a class extends another class, a copy of members of the parent class will be created in the subclass i.e. Using the object of the subclass you can access the members of both subclass and the superclass." }, { "code": null, "e": 1799, "s": 1619, "text": "If a class has a variable with name same as the variable of the superclass then, you can differentiate the superclass variable from the subclass variable using the super keyword." }, { "code": null, "e": 1957, "s": 1799, "text": "In the following Java example, we have two classes SuperClass and SubClass here, the SubClass extends the SuperClass and, both have the same variable \"name\"." }, { "code": null, "e": 2130, "s": 1957, "text": "From a method of the class SubClass (display()), we are printing the value of the instance variable (name) of both classes using \"super\" and \"this\" keywords respectively −" }, { "code": null, "e": 2141, "s": 2130, "text": " Live Demo" }, { "code": null, "e": 2665, "s": 2141, "text": "class SuperClass{\n String name = \"Raju\";\n public void display() {\n System.out.println(\"This is a method of the superclass\");\n }\n}\npublic class SubClass extends SuperClass{\n String name = \"Ramu\";\n public void display() {\n System.out.println(\"This is a method of the superclass\");\n System.out.println(\"Value of name in superclass: \"+super.name);\n System.out.println(\"Value of name in subclass: \"+this.name);\n }\n public static void main(String args[]) {\n new SubClass().display();\n }\n}" }, { "code": null, "e": 2766, "s": 2665, "text": "This is a method of the superclass\nValue of name in superclass: Raju\nValue of name in subclass: Ramu" }, { "code": null, "e": 2905, "s": 2766, "text": "You can also refer/call a constructor of the superclass from the constructor of the child/subclass using the \"super\" keyword (explicitly)." }, { "code": null, "e": 3186, "s": 2905, "text": "In the following Java example, we have two classes SuperClass and SubClass. Here, the SubClass extends the SuperClass and both classes have default constructors. We are trying to call the constructor of the superclass from the constructor of the subclass using the super keyword −" }, { "code": null, "e": 3197, "s": 3186, "text": " Live Demo" }, { "code": null, "e": 3578, "s": 3197, "text": "class SuperClass{\n String name = \"Raju\";\n public SuperClass() {\n System.out.println(\"This is the constructor of the superclass\");\n }\n}\npublic class SubClass extends SuperClass{\n String name = \"Ramu\";\n public SubClass() {\n System.out.println(\"This is a constructor of the subclass\");\n }\n public static void main(String args[]) {\n new SubClass();\n }\n}" }, { "code": null, "e": 3658, "s": 3578, "text": "This is the constructor of the superclass\nThis is a constructor of the subclass" }, { "code": null, "e": 3769, "s": 3658, "text": "You can also use this to call an (instance) method of the superclass from the instance method of the subclass." }, { "code": null, "e": 3888, "s": 3769, "text": "In the following Java example, we have two classes SuperClass and SubClass. Here, the SubClass extends the SuperClass." }, { "code": null, "e": 4020, "s": 3888, "text": "Here, we are trying to invoke the display() method of the superclass using the super keyword from the subclass’s method named show." }, { "code": null, "e": 4031, "s": 4020, "text": " Live Demo" }, { "code": null, "e": 4433, "s": 4031, "text": "class SuperClass{\n String name = \"Raju\";\n public void display() {\n System.out.println(\"This is a method of the superclass\");\n }\n}\npublic class SubClass extends SuperClass{\n String name = \"Ramu\";\n public void show() {\n System.out.println(\"This is a method of the subclass\");\n super.display();\n }\n public static void main(String args[]) {\n new SubClass().show();\n }\n}" }, { "code": null, "e": 4513, "s": 4433, "text": "This is the constructor of the superclass\nThis is a constructor of the subclass" } ]
MongoDB query to find documents with specific FirstName and LastName
To find documents with specific FirstName and LastName, use $and along with $in. Implement this in MongoDB find(). Let us create a collection with documents − > db.demo692.insertOne({FirstName:"Chris","LastName":"Brown"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea585dca7e81adc6a0b396a") } > db.demo692.insertOne({FirstName:"John","LastName":"Brown"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea585e2a7e81adc6a0b396b") } > db.demo692.insertOne({FirstName:"John","LastName":"Smith"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea585e7a7e81adc6a0b396c") } > db.demo692.insertOne({FirstName:"John","LastName":"Doe"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea585efa7e81adc6a0b396d") } > db.demo692.insertOne({FirstName:"Adam","LastName":"Smith"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea585faa7e81adc6a0b396e") } Display all documents from a collection with the help of find() method − > db.demo692.find(); This will produce the following output − { "_id" : ObjectId("5ea585dca7e81adc6a0b396a"), "FirstName" : "Chris", "LastName" : "Brown" } { "_id" : ObjectId("5ea585e2a7e81adc6a0b396b"), "FirstName" : "John", "LastName" : "Brown" } { "_id" : ObjectId("5ea585e7a7e81adc6a0b396c"), "FirstName" : "John", "LastName" : "Smith" } { "_id" : ObjectId("5ea585efa7e81adc6a0b396d"), "FirstName" : "John", "LastName" : "Doe" } { "_id" : ObjectId("5ea585faa7e81adc6a0b396e"), "FirstName" : "Adam", "LastName" : "Smith" } Following is the query to find documents with specific FirstName and LastName − > db.demo692.find({$and:[ {FirstName: {$in: ["Chris", "John"]}}, ... {LastName:{$in:["Brown", "Smith"]}} ... ] ... } ... ); This will produce the following output − { "_id" : ObjectId("5ea585dca7e81adc6a0b396a"), "FirstName" : "Chris", "LastName" : "Brown" } { "_id" : ObjectId("5ea585e2a7e81adc6a0b396b"), "FirstName" : "John", "LastName" : "Brown" } { "_id" : ObjectId("5ea585e7a7e81adc6a0b396c"), "FirstName" : "John", "LastName" : "Smith" }
[ { "code": null, "e": 1221, "s": 1062, "text": "To find documents with specific FirstName and LastName, use $and along with $in. Implement this in MongoDB find(). Let us create a collection with documents −" }, { "code": null, "e": 1960, "s": 1221, "text": "> db.demo692.insertOne({FirstName:\"Chris\",\"LastName\":\"Brown\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ea585dca7e81adc6a0b396a\")\n}\n> db.demo692.insertOne({FirstName:\"John\",\"LastName\":\"Brown\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ea585e2a7e81adc6a0b396b\")\n}\n> db.demo692.insertOne({FirstName:\"John\",\"LastName\":\"Smith\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ea585e7a7e81adc6a0b396c\")\n}\n> db.demo692.insertOne({FirstName:\"John\",\"LastName\":\"Doe\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ea585efa7e81adc6a0b396d\")\n}\n> db.demo692.insertOne({FirstName:\"Adam\",\"LastName\":\"Smith\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ea585faa7e81adc6a0b396e\")\n}" }, { "code": null, "e": 2033, "s": 1960, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 2054, "s": 2033, "text": "> db.demo692.find();" }, { "code": null, "e": 2095, "s": 2054, "text": "This will produce the following output −" }, { "code": null, "e": 2559, "s": 2095, "text": "{ \"_id\" : ObjectId(\"5ea585dca7e81adc6a0b396a\"), \"FirstName\" : \"Chris\", \"LastName\" : \"Brown\" }\n{ \"_id\" : ObjectId(\"5ea585e2a7e81adc6a0b396b\"), \"FirstName\" : \"John\", \"LastName\" : \"Brown\" }\n{ \"_id\" : ObjectId(\"5ea585e7a7e81adc6a0b396c\"), \"FirstName\" : \"John\", \"LastName\" : \"Smith\" }\n{ \"_id\" : ObjectId(\"5ea585efa7e81adc6a0b396d\"), \"FirstName\" : \"John\", \"LastName\" : \"Doe\" }\n{ \"_id\" : ObjectId(\"5ea585faa7e81adc6a0b396e\"), \"FirstName\" : \"Adam\", \"LastName\" : \"Smith\" }" }, { "code": null, "e": 2639, "s": 2559, "text": "Following is the query to find documents with specific FirstName and LastName −" }, { "code": null, "e": 2763, "s": 2639, "text": "> db.demo692.find({$and:[ {FirstName: {$in: [\"Chris\", \"John\"]}},\n... {LastName:{$in:[\"Brown\", \"Smith\"]}}\n... ]\n... }\n... );" }, { "code": null, "e": 2804, "s": 2763, "text": "This will produce the following output −" }, { "code": null, "e": 3084, "s": 2804, "text": "{ \"_id\" : ObjectId(\"5ea585dca7e81adc6a0b396a\"), \"FirstName\" : \"Chris\", \"LastName\" : \"Brown\" }\n{ \"_id\" : ObjectId(\"5ea585e2a7e81adc6a0b396b\"), \"FirstName\" : \"John\", \"LastName\" : \"Brown\" }\n{ \"_id\" : ObjectId(\"5ea585e7a7e81adc6a0b396c\"), \"FirstName\" : \"John\", \"LastName\" : \"Smith\" }" } ]
First Missing Positive in Python
Suppose we have one unsorted integer array; we have to find the smallest missing positive number. So if the array is like [4, -3, 1, -1], then the result will be 2. To solve this, we will follow these steps − set i := 0 and update array nums by adding one 0 before all numbers set i := 0 and update array nums by adding one 0 before all numbers for i in range 0 to length of numswhile nums[i] >= 0 and nums[i] < length of nums and nums[nums[i]] is not nums[i] −nums[nums[i]] := nums[i]nums[i] := nums[nums[i]] for i in range 0 to length of nums while nums[i] >= 0 and nums[i] < length of nums and nums[nums[i]] is not nums[i] −nums[nums[i]] := nums[i]nums[i] := nums[nums[i]] while nums[i] >= 0 and nums[i] < length of nums and nums[nums[i]] is not nums[i] − nums[nums[i]] := nums[i] nums[nums[i]] := nums[i] nums[i] := nums[nums[i]] nums[i] := nums[nums[i]] num := 1 num := 1 for i in range 1 to length of numsif num = nums[i], then increase num by 1 for i in range 1 to length of nums if num = nums[i], then increase num by 1 if num = nums[i], then increase num by 1 return num return num Let us see the following implementation to get better understanding − Live Demo class Solution(object): def firstMissingPositive(self, nums): i = 0 nums = [0] + nums for i in range(len(nums)): while nums[i]>=0 and nums[i]<len(nums) and nums[nums[i]]!=nums[i]: nums[nums[i]],nums[i] = nums[i],nums[nums[i]] num = 1 for i in range(1,len(nums)): if num == nums[i]: num+=1 return num ob = Solution() print(ob.firstMissingPositive([4,-3,1,-1])) [4,-3,1,-1] 2
[ { "code": null, "e": 1227, "s": 1062, "text": "Suppose we have one unsorted integer array; we have to find the smallest missing positive number. So if the array is like [4, -3, 1, -1], then the result will be 2." }, { "code": null, "e": 1271, "s": 1227, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1339, "s": 1271, "text": "set i := 0 and update array nums by adding one 0 before all numbers" }, { "code": null, "e": 1407, "s": 1339, "text": "set i := 0 and update array nums by adding one 0 before all numbers" }, { "code": null, "e": 1572, "s": 1407, "text": "for i in range 0 to length of numswhile nums[i] >= 0 and nums[i] < length of nums and nums[nums[i]] is not\nnums[i] −nums[nums[i]] := nums[i]nums[i] := nums[nums[i]]" }, { "code": null, "e": 1607, "s": 1572, "text": "for i in range 0 to length of nums" }, { "code": null, "e": 1738, "s": 1607, "text": "while nums[i] >= 0 and nums[i] < length of nums and nums[nums[i]] is not\nnums[i] −nums[nums[i]] := nums[i]nums[i] := nums[nums[i]]" }, { "code": null, "e": 1821, "s": 1738, "text": "while nums[i] >= 0 and nums[i] < length of nums and nums[nums[i]] is not\nnums[i] −" }, { "code": null, "e": 1846, "s": 1821, "text": "nums[nums[i]] := nums[i]" }, { "code": null, "e": 1871, "s": 1846, "text": "nums[nums[i]] := nums[i]" }, { "code": null, "e": 1896, "s": 1871, "text": "nums[i] := nums[nums[i]]" }, { "code": null, "e": 1921, "s": 1896, "text": "nums[i] := nums[nums[i]]" }, { "code": null, "e": 1930, "s": 1921, "text": "num := 1" }, { "code": null, "e": 1939, "s": 1930, "text": "num := 1" }, { "code": null, "e": 2014, "s": 1939, "text": "for i in range 1 to length of numsif num = nums[i], then increase num by 1" }, { "code": null, "e": 2049, "s": 2014, "text": "for i in range 1 to length of nums" }, { "code": null, "e": 2090, "s": 2049, "text": "if num = nums[i], then increase num by 1" }, { "code": null, "e": 2131, "s": 2090, "text": "if num = nums[i], then increase num by 1" }, { "code": null, "e": 2142, "s": 2131, "text": "return num" }, { "code": null, "e": 2153, "s": 2142, "text": "return num" }, { "code": null, "e": 2223, "s": 2153, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2234, "s": 2223, "text": " Live Demo" }, { "code": null, "e": 2661, "s": 2234, "text": "class Solution(object):\n def firstMissingPositive(self, nums):\n i = 0\n nums = [0] + nums\n for i in range(len(nums)):\n while nums[i]>=0 and nums[i]<len(nums) and nums[nums[i]]!=nums[i]:\n nums[nums[i]],nums[i] = nums[i],nums[nums[i]]\n num = 1\n for i in range(1,len(nums)):\n if num == nums[i]:\n num+=1\n return num\n\nob = Solution()\nprint(ob.firstMissingPositive([4,-3,1,-1]))" }, { "code": null, "e": 2673, "s": 2661, "text": "[4,-3,1,-1]" }, { "code": null, "e": 2675, "s": 2673, "text": "2" } ]
Java Networking - GeeksforGeeks
07 Sep, 2021 When computing devices such as laptops, desktops, servers, smartphones, and tablets and an eternally-expanding arrangement of IoT gadgets such as cameras, door locks, doorbells, refrigerators, audio/visual systems, thermostats, and various sensors are sharing information and data with each other is known as networking. In simple words, the term network programming or networking associates with writing programs that can be executed over various computer devices, in which all the devices are connected to each other to share resources using a network. Here, we are going to discuss Java Networking. What is Java Networking? Common Network Protocols Java Network Terminology Java Networking Classes Java Networking Interfaces Socket Programming Inet Address URL Class Networking supplements a lot of power to simple programs. With networks, a single program can regain information stored in millions of computers positioned anywhere in the world. Java is the leading programming language composed from scratch with networking in mind. Java Networking is a notion of combining two or more computing devices together to share resources. All the Java program communications over the network are done at the application layer. The java.net package of the J2SE APIs comprises various classes and interfaces that execute the low-level communication features, enabling the user to formulate programs that focus on resolving the problem. As stated earlier, the java.net package of the Java programming language includes various classes and interfaces that provide an easy-to-use means to access network resources. Other than classes and interfaces, the java.net package also provides support for the two well-known network protocols. These are: Transmission Control Protocol (TCP) – TCP or Transmission Control Protocol allows secure communication between different applications. TCP is a connection-oriented protocol which means that once a connection is established, data can be transmitted in two directions. This protocol is typically used over the Internet Protocol. Therefore, TCP is also referred to as TCP/IP. TCP has built-in methods to examine for errors and ensure the delivery of data in the order it was sent, making it a complete protocol for transporting information like still images, data files, and web pages. User Datagram Protocol (UDP) – UDP or User Datagram Protocol is a connection-less protocol that allows data packets to be transmitted between different applications. UDP is a simpler Internet protocol in which error-checking and recovery services are not required. In UDP, there is no overhead for opening a connection, maintaining a connection, or terminating a connection. In UDP, the data is continuously sent to the recipient, whether they receive it or not. Transmission Control Protocol (TCP) – TCP or Transmission Control Protocol allows secure communication between different applications. TCP is a connection-oriented protocol which means that once a connection is established, data can be transmitted in two directions. This protocol is typically used over the Internet Protocol. Therefore, TCP is also referred to as TCP/IP. TCP has built-in methods to examine for errors and ensure the delivery of data in the order it was sent, making it a complete protocol for transporting information like still images, data files, and web pages. User Datagram Protocol (UDP) – UDP or User Datagram Protocol is a connection-less protocol that allows data packets to be transmitted between different applications. UDP is a simpler Internet protocol in which error-checking and recovery services are not required. In UDP, there is no overhead for opening a connection, maintaining a connection, or terminating a connection. In UDP, the data is continuously sent to the recipient, whether they receive it or not. Note: You can study more about TCP and UDP from the Differences between TCP and UDP. In Java Networking, many terminologies are used frequently. These widely used Java Networking Terminologies are given as follows: IP Address – An IP address is a unique address that distinguishes a device on the internet or a local network. IP stands for “Internet Protocol.” It comprises a set of rules governing the format of data sent via the internet or local network. IP Address is referred to as a logical address that can be modified. It is composed of octets. The range of each octet varies from 0 to 255.Range of the IP Address – 0.0.0.0 to 255.255.255.255For Example – 192.168.0.1 Port Number – A port number is a method to recognize a particular process connecting internet or other network information when it reaches a server. The port number is used to identify different applications uniquely. The port number behaves as a communication endpoint among applications. The port number is correlated with the IP address for transmission and communication among two applications. There are 65,535 port numbers, but not all are used every day. Protocol – A network protocol is an organized set of commands that define how data is transmitted between different devices in the same network. Network protocols are the reason through which a user can easily communicate with people all over the world and thus play a critical role in modern digital communications. For Example – TCP, FTP, POP, etc. MAC Address – MAC address stands for Media Access Control address. It is a bizarre identifier that is allocated to a NIC (Network Interface Controller/ Card). It contains a 48 bit or 64-bit address, which is combined with the network adapter. MAC address can be in hexadecimal composition. In simple words, a MAC address is a unique number that is used to track a device in a network. Socket – A socket is one endpoint of a two-way communication connection between the two applications running on the network. The socket mechanism presents a method of inter-process communication (IPC) by setting named contact points between which the communication occurs. A socket is tied to a port number so that the TCP layer can recognize the application to which the data is intended to be sent. Connection-oriented and connection-less protocol – In a connection-oriented service, the user must establish a connection before starting the communication. When the connection is established, the user can send the message or the information, and after this, they can release the connection. However, In connectionless protocol, the data is transported in one route from source to destination without verifying that the destination is still there or not or if it is ready to receive the message. Authentication is not needed in the connectionless protocol.Example of Connection-oriented Protocol – Transmission Control Protocol (TCP)Example of Connectionless Protocol – User Datagram Protocol (UDP) IP Address – An IP address is a unique address that distinguishes a device on the internet or a local network. IP stands for “Internet Protocol.” It comprises a set of rules governing the format of data sent via the internet or local network. IP Address is referred to as a logical address that can be modified. It is composed of octets. The range of each octet varies from 0 to 255.Range of the IP Address – 0.0.0.0 to 255.255.255.255For Example – 192.168.0.1 Range of the IP Address – 0.0.0.0 to 255.255.255.255 For Example – 192.168.0.1 Port Number – A port number is a method to recognize a particular process connecting internet or other network information when it reaches a server. The port number is used to identify different applications uniquely. The port number behaves as a communication endpoint among applications. The port number is correlated with the IP address for transmission and communication among two applications. There are 65,535 port numbers, but not all are used every day. Protocol – A network protocol is an organized set of commands that define how data is transmitted between different devices in the same network. Network protocols are the reason through which a user can easily communicate with people all over the world and thus play a critical role in modern digital communications. For Example – TCP, FTP, POP, etc. MAC Address – MAC address stands for Media Access Control address. It is a bizarre identifier that is allocated to a NIC (Network Interface Controller/ Card). It contains a 48 bit or 64-bit address, which is combined with the network adapter. MAC address can be in hexadecimal composition. In simple words, a MAC address is a unique number that is used to track a device in a network. Socket – A socket is one endpoint of a two-way communication connection between the two applications running on the network. The socket mechanism presents a method of inter-process communication (IPC) by setting named contact points between which the communication occurs. A socket is tied to a port number so that the TCP layer can recognize the application to which the data is intended to be sent. Connection-oriented and connection-less protocol – In a connection-oriented service, the user must establish a connection before starting the communication. When the connection is established, the user can send the message or the information, and after this, they can release the connection. However, In connectionless protocol, the data is transported in one route from source to destination without verifying that the destination is still there or not or if it is ready to receive the message. Authentication is not needed in the connectionless protocol.Example of Connection-oriented Protocol – Transmission Control Protocol (TCP)Example of Connectionless Protocol – User Datagram Protocol (UDP) Example of Connection-oriented Protocol – Transmission Control Protocol (TCP) Example of Connectionless Protocol – User Datagram Protocol (UDP) The java.net package of the Java programming language includes various classes that provide an easy-to-use means to access network resources. The classes covered in the java.net package are given as follows – CacheRequest – The CacheRequest class is used in java whenever there is a need to store resources in ResponseCache. The objects of this class provide an edge for the OutputStream object to store resource data into the cache. CookieHandler – The CookieHandler class is used in Java to implement a callback mechanism for securing up an HTTP state management policy implementation inside the HTTP protocol handler. The HTTP state management mechanism specifies the mechanism of how to make HTTP requests and responses. CookieManager – The CookieManager class is used to provide a precise implementation of CookieHandler. This class separates the storage of cookies from the policy surrounding accepting and rejecting cookies. A CookieManager comprises a CookieStore and a CookiePolicy. DatagramPacket – The DatagramPacket class is used to provide a facility for the connectionless transfer of messages from one system to another. This class provides tools for the production of datagram packets for connectionless transmission applying the datagram socket class. InetAddress – The InetAddress class is used to provide methods to get the IP address of any hostname. An IP address is expressed by a 32-bit or 128-bit unsigned number. InetAddress can handle both IPv4 and IPv6 addresses. Server Socket – The ServerSocket class is used for implementing system-independent implementation of the server-side of a client/server Socket Connection. The constructor for ServerSocket class throws an exception if it can’t listen on the specified port. For example – it will throw an exception if the port is already being used. Socket – The Socket class is used to create socket objects that help the users in implementing all fundamental socket operations. The users can implement various networking actions such as sending, reading data, and closing connections. Each Socket object built using java.net.Socket class has been connected exactly with 1 remote host; for connecting to another host, a user must create a new socket object. DatagramSocket – The DatagramSocket class is a network socket that provides a connection-less point for sending and receiving packets. Every packet sent from a datagram socket is individually routed and delivered. It can further be practiced for transmitting and accepting broadcast information. Datagram Sockets is Java’s mechanism for providing network communication via UDP instead of TCP. Proxy – A proxy is a changeless object and a kind of tool or method or program or system, which serves to preserve the data of its users and computers. It behaves like a wall between computers and internet users. A Proxy Object represents the Proxy settings to be applied with a connection. URL – The URL class in Java is the entry point to any available sources on the internet. A Class URL describes a Uniform Resource Locator, which is a signal to a “resource” on the World Wide Web. A source can denote a simple file or directory, or it can indicate a more difficult object, such as a query to a database or a search engine. URLConnection – The URLConnection class in Java is an abstract class describing a connection of a resource as defined by a similar URL. The URLConnection class is used for assisting two distinct yet interrelated purposes. Firstly it provides control on interaction with a server(especially an HTTP server) than a URL class. Furthermore, with a URLConnection, a user can verify the header transferred by the server and can react consequently. A user can also configure header fields used in client requests using URLConnection. CacheRequest – The CacheRequest class is used in java whenever there is a need to store resources in ResponseCache. The objects of this class provide an edge for the OutputStream object to store resource data into the cache. CookieHandler – The CookieHandler class is used in Java to implement a callback mechanism for securing up an HTTP state management policy implementation inside the HTTP protocol handler. The HTTP state management mechanism specifies the mechanism of how to make HTTP requests and responses. CookieManager – The CookieManager class is used to provide a precise implementation of CookieHandler. This class separates the storage of cookies from the policy surrounding accepting and rejecting cookies. A CookieManager comprises a CookieStore and a CookiePolicy. DatagramPacket – The DatagramPacket class is used to provide a facility for the connectionless transfer of messages from one system to another. This class provides tools for the production of datagram packets for connectionless transmission applying the datagram socket class. InetAddress – The InetAddress class is used to provide methods to get the IP address of any hostname. An IP address is expressed by a 32-bit or 128-bit unsigned number. InetAddress can handle both IPv4 and IPv6 addresses. Server Socket – The ServerSocket class is used for implementing system-independent implementation of the server-side of a client/server Socket Connection. The constructor for ServerSocket class throws an exception if it can’t listen on the specified port. For example – it will throw an exception if the port is already being used. Socket – The Socket class is used to create socket objects that help the users in implementing all fundamental socket operations. The users can implement various networking actions such as sending, reading data, and closing connections. Each Socket object built using java.net.Socket class has been connected exactly with 1 remote host; for connecting to another host, a user must create a new socket object. DatagramSocket – The DatagramSocket class is a network socket that provides a connection-less point for sending and receiving packets. Every packet sent from a datagram socket is individually routed and delivered. It can further be practiced for transmitting and accepting broadcast information. Datagram Sockets is Java’s mechanism for providing network communication via UDP instead of TCP. Proxy – A proxy is a changeless object and a kind of tool or method or program or system, which serves to preserve the data of its users and computers. It behaves like a wall between computers and internet users. A Proxy Object represents the Proxy settings to be applied with a connection. URL – The URL class in Java is the entry point to any available sources on the internet. A Class URL describes a Uniform Resource Locator, which is a signal to a “resource” on the World Wide Web. A source can denote a simple file or directory, or it can indicate a more difficult object, such as a query to a database or a search engine. URLConnection – The URLConnection class in Java is an abstract class describing a connection of a resource as defined by a similar URL. The URLConnection class is used for assisting two distinct yet interrelated purposes. Firstly it provides control on interaction with a server(especially an HTTP server) than a URL class. Furthermore, with a URLConnection, a user can verify the header transferred by the server and can react consequently. A user can also configure header fields used in client requests using URLConnection. The java.net package of the Java programming language includes various interfaces also that provide an easy-to-use means to access network resources. The interfaces included in the java.net package are as follows: CookiePolicy – The CookiePolicy interface in the java.net package provides the classes for implementing various networking applications. It decides which cookies should be accepted and which should be rejected. In CookiePolicy, there are three pre-defined policy implementations, namely ACCEPT_ALL, ACCEPT_NONE, and ACCEPT_ORIGINAL_SERVER. CookieStore – A CookieStore is an interface that describes a storage space for cookies. CookieManager combines the cookies to the CookieStore for each HTTP response and recovers cookies from the CookieStore for each HTTP request. FileNameMap – The FileNameMap interface is an uncomplicated interface that implements a tool to outline a file name and a MIME type string. FileNameMap charges a filename map ( known as a mimetable) from a data file. SocketOption – The SocketOption interface helps the users to control the behavior of sockets. Often, it is essential to develop necessary features in Sockets. SocketOptions allows the user to set various standard options. SocketImplFactory – The SocketImplFactory interface defines a factory for SocketImpl instances. It is used by the socket class to create socket implementations that implement various policies. ProtocolFamily – This interface represents a family of communication protocols. The ProtocolFamily interface contains a method known as name(), which returns the name of the protocol family. CookiePolicy – The CookiePolicy interface in the java.net package provides the classes for implementing various networking applications. It decides which cookies should be accepted and which should be rejected. In CookiePolicy, there are three pre-defined policy implementations, namely ACCEPT_ALL, ACCEPT_NONE, and ACCEPT_ORIGINAL_SERVER. CookieStore – A CookieStore is an interface that describes a storage space for cookies. CookieManager combines the cookies to the CookieStore for each HTTP response and recovers cookies from the CookieStore for each HTTP request. FileNameMap – The FileNameMap interface is an uncomplicated interface that implements a tool to outline a file name and a MIME type string. FileNameMap charges a filename map ( known as a mimetable) from a data file. SocketOption – The SocketOption interface helps the users to control the behavior of sockets. Often, it is essential to develop necessary features in Sockets. SocketOptions allows the user to set various standard options. SocketImplFactory – The SocketImplFactory interface defines a factory for SocketImpl instances. It is used by the socket class to create socket implementations that implement various policies. ProtocolFamily – This interface represents a family of communication protocols. The ProtocolFamily interface contains a method known as name(), which returns the name of the protocol family. Java Socket programming is practiced for communication between the applications working on different JRE. Sockets implement the communication tool between two computers using TCP. Java Socket programming can either be connection-oriented or connection-less. In Socket Programming, Socket and ServerSocket classes are managed for connection-oriented socket programming. However, DatagramSocket and DatagramPacket classes are utilized for connection-less socket programming. A client application generates a socket on its end of the communication and strives to combine that socket with a server. When the connection is established, the server generates an object of socket class on its communication end. The client and the server can now communicate by writing to and reading from the socket. The java.net.Socket class describes a socket, and the java.net.ServerSocket class implements a tool for the server program to host clients and build connections with them. Steps to establishing a TCP connection between two computing devices using Socket Programming The following are the steps that occur on establishing a TCP connection between two computers using socket programming are given as follows: Step 1 – The server instantiates a ServerSocket object, indicating at which port number communication will occur. Step 2 – After instantiating the ServerSocket object, the server requests the accept() method of the ServerSocket class. This program pauses until a client connects to the server on the given port. Step 3 – After the server is idling, a client instantiates an object of Socket class, defining the server name and the port number to connect to. Step 4 – After the above step, the constructor of the Socket class strives to connect the client to the designated server and the port number. If communication is authenticated, the client forthwith has a Socket object proficient in interacting with the server. Step 5 – On the server-side, the accept() method returns a reference to a new socket on the server connected to the client’s socket. After the connections are stabilized, communication can happen using I/O streams. Each object of a socket class has both an OutputStream and an InputStream. The client’s OutputStream is correlated to the server’s InputStream, and the client’s InputStream is combined with the server’s OutputStream. Transmission Control Protocol (TCP) is a two-way communication protocol. Hence information can be transmitted over both streams at the corresponding time. The Socket class is used to create socket objects that help the users in implementing all fundamental socket operations. The users can implement various networking actions such as sending, reading data, and closing connections. Each Socket object created using java.net.Socket class has been correlated specifically with 1 remote host. If a user wants to connect to another host, then he must build a new socket object. Methods of Socket Class In Socket programming, both the client and the server have a Socket object, so all the methods under the Socket class can be invoked by both the client and the server. There are many methods in the Socket class. Method Description The ServerSocket class is used for providing system-independent implementation of the server-side of a client/server Socket Connection. The constructor for ServerSocket class throws an exception if it can’t listen on the specified port. For example – it will throw an exception if the port is already being used. Methods of ServerSocket Class: There are many methods in the ServerSocket class which are very useful for the users. These methods are: Method Description The below example illustrates a pretty basic one-way Client and Server setup where a Client connects, sends messages to the server and the server shows them using a socket connection. Client-Side Java Implementation: Java // A Java program for a ClientSide import java.io.*;import java.net.*; public class clientSide { // initialize socket and input output streams private Socket socket = null; private DataInputStream input = null; private DataOutputStream out = null; // constructor to put ip address and port public clientSide(String address, int port) { // establish a connection try { socket = new Socket(address, port); System.out.println("Connected"); // takes input from terminal input = new DataInputStream(System.in); // sends output to the socket out = new DataOutputStream( socket.getOutputStream()); } catch (UnknownHostException u) { System.out.println(u); } catch (IOException i) { System.out.println(i); } // string to read message from input String line = ""; // keep reading until "End" is input while (!line.equals("End")) { try { line = input.readLine(); out.writeUTF(line); } catch (IOException i) { System.out.println(i); } } // close the connection try { input.close(); out.close(); socket.close(); } catch (IOException i) { System.out.println(i); } } public static void main(String[] args) { clientSide client = new clientSide("127.0.0.1", 5000); }} Server Side Java Implementation: Java // A Java program for a serverSideimport java.io.*;import java.net.*; public class serverSide { // initialize socket and input stream private Socket socket = null; private ServerSocket server = null; private DataInputStream in = null; // constructor with port public serverSide(int port) { // starts server and waits for a connection try { server = new ServerSocket(port); System.out.println("Server started"); System.out.println("Waiting for a client ..."); socket = server.accept(); System.out.println("Client accepted"); // takes input from the client socket in = new DataInputStream( new BufferedInputStream( socket.getInputStream())); String line = ""; // reads message from client until "End" is sent while (!line.equals("End")) { try { line = in.readUTF(); System.out.println(line); } catch (IOException i) { System.out.println(i); } } System.out.println("Closing connection"); // close connection socket.close(); in.close(); } catch (IOException i) { System.out.println(i); } } public static void main(String[] args) { serverSide server = new serverSide(5000); }} To run on Terminal or Command Prompt Open two windows one for Server and another for Client. 1. First run the Server application. It will show – Server started Waiting for a client ... 2. Then run the Client application on another terminal. It will show: Connected and the server accepts the client and shows, Client accepted 3. Then you can start typing messages in the Client window. Here is the sample video of the output. The InetAddress class is used to provide methods to get the IP address of any hostname. An IP address is expressed by 32-bit or 128-bit unsigned number. An object of InetAddress describes the IP address with its analogous hostname. InetAddress can control both IPv4 and IPv6 addresses. There are two different types of addresses: Unicast – It is an identifier for a single interface. Multicast – It is an identifier for a collection of interfaces. Methods of InetAddress Class Java InetAddress class represents an IP address. The following given are the important methods of the InetAddress class – Method Description The Java implementation of the Inet Address class to illustrate the usage of methods is shown below: Example 1: Java import java.net.*; public class InetAddressExample1 { public static void main(String[] args) throws UnknownHostException{ // To get and print InetAddress of the Local Host InetAddress address = InetAddress.getLocalHost(); System.out.println("InetAddress of the Local Host : "+address); // To get and print host name of the Local Host String hostName=address.getHostName(); System.out.println("\nHost name of the Local Host : "+hostName); } } InetAddress of the Local Host : localhost/127.0.0.1 Host name of the Local Host : localhost Example 2: Java import java.net.*; public class InetAddressExample2 { public static void main(String[] args) throws UnknownHostException { // To get and print InetAddress of Named Hosts InetAddress address1 = InetAddress.getByName( "write.geeksforgeeks.org"); System.out.println("Inet Address of named hosts : " + address1); // To get and print ALL InetAddress of Named Host InetAddress arr[] = InetAddress.getAllByName( "www.geeksforgeeks.org"); System.out.println("\nInet Address of ALL named hosts :"); for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } }} Output The URL class in Java is the entry point to any available sources on the internet. A Class URL describes a Uniform Resource Locator, which is a signal to a “resource” on the World Wide Web. A source can denote a simple file or directory, or it can indicate a more difficult object, such as a query to a database or a search engine. URL is a string of text that recognizes all the sources on the Internet, showing us the address of the source, how to interact with it, and recover something from it. Components of a URL A URL can have many forms. The most general however follows a three-components system- Protocol – The protocol in a URL defines how information is transported among the host and a client (or web browser).Hostname – The hostname is the name of the device on which the resource exists.File Name – The filename is the pathname to the file on the device.Port Number – The port number is used to identify different applications uniquely. It is typically optional. Protocol – The protocol in a URL defines how information is transported among the host and a client (or web browser). Hostname – The hostname is the name of the device on which the resource exists. File Name – The filename is the pathname to the file on the device. Port Number – The port number is used to identify different applications uniquely. It is typically optional. There are many methods in Java URL Class that are commonly used in Java Networking. These methods are: The Java implementation of the URL class to illustrate the usage of methods is shown below Example 1: Java import java.net.*; public class URLclassExample1 { public static void main(String[] args) throws MalformedURLException { // creates a URL with string representation. URL url = new URL( "https://write.geeksforgeeks.org/post/3038131"); // print the string representation of the URL String s = url.toString(); System.out.println("URL :" + s); }} URL :https://write.geeksforgeeks.org/post/3038131 Example 2: Java import java.net.*; public class URLclassExample2 { public static void main(String[] args) throws MalformedURLException { URL url = new URL( "https://write.geeksforgeeks.org/post/3038131"); // to get and print the protocol of the URL String protocol = url.getProtocol(); System.out.println("Protocol : " + protocol); // to get and print the hostName of the URL String host = url.getHost(); System.out.println("HostName : " + host); // to get and print the file name of the URL String fileName = url.getFile(); System.out.println("File Name : " + fileName); }} Protocol : https HostName : write.geeksforgeeks.org File Name : /post/3038131 Example 3: Java import java.net.*; public class URLclassExample3 { public static void main(String[] args) throws MalformedURLException { URL url = new URL( "https://write.geeksforgeeks.org/post/3038131"); // to get and print the default port of the URL int defaultPort = url.getDefaultPort(); System.out.println("Default Port : " + defaultPort); // to get and print the path of the URL String path = url.getPath(); System.out.println("Path : " + path); }} Default Port : 443 Path : /post/3038131 This was a brief introduction to Java Networking. In this article, many important topics like Introduction of Java Networking, Common Network Protocols, Java Network Terminology, Java Networking Classes, Java Networking Interfaces, Socket Programming, Inet Address, and URL Class were covered. Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Functional Interfaces in Java Stream In Java Constructors in Java Different ways of Reading a text file in Java Exceptions in Java Generics in Java Comparator Interface in Java with Examples Strings in Java How to remove an element from ArrayList in Java? Difference between Abstract Class and Interface in Java
[ { "code": null, "e": 23581, "s": 23553, "text": "\n07 Sep, 2021" }, { "code": null, "e": 23902, "s": 23581, "text": "When computing devices such as laptops, desktops, servers, smartphones, and tablets and an eternally-expanding arrangement of IoT gadgets such as cameras, door locks, doorbells, refrigerators, audio/visual systems, thermostats, and various sensors are sharing information and data with each other is known as networking." }, { "code": null, "e": 24183, "s": 23902, "text": "In simple words, the term network programming or networking associates with writing programs that can be executed over various computer devices, in which all the devices are connected to each other to share resources using a network. Here, we are going to discuss Java Networking." }, { "code": null, "e": 24208, "s": 24183, "text": "What is Java Networking?" }, { "code": null, "e": 24233, "s": 24208, "text": "Common Network Protocols" }, { "code": null, "e": 24258, "s": 24233, "text": "Java Network Terminology" }, { "code": null, "e": 24282, "s": 24258, "text": "Java Networking Classes" }, { "code": null, "e": 24309, "s": 24282, "text": "Java Networking Interfaces" }, { "code": null, "e": 24328, "s": 24309, "text": "Socket Programming" }, { "code": null, "e": 24341, "s": 24328, "text": "Inet Address" }, { "code": null, "e": 24351, "s": 24341, "text": "URL Class" }, { "code": null, "e": 24718, "s": 24351, "text": "Networking supplements a lot of power to simple programs. With networks, a single program can regain information stored in millions of computers positioned anywhere in the world. Java is the leading programming language composed from scratch with networking in mind. Java Networking is a notion of combining two or more computing devices together to share resources." }, { "code": null, "e": 25013, "s": 24718, "text": "All the Java program communications over the network are done at the application layer. The java.net package of the J2SE APIs comprises various classes and interfaces that execute the low-level communication features, enabling the user to formulate programs that focus on resolving the problem." }, { "code": null, "e": 25320, "s": 25013, "text": "As stated earlier, the java.net package of the Java programming language includes various classes and interfaces that provide an easy-to-use means to access network resources. Other than classes and interfaces, the java.net package also provides support for the two well-known network protocols. These are:" }, { "code": null, "e": 26366, "s": 25320, "text": "Transmission Control Protocol (TCP) – TCP or Transmission Control Protocol allows secure communication between different applications. TCP is a connection-oriented protocol which means that once a connection is established, data can be transmitted in two directions. This protocol is typically used over the Internet Protocol. Therefore, TCP is also referred to as TCP/IP. TCP has built-in methods to examine for errors and ensure the delivery of data in the order it was sent, making it a complete protocol for transporting information like still images, data files, and web pages. User Datagram Protocol (UDP) – UDP or User Datagram Protocol is a connection-less protocol that allows data packets to be transmitted between different applications. UDP is a simpler Internet protocol in which error-checking and recovery services are not required. In UDP, there is no overhead for opening a connection, maintaining a connection, or terminating a connection. In UDP, the data is continuously sent to the recipient, whether they receive it or not." }, { "code": null, "e": 26950, "s": 26366, "text": "Transmission Control Protocol (TCP) – TCP or Transmission Control Protocol allows secure communication between different applications. TCP is a connection-oriented protocol which means that once a connection is established, data can be transmitted in two directions. This protocol is typically used over the Internet Protocol. Therefore, TCP is also referred to as TCP/IP. TCP has built-in methods to examine for errors and ensure the delivery of data in the order it was sent, making it a complete protocol for transporting information like still images, data files, and web pages. " }, { "code": null, "e": 27413, "s": 26950, "text": "User Datagram Protocol (UDP) – UDP or User Datagram Protocol is a connection-less protocol that allows data packets to be transmitted between different applications. UDP is a simpler Internet protocol in which error-checking and recovery services are not required. In UDP, there is no overhead for opening a connection, maintaining a connection, or terminating a connection. In UDP, the data is continuously sent to the recipient, whether they receive it or not." }, { "code": null, "e": 27498, "s": 27413, "text": "Note: You can study more about TCP and UDP from the Differences between TCP and UDP." }, { "code": null, "e": 27628, "s": 27498, "text": "In Java Networking, many terminologies are used frequently. These widely used Java Networking Terminologies are given as follows:" }, { "code": null, "e": 30389, "s": 27628, "text": "IP Address – An IP address is a unique address that distinguishes a device on the internet or a local network. IP stands for “Internet Protocol.” It comprises a set of rules governing the format of data sent via the internet or local network. IP Address is referred to as a logical address that can be modified. It is composed of octets. The range of each octet varies from 0 to 255.Range of the IP Address – 0.0.0.0 to 255.255.255.255For Example – 192.168.0.1 Port Number – A port number is a method to recognize a particular process connecting internet or other network information when it reaches a server. The port number is used to identify different applications uniquely. The port number behaves as a communication endpoint among applications. The port number is correlated with the IP address for transmission and communication among two applications. There are 65,535 port numbers, but not all are used every day. Protocol – A network protocol is an organized set of commands that define how data is transmitted between different devices in the same network. Network protocols are the reason through which a user can easily communicate with people all over the world and thus play a critical role in modern digital communications. For Example – TCP, FTP, POP, etc. MAC Address – MAC address stands for Media Access Control address. It is a bizarre identifier that is allocated to a NIC (Network Interface Controller/ Card). It contains a 48 bit or 64-bit address, which is combined with the network adapter. MAC address can be in hexadecimal composition. In simple words, a MAC address is a unique number that is used to track a device in a network. Socket – A socket is one endpoint of a two-way communication connection between the two applications running on the network. The socket mechanism presents a method of inter-process communication (IPC) by setting named contact points between which the communication occurs. A socket is tied to a port number so that the TCP layer can recognize the application to which the data is intended to be sent. Connection-oriented and connection-less protocol – In a connection-oriented service, the user must establish a connection before starting the communication. When the connection is established, the user can send the message or the information, and after this, they can release the connection. However, In connectionless protocol, the data is transported in one route from source to destination without verifying that the destination is still there or not or if it is ready to receive the message. Authentication is not needed in the connectionless protocol.Example of Connection-oriented Protocol – Transmission Control Protocol (TCP)Example of Connectionless Protocol – User Datagram Protocol (UDP)" }, { "code": null, "e": 30853, "s": 30389, "text": "IP Address – An IP address is a unique address that distinguishes a device on the internet or a local network. IP stands for “Internet Protocol.” It comprises a set of rules governing the format of data sent via the internet or local network. IP Address is referred to as a logical address that can be modified. It is composed of octets. The range of each octet varies from 0 to 255.Range of the IP Address – 0.0.0.0 to 255.255.255.255For Example – 192.168.0.1 " }, { "code": null, "e": 30908, "s": 30853, "text": "Range of the IP Address – 0.0.0.0 to 255.255.255.255" }, { "code": null, "e": 30935, "s": 30908, "text": "For Example – 192.168.0.1 " }, { "code": null, "e": 31398, "s": 30935, "text": "Port Number – A port number is a method to recognize a particular process connecting internet or other network information when it reaches a server. The port number is used to identify different applications uniquely. The port number behaves as a communication endpoint among applications. The port number is correlated with the IP address for transmission and communication among two applications. There are 65,535 port numbers, but not all are used every day. " }, { "code": null, "e": 31750, "s": 31398, "text": "Protocol – A network protocol is an organized set of commands that define how data is transmitted between different devices in the same network. Network protocols are the reason through which a user can easily communicate with people all over the world and thus play a critical role in modern digital communications. For Example – TCP, FTP, POP, etc. " }, { "code": null, "e": 32136, "s": 31750, "text": "MAC Address – MAC address stands for Media Access Control address. It is a bizarre identifier that is allocated to a NIC (Network Interface Controller/ Card). It contains a 48 bit or 64-bit address, which is combined with the network adapter. MAC address can be in hexadecimal composition. In simple words, a MAC address is a unique number that is used to track a device in a network. " }, { "code": null, "e": 32538, "s": 32136, "text": "Socket – A socket is one endpoint of a two-way communication connection between the two applications running on the network. The socket mechanism presents a method of inter-process communication (IPC) by setting named contact points between which the communication occurs. A socket is tied to a port number so that the TCP layer can recognize the application to which the data is intended to be sent. " }, { "code": null, "e": 33237, "s": 32538, "text": "Connection-oriented and connection-less protocol – In a connection-oriented service, the user must establish a connection before starting the communication. When the connection is established, the user can send the message or the information, and after this, they can release the connection. However, In connectionless protocol, the data is transported in one route from source to destination without verifying that the destination is still there or not or if it is ready to receive the message. Authentication is not needed in the connectionless protocol.Example of Connection-oriented Protocol – Transmission Control Protocol (TCP)Example of Connectionless Protocol – User Datagram Protocol (UDP)" }, { "code": null, "e": 33315, "s": 33237, "text": "Example of Connection-oriented Protocol – Transmission Control Protocol (TCP)" }, { "code": null, "e": 33381, "s": 33315, "text": "Example of Connectionless Protocol – User Datagram Protocol (UDP)" }, { "code": null, "e": 33592, "s": 33381, "text": "The java.net package of the Java programming language includes various classes that provide an easy-to-use means to access network resources. The classes covered in the java.net package are given as follows – " }, { "code": null, "e": 37168, "s": 33592, "text": "CacheRequest – The CacheRequest class is used in java whenever there is a need to store resources in ResponseCache. The objects of this class provide an edge for the OutputStream object to store resource data into the cache. CookieHandler – The CookieHandler class is used in Java to implement a callback mechanism for securing up an HTTP state management policy implementation inside the HTTP protocol handler. The HTTP state management mechanism specifies the mechanism of how to make HTTP requests and responses. CookieManager – The CookieManager class is used to provide a precise implementation of CookieHandler. This class separates the storage of cookies from the policy surrounding accepting and rejecting cookies. A CookieManager comprises a CookieStore and a CookiePolicy. DatagramPacket – The DatagramPacket class is used to provide a facility for the connectionless transfer of messages from one system to another. This class provides tools for the production of datagram packets for connectionless transmission applying the datagram socket class. InetAddress – The InetAddress class is used to provide methods to get the IP address of any hostname. An IP address is expressed by a 32-bit or 128-bit unsigned number. InetAddress can handle both IPv4 and IPv6 addresses. Server Socket – The ServerSocket class is used for implementing system-independent implementation of the server-side of a client/server Socket Connection. The constructor for ServerSocket class throws an exception if it can’t listen on the specified port. For example – it will throw an exception if the port is already being used. Socket – The Socket class is used to create socket objects that help the users in implementing all fundamental socket operations. The users can implement various networking actions such as sending, reading data, and closing connections. Each Socket object built using java.net.Socket class has been connected exactly with 1 remote host; for connecting to another host, a user must create a new socket object. DatagramSocket – The DatagramSocket class is a network socket that provides a connection-less point for sending and receiving packets. Every packet sent from a datagram socket is individually routed and delivered. It can further be practiced for transmitting and accepting broadcast information. Datagram Sockets is Java’s mechanism for providing network communication via UDP instead of TCP. Proxy – A proxy is a changeless object and a kind of tool or method or program or system, which serves to preserve the data of its users and computers. It behaves like a wall between computers and internet users. A Proxy Object represents the Proxy settings to be applied with a connection. URL – The URL class in Java is the entry point to any available sources on the internet. A Class URL describes a Uniform Resource Locator, which is a signal to a “resource” on the World Wide Web. A source can denote a simple file or directory, or it can indicate a more difficult object, such as a query to a database or a search engine. URLConnection – The URLConnection class in Java is an abstract class describing a connection of a resource as defined by a similar URL. The URLConnection class is used for assisting two distinct yet interrelated purposes. Firstly it provides control on interaction with a server(especially an HTTP server) than a URL class. Furthermore, with a URLConnection, a user can verify the header transferred by the server and can react consequently. A user can also configure header fields used in client requests using URLConnection." }, { "code": null, "e": 37395, "s": 37168, "text": "CacheRequest – The CacheRequest class is used in java whenever there is a need to store resources in ResponseCache. The objects of this class provide an edge for the OutputStream object to store resource data into the cache. " }, { "code": null, "e": 37687, "s": 37395, "text": "CookieHandler – The CookieHandler class is used in Java to implement a callback mechanism for securing up an HTTP state management policy implementation inside the HTTP protocol handler. The HTTP state management mechanism specifies the mechanism of how to make HTTP requests and responses. " }, { "code": null, "e": 37957, "s": 37687, "text": "CookieManager – The CookieManager class is used to provide a precise implementation of CookieHandler. This class separates the storage of cookies from the policy surrounding accepting and rejecting cookies. A CookieManager comprises a CookieStore and a CookiePolicy. " }, { "code": null, "e": 38235, "s": 37957, "text": "DatagramPacket – The DatagramPacket class is used to provide a facility for the connectionless transfer of messages from one system to another. This class provides tools for the production of datagram packets for connectionless transmission applying the datagram socket class. " }, { "code": null, "e": 38459, "s": 38235, "text": "InetAddress – The InetAddress class is used to provide methods to get the IP address of any hostname. An IP address is expressed by a 32-bit or 128-bit unsigned number. InetAddress can handle both IPv4 and IPv6 addresses. " }, { "code": null, "e": 38792, "s": 38459, "text": "Server Socket – The ServerSocket class is used for implementing system-independent implementation of the server-side of a client/server Socket Connection. The constructor for ServerSocket class throws an exception if it can’t listen on the specified port. For example – it will throw an exception if the port is already being used. " }, { "code": null, "e": 39202, "s": 38792, "text": "Socket – The Socket class is used to create socket objects that help the users in implementing all fundamental socket operations. The users can implement various networking actions such as sending, reading data, and closing connections. Each Socket object built using java.net.Socket class has been connected exactly with 1 remote host; for connecting to another host, a user must create a new socket object. " }, { "code": null, "e": 39596, "s": 39202, "text": "DatagramSocket – The DatagramSocket class is a network socket that provides a connection-less point for sending and receiving packets. Every packet sent from a datagram socket is individually routed and delivered. It can further be practiced for transmitting and accepting broadcast information. Datagram Sockets is Java’s mechanism for providing network communication via UDP instead of TCP. " }, { "code": null, "e": 39888, "s": 39596, "text": "Proxy – A proxy is a changeless object and a kind of tool or method or program or system, which serves to preserve the data of its users and computers. It behaves like a wall between computers and internet users. A Proxy Object represents the Proxy settings to be applied with a connection. " }, { "code": null, "e": 40227, "s": 39888, "text": "URL – The URL class in Java is the entry point to any available sources on the internet. A Class URL describes a Uniform Resource Locator, which is a signal to a “resource” on the World Wide Web. A source can denote a simple file or directory, or it can indicate a more difficult object, such as a query to a database or a search engine. " }, { "code": null, "e": 40754, "s": 40227, "text": "URLConnection – The URLConnection class in Java is an abstract class describing a connection of a resource as defined by a similar URL. The URLConnection class is used for assisting two distinct yet interrelated purposes. Firstly it provides control on interaction with a server(especially an HTTP server) than a URL class. Furthermore, with a URLConnection, a user can verify the header transferred by the server and can react consequently. A user can also configure header fields used in client requests using URLConnection." }, { "code": null, "e": 40968, "s": 40754, "text": "The java.net package of the Java programming language includes various interfaces also that provide an easy-to-use means to access network resources. The interfaces included in the java.net package are as follows:" }, { "code": null, "e": 42361, "s": 40968, "text": "CookiePolicy – The CookiePolicy interface in the java.net package provides the classes for implementing various networking applications. It decides which cookies should be accepted and which should be rejected. In CookiePolicy, there are three pre-defined policy implementations, namely ACCEPT_ALL, ACCEPT_NONE, and ACCEPT_ORIGINAL_SERVER. CookieStore – A CookieStore is an interface that describes a storage space for cookies. CookieManager combines the cookies to the CookieStore for each HTTP response and recovers cookies from the CookieStore for each HTTP request. FileNameMap – The FileNameMap interface is an uncomplicated interface that implements a tool to outline a file name and a MIME type string. FileNameMap charges a filename map ( known as a mimetable) from a data file. SocketOption – The SocketOption interface helps the users to control the behavior of sockets. Often, it is essential to develop necessary features in Sockets. SocketOptions allows the user to set various standard options. SocketImplFactory – The SocketImplFactory interface defines a factory for SocketImpl instances. It is used by the socket class to create socket implementations that implement various policies. ProtocolFamily – This interface represents a family of communication protocols. The ProtocolFamily interface contains a method known as name(), which returns the name of the protocol family." }, { "code": null, "e": 42702, "s": 42361, "text": "CookiePolicy – The CookiePolicy interface in the java.net package provides the classes for implementing various networking applications. It decides which cookies should be accepted and which should be rejected. In CookiePolicy, there are three pre-defined policy implementations, namely ACCEPT_ALL, ACCEPT_NONE, and ACCEPT_ORIGINAL_SERVER. " }, { "code": null, "e": 42933, "s": 42702, "text": "CookieStore – A CookieStore is an interface that describes a storage space for cookies. CookieManager combines the cookies to the CookieStore for each HTTP response and recovers cookies from the CookieStore for each HTTP request. " }, { "code": null, "e": 43151, "s": 42933, "text": "FileNameMap – The FileNameMap interface is an uncomplicated interface that implements a tool to outline a file name and a MIME type string. FileNameMap charges a filename map ( known as a mimetable) from a data file. " }, { "code": null, "e": 43374, "s": 43151, "text": "SocketOption – The SocketOption interface helps the users to control the behavior of sockets. Often, it is essential to develop necessary features in Sockets. SocketOptions allows the user to set various standard options. " }, { "code": null, "e": 43568, "s": 43374, "text": "SocketImplFactory – The SocketImplFactory interface defines a factory for SocketImpl instances. It is used by the socket class to create socket implementations that implement various policies. " }, { "code": null, "e": 43759, "s": 43568, "text": "ProtocolFamily – This interface represents a family of communication protocols. The ProtocolFamily interface contains a method known as name(), which returns the name of the protocol family." }, { "code": null, "e": 44232, "s": 43759, "text": "Java Socket programming is practiced for communication between the applications working on different JRE. Sockets implement the communication tool between two computers using TCP. Java Socket programming can either be connection-oriented or connection-less. In Socket Programming, Socket and ServerSocket classes are managed for connection-oriented socket programming. However, DatagramSocket and DatagramPacket classes are utilized for connection-less socket programming." }, { "code": null, "e": 44552, "s": 44232, "text": "A client application generates a socket on its end of the communication and strives to combine that socket with a server. When the connection is established, the server generates an object of socket class on its communication end. The client and the server can now communicate by writing to and reading from the socket." }, { "code": null, "e": 44818, "s": 44552, "text": "The java.net.Socket class describes a socket, and the java.net.ServerSocket class implements a tool for the server program to host clients and build connections with them. Steps to establishing a TCP connection between two computing devices using Socket Programming" }, { "code": null, "e": 44960, "s": 44818, "text": "The following are the steps that occur on establishing a TCP connection between two computers using socket programming are given as follows: " }, { "code": null, "e": 45074, "s": 44960, "text": "Step 1 – The server instantiates a ServerSocket object, indicating at which port number communication will occur." }, { "code": null, "e": 45272, "s": 45074, "text": "Step 2 – After instantiating the ServerSocket object, the server requests the accept() method of the ServerSocket class. This program pauses until a client connects to the server on the given port." }, { "code": null, "e": 45418, "s": 45272, "text": "Step 3 – After the server is idling, a client instantiates an object of Socket class, defining the server name and the port number to connect to." }, { "code": null, "e": 45680, "s": 45418, "text": "Step 4 – After the above step, the constructor of the Socket class strives to connect the client to the designated server and the port number. If communication is authenticated, the client forthwith has a Socket object proficient in interacting with the server." }, { "code": null, "e": 45813, "s": 45680, "text": "Step 5 – On the server-side, the accept() method returns a reference to a new socket on the server connected to the client’s socket." }, { "code": null, "e": 46268, "s": 45813, "text": "After the connections are stabilized, communication can happen using I/O streams. Each object of a socket class has both an OutputStream and an InputStream. The client’s OutputStream is correlated to the server’s InputStream, and the client’s InputStream is combined with the server’s OutputStream. Transmission Control Protocol (TCP) is a two-way communication protocol. Hence information can be transmitted over both streams at the corresponding time. " }, { "code": null, "e": 46688, "s": 46268, "text": "The Socket class is used to create socket objects that help the users in implementing all fundamental socket operations. The users can implement various networking actions such as sending, reading data, and closing connections. Each Socket object created using java.net.Socket class has been correlated specifically with 1 remote host. If a user wants to connect to another host, then he must build a new socket object." }, { "code": null, "e": 46712, "s": 46688, "text": "Methods of Socket Class" }, { "code": null, "e": 46926, "s": 46712, "text": "In Socket programming, both the client and the server have a Socket object, so all the methods under the Socket class can be invoked by both the client and the server. There are many methods in the Socket class. " }, { "code": null, "e": 46933, "s": 46926, "text": "Method" }, { "code": null, "e": 46945, "s": 46933, "text": "Description" }, { "code": null, "e": 47258, "s": 46945, "text": "The ServerSocket class is used for providing system-independent implementation of the server-side of a client/server Socket Connection. The constructor for ServerSocket class throws an exception if it can’t listen on the specified port. For example – it will throw an exception if the port is already being used." }, { "code": null, "e": 47289, "s": 47258, "text": "Methods of ServerSocket Class:" }, { "code": null, "e": 47395, "s": 47289, "text": "There are many methods in the ServerSocket class which are very useful for the users. These methods are: " }, { "code": null, "e": 47402, "s": 47395, "text": "Method" }, { "code": null, "e": 47414, "s": 47402, "text": "Description" }, { "code": null, "e": 47598, "s": 47414, "text": "The below example illustrates a pretty basic one-way Client and Server setup where a Client connects, sends messages to the server and the server shows them using a socket connection." }, { "code": null, "e": 47631, "s": 47598, "text": "Client-Side Java Implementation:" }, { "code": null, "e": 47636, "s": 47631, "text": "Java" }, { "code": "// A Java program for a ClientSide import java.io.*;import java.net.*; public class clientSide { // initialize socket and input output streams private Socket socket = null; private DataInputStream input = null; private DataOutputStream out = null; // constructor to put ip address and port public clientSide(String address, int port) { // establish a connection try { socket = new Socket(address, port); System.out.println(\"Connected\"); // takes input from terminal input = new DataInputStream(System.in); // sends output to the socket out = new DataOutputStream( socket.getOutputStream()); } catch (UnknownHostException u) { System.out.println(u); } catch (IOException i) { System.out.println(i); } // string to read message from input String line = \"\"; // keep reading until \"End\" is input while (!line.equals(\"End\")) { try { line = input.readLine(); out.writeUTF(line); } catch (IOException i) { System.out.println(i); } } // close the connection try { input.close(); out.close(); socket.close(); } catch (IOException i) { System.out.println(i); } } public static void main(String[] args) { clientSide client = new clientSide(\"127.0.0.1\", 5000); }}", "e": 49248, "s": 47636, "text": null }, { "code": null, "e": 49281, "s": 49248, "text": "Server Side Java Implementation:" }, { "code": null, "e": 49286, "s": 49281, "text": "Java" }, { "code": "// A Java program for a serverSideimport java.io.*;import java.net.*; public class serverSide { // initialize socket and input stream private Socket socket = null; private ServerSocket server = null; private DataInputStream in = null; // constructor with port public serverSide(int port) { // starts server and waits for a connection try { server = new ServerSocket(port); System.out.println(\"Server started\"); System.out.println(\"Waiting for a client ...\"); socket = server.accept(); System.out.println(\"Client accepted\"); // takes input from the client socket in = new DataInputStream( new BufferedInputStream( socket.getInputStream())); String line = \"\"; // reads message from client until \"End\" is sent while (!line.equals(\"End\")) { try { line = in.readUTF(); System.out.println(line); } catch (IOException i) { System.out.println(i); } } System.out.println(\"Closing connection\"); // close connection socket.close(); in.close(); } catch (IOException i) { System.out.println(i); } } public static void main(String[] args) { serverSide server = new serverSide(5000); }}", "e": 50805, "s": 49286, "text": null }, { "code": null, "e": 50842, "s": 50805, "text": "To run on Terminal or Command Prompt" }, { "code": null, "e": 50899, "s": 50842, "text": "Open two windows one for Server and another for Client. " }, { "code": null, "e": 50952, "s": 50899, "text": "1. First run the Server application. It will show – " }, { "code": null, "e": 50992, "s": 50952, "text": "Server started\nWaiting for a client ..." }, { "code": null, "e": 51062, "s": 50992, "text": "2. Then run the Client application on another terminal. It will show:" }, { "code": null, "e": 51073, "s": 51062, "text": "Connected " }, { "code": null, "e": 51118, "s": 51073, "text": "and the server accepts the client and shows," }, { "code": null, "e": 51134, "s": 51118, "text": "Client accepted" }, { "code": null, "e": 51234, "s": 51134, "text": "3. Then you can start typing messages in the Client window. Here is the sample video of the output." }, { "code": null, "e": 51521, "s": 51234, "text": "The InetAddress class is used to provide methods to get the IP address of any hostname. An IP address is expressed by 32-bit or 128-bit unsigned number. An object of InetAddress describes the IP address with its analogous hostname. InetAddress can control both IPv4 and IPv6 addresses. " }, { "code": null, "e": 51565, "s": 51521, "text": "There are two different types of addresses:" }, { "code": null, "e": 51619, "s": 51565, "text": "Unicast – It is an identifier for a single interface." }, { "code": null, "e": 51683, "s": 51619, "text": "Multicast – It is an identifier for a collection of interfaces." }, { "code": null, "e": 51713, "s": 51683, "text": "Methods of InetAddress Class " }, { "code": null, "e": 51835, "s": 51713, "text": "Java InetAddress class represents an IP address. The following given are the important methods of the InetAddress class –" }, { "code": null, "e": 51842, "s": 51835, "text": "Method" }, { "code": null, "e": 51854, "s": 51842, "text": "Description" }, { "code": null, "e": 51955, "s": 51854, "text": "The Java implementation of the Inet Address class to illustrate the usage of methods is shown below:" }, { "code": null, "e": 51966, "s": 51955, "text": "Example 1:" }, { "code": null, "e": 51971, "s": 51966, "text": "Java" }, { "code": "import java.net.*; public class InetAddressExample1 { public static void main(String[] args) throws UnknownHostException{ // To get and print InetAddress of the Local Host InetAddress address = InetAddress.getLocalHost(); System.out.println(\"InetAddress of the Local Host : \"+address); // To get and print host name of the Local Host String hostName=address.getHostName(); System.out.println(\"\\nHost name of the Local Host : \"+hostName); } }", "e": 52487, "s": 51971, "text": null }, { "code": null, "e": 52580, "s": 52487, "text": "InetAddress of the Local Host : localhost/127.0.0.1\n\nHost name of the Local Host : localhost" }, { "code": null, "e": 52591, "s": 52580, "text": "Example 2:" }, { "code": null, "e": 52596, "s": 52591, "text": "Java" }, { "code": "import java.net.*; public class InetAddressExample2 { public static void main(String[] args) throws UnknownHostException { // To get and print InetAddress of Named Hosts InetAddress address1 = InetAddress.getByName( \"write.geeksforgeeks.org\"); System.out.println(\"Inet Address of named hosts : \" + address1); // To get and print ALL InetAddress of Named Host InetAddress arr[] = InetAddress.getAllByName( \"www.geeksforgeeks.org\"); System.out.println(\"\\nInet Address of ALL named hosts :\"); for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } }}", "e": 53355, "s": 52596, "text": null }, { "code": null, "e": 53363, "s": 53355, "text": "Output " }, { "code": null, "e": 53862, "s": 53363, "text": "The URL class in Java is the entry point to any available sources on the internet. A Class URL describes a Uniform Resource Locator, which is a signal to a “resource” on the World Wide Web. A source can denote a simple file or directory, or it can indicate a more difficult object, such as a query to a database or a search engine. URL is a string of text that recognizes all the sources on the Internet, showing us the address of the source, how to interact with it, and recover something from it." }, { "code": null, "e": 53882, "s": 53862, "text": "Components of a URL" }, { "code": null, "e": 53972, "s": 53882, "text": "A URL can have many forms. The most general however follows a three-components system- " }, { "code": null, "e": 54344, "s": 53972, "text": "Protocol – The protocol in a URL defines how information is transported among the host and a client (or web browser).Hostname – The hostname is the name of the device on which the resource exists.File Name – The filename is the pathname to the file on the device.Port Number – The port number is used to identify different applications uniquely. It is typically optional." }, { "code": null, "e": 54462, "s": 54344, "text": "Protocol – The protocol in a URL defines how information is transported among the host and a client (or web browser)." }, { "code": null, "e": 54542, "s": 54462, "text": "Hostname – The hostname is the name of the device on which the resource exists." }, { "code": null, "e": 54610, "s": 54542, "text": "File Name – The filename is the pathname to the file on the device." }, { "code": null, "e": 54719, "s": 54610, "text": "Port Number – The port number is used to identify different applications uniquely. It is typically optional." }, { "code": null, "e": 54822, "s": 54719, "text": "There are many methods in Java URL Class that are commonly used in Java Networking. These methods are:" }, { "code": null, "e": 54913, "s": 54822, "text": "The Java implementation of the URL class to illustrate the usage of methods is shown below" }, { "code": null, "e": 54924, "s": 54913, "text": "Example 1:" }, { "code": null, "e": 54929, "s": 54924, "text": "Java" }, { "code": "import java.net.*; public class URLclassExample1 { public static void main(String[] args) throws MalformedURLException { // creates a URL with string representation. URL url = new URL( \"https://write.geeksforgeeks.org/post/3038131\"); // print the string representation of the URL String s = url.toString(); System.out.println(\"URL :\" + s); }}", "e": 55343, "s": 54929, "text": null }, { "code": null, "e": 55393, "s": 55343, "text": "URL :https://write.geeksforgeeks.org/post/3038131" }, { "code": null, "e": 55404, "s": 55393, "text": "Example 2:" }, { "code": null, "e": 55409, "s": 55404, "text": "Java" }, { "code": "import java.net.*; public class URLclassExample2 { public static void main(String[] args) throws MalformedURLException { URL url = new URL( \"https://write.geeksforgeeks.org/post/3038131\"); // to get and print the protocol of the URL String protocol = url.getProtocol(); System.out.println(\"Protocol : \" + protocol); // to get and print the hostName of the URL String host = url.getHost(); System.out.println(\"HostName : \" + host); // to get and print the file name of the URL String fileName = url.getFile(); System.out.println(\"File Name : \" + fileName); }}", "e": 56082, "s": 55409, "text": null }, { "code": null, "e": 56160, "s": 56082, "text": "Protocol : https\nHostName : write.geeksforgeeks.org\nFile Name : /post/3038131" }, { "code": null, "e": 56171, "s": 56160, "text": "Example 3:" }, { "code": null, "e": 56176, "s": 56171, "text": "Java" }, { "code": "import java.net.*; public class URLclassExample3 { public static void main(String[] args) throws MalformedURLException { URL url = new URL( \"https://write.geeksforgeeks.org/post/3038131\"); // to get and print the default port of the URL int defaultPort = url.getDefaultPort(); System.out.println(\"Default Port : \" + defaultPort); // to get and print the path of the URL String path = url.getPath(); System.out.println(\"Path : \" + path); }}", "e": 56705, "s": 56176, "text": null }, { "code": null, "e": 56745, "s": 56705, "text": "Default Port : 443\nPath : /post/3038131" }, { "code": null, "e": 57039, "s": 56745, "text": "This was a brief introduction to Java Networking. In this article, many important topics like Introduction of Java Networking, Common Network Protocols, Java Network Terminology, Java Networking Classes, Java Networking Interfaces, Socket Programming, Inet Address, and URL Class were covered." }, { "code": null, "e": 57044, "s": 57039, "text": "Java" }, { "code": null, "e": 57049, "s": 57044, "text": "Java" }, { "code": null, "e": 57147, "s": 57049, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 57156, "s": 57147, "text": "Comments" }, { "code": null, "e": 57169, "s": 57156, "text": "Old Comments" }, { "code": null, "e": 57199, "s": 57169, "text": "Functional Interfaces in Java" }, { "code": null, "e": 57214, "s": 57199, "text": "Stream In Java" }, { "code": null, "e": 57235, "s": 57214, "text": "Constructors in Java" }, { "code": null, "e": 57281, "s": 57235, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 57300, "s": 57281, "text": "Exceptions in Java" }, { "code": null, "e": 57317, "s": 57300, "text": "Generics in Java" }, { "code": null, "e": 57360, "s": 57317, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 57376, "s": 57360, "text": "Strings in Java" }, { "code": null, "e": 57425, "s": 57376, "text": "How to remove an element from ArrayList in Java?" } ]
Lemoine's Conjecture - GeeksforGeeks
21 Dec, 2020 Any odd integer greater than 5 can be expressed as a sum of an odd prime (all primes other than 2 are odd) and an even semiprime. A semiprime number is a product of two prime numbers. This is called Lemoine’s conjecture. Examples : 7 = 3 + (2 × 2), where 3 is a prime number (other than 2) and 4 (= 2 × 2) is a semiprime number.11 = 5 + (2 × 3) where 5 is a prime number and 6(= 2 × 3) is a semiprime number.9 = 3 + (2 × 3) or 9 = 5 + (2 × 2)47 = 13 + 2 × 17 = 37 + 2 × 5 = 41 + 2 × 3 = 43 + 2 × 2 C++ Java Python3 C# // C++ code to verify Lemoine's Conjecture// for any odd number >= 7#include<bits/stdc++.h>using namespace std; // Function to check if a number is// prime or notbool isPrime(int n){ if (n < 2) return false; for (int i = 2; i <= sqrt(n); i++) { if (n % i == 0) return false; } return true;} // Representing n as p + (2 * q) to satisfy// lemoine's conjecturevoid lemoine(int n){ // Declaring a map to hold pairs (p, q) map<int, int> pr; // Declaring an iterator for map map<int, int>::iterator it; it = pr.begin(); // Finding various values of p for each q // to satisfy n = p + (2 * q) for (int q = 1; q <= n / 2; q++) { int p = n - 2 * q; // After finding a pair that satisfies the // equation, check if both p and q are // prime or not if (isPrime(p) && isPrime(q)) // If both p and q are prime, store // them in the map pr.insert(it, pair<int, int>(p, q)); } // Displaying all pairs (p, q) that satisfy // lemoine's conjecture for the number 'n' for (it = pr.begin(); it != pr.end(); ++it) cout << n << " = " << it->first << " + (2 * " << it->second << ")\n";} // Driver Functionint main(){ int n = 39; cout << n << " can be expressed as " << endl; // Function calling lemoine(n); return 0;} // This code is contributed by Saagnik Adhikary // Java code to verify Lemoine's Conjecture// for any odd number >= 7 import java.util.*; class GFG { static class pair { int first, second; public pair(int first, int second) { this.first = first; this.second = second; } } // Function to check if a number is // prime or not static boolean isPrime(int n) { if (n < 2) return false; for (int i = 2; i <= Math.sqrt(n); i++) { if (n % i == 0) return false; } return true; } // Representing n as p + (2 * q) to satisfy // lemoine's conjecture static void lemoine(int n) { // Declaring a map to hold pairs (p, q) HashMap<Integer, pair> pr = new HashMap<>(); // Declaring an iterator for map // HashMap<Integer,Integer>::iterator it; // it = pr.begin(); int i = 0; // Finding various values of p for each q // to satisfy n = p + (2 * q) for (int q = 1; q <= n / 2; q++) { int p = n - 2 * q; // After finding a pair that satisfies the // equation, check if both p and q are // prime or not if (isPrime(p) && isPrime(q)) // If both p and q are prime, store // them in the map pr.put(i, new pair(p, q)); i++; } // Displaying all pairs (p, q) that satisfy // lemoine's conjecture for the number 'n' for (Map.Entry<Integer, pair> it : pr.entrySet()) System.out.print(n + " = " + it.getValue().first + " + (2 * " + it.getValue().second + ")\n"); } // Driver Function public static void main(String[] args) { int n = 39; System.out.print(n + " can be expressed as " + "\n"); // Function calling lemoine(n); }} // This code contributed by aashish1995 # Python code to verify Lemoine's Conjecture# for any odd number >= 7from math import sqrt # Function to check if a number is# prime or notdef isPrime(n: int) -> bool: if n < 2: return False for i in range(2, int(sqrt(n)) + 1): if n % i == 0: return False return True # Representing n as p + (2 * q) to satisfy# lemoine's conjecturedef lemoine(n: int) -> None: # Declaring a map to hold pairs (p, q) pr = dict() # Finding various values of p for each q # to satisfy n = p + (2 * q) for q in range(1, n // 2 + 1): p = n - 2 * q # After finding a pair that satisfies the # equation, check if both p and q are # prime or not if isPrime(p) and isPrime(q): # If both p and q are prime, store # them in the map if p not in pr: pr[p] = q # Displaying all pairs (p, q) that satisfy # lemoine's conjecture for the number 'n' for it in pr: print("%d = %d + (2 * %d)" % (n, it, pr[it])) # Driver Codeif __name__ == "__main__": n = 39 print(n, "can be expressed as ") # Function calling lemoine(n) # This code is contributed by# sanjeev2552 // C# code to verify Lemoine's Conjecture// for any odd number >= 7using System;using System.Collections.Generic; class GFG{ public class pair { public int first, second; public pair(int first, int second) { this.first = first; this.second = second; } } // Function to check if a number is // prime or not static bool isPrime(int n) { if (n < 2) return false; for (int i = 2; i <= Math.Sqrt(n); i++) { if (n % i == 0) return false; } return true; } // Representing n as p + (2 * q) to satisfy // lemoine's conjecture static void lemoine(int n) { // Declaring a map to hold pairs (p, q) Dictionary<int, pair> pr = new Dictionary<int, pair>(); // Declaring an iterator for map // Dictionary<int,int>::iterator it; // it = pr.begin(); int i = 0; // Finding various values of p for each q // to satisfy n = p + (2 * q) for (int q = 1; q <= n / 2; q++) { int p = n - 2 * q; // After finding a pair that satisfies the // equation, check if both p and q are // prime or not if (isPrime(p) && isPrime(q)) // If both p and q are prime, store // them in the map pr.Add(i, new pair(p, q)); i++; } // Displaying all pairs (p, q) that satisfy // lemoine's conjecture for the number 'n' foreach (KeyValuePair<int, pair> it in pr) Console.Write(n + " = " + it.Value.first + " + (2 * " + it.Value.second + ")\n"); } // Driver code public static void Main(String[] args) { int n = 39; Console.Write(n + " can be expressed as " + "\n"); // Function calling lemoine(n); } } // This code is contributed by aashish1995 Output : 39 can be expressed as : 39 = 5 + (2 * 17) 39 = 13 + (2 * 13) 39 = 17 + (2 * 11) 39 = 29 + (2 * 5) SaagnikAdhikary sanjeev2552 aashish1995 number-theory Prime Number prime-factor Mathematical number-theory Mathematical Prime Number Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples 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 Program for factorial of a number Minimum number of jumps to reach end Operators in C / C++
[ { "code": null, "e": 24181, "s": 24153, "text": "\n21 Dec, 2020" }, { "code": null, "e": 24414, "s": 24181, "text": "Any odd integer greater than 5 can be expressed as a sum of an odd prime (all primes other than 2 are odd) and an even semiprime. A semiprime number is a product of two prime numbers. This is called Lemoine’s conjecture. Examples : " }, { "code": null, "e": 24680, "s": 24414, "text": "7 = 3 + (2 × 2), where 3 is a prime number (other than 2) and 4 (= 2 × 2) is a semiprime number.11 = 5 + (2 × 3) where 5 is a prime number and 6(= 2 × 3) is a semiprime number.9 = 3 + (2 × 3) or 9 = 5 + (2 × 2)47 = 13 + 2 × 17 = 37 + 2 × 5 = 41 + 2 × 3 = 43 + 2 × 2" }, { "code": null, "e": 24686, "s": 24682, "text": "C++" }, { "code": null, "e": 24691, "s": 24686, "text": "Java" }, { "code": null, "e": 24699, "s": 24691, "text": "Python3" }, { "code": null, "e": 24702, "s": 24699, "text": "C#" }, { "code": "// C++ code to verify Lemoine's Conjecture// for any odd number >= 7#include<bits/stdc++.h>using namespace std; // Function to check if a number is// prime or notbool isPrime(int n){ if (n < 2) return false; for (int i = 2; i <= sqrt(n); i++) { if (n % i == 0) return false; } return true;} // Representing n as p + (2 * q) to satisfy// lemoine's conjecturevoid lemoine(int n){ // Declaring a map to hold pairs (p, q) map<int, int> pr; // Declaring an iterator for map map<int, int>::iterator it; it = pr.begin(); // Finding various values of p for each q // to satisfy n = p + (2 * q) for (int q = 1; q <= n / 2; q++) { int p = n - 2 * q; // After finding a pair that satisfies the // equation, check if both p and q are // prime or not if (isPrime(p) && isPrime(q)) // If both p and q are prime, store // them in the map pr.insert(it, pair<int, int>(p, q)); } // Displaying all pairs (p, q) that satisfy // lemoine's conjecture for the number 'n' for (it = pr.begin(); it != pr.end(); ++it) cout << n << \" = \" << it->first << \" + (2 * \" << it->second << \")\\n\";} // Driver Functionint main(){ int n = 39; cout << n << \" can be expressed as \" << endl; // Function calling lemoine(n); return 0;} // This code is contributed by Saagnik Adhikary", "e": 26175, "s": 24702, "text": null }, { "code": "// Java code to verify Lemoine's Conjecture// for any odd number >= 7 import java.util.*; class GFG { static class pair { int first, second; public pair(int first, int second) { this.first = first; this.second = second; } } // Function to check if a number is // prime or not static boolean isPrime(int n) { if (n < 2) return false; for (int i = 2; i <= Math.sqrt(n); i++) { if (n % i == 0) return false; } return true; } // Representing n as p + (2 * q) to satisfy // lemoine's conjecture static void lemoine(int n) { // Declaring a map to hold pairs (p, q) HashMap<Integer, pair> pr = new HashMap<>(); // Declaring an iterator for map // HashMap<Integer,Integer>::iterator it; // it = pr.begin(); int i = 0; // Finding various values of p for each q // to satisfy n = p + (2 * q) for (int q = 1; q <= n / 2; q++) { int p = n - 2 * q; // After finding a pair that satisfies the // equation, check if both p and q are // prime or not if (isPrime(p) && isPrime(q)) // If both p and q are prime, store // them in the map pr.put(i, new pair(p, q)); i++; } // Displaying all pairs (p, q) that satisfy // lemoine's conjecture for the number 'n' for (Map.Entry<Integer, pair> it : pr.entrySet()) System.out.print(n + \" = \" + it.getValue().first + \" + (2 * \" + it.getValue().second + \")\\n\"); } // Driver Function public static void main(String[] args) { int n = 39; System.out.print(n + \" can be expressed as \" + \"\\n\"); // Function calling lemoine(n); }} // This code contributed by aashish1995", "e": 28062, "s": 26175, "text": null }, { "code": "# Python code to verify Lemoine's Conjecture# for any odd number >= 7from math import sqrt # Function to check if a number is# prime or notdef isPrime(n: int) -> bool: if n < 2: return False for i in range(2, int(sqrt(n)) + 1): if n % i == 0: return False return True # Representing n as p + (2 * q) to satisfy# lemoine's conjecturedef lemoine(n: int) -> None: # Declaring a map to hold pairs (p, q) pr = dict() # Finding various values of p for each q # to satisfy n = p + (2 * q) for q in range(1, n // 2 + 1): p = n - 2 * q # After finding a pair that satisfies the # equation, check if both p and q are # prime or not if isPrime(p) and isPrime(q): # If both p and q are prime, store # them in the map if p not in pr: pr[p] = q # Displaying all pairs (p, q) that satisfy # lemoine's conjecture for the number 'n' for it in pr: print(\"%d = %d + (2 * %d)\" % (n, it, pr[it])) # Driver Codeif __name__ == \"__main__\": n = 39 print(n, \"can be expressed as \") # Function calling lemoine(n) # This code is contributed by# sanjeev2552", "e": 29259, "s": 28062, "text": null }, { "code": "// C# code to verify Lemoine's Conjecture// for any odd number >= 7using System;using System.Collections.Generic; class GFG{ public class pair { public int first, second; public pair(int first, int second) { this.first = first; this.second = second; } } // Function to check if a number is // prime or not static bool isPrime(int n) { if (n < 2) return false; for (int i = 2; i <= Math.Sqrt(n); i++) { if (n % i == 0) return false; } return true; } // Representing n as p + (2 * q) to satisfy // lemoine's conjecture static void lemoine(int n) { // Declaring a map to hold pairs (p, q) Dictionary<int, pair> pr = new Dictionary<int, pair>(); // Declaring an iterator for map // Dictionary<int,int>::iterator it; // it = pr.begin(); int i = 0; // Finding various values of p for each q // to satisfy n = p + (2 * q) for (int q = 1; q <= n / 2; q++) { int p = n - 2 * q; // After finding a pair that satisfies the // equation, check if both p and q are // prime or not if (isPrime(p) && isPrime(q)) // If both p and q are prime, store // them in the map pr.Add(i, new pair(p, q)); i++; } // Displaying all pairs (p, q) that satisfy // lemoine's conjecture for the number 'n' foreach (KeyValuePair<int, pair> it in pr) Console.Write(n + \" = \" + it.Value.first + \" + (2 * \" + it.Value.second + \")\\n\"); } // Driver code public static void Main(String[] args) { int n = 39; Console.Write(n + \" can be expressed as \" + \"\\n\"); // Function calling lemoine(n); } } // This code is contributed by aashish1995", "e": 31344, "s": 29259, "text": null }, { "code": null, "e": 31355, "s": 31344, "text": "Output : " }, { "code": null, "e": 31454, "s": 31355, "text": "39 can be expressed as :\n39 = 5 + (2 * 17)\n39 = 13 + (2 * 13)\n39 = 17 + (2 * 11)\n39 = 29 + (2 * 5)" }, { "code": null, "e": 31476, "s": 31460, "text": "SaagnikAdhikary" }, { "code": null, "e": 31488, "s": 31476, "text": "sanjeev2552" }, { "code": null, "e": 31500, "s": 31488, "text": "aashish1995" }, { "code": null, "e": 31514, "s": 31500, "text": "number-theory" }, { "code": null, "e": 31527, "s": 31514, "text": "Prime Number" }, { "code": null, "e": 31540, "s": 31527, "text": "prime-factor" }, { "code": null, "e": 31553, "s": 31540, "text": "Mathematical" }, { "code": null, "e": 31567, "s": 31553, "text": "number-theory" }, { "code": null, "e": 31580, "s": 31567, "text": "Mathematical" }, { "code": null, "e": 31593, "s": 31580, "text": "Prime Number" }, { "code": null, "e": 31691, "s": 31593, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31700, "s": 31691, "text": "Comments" }, { "code": null, "e": 31713, "s": 31700, "text": "Old Comments" }, { "code": null, "e": 31737, "s": 31713, "text": "Merge two sorted arrays" }, { "code": null, "e": 31780, "s": 31737, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 31821, "s": 31780, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 31866, "s": 31821, "text": "Find all factors of a natural number | Set 1" }, { "code": null, "e": 31893, "s": 31866, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 31942, "s": 31893, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 31985, "s": 31942, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 32019, "s": 31985, "text": "Program for factorial of a number" }, { "code": null, "e": 32056, "s": 32019, "text": "Minimum number of jumps to reach end" } ]
Find if given number is sum of first n natural numbers - GeeksforGeeks
26 Apr, 2021 Given a number s (1 <= s <= 1000000000). If this number is the sum of first n natural number then print, otherwise print -1. Examples: Input: s = 10 Output: n = 4 Explanation: 1 + 2 + 3 + 4 = 10 Input: s = 17 Output: n = -1 Explanation: 17 can't be expressed as a sum of consecutive from 1. Method 1 (Simple): Start adding numbers from i = 1 to n. Check if the sum is equal to n, return i. Else if sum > n, return -1. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ program for above implementation#include <iostream>using namespace std; // Function to find no. of elements// to be added from 1 to get nint findS(int s){ int sum = 0; // Start adding numbers from 1 for (int n = 1; sum < s; n++) { sum += n; // If sum becomes equal to s // return n if (sum == s) return n; } return -1;} // Drivers codeint main(){ int s = 15; int n = findS(s); n == -1 ? cout << "-1" : cout << n; return 0;} // Java program for above implementationclass GFG { // Function to find no. of elements // to be added from 1 to get n static int findS(int s) { int sum = 0; // Start adding numbers from 1 for (int n = 1; sum < s; n++) { sum += n; // If sum becomes equal to s // return n if (sum == s) return n; } return -1; } // Drivers code public static void main(String[]args) { int s = 15; int n = findS(s); if(n == -1) System.out.println("-1"); else System.out.println(n); }} //This code is contributed by Azkia Anam. # Python3 program to check if# given number is sum of first n# natural numbers # Function to find no. of elements# to be added from 1 to get ndef findS (s): _sum = 0 n = 1 # Start adding numbers from 1 while(_sum < s): _sum += n n+=1 n-=1 # If sum becomes equal to s # return n if _sum == s: return n return -1 # Driver codes = 15n = findS (s)if n == -1: print("-1")else: print(n) # This code is contributed by "Abhishek Sharma 44". // C# program for above implementationusing System; class GFG { // Function to find no. of elements // to be added from 1 to get n static int findS(int s) { int sum = 0; // Start adding numbers from 1 for (int n = 1; sum < s; n++) { sum += n; // If sum becomes equal to s // return n if (sum == s) return n; } return -1; } // Drivers code public static void Main() { int s = 15; int n = findS(s); if(n == -1) Console.WriteLine("-1"); else Console.WriteLine(n); }} // This code is contributed by vt_m. <?php// PHP program for above implementation // Function to find no. of elements// to be added from 1 to get nfunction findS($s){ $sum = 0; // Start adding numbers from 1 for ($n = 1; $sum < $s; $n++) { $sum += $n; // If sum becomes equal // to s return n if ($sum == $s) return $n; } return -1;} // Drivers code$s = 15;$n = findS($s);if($n == -1)echo "-1";elseecho $n; // This code is contributed by Sam007?> <script> // Javascript program for above implementation // Function to find no. of elements// to be added from 1 to get n function findS(s) { var sum = 0; // Start adding numbers from 1 for (n = 1; sum < s; n++) { sum += n; // If sum becomes equal to s // return n if (sum == s) return n; } return -1; } // Drivers code var s = 15; var n = findS(s); if (n == -1) document.write("-1"); else document.write(n); // This code is contributed by Rajput-Ji </script> 5 Time Complexity: O(s), where s are the no. of consecutive numbers from 1 to sAuxiliary Space: O(1) Method 2 (Binary Search): 1- Initialize l = 1 and r = n / 2. 2- Apply binary search from l to r. a) Find mid = (l+r) / 2 b) Find sum from 1 to mid using formula mid*(mid+1)/2 c) If sum of mid natural numbers is equal to n, return mid. d) Else if sum > n, r = mid - 1. e) Else sum < n, l = mid + 1. 3- Return -1, if not possible. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ program for finding s such// that sum from 1 to s equals to n#include <iostream>using namespace std; // Function to find no. of elements// to be added to get sint findS(int s){ int l = 1, r = (s / 2) + 1; // Apply Binary search while (l <= r) { // Find mid int mid = (l + r) / 2; // find sum of 1 to mid natural numbers // using formula int sum = mid * (mid + 1) / 2; // If sum is equal to n // return mid if (sum == s) return mid; // If greater than n // do r = mid-1 else if (sum > s) r = mid - 1; // else do l = mid + 1 else l = mid + 1; } // If not possible, return -1 return -1;} // Drivers codeint main(){ int s = 15; int n = findS(s); n == -1 ? cout << "-1" : cout << n; return 0;} // java program for finding s such// that sum from 1 to s equals to nimport java.io.*; public class GFG { // Function to find no. of elements // to be added to get s static int findS(int s) { int l = 1, r = (s / 2) + 1; // Apply Binary search while (l <= r) { // Find mid int mid = (l + r) / 2; // find sum of 1 to mid natural // numbers using formula int sum = mid * (mid + 1) / 2; // If sum is equal to n // return mid if (sum == s) return mid; // If greater than n // do r = mid-1 else if (sum > s) r = mid - 1; // else do l = mid + 1 else l = mid + 1; } // If not possible, return -1 return -1; } // Drivers code static public void main (String[] args) { int s = 15; int n = findS(s); if(n==-1) System.out.println("-1"); else System.out.println(n); }} // This code is contributed by vt_m. # python program for finding s such# that sum from 1 to s equals to n # Function to find no. of elements# to be added to get sdef findS(s): l = 1 r = int(s / 2) + 1 # Apply Binary search while (l <= r) : # Find mid mid = int((l + r) / 2) # find sum of 1 to mid natural numbers # using formula sum = int(mid * (mid + 1) / 2) # If sum is equal to n # return mid if (sum == s): return mid # If greater than n # do r = mid-1 elif (sum > s): r = mid - 1 # else do l = mid + 1 else: l = mid + 1 # If not possible, return -1 return -1 s = 15n = findS(s)if(n == -1): print( "-1")else: print( n ) # This code is contributed by Sam007 // C# program for finding s such// that sum from 1 to s equals to nusing System; public class GFG { // Function to find no. of elements // to be added to get s static int findS(int s) { int l = 1, r = (s / 2) + 1; // Apply Binary search while (l <= r) { // Find mid int mid = (l + r) / 2; // find sum of 1 to mid natural // numbers using formula int sum = mid * (mid + 1) / 2; // If sum is equal to n // return mid if (sum == s) return mid; // If greater than n // do r = mid-1 else if (sum > s) r = mid - 1; // else do l = mid + 1 else l = mid + 1; } // If not possible, return -1 return -1; } // Drivers code static public void Main () { int s = 15; int n = findS(s); if(n==-1) Console.WriteLine("-1"); else Console.WriteLine(n); }} // This code is contributed by vt_m. <?php// PHP program for finding// s such that sum from 1// to s equals to n // Function to find no.// of elements to be added// to get sfunction findS($s){ $l = 1; $r = 1 + (int)$s / 2; // Apply Binary search while ($l <= $r) { // Find mid $mid = (int)(($l + $r) / 2); // find sum of 1 to mid natural // numbers using formula $sum = (int)($mid * ($mid + 1) / 2); // If sum is equal to n // return mid if ($sum == $s) return $mid; // If greater than n // do r = mid-1 else if ($sum > $s) $r = $mid - 1; // else do l = mid + 1 else $l = $mid + 1; } // If not possible, // return -1 return -1;} // Drivers code$s = 15;$n = findS($s);if($n == -1 )echo "-1";elseecho $n; // This code is contributed by Sam007?> <script> // Javascript program for finding s such// that sum from 1 to s equals to n public // Function to find no. of elements // to be added to get s function findS(s) { var l = 1, r = parseInt((s / 2) + 1); // Apply Binary search while (l <= r) { // Find mid var mid = parseInt( (l + r) / 2); // find sum of 1 to mid natural // numbers using formula var sum = mid * parseInt((mid + 1) / 2); // If sum is equal to n // return mid if (sum == s) return mid; // If greater than n // do r = mid-1 else if (sum > s) r = mid - 1; // else do l = mid + 1 else l = mid + 1; } // If not possible, return -1 return -1; } // Drivers code var s = 15; var n = findS(s); if (n == -1) document.write("-1"); else document.write(n); // This code contributed by Rajput-Ji </script> 5 Time Complexity: O(log n)Auxiliary Space: O(1) Method 3: Using Mathematical formula The idea is to use the formulae of the sum of first N natural numbers to compute the value of the N. Below is the illustration: ⇾ 1 + 2 + 3 + .... N = S⇾ (N * (N + 1)) / 2 = S⇾ N * (N + 1) = 2 * S⇾ N2 + N – 2 * S = 0 Therefore, Check if the solution of the quadratic equation is equal to integer or not. If Yes then the solution exists. Otherwise, the given number is not sum of first N natural number. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program of the above// approach #include <bits/stdc++.h> # define ll long long using namespace std; // Function to check if the// s is the sum of first N// natural numberll int isvalid(ll int s){ // Solution of Quadratic Equation float k=(-1+sqrt(1+8*s))/2; // Condition to check if the // solution is a integer if(ceil(k)==floor(k)) return k; else return -1;} // Driver Codeint main(){ int s = 15; // Function Call cout<< isvalid(s); return 0;} // Java program of the above// approachimport java.util.*; class GFG{ // Function to check if the// s is the sum of first N// natural numberpublic static int isvalid(int s){ // Solution of Quadratic Equation double k = (-1.0 + Math.sqrt(1 + 8 * s)) / 2; // Condition to check if the // solution is a integer if (Math.ceil(k) == Math.floor(k)) return (int)k; else return -1;} // Driver codepublic static void main(String[] args){ int s = 15; // Function call System.out.print(isvalid(s));}} // This code is contributed by divyeshrabadiya07 # Python3 program of the above# approachimport math # Function to check if the# s is the sum of first N# natural numberdef isvalid(s): # Solution of Quadratic Equation k = (-1 + math.sqrt(1 + 8 * s)) / 2 # Condition to check if the # solution is a integer if (math.ceil(k) == math.floor(k)): return int(k) else: return -1 # Driver Codes = 15 # Function Callprint(isvalid(s)) # This code is contributed by vishu2908 // C# program of the above// approachusing System;class GFG{ // Function to check if the// s is the sum of first N// natural numberpublic static int isvalid(int s){ // Solution of Quadratic Equation double k = (-1.0 + Math.Sqrt (1 + 8 * s)) / 2; // Condition to check if the // solution is a integer if (Math.Ceiling(k) == Math.Floor(k)) return (int)k; else return -1;} // Driver codepublic static void Main(string[] args){ int s = 15; // Function call Console.Write(isvalid(s));}} // This code is contributed by Chitranayal <script> // Javascript program of the above// approach // Function to check if the// s is the sum of first N// natural numberfunction isvalid(s){ // Solution of Quadratic Equation let k = (-1.0 + Math.sqrt(1 + 8 * s)) / 2; // Condition to check if the // solution is a integer if (Math.ceil(k) == Math.floor(k)) return k; else return -1;}// Driver code let s = 15; // Function call document.write(isvalid(s)); </script> 5 Time Complexity: O(1)Auxiliary Space: O(1) vt_m Sam007 Roshan Srivastava 1 ajaykr00kj divyeshrabadiya07 vishu2908 ukasp Rajput-Ji sanjoy_62 Binary Search Mathematical Misc Searching Misc Searching Mathematical Misc Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithm to solve Rubik's Cube Program to print prime numbers from 1 to N. Fizz Buzz Implementation Program to multiply two matrices Modular multiplicative inverse Top 10 algorithms in Interview Questions vector::push_back() and vector::pop_back() in C++ STL Overview of Data Structures | Set 1 (Linear Data Structures) How to write Regular Expressions? fgets() and gets() in C language
[ { "code": null, "e": 24718, "s": 24690, "text": "\n26 Apr, 2021" }, { "code": null, "e": 24854, "s": 24718, "text": "Given a number s (1 <= s <= 1000000000). If this number is the sum of first n natural number then print, otherwise print -1. Examples: " }, { "code": null, "e": 25012, "s": 24854, "text": "Input: s = 10\nOutput: n = 4\nExplanation:\n1 + 2 + 3 + 4 = 10\n\nInput: s = 17\nOutput: n = -1\nExplanation:\n17 can't be expressed as a \nsum of consecutive from 1." }, { "code": null, "e": 25032, "s": 25012, "text": " Method 1 (Simple):" }, { "code": null, "e": 25070, "s": 25032, "text": "Start adding numbers from i = 1 to n." }, { "code": null, "e": 25112, "s": 25070, "text": "Check if the sum is equal to n, return i." }, { "code": null, "e": 25140, "s": 25112, "text": "Else if sum > n, return -1." }, { "code": null, "e": 25191, "s": 25140, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 25195, "s": 25191, "text": "C++" }, { "code": null, "e": 25200, "s": 25195, "text": "Java" }, { "code": null, "e": 25208, "s": 25200, "text": "Python3" }, { "code": null, "e": 25211, "s": 25208, "text": "C#" }, { "code": null, "e": 25215, "s": 25211, "text": "PHP" }, { "code": null, "e": 25226, "s": 25215, "text": "Javascript" }, { "code": "// C++ program for above implementation#include <iostream>using namespace std; // Function to find no. of elements// to be added from 1 to get nint findS(int s){ int sum = 0; // Start adding numbers from 1 for (int n = 1; sum < s; n++) { sum += n; // If sum becomes equal to s // return n if (sum == s) return n; } return -1;} // Drivers codeint main(){ int s = 15; int n = findS(s); n == -1 ? cout << \"-1\" : cout << n; return 0;}", "e": 25738, "s": 25226, "text": null }, { "code": "// Java program for above implementationclass GFG { // Function to find no. of elements // to be added from 1 to get n static int findS(int s) { int sum = 0; // Start adding numbers from 1 for (int n = 1; sum < s; n++) { sum += n; // If sum becomes equal to s // return n if (sum == s) return n; } return -1; } // Drivers code public static void main(String[]args) { int s = 15; int n = findS(s); if(n == -1) System.out.println(\"-1\"); else System.out.println(n); }} //This code is contributed by Azkia Anam.", "e": 26446, "s": 25738, "text": null }, { "code": "# Python3 program to check if# given number is sum of first n# natural numbers # Function to find no. of elements# to be added from 1 to get ndef findS (s): _sum = 0 n = 1 # Start adding numbers from 1 while(_sum < s): _sum += n n+=1 n-=1 # If sum becomes equal to s # return n if _sum == s: return n return -1 # Driver codes = 15n = findS (s)if n == -1: print(\"-1\")else: print(n) # This code is contributed by \"Abhishek Sharma 44\".", "e": 26943, "s": 26446, "text": null }, { "code": "// C# program for above implementationusing System; class GFG { // Function to find no. of elements // to be added from 1 to get n static int findS(int s) { int sum = 0; // Start adding numbers from 1 for (int n = 1; sum < s; n++) { sum += n; // If sum becomes equal to s // return n if (sum == s) return n; } return -1; } // Drivers code public static void Main() { int s = 15; int n = findS(s); if(n == -1) Console.WriteLine(\"-1\"); else Console.WriteLine(n); }} // This code is contributed by vt_m.", "e": 27653, "s": 26943, "text": null }, { "code": "<?php// PHP program for above implementation // Function to find no. of elements// to be added from 1 to get nfunction findS($s){ $sum = 0; // Start adding numbers from 1 for ($n = 1; $sum < $s; $n++) { $sum += $n; // If sum becomes equal // to s return n if ($sum == $s) return $n; } return -1;} // Drivers code$s = 15;$n = findS($s);if($n == -1)echo \"-1\";elseecho $n; // This code is contributed by Sam007?>", "e": 28123, "s": 27653, "text": null }, { "code": "<script> // Javascript program for above implementation // Function to find no. of elements// to be added from 1 to get n function findS(s) { var sum = 0; // Start adding numbers from 1 for (n = 1; sum < s; n++) { sum += n; // If sum becomes equal to s // return n if (sum == s) return n; } return -1; } // Drivers code var s = 15; var n = findS(s); if (n == -1) document.write(\"-1\"); else document.write(n); // This code is contributed by Rajput-Ji </script>", "e": 28749, "s": 28123, "text": null }, { "code": null, "e": 28751, "s": 28749, "text": "5" }, { "code": null, "e": 28850, "s": 28751, "text": "Time Complexity: O(s), where s are the no. of consecutive numbers from 1 to sAuxiliary Space: O(1)" }, { "code": null, "e": 28876, "s": 28850, "text": "Method 2 (Binary Search):" }, { "code": null, "e": 29206, "s": 28876, "text": "1- Initialize l = 1 and r = n / 2.\n2- Apply binary search from l to r.\n a) Find mid = (l+r) / 2\n b) Find sum from 1 to mid using formula \n mid*(mid+1)/2\n c) If sum of mid natural numbers is equal \n to n, return mid.\n d) Else if sum > n, r = mid - 1.\n e) Else sum < n, l = mid + 1.\n3- Return -1, if not possible." }, { "code": null, "e": 29257, "s": 29206, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 29261, "s": 29257, "text": "C++" }, { "code": null, "e": 29266, "s": 29261, "text": "Java" }, { "code": null, "e": 29274, "s": 29266, "text": "Python3" }, { "code": null, "e": 29277, "s": 29274, "text": "C#" }, { "code": null, "e": 29281, "s": 29277, "text": "PHP" }, { "code": null, "e": 29292, "s": 29281, "text": "Javascript" }, { "code": "// C++ program for finding s such// that sum from 1 to s equals to n#include <iostream>using namespace std; // Function to find no. of elements// to be added to get sint findS(int s){ int l = 1, r = (s / 2) + 1; // Apply Binary search while (l <= r) { // Find mid int mid = (l + r) / 2; // find sum of 1 to mid natural numbers // using formula int sum = mid * (mid + 1) / 2; // If sum is equal to n // return mid if (sum == s) return mid; // If greater than n // do r = mid-1 else if (sum > s) r = mid - 1; // else do l = mid + 1 else l = mid + 1; } // If not possible, return -1 return -1;} // Drivers codeint main(){ int s = 15; int n = findS(s); n == -1 ? cout << \"-1\" : cout << n; return 0;}", "e": 30161, "s": 29292, "text": null }, { "code": "// java program for finding s such// that sum from 1 to s equals to nimport java.io.*; public class GFG { // Function to find no. of elements // to be added to get s static int findS(int s) { int l = 1, r = (s / 2) + 1; // Apply Binary search while (l <= r) { // Find mid int mid = (l + r) / 2; // find sum of 1 to mid natural // numbers using formula int sum = mid * (mid + 1) / 2; // If sum is equal to n // return mid if (sum == s) return mid; // If greater than n // do r = mid-1 else if (sum > s) r = mid - 1; // else do l = mid + 1 else l = mid + 1; } // If not possible, return -1 return -1; } // Drivers code static public void main (String[] args) { int s = 15; int n = findS(s); if(n==-1) System.out.println(\"-1\"); else System.out.println(n); }} // This code is contributed by vt_m.", "e": 31315, "s": 30161, "text": null }, { "code": "# python program for finding s such# that sum from 1 to s equals to n # Function to find no. of elements# to be added to get sdef findS(s): l = 1 r = int(s / 2) + 1 # Apply Binary search while (l <= r) : # Find mid mid = int((l + r) / 2) # find sum of 1 to mid natural numbers # using formula sum = int(mid * (mid + 1) / 2) # If sum is equal to n # return mid if (sum == s): return mid # If greater than n # do r = mid-1 elif (sum > s): r = mid - 1 # else do l = mid + 1 else: l = mid + 1 # If not possible, return -1 return -1 s = 15n = findS(s)if(n == -1): print( \"-1\")else: print( n ) # This code is contributed by Sam007", "e": 32111, "s": 31315, "text": null }, { "code": "// C# program for finding s such// that sum from 1 to s equals to nusing System; public class GFG { // Function to find no. of elements // to be added to get s static int findS(int s) { int l = 1, r = (s / 2) + 1; // Apply Binary search while (l <= r) { // Find mid int mid = (l + r) / 2; // find sum of 1 to mid natural // numbers using formula int sum = mid * (mid + 1) / 2; // If sum is equal to n // return mid if (sum == s) return mid; // If greater than n // do r = mid-1 else if (sum > s) r = mid - 1; // else do l = mid + 1 else l = mid + 1; } // If not possible, return -1 return -1; } // Drivers code static public void Main () { int s = 15; int n = findS(s); if(n==-1) Console.WriteLine(\"-1\"); else Console.WriteLine(n); }} // This code is contributed by vt_m.", "e": 33244, "s": 32111, "text": null }, { "code": "<?php// PHP program for finding// s such that sum from 1// to s equals to n // Function to find no.// of elements to be added// to get sfunction findS($s){ $l = 1; $r = 1 + (int)$s / 2; // Apply Binary search while ($l <= $r) { // Find mid $mid = (int)(($l + $r) / 2); // find sum of 1 to mid natural // numbers using formula $sum = (int)($mid * ($mid + 1) / 2); // If sum is equal to n // return mid if ($sum == $s) return $mid; // If greater than n // do r = mid-1 else if ($sum > $s) $r = $mid - 1; // else do l = mid + 1 else $l = $mid + 1; } // If not possible, // return -1 return -1;} // Drivers code$s = 15;$n = findS($s);if($n == -1 )echo \"-1\";elseecho $n; // This code is contributed by Sam007?>", "e": 34128, "s": 33244, "text": null }, { "code": "<script> // Javascript program for finding s such// that sum from 1 to s equals to n public // Function to find no. of elements // to be added to get s function findS(s) { var l = 1, r = parseInt((s / 2) + 1); // Apply Binary search while (l <= r) { // Find mid var mid = parseInt( (l + r) / 2); // find sum of 1 to mid natural // numbers using formula var sum = mid * parseInt((mid + 1) / 2); // If sum is equal to n // return mid if (sum == s) return mid; // If greater than n // do r = mid-1 else if (sum > s) r = mid - 1; // else do l = mid + 1 else l = mid + 1; } // If not possible, return -1 return -1; } // Drivers code var s = 15; var n = findS(s); if (n == -1) document.write(\"-1\"); else document.write(n); // This code contributed by Rajput-Ji </script>", "e": 35198, "s": 34128, "text": null }, { "code": null, "e": 35200, "s": 35198, "text": "5" }, { "code": null, "e": 35248, "s": 35200, "text": "Time Complexity: O(log n)Auxiliary Space: O(1) " }, { "code": null, "e": 35285, "s": 35248, "text": "Method 3: Using Mathematical formula" }, { "code": null, "e": 35413, "s": 35285, "text": "The idea is to use the formulae of the sum of first N natural numbers to compute the value of the N. Below is the illustration:" }, { "code": null, "e": 35506, "s": 35413, "text": "⇾ 1 + 2 + 3 + .... N = S⇾ (N * (N + 1)) / 2 = S⇾ N * (N + 1) = 2 * S⇾ N2 + N – 2 * S = 0" }, { "code": null, "e": 35692, "s": 35506, "text": "Therefore, Check if the solution of the quadratic equation is equal to integer or not. If Yes then the solution exists. Otherwise, the given number is not sum of first N natural number." }, { "code": null, "e": 35743, "s": 35692, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 35747, "s": 35743, "text": "C++" }, { "code": null, "e": 35752, "s": 35747, "text": "Java" }, { "code": null, "e": 35760, "s": 35752, "text": "Python3" }, { "code": null, "e": 35763, "s": 35760, "text": "C#" }, { "code": null, "e": 35774, "s": 35763, "text": "Javascript" }, { "code": "// C++ program of the above// approach #include <bits/stdc++.h> # define ll long long using namespace std; // Function to check if the// s is the sum of first N// natural numberll int isvalid(ll int s){ // Solution of Quadratic Equation float k=(-1+sqrt(1+8*s))/2; // Condition to check if the // solution is a integer if(ceil(k)==floor(k)) return k; else return -1;} // Driver Codeint main(){ int s = 15; // Function Call cout<< isvalid(s); return 0;}", "e": 36275, "s": 35774, "text": null }, { "code": "// Java program of the above// approachimport java.util.*; class GFG{ // Function to check if the// s is the sum of first N// natural numberpublic static int isvalid(int s){ // Solution of Quadratic Equation double k = (-1.0 + Math.sqrt(1 + 8 * s)) / 2; // Condition to check if the // solution is a integer if (Math.ceil(k) == Math.floor(k)) return (int)k; else return -1;} // Driver codepublic static void main(String[] args){ int s = 15; // Function call System.out.print(isvalid(s));}} // This code is contributed by divyeshrabadiya07", "e": 36871, "s": 36275, "text": null }, { "code": "# Python3 program of the above# approachimport math # Function to check if the# s is the sum of first N# natural numberdef isvalid(s): # Solution of Quadratic Equation k = (-1 + math.sqrt(1 + 8 * s)) / 2 # Condition to check if the # solution is a integer if (math.ceil(k) == math.floor(k)): return int(k) else: return -1 # Driver Codes = 15 # Function Callprint(isvalid(s)) # This code is contributed by vishu2908", "e": 37324, "s": 36871, "text": null }, { "code": "// C# program of the above// approachusing System;class GFG{ // Function to check if the// s is the sum of first N// natural numberpublic static int isvalid(int s){ // Solution of Quadratic Equation double k = (-1.0 + Math.Sqrt (1 + 8 * s)) / 2; // Condition to check if the // solution is a integer if (Math.Ceiling(k) == Math.Floor(k)) return (int)k; else return -1;} // Driver codepublic static void Main(string[] args){ int s = 15; // Function call Console.Write(isvalid(s));}} // This code is contributed by Chitranayal", "e": 37887, "s": 37324, "text": null }, { "code": "<script> // Javascript program of the above// approach // Function to check if the// s is the sum of first N// natural numberfunction isvalid(s){ // Solution of Quadratic Equation let k = (-1.0 + Math.sqrt(1 + 8 * s)) / 2; // Condition to check if the // solution is a integer if (Math.ceil(k) == Math.floor(k)) return k; else return -1;}// Driver code let s = 15; // Function call document.write(isvalid(s)); </script>", "e": 38374, "s": 37887, "text": null }, { "code": null, "e": 38376, "s": 38374, "text": "5" }, { "code": null, "e": 38419, "s": 38376, "text": "Time Complexity: O(1)Auxiliary Space: O(1)" }, { "code": null, "e": 38424, "s": 38419, "text": "vt_m" }, { "code": null, "e": 38431, "s": 38424, "text": "Sam007" }, { "code": null, "e": 38451, "s": 38431, "text": "Roshan Srivastava 1" }, { "code": null, "e": 38462, "s": 38451, "text": "ajaykr00kj" }, { "code": null, "e": 38480, "s": 38462, "text": "divyeshrabadiya07" }, { "code": null, "e": 38490, "s": 38480, "text": "vishu2908" }, { "code": null, "e": 38496, "s": 38490, "text": "ukasp" }, { "code": null, "e": 38506, "s": 38496, "text": "Rajput-Ji" }, { "code": null, "e": 38516, "s": 38506, "text": "sanjoy_62" }, { "code": null, "e": 38530, "s": 38516, "text": "Binary Search" }, { "code": null, "e": 38543, "s": 38530, "text": "Mathematical" }, { "code": null, "e": 38548, "s": 38543, "text": "Misc" }, { "code": null, "e": 38558, "s": 38548, "text": "Searching" }, { "code": null, "e": 38563, "s": 38558, "text": "Misc" }, { "code": null, "e": 38573, "s": 38563, "text": "Searching" }, { "code": null, "e": 38586, "s": 38573, "text": "Mathematical" }, { "code": null, "e": 38591, "s": 38586, "text": "Misc" }, { "code": null, "e": 38605, "s": 38591, "text": "Binary Search" }, { "code": null, "e": 38703, "s": 38605, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38735, "s": 38703, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 38779, "s": 38735, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 38804, "s": 38779, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 38837, "s": 38804, "text": "Program to multiply two matrices" }, { "code": null, "e": 38868, "s": 38837, "text": "Modular multiplicative inverse" }, { "code": null, "e": 38909, "s": 38868, "text": "Top 10 algorithms in Interview Questions" }, { "code": null, "e": 38963, "s": 38909, "text": "vector::push_back() and vector::pop_back() in C++ STL" }, { "code": null, "e": 39024, "s": 38963, "text": "Overview of Data Structures | Set 1 (Linear Data Structures)" }, { "code": null, "e": 39058, "s": 39024, "text": "How to write Regular Expressions?" } ]
Pascal - Functions
A subprogram is a program unit/module that performs a particular task. These subprograms are combined to form larger programs. This is basically called the 'Modular design.' A subprogram can be invoked by a subprogram/program, which is called the calling program. Pascal provides two kinds of subprograms − Functions − these subprograms return a single value. Functions − these subprograms return a single value. Procedures − these subprograms do not return a value directly. Procedures − these subprograms do not return a value directly. A function is a group of statements that together perform a task. Every Pascal program has at least one function, which is the program itself, and all the most trivial programs can define additional functions. A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function. Pascal standard library provides numerous built-in functions that your program can call. For example, function AppendStr() appends two strings, function New() dynamically allocates memory to variables and many more functions. In Pascal, a function is defined using the function keyword. The general form of a function definition is as follows − function name(argument(s): type1; argument(s): type2; ...): function_type; local declarations; begin ... < statements > ... name:= expression; end; A function definition in Pascal consists of a function header, local declarations and a function body. The function header consists of the keyword function and a name given to the function. Here are all the parts of a function − Arguments − The argument(s) establish the linkage between the calling program and the function identifiers and also called the formal parameters. A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of parameters of a function. Use of such formal parameters is optional. These parameters may have standard data type, user-defined data type or subrange data type. The formal parameters list appearing in the function statement could be simple or subscripted variables, arrays or structured variables, or subprograms. Arguments − The argument(s) establish the linkage between the calling program and the function identifiers and also called the formal parameters. A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of parameters of a function. Use of such formal parameters is optional. These parameters may have standard data type, user-defined data type or subrange data type. The formal parameters list appearing in the function statement could be simple or subscripted variables, arrays or structured variables, or subprograms. Return Type − All functions must return a value, so all functions must be assigned a type. The function-type is the data type of the value the function returns. It may be standard, user-defined scalar or subrange type but it cannot be structured type. Return Type − All functions must return a value, so all functions must be assigned a type. The function-type is the data type of the value the function returns. It may be standard, user-defined scalar or subrange type but it cannot be structured type. Local declarations − Local declarations refer to the declarations for labels, constants, variables, functions and procedures, which are application to the body of function only. Local declarations − Local declarations refer to the declarations for labels, constants, variables, functions and procedures, which are application to the body of function only. Function Body − The function body contains a collection of statements that define what the function does. It should always be enclosed between the reserved words begin and end. It is the part of a function where all computations are done. There must be an assignment statement of the type - name := expression; in the function body that assigns a value to the function name. This value is returned as and when the function is executed. The last statement in the body must be an end statement. Function Body − The function body contains a collection of statements that define what the function does. It should always be enclosed between the reserved words begin and end. It is the part of a function where all computations are done. There must be an assignment statement of the type - name := expression; in the function body that assigns a value to the function name. This value is returned as and when the function is executed. The last statement in the body must be an end statement. Following is an example showing how to define a function in pascal − (* function returning the max between two numbers *) function max(num1, num2: integer): integer; var (* local variable declaration *) result: integer; begin if (num1 > num2) then result := num1 else result := num2; max := result; end; A function declaration tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately. A function declaration has the following parts − function name(argument(s): type1; argument(s): type2; ...): function_type; For the above-defined function max(), following is the function declaration − function max(num1, num2: integer): integer; Function declaration is required when you define a function in one source file and you call that function in another file. In such case, you should declare the function at the top of the file calling the function. While creating a function, you give a definition of what the function has to do. To use a function, you will have to call that function to perform the defined task. When a program calls a function, program control is transferred to the called function. A called function performs defined task, and when its return statement is executed or when it last end statement is reached, it returns program control back to the main program. To call a function, you simply need to pass the required parameters along with function name, and if function returns a value, then you can store returned value. Following is a simple example to show the usage − program exFunction; var a, b, ret : integer; (*function definition *) function max(num1, num2: integer): integer; var (* local variable declaration *) result: integer; begin if (num1 > num2) then result := num1 else result := num2; max := result; end; begin a := 100; b := 200; (* calling a function to get max value *) ret := max(a, b); writeln( 'Max value is : ', ret ); end. When the above code is compiled and executed, it produces the following result − Max value is : 200 94 Lectures 8.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2347, "s": 2083, "text": "A subprogram is a program unit/module that performs a particular task. These subprograms are combined to form larger programs. This is basically called the 'Modular design.' A subprogram can be invoked by a subprogram/program, which is called the calling program." }, { "code": null, "e": 2390, "s": 2347, "text": "Pascal provides two kinds of subprograms −" }, { "code": null, "e": 2444, "s": 2390, "text": "Functions − these subprograms return a single value. " }, { "code": null, "e": 2498, "s": 2444, "text": "Functions − these subprograms return a single value. " }, { "code": null, "e": 2561, "s": 2498, "text": "Procedures − these subprograms do not return a value directly." }, { "code": null, "e": 2624, "s": 2561, "text": "Procedures − these subprograms do not return a value directly." }, { "code": null, "e": 2834, "s": 2624, "text": "A function is a group of statements that together perform a task. Every Pascal program has at least one function, which is the program itself, and all the most trivial programs can define additional functions." }, { "code": null, "e": 2994, "s": 2834, "text": "A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function." }, { "code": null, "e": 3220, "s": 2994, "text": "Pascal standard library provides numerous built-in functions that your program can call. For example, function AppendStr() appends two strings, function New() dynamically allocates memory to variables and many more functions." }, { "code": null, "e": 3339, "s": 3220, "text": "In Pascal, a function is defined using the function keyword. The general form of a function definition is as follows −" }, { "code": null, "e": 3500, "s": 3339, "text": "function name(argument(s): type1; argument(s): type2; ...): function_type;\nlocal declarations;\n\nbegin\n ...\n < statements >\n ...\n name:= expression;\nend;" }, { "code": null, "e": 3729, "s": 3500, "text": "A function definition in Pascal consists of a function header, local declarations and a function body. The function header consists of the keyword function and a name given to the function. Here are all the parts of a function −" }, { "code": null, "e": 4406, "s": 3729, "text": "Arguments − The argument(s) establish the linkage between the calling program and the function identifiers and also called the formal parameters. A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of parameters of a function. Use of such formal parameters is optional. These parameters may have standard data type, user-defined data type or subrange data type.\nThe formal parameters list appearing in the function statement could be simple or subscripted variables, arrays or structured variables, or subprograms." }, { "code": null, "e": 4930, "s": 4406, "text": "Arguments − The argument(s) establish the linkage between the calling program and the function identifiers and also called the formal parameters. A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of parameters of a function. Use of such formal parameters is optional. These parameters may have standard data type, user-defined data type or subrange data type." }, { "code": null, "e": 5083, "s": 4930, "text": "The formal parameters list appearing in the function statement could be simple or subscripted variables, arrays or structured variables, or subprograms." }, { "code": null, "e": 5335, "s": 5083, "text": "Return Type − All functions must return a value, so all functions must be assigned a type. The function-type is the data type of the value the function returns. It may be standard, user-defined scalar or subrange type but it cannot be structured type." }, { "code": null, "e": 5587, "s": 5335, "text": "Return Type − All functions must return a value, so all functions must be assigned a type. The function-type is the data type of the value the function returns. It may be standard, user-defined scalar or subrange type but it cannot be structured type." }, { "code": null, "e": 5765, "s": 5587, "text": "Local declarations − Local declarations refer to the declarations for labels, constants, variables, functions and procedures, which are application to the body of function only." }, { "code": null, "e": 5943, "s": 5765, "text": "Local declarations − Local declarations refer to the declarations for labels, constants, variables, functions and procedures, which are application to the body of function only." }, { "code": null, "e": 6437, "s": 5943, "text": "Function Body − The function body contains a collection of statements that define what the function does. It should always be enclosed between the reserved words begin and end. It is the part of a function where all computations are done. There must be an assignment statement of the type - name := expression; in the function body that assigns a value to the function name. This value is returned as and when the function is executed. The last statement in the body must be an end statement." }, { "code": null, "e": 6931, "s": 6437, "text": "Function Body − The function body contains a collection of statements that define what the function does. It should always be enclosed between the reserved words begin and end. It is the part of a function where all computations are done. There must be an assignment statement of the type - name := expression; in the function body that assigns a value to the function name. This value is returned as and when the function is executed. The last statement in the body must be an end statement." }, { "code": null, "e": 7000, "s": 6931, "text": "Following is an example showing how to define a function in pascal −" }, { "code": null, "e": 7268, "s": 7000, "text": "(* function returning the max between two numbers *)\nfunction max(num1, num2: integer): integer;\n\nvar\n (* local variable declaration *)\n result: integer;\n\nbegin\n if (num1 > num2) then\n result := num1\n \n else\n result := num2;\n max := result;\nend;" }, { "code": null, "e": 7421, "s": 7268, "text": "A function declaration tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately." }, { "code": null, "e": 7470, "s": 7421, "text": "A function declaration has the following parts −" }, { "code": null, "e": 7545, "s": 7470, "text": "function name(argument(s): type1; argument(s): type2; ...): function_type;" }, { "code": null, "e": 7623, "s": 7545, "text": "For the above-defined function max(), following is the function declaration −" }, { "code": null, "e": 7667, "s": 7623, "text": "function max(num1, num2: integer): integer;" }, { "code": null, "e": 7881, "s": 7667, "text": "Function declaration is required when you define a function in one source file and you call that function in another file. In such case, you should declare the function at the top of the file calling the function." }, { "code": null, "e": 8312, "s": 7881, "text": "While creating a function, you give a definition of what the function has to do. To use a function, you will have to call that function to perform the defined task. When a program calls a function, program control is transferred to the called function. A called function performs defined task, and when its return statement is executed or when it last end statement is reached, it returns program control back to the main program." }, { "code": null, "e": 8524, "s": 8312, "text": "To call a function, you simply need to pass the required parameters along with function name, and if function returns a value, then you can store returned value. Following is a simple example to show the usage −" }, { "code": null, "e": 8958, "s": 8524, "text": "program exFunction;\nvar\n a, b, ret : integer;\n\n(*function definition *)\nfunction max(num1, num2: integer): integer;\nvar\n (* local variable declaration *)\n result: integer;\n\nbegin\n if (num1 > num2) then\n result := num1\n \n else\n result := num2;\n max := result;\nend;\n\nbegin\n a := 100;\n b := 200;\n (* calling a function to get max value *)\n ret := max(a, b);\n \n writeln( 'Max value is : ', ret );\nend." }, { "code": null, "e": 9039, "s": 8958, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 9060, "s": 9039, "text": "Max value is : 200 \n" }, { "code": null, "e": 9095, "s": 9060, "text": "\n 94 Lectures \n 8.5 hours \n" }, { "code": null, "e": 9118, "s": 9095, "text": " Stone River ELearning" }, { "code": null, "e": 9125, "s": 9118, "text": " Print" }, { "code": null, "e": 9136, "s": 9125, "text": " Add Notes" } ]
Apex - nested if statement
We can also have the nested if-else statement for complex condition as given below − if boolean_expression_1 { /* Executes when the boolean expression 1 is true */ if boolean_expression_2 { /* Executes when the boolean expression 2 is true */ } } String pinCode = '12345'; String customerType = 'Premium'; if (pinCode == '12345') { System.debug('Condition met and Pin Code is'+pinCode); if(customerType = 'Premium') { System.debug('This is a Premium customer living in pinCode 12345'); }else if(customerType = 'Normal') { System.debug('This is a Normal customer living in pinCode 12345'); } }else { //this can go on as per the requirement System.debug('Pincode not found'); } 14 Lectures 2 hours Vijay Thapa 7 Lectures 2 hours Uplatz 29 Lectures 6 hours Ramnarayan Ramakrishnan 49 Lectures 3 hours Ali Saleh Ali 10 Lectures 4 hours Soham Ghosh 48 Lectures 4.5 hours GUHARAJANM Print Add Notes Bookmark this page
[ { "code": null, "e": 2137, "s": 2052, "text": "We can also have the nested if-else statement for complex condition as given below −" }, { "code": null, "e": 2315, "s": 2137, "text": "if boolean_expression_1 {\n /* Executes when the boolean expression 1 is true */\n if boolean_expression_2 {\n /* Executes when the boolean expression 2 is true */\n }\n}\n" }, { "code": null, "e": 2774, "s": 2315, "text": "String pinCode = '12345';\nString customerType = 'Premium';\nif (pinCode == '12345') {\n System.debug('Condition met and Pin Code is'+pinCode);\n if(customerType = 'Premium') {\n System.debug('This is a Premium customer living in pinCode 12345');\n }else if(customerType = 'Normal') {\n System.debug('This is a Normal customer living in pinCode 12345');\n }\n}else {\n //this can go on as per the requirement\n System.debug('Pincode not found');\n}" }, { "code": null, "e": 2807, "s": 2774, "text": "\n 14 Lectures \n 2 hours \n" }, { "code": null, "e": 2820, "s": 2807, "text": " Vijay Thapa" }, { "code": null, "e": 2852, "s": 2820, "text": "\n 7 Lectures \n 2 hours \n" }, { "code": null, "e": 2860, "s": 2852, "text": " Uplatz" }, { "code": null, "e": 2893, "s": 2860, "text": "\n 29 Lectures \n 6 hours \n" }, { "code": null, "e": 2918, "s": 2893, "text": " Ramnarayan Ramakrishnan" }, { "code": null, "e": 2951, "s": 2918, "text": "\n 49 Lectures \n 3 hours \n" }, { "code": null, "e": 2966, "s": 2951, "text": " Ali Saleh Ali" }, { "code": null, "e": 2999, "s": 2966, "text": "\n 10 Lectures \n 4 hours \n" }, { "code": null, "e": 3012, "s": 2999, "text": " Soham Ghosh" }, { "code": null, "e": 3047, "s": 3012, "text": "\n 48 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3059, "s": 3047, "text": " GUHARAJANM" }, { "code": null, "e": 3066, "s": 3059, "text": " Print" }, { "code": null, "e": 3077, "s": 3066, "text": " Add Notes" } ]
Check if a Rook can reach the given destination in a single move - GeeksforGeeks
03 May, 2021 Given integers current_row and current_col, representing the current position of a Rook on an 8 × 8 chessboard and two more integers destination_row and destination_col which represents the position to be reached by a Rook. The task is to check if it is possible or not for a Rook to reach the given destination in a single move from its current position. If found to be true, print “POSSIBLE”. Otherwise, print “NOT POSSIBLE”. Examples: Input: current_row=8, current_col=8, destination_row=8, destination_col=4 Output: POSSIBLEExplanation: Possible Input: current_row=3, current_col=2, destination_row=2, destination_col=4 Output: NOT POSSIBLE Explanation: Not Possible Approach: The given problem can be solved using the following observation: On a chessboard, a rook can move as many squares as possible, horizontally as well as vertically, in a single move. Therefore, it can move to any position present in the same row or the column as in its initial position. Therefore, the problem reduces to simply checking for the following two conditions: If destination_row and current_row are equal or not. Otherwise, check if destination_col is equal to current_col or not. If any of the above two conditions are satisfied, print “POSSIBLE“. Otherwise, print “NOT POSSIBLE”. Below is the implementation of the above approach: C++14 Java Python3 C# Javascript // C++ program to implement// for the above approach#include <bits/stdc++.h>using namespace std; // Function to check if it is// possible to reach destination// in a single move by a rookstring check(int current_row, int current_col, int destination_row, int destination_col){ if(current_row == destination_row) return "POSSIBLE"; else if(current_col == destination_col) return "POSSIBLE"; else return "NOT POSSIBLE";} // Driver Codeint main(){ // Given arrays int current_row = 8; int current_col = 8; int destination_row = 8; int destination_col = 4; string output = check(current_row, current_col, destination_row, destination_col); cout << output; return 0;} // This code is contributed by mohit kumar 29. // Java program for the above approachimport java.util.*;import java.lang.*; class GFG{ // Function to check if it is// possible to reach destination// in a single move by a rookstatic String check(int current_row, int current_col, int destination_row, int destination_col){ if(current_row == destination_row) return "POSSIBLE"; else if(current_col == destination_col) return "POSSIBLE"; else return "NOT POSSIBLE";} // Driver codepublic static void main(String[] args){ // Given arrays int current_row = 8; int current_col = 8; int destination_row = 8; int destination_col = 4; String output = check(current_row, current_col, destination_row, destination_col); System.out.println(output);}} // This code is contributed by code_hunt. # Python program to implement# for the above approach # Function to check if it is# possible to reach destination# in a single move by a rookdef check(current_row, current_col, destination_row, destination_col): if(current_row == destination_row): return("POSSIBLE") elif(current_col == destination_col): return("POSSIBLE") else: return("NOT POSSIBLE") # Driver Codecurrent_row = 8current_col = 8destination_row = 8destination_col = 4 output = check(current_row, current_col, destination_row, destination_col)print(output) // C# program to implement// the above approachusing System; class GFG{ // Function to check if it is // possible to reach destination // in a single move by a rook static string check(int current_row, int current_col, int destination_row, int destination_col) { if(current_row == destination_row) return "POSSIBLE"; else if(current_col == destination_col) return "POSSIBLE"; else return "NOT POSSIBLE"; } // Driver Code public static void Main() { // Given arrays int current_row = 8; int current_col = 8; int destination_row = 8; int destination_col = 4; string output = check(current_row, current_col, destination_row, destination_col); Console.WriteLine(output); }} // This code is contributed by susmitakundugoaldanga. <script>// javascript program of the above approach // Function to check if it is// possible to reach destination// in a single move by a rookfunction check(current_row, current_col, destination_row, destination_col){ if(current_row == destination_row) return "POSSIBLE"; else if(current_col == destination_col) return "POSSIBLE"; else return "NOT POSSIBLE";} // Driver Code // Given arrays let current_row = 8; let current_col = 8; let destination_row = 8; let destination_col = 4; let output = check(current_row, current_col, destination_row, destination_col); document.write(output); </script> POSSIBLE Time complexity: O(1) Space complexity: O(1) mohit kumar 29 code_hunt susmitakundugoaldanga avijitmondal1998 chessboard-problems Greedy Pattern Searching Greedy Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive) Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8 Program for Least Recently Used (LRU) Page Replacement algorithm Difference between Prim's and Kruskal's algorithm for MST Split the given array into K sub-arrays such that maximum sum of all sub arrays is minimum KMP Algorithm for Pattern Searching Rabin-Karp Algorithm for Pattern Searching Check if a string is substring of another Naive algorithm for Pattern Searching Boyer Moore Algorithm for Pattern Searching
[ { "code": null, "e": 25217, "s": 25189, "text": "\n03 May, 2021" }, { "code": null, "e": 25645, "s": 25217, "text": "Given integers current_row and current_col, representing the current position of a Rook on an 8 × 8 chessboard and two more integers destination_row and destination_col which represents the position to be reached by a Rook. The task is to check if it is possible or not for a Rook to reach the given destination in a single move from its current position. If found to be true, print “POSSIBLE”. Otherwise, print “NOT POSSIBLE”." }, { "code": null, "e": 25655, "s": 25645, "text": "Examples:" }, { "code": null, "e": 25760, "s": 25655, "text": "Input: current_row=8, current_col=8, destination_row=8, destination_col=4 Output: POSSIBLEExplanation: " }, { "code": null, "e": 25769, "s": 25760, "text": "Possible" }, { "code": null, "e": 25879, "s": 25769, "text": "Input: current_row=3, current_col=2, destination_row=2, destination_col=4 Output: NOT POSSIBLE Explanation: " }, { "code": null, "e": 25892, "s": 25879, "text": "Not Possible" }, { "code": null, "e": 25971, "s": 25896, "text": "Approach: The given problem can be solved using the following observation:" }, { "code": null, "e": 26192, "s": 25971, "text": "On a chessboard, a rook can move as many squares as possible, horizontally as well as vertically, in a single move. Therefore, it can move to any position present in the same row or the column as in its initial position." }, { "code": null, "e": 26278, "s": 26192, "text": "Therefore, the problem reduces to simply checking for the following two conditions: " }, { "code": null, "e": 26331, "s": 26278, "text": "If destination_row and current_row are equal or not." }, { "code": null, "e": 26399, "s": 26331, "text": "Otherwise, check if destination_col is equal to current_col or not." }, { "code": null, "e": 26500, "s": 26399, "text": "If any of the above two conditions are satisfied, print “POSSIBLE“. Otherwise, print “NOT POSSIBLE”." }, { "code": null, "e": 26551, "s": 26500, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26557, "s": 26551, "text": "C++14" }, { "code": null, "e": 26562, "s": 26557, "text": "Java" }, { "code": null, "e": 26570, "s": 26562, "text": "Python3" }, { "code": null, "e": 26573, "s": 26570, "text": "C#" }, { "code": null, "e": 26584, "s": 26573, "text": "Javascript" }, { "code": "// C++ program to implement// for the above approach#include <bits/stdc++.h>using namespace std; // Function to check if it is// possible to reach destination// in a single move by a rookstring check(int current_row, int current_col, int destination_row, int destination_col){ if(current_row == destination_row) return \"POSSIBLE\"; else if(current_col == destination_col) return \"POSSIBLE\"; else return \"NOT POSSIBLE\";} // Driver Codeint main(){ // Given arrays int current_row = 8; int current_col = 8; int destination_row = 8; int destination_col = 4; string output = check(current_row, current_col, destination_row, destination_col); cout << output; return 0;} // This code is contributed by mohit kumar 29.", "e": 27371, "s": 26584, "text": null }, { "code": "// Java program for the above approachimport java.util.*;import java.lang.*; class GFG{ // Function to check if it is// possible to reach destination// in a single move by a rookstatic String check(int current_row, int current_col, int destination_row, int destination_col){ if(current_row == destination_row) return \"POSSIBLE\"; else if(current_col == destination_col) return \"POSSIBLE\"; else return \"NOT POSSIBLE\";} // Driver codepublic static void main(String[] args){ // Given arrays int current_row = 8; int current_col = 8; int destination_row = 8; int destination_col = 4; String output = check(current_row, current_col, destination_row, destination_col); System.out.println(output);}} // This code is contributed by code_hunt.", "e": 28184, "s": 27371, "text": null }, { "code": "# Python program to implement# for the above approach # Function to check if it is# possible to reach destination# in a single move by a rookdef check(current_row, current_col, destination_row, destination_col): if(current_row == destination_row): return(\"POSSIBLE\") elif(current_col == destination_col): return(\"POSSIBLE\") else: return(\"NOT POSSIBLE\") # Driver Codecurrent_row = 8current_col = 8destination_row = 8destination_col = 4 output = check(current_row, current_col, destination_row, destination_col)print(output)", "e": 28768, "s": 28184, "text": null }, { "code": "// C# program to implement// the above approachusing System; class GFG{ // Function to check if it is // possible to reach destination // in a single move by a rook static string check(int current_row, int current_col, int destination_row, int destination_col) { if(current_row == destination_row) return \"POSSIBLE\"; else if(current_col == destination_col) return \"POSSIBLE\"; else return \"NOT POSSIBLE\"; } // Driver Code public static void Main() { // Given arrays int current_row = 8; int current_col = 8; int destination_row = 8; int destination_col = 4; string output = check(current_row, current_col, destination_row, destination_col); Console.WriteLine(output); }} // This code is contributed by susmitakundugoaldanga.", "e": 29597, "s": 28768, "text": null }, { "code": "<script>// javascript program of the above approach // Function to check if it is// possible to reach destination// in a single move by a rookfunction check(current_row, current_col, destination_row, destination_col){ if(current_row == destination_row) return \"POSSIBLE\"; else if(current_col == destination_col) return \"POSSIBLE\"; else return \"NOT POSSIBLE\";} // Driver Code // Given arrays let current_row = 8; let current_col = 8; let destination_row = 8; let destination_col = 4; let output = check(current_row, current_col, destination_row, destination_col); document.write(output); </script>", "e": 30277, "s": 29597, "text": null }, { "code": null, "e": 30286, "s": 30277, "text": "POSSIBLE" }, { "code": null, "e": 30333, "s": 30288, "text": "Time complexity: O(1) Space complexity: O(1)" }, { "code": null, "e": 30348, "s": 30333, "text": "mohit kumar 29" }, { "code": null, "e": 30358, "s": 30348, "text": "code_hunt" }, { "code": null, "e": 30380, "s": 30358, "text": "susmitakundugoaldanga" }, { "code": null, "e": 30397, "s": 30380, "text": "avijitmondal1998" }, { "code": null, "e": 30417, "s": 30397, "text": "chessboard-problems" }, { "code": null, "e": 30424, "s": 30417, "text": "Greedy" }, { "code": null, "e": 30442, "s": 30424, "text": "Pattern Searching" }, { "code": null, "e": 30449, "s": 30442, "text": "Greedy" }, { "code": null, "e": 30467, "s": 30449, "text": "Pattern Searching" }, { "code": null, "e": 30565, "s": 30467, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30574, "s": 30565, "text": "Comments" }, { "code": null, "e": 30587, "s": 30574, "text": "Old Comments" }, { "code": null, "e": 30668, "s": 30587, "text": "Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)" }, { "code": null, "e": 30739, "s": 30668, "text": "Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8" }, { "code": null, "e": 30804, "s": 30739, "text": "Program for Least Recently Used (LRU) Page Replacement algorithm" }, { "code": null, "e": 30862, "s": 30804, "text": "Difference between Prim's and Kruskal's algorithm for MST" }, { "code": null, "e": 30953, "s": 30862, "text": "Split the given array into K sub-arrays such that maximum sum of all sub arrays is minimum" }, { "code": null, "e": 30989, "s": 30953, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 31032, "s": 30989, "text": "Rabin-Karp Algorithm for Pattern Searching" }, { "code": null, "e": 31074, "s": 31032, "text": "Check if a string is substring of another" }, { "code": null, "e": 31112, "s": 31074, "text": "Naive algorithm for Pattern Searching" } ]
How to remove a specific element from array in MongoDB?
To remove a specific element, use $pull. Let us create a collection with documents − > db.demo125.insertOne({"ListOfNames":["John","Chris","Bob","David","Carol"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e2f304068e7f832db1a7f55") } Display all documents from a collection with the help of find() method − > db.demo125.find().pretty(); This will produce the following output − { "_id" : ObjectId("5e2f304068e7f832db1a7f55"), "ListOfNames" : [ "John", "Chris", "Bob", "David", "Carol" ] } Following is the query to remove a specific element from array in MongoDB − > db.demo125.update( ... { }, ... { $pull: { ListOfNames: { $in: [ "David"] }} }, ... { multi: true } ... ) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) Display all documents from a collection with the help of find() method − > db.demo125.find().pretty(); This will produce the following output − { "_id" : ObjectId("5e2f304068e7f832db1a7f55"), "ListOfNames" : [ "John", "Chris", "Bob", "Carol" ] }
[ { "code": null, "e": 1147, "s": 1062, "text": "To remove a specific element, use $pull. Let us create a collection with documents −" }, { "code": null, "e": 1312, "s": 1147, "text": "> db.demo125.insertOne({\"ListOfNames\":[\"John\",\"Chris\",\"Bob\",\"David\",\"Carol\"]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e2f304068e7f832db1a7f55\")\n}" }, { "code": null, "e": 1385, "s": 1312, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1415, "s": 1385, "text": "> db.demo125.find().pretty();" }, { "code": null, "e": 1456, "s": 1415, "text": "This will produce the following output −" }, { "code": null, "e": 1606, "s": 1456, "text": "{\n \"_id\" : ObjectId(\"5e2f304068e7f832db1a7f55\"),\n \"ListOfNames\" : [\n \"John\",\n \"Chris\",\n \"Bob\",\n \"David\",\n \"Carol\"\n ]\n}" }, { "code": null, "e": 1682, "s": 1606, "text": "Following is the query to remove a specific element from array in MongoDB −" }, { "code": null, "e": 1856, "s": 1682, "text": "> db.demo125.update(\n... { },\n... { $pull: { ListOfNames: { $in: [ \"David\"] }} },\n... { multi: true }\n... )\nWriteResult({ \"nMatched\" : 1, \"nUpserted\" : 0, \"nModified\" : 1 })" }, { "code": null, "e": 1929, "s": 1856, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1959, "s": 1929, "text": "> db.demo125.find().pretty();" }, { "code": null, "e": 2000, "s": 1959, "text": "This will produce the following output −" }, { "code": null, "e": 2135, "s": 2000, "text": "{\n \"_id\" : ObjectId(\"5e2f304068e7f832db1a7f55\"),\n \"ListOfNames\" : [\n \"John\",\n \"Chris\",\n \"Bob\",\n \"Carol\"\n ]\n}" } ]
Tryit Editor v3.7
Tryit: Some HEX color values
[]
Find K missing numbers from given Array in range [1, M] such that total average is X - GeeksforGeeks
15 Dec, 2021 Given an array arr[] of integers of size N where each element can be in the range [1, M], and two integers X and K. The task is to find K possible numbers in range [1, M] such that the average of all the (N + K) numbers is equal to X. If there are multiple valid answers, any one is acceptable. Examples: Input: arr[] = {3, 2, 4, 3}, M = 6, K = 2, X = 4Output: 6 6Explanation: The mean of all elements is (3 + 2 + 4 + 3 + 6 + 6) / 6 = 4. Input: arr[] = {1}, M = 8, K = 1, X = 4Output: 7Explanation: The mean of all elements is (1 + 7) / 2 = 4. Input: arr[] = {1, 2, 3, 4}, M = 6, K = 4, X = 6Output: []Explanation: It is impossible for the mean to be 6 no matter what the 4 missing elements are. Approach: The approach is based on the following mathematical observation. If the total expected sum after adding M elements is such that the sum of the M elements added needs to be less than M or greater than K*M then no solution is possible. Otherwise, there is always a possible solution. Find the sum of missing elements(Y), that is = X*(K + N) – sum(arr).If this is less than K or greater than K*M then the array cannot be created. So return an empty array.Otherwise, try to equally divide the value Y in K elements, i.e assign all the K elements with value Y/K.if still some value remains to be assigned then after assigning every element equally, the value left will be = (Y%K). So add 1 to (Y%K) elements of the new array. Find the sum of missing elements(Y), that is = X*(K + N) – sum(arr). If this is less than K or greater than K*M then the array cannot be created. So return an empty array. Otherwise, try to equally divide the value Y in K elements, i.e assign all the K elements with value Y/K. if still some value remains to be assigned then after assigning every element equally, the value left will be = (Y%K). So add 1 to (Y%K) elements of the new array. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ code to implement above approach#include <bits/stdc++.h>using namespace std; // Function to get the missing elementsvector<int> missing(vector<int>& arr, int M, int X, int K){ int N = arr.size(), sum = accumulate(arr.begin(), arr.end(), 0), newsum = 0; newsum = X * (K + N) - sum; // If this newsum is less than M // or greater than K*M then // no array can be created. if (newsum < K || newsum > K * M) return {}; int mod = newsum % K; vector<int> ans(K, newsum / K); for (int i = 0; i < mod; i++) ans[i] += 1; return ans;} // Driver codeint main(){ vector<int> arr{ 3, 2, 4, 3 }; int X = 4; int K = 2; int M = 6; // Vector to store resultant list vector<int> ans = missing(arr, M, X, K); for (auto i : ans) cout << i << " "; return 0;} // Java code to implement above approachimport java.util.*;class GFG{ // Function to get the missing elementsstatic int []missing(int []arr, int M, int X, int K){ int N = arr.length, sum = accumulate(arr,0,N), newsum = 0; newsum = X * (K + N) - sum; // If this newsum is less than M // or greater than K*M then // no array can be created. if (newsum < K || newsum > K * M) return new int[]{}; int mod = newsum % K; int []ans = new int[K]; Arrays.fill(ans, newsum / K); for (int i = 0; i < mod; i++) ans[i] += 1; return ans;}static int accumulate(int[] arr, int start, int end){ int sum=0; for(int i= 0; i < arr.length; i++) sum+=arr[i]; return sum;} // Driver codepublic static void main(String[] args){ int[]arr = { 3, 2, 4, 3 }; int X = 4; int K = 2; int M = 6; // Vector to store resultant list int []ans = missing(arr, M, X, K); for (int i : ans) System.out.print(i+ " ");}} // This code is contributed by shikhasingrajput # Python code for the above approach # Function to get the missing elementsdef missing(arr, M, X, K): N = len(arr) sum = 0 for i in range(len(arr)): sum += arr[i] newsum = 0 newsum = X * (K + N) - sum # If this newsum is less than M # or greater than K*M then # no array can be created. if (newsum < K or newsum > K * M): return [] mod = newsum % K ans = [newsum // K] * K for i in range(mod): ans[i] += 1 return ans # Driver codearr = [3, 2, 4, 3]X = 4K = 2M = 6 # Vector to store resultant listans = missing(arr, M, X, K) for i in ans: print(i, end=" ") # This code is contributed by gfgking // C# code to implement above approachusing System; class GFG { // Function to get the missing elements static int[] missing(int[] arr, int M, int X, int K) { int N = arr.Length, sum = accumulate(arr, 0, N), newsum = 0; newsum = X * (K + N) - sum; // If this newsum is less than M // or greater than K*M then // no array can be created. if (newsum < K || newsum > K * M) return new int[] {}; int mod = newsum % K; int[] ans = new int[K]; Array.Fill(ans, newsum / K); for (int i = 0; i < mod; i++) ans[i] += 1; return ans; } static int accumulate(int[] arr, int start, int end) { int sum = 0; for (int i = 0; i < arr.Length; i++) sum += arr[i]; return sum; } // Driver code public static void Main(string[] args) { int[] arr = { 3, 2, 4, 3 }; int X = 4; int K = 2; int M = 6; // Vector to store resultant list int[] ans = missing(arr, M, X, K); foreach(int i in ans) Console.Write(i + " "); }} // This code is contributed by ukasp. <script> // JavaScript code for the above approach // Function to get the missing elements function missing(arr, M, X, K) { let N = arr.length; let sum = 0; for (let i = 0; i < arr.length; i++) { sum += arr[i]; } newsum = 0; newsum = X * (K + N) - sum; // If this newsum is less than M // or greater than K*M then // no array can be created. if (newsum < K || newsum > K * M) return []; let mod = newsum % K; let ans = new Array(K).fill(Math.floor(newsum / K)) for (let i = 0; i < mod; i++) ans[i] += 1; return ans; } // Driver code let arr = [3, 2, 4, 3]; let X = 4; let K = 2; let M = 6; // Vector to store resultant list let ans = missing(arr, M, X, K); for (let i of ans) document.write(i + " "); // This code is contributed by Potta Lokesh </script> 6 6 Time Complexity: O(N)Auxiliary Space: O(1) When space of the resultant list is not considered lokeshpotta20 shikhasingrajput ukasp gfgking maths-mean Arrays Mathematical Pattern Searching Arrays Mathematical Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stack Data Structure (Introduction and Program) Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Introduction to Arrays Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 25458, "s": 25430, "text": "\n15 Dec, 2021" }, { "code": null, "e": 25753, "s": 25458, "text": "Given an array arr[] of integers of size N where each element can be in the range [1, M], and two integers X and K. The task is to find K possible numbers in range [1, M] such that the average of all the (N + K) numbers is equal to X. If there are multiple valid answers, any one is acceptable." }, { "code": null, "e": 25763, "s": 25753, "text": "Examples:" }, { "code": null, "e": 25896, "s": 25763, "text": "Input: arr[] = {3, 2, 4, 3}, M = 6, K = 2, X = 4Output: 6 6Explanation: The mean of all elements is (3 + 2 + 4 + 3 + 6 + 6) / 6 = 4." }, { "code": null, "e": 26002, "s": 25896, "text": "Input: arr[] = {1}, M = 8, K = 1, X = 4Output: 7Explanation: The mean of all elements is (1 + 7) / 2 = 4." }, { "code": null, "e": 26154, "s": 26002, "text": "Input: arr[] = {1, 2, 3, 4}, M = 6, K = 4, X = 6Output: []Explanation: It is impossible for the mean to be 6 no matter what the 4 missing elements are." }, { "code": null, "e": 26446, "s": 26154, "text": "Approach: The approach is based on the following mathematical observation. If the total expected sum after adding M elements is such that the sum of the M elements added needs to be less than M or greater than K*M then no solution is possible. Otherwise, there is always a possible solution." }, { "code": null, "e": 26885, "s": 26446, "text": "Find the sum of missing elements(Y), that is = X*(K + N) – sum(arr).If this is less than K or greater than K*M then the array cannot be created. So return an empty array.Otherwise, try to equally divide the value Y in K elements, i.e assign all the K elements with value Y/K.if still some value remains to be assigned then after assigning every element equally, the value left will be = (Y%K). So add 1 to (Y%K) elements of the new array." }, { "code": null, "e": 26954, "s": 26885, "text": "Find the sum of missing elements(Y), that is = X*(K + N) – sum(arr)." }, { "code": null, "e": 27057, "s": 26954, "text": "If this is less than K or greater than K*M then the array cannot be created. So return an empty array." }, { "code": null, "e": 27163, "s": 27057, "text": "Otherwise, try to equally divide the value Y in K elements, i.e assign all the K elements with value Y/K." }, { "code": null, "e": 27327, "s": 27163, "text": "if still some value remains to be assigned then after assigning every element equally, the value left will be = (Y%K). So add 1 to (Y%K) elements of the new array." }, { "code": null, "e": 27378, "s": 27327, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27382, "s": 27378, "text": "C++" }, { "code": null, "e": 27387, "s": 27382, "text": "Java" }, { "code": null, "e": 27395, "s": 27387, "text": "Python3" }, { "code": null, "e": 27398, "s": 27395, "text": "C#" }, { "code": null, "e": 27409, "s": 27398, "text": "Javascript" }, { "code": "// C++ code to implement above approach#include <bits/stdc++.h>using namespace std; // Function to get the missing elementsvector<int> missing(vector<int>& arr, int M, int X, int K){ int N = arr.size(), sum = accumulate(arr.begin(), arr.end(), 0), newsum = 0; newsum = X * (K + N) - sum; // If this newsum is less than M // or greater than K*M then // no array can be created. if (newsum < K || newsum > K * M) return {}; int mod = newsum % K; vector<int> ans(K, newsum / K); for (int i = 0; i < mod; i++) ans[i] += 1; return ans;} // Driver codeint main(){ vector<int> arr{ 3, 2, 4, 3 }; int X = 4; int K = 2; int M = 6; // Vector to store resultant list vector<int> ans = missing(arr, M, X, K); for (auto i : ans) cout << i << \" \"; return 0;}", "e": 28289, "s": 27409, "text": null }, { "code": "// Java code to implement above approachimport java.util.*;class GFG{ // Function to get the missing elementsstatic int []missing(int []arr, int M, int X, int K){ int N = arr.length, sum = accumulate(arr,0,N), newsum = 0; newsum = X * (K + N) - sum; // If this newsum is less than M // or greater than K*M then // no array can be created. if (newsum < K || newsum > K * M) return new int[]{}; int mod = newsum % K; int []ans = new int[K]; Arrays.fill(ans, newsum / K); for (int i = 0; i < mod; i++) ans[i] += 1; return ans;}static int accumulate(int[] arr, int start, int end){ int sum=0; for(int i= 0; i < arr.length; i++) sum+=arr[i]; return sum;} // Driver codepublic static void main(String[] args){ int[]arr = { 3, 2, 4, 3 }; int X = 4; int K = 2; int M = 6; // Vector to store resultant list int []ans = missing(arr, M, X, K); for (int i : ans) System.out.print(i+ \" \");}} // This code is contributed by shikhasingrajput", "e": 29349, "s": 28289, "text": null }, { "code": "# Python code for the above approach # Function to get the missing elementsdef missing(arr, M, X, K): N = len(arr) sum = 0 for i in range(len(arr)): sum += arr[i] newsum = 0 newsum = X * (K + N) - sum # If this newsum is less than M # or greater than K*M then # no array can be created. if (newsum < K or newsum > K * M): return [] mod = newsum % K ans = [newsum // K] * K for i in range(mod): ans[i] += 1 return ans # Driver codearr = [3, 2, 4, 3]X = 4K = 2M = 6 # Vector to store resultant listans = missing(arr, M, X, K) for i in ans: print(i, end=\" \") # This code is contributed by gfgking", "e": 30009, "s": 29349, "text": null }, { "code": "// C# code to implement above approachusing System; class GFG { // Function to get the missing elements static int[] missing(int[] arr, int M, int X, int K) { int N = arr.Length, sum = accumulate(arr, 0, N), newsum = 0; newsum = X * (K + N) - sum; // If this newsum is less than M // or greater than K*M then // no array can be created. if (newsum < K || newsum > K * M) return new int[] {}; int mod = newsum % K; int[] ans = new int[K]; Array.Fill(ans, newsum / K); for (int i = 0; i < mod; i++) ans[i] += 1; return ans; } static int accumulate(int[] arr, int start, int end) { int sum = 0; for (int i = 0; i < arr.Length; i++) sum += arr[i]; return sum; } // Driver code public static void Main(string[] args) { int[] arr = { 3, 2, 4, 3 }; int X = 4; int K = 2; int M = 6; // Vector to store resultant list int[] ans = missing(arr, M, X, K); foreach(int i in ans) Console.Write(i + \" \"); }} // This code is contributed by ukasp.", "e": 31170, "s": 30009, "text": null }, { "code": " <script> // JavaScript code for the above approach // Function to get the missing elements function missing(arr, M, X, K) { let N = arr.length; let sum = 0; for (let i = 0; i < arr.length; i++) { sum += arr[i]; } newsum = 0; newsum = X * (K + N) - sum; // If this newsum is less than M // or greater than K*M then // no array can be created. if (newsum < K || newsum > K * M) return []; let mod = newsum % K; let ans = new Array(K).fill(Math.floor(newsum / K)) for (let i = 0; i < mod; i++) ans[i] += 1; return ans; } // Driver code let arr = [3, 2, 4, 3]; let X = 4; let K = 2; let M = 6; // Vector to store resultant list let ans = missing(arr, M, X, K); for (let i of ans) document.write(i + \" \"); // This code is contributed by Potta Lokesh </script>", "e": 32189, "s": 31170, "text": null }, { "code": null, "e": 32197, "s": 32192, "text": "6 6 " }, { "code": null, "e": 32293, "s": 32199, "text": "Time Complexity: O(N)Auxiliary Space: O(1) When space of the resultant list is not considered" }, { "code": null, "e": 32309, "s": 32295, "text": "lokeshpotta20" }, { "code": null, "e": 32326, "s": 32309, "text": "shikhasingrajput" }, { "code": null, "e": 32332, "s": 32326, "text": "ukasp" }, { "code": null, "e": 32340, "s": 32332, "text": "gfgking" }, { "code": null, "e": 32351, "s": 32340, "text": "maths-mean" }, { "code": null, "e": 32358, "s": 32351, "text": "Arrays" }, { "code": null, "e": 32371, "s": 32358, "text": "Mathematical" }, { "code": null, "e": 32389, "s": 32371, "text": "Pattern Searching" }, { "code": null, "e": 32396, "s": 32389, "text": "Arrays" }, { "code": null, "e": 32409, "s": 32396, "text": "Mathematical" }, { "code": null, "e": 32427, "s": 32409, "text": "Pattern Searching" }, { "code": null, "e": 32525, "s": 32427, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32573, "s": 32525, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 32641, "s": 32573, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 32685, "s": 32641, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 32717, "s": 32685, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 32740, "s": 32717, "text": "Introduction to Arrays" }, { "code": null, "e": 32770, "s": 32740, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 32830, "s": 32770, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 32845, "s": 32830, "text": "C++ Data Types" }, { "code": null, "e": 32888, "s": 32845, "text": "Set in C++ Standard Template Library (STL)" } ]
C++ Program for sorting variables of any data type
We are given with the values of different datatypes like it can be of type integer, float, string, bool, etc. and the task is to sort the variables of any data type using one common method or function and display the result. In C++, we can use std::sort to sort any type of array which is available in C++ standard template library(STL). By default sort function sorts the array element in ascending order. Sort() function takes three arguments − Start element in the array list i.e. from where you want to start your sort End element in the array list i.e. till where you want your sorting to be done Change the default setting of sort function to descending order by passing the greater() function to sort in descending order. Input-: int arr[] = { 2, 1, 5, 4, 6, 3} Output-: 1, 2, 3, 4, 5, 6 Input-: float arr[] = { 30.0, 21.1, 29.0, 45.0} Output-: 21.1, 29.0, 30.0, 45.0 Input-: string str = {"tutorials point is best", "tutorials point", "www.tutorialspoint.com"} Output-: tutorials point tutorials point is best www.tutorialspoint.com Approach used in the below program is as follows − Input the variables of different data types like integer, float, string, etc. Apply the sort() function that will sort the elements of any type of array Print the results Start Step 1-> create template class for operating upon different type of data Template <class T> Step 2-> Create function to display the sorted array of any data type void print(T arr[], int size) Loop For size_t i = 0 and i < size and ++i print arr[i] End Step 3-> In main() Declare variable for size of an array int num = 6 Create an array of type integer int arr[num] = { 10, 90, 1, 2, 3 } Call the sort function sort(arr, arr + num) Call the print function print(arr, num) Create an array of type string string str[num] = { "tutorials point is best", "tutorials point", "www.tutorialspoint.com" } Call the sort function sort(str, str + num) Call the print function print(str, num) Create an array of type float float float_arr[num] = { 32.0, 12.76, 10.00 } Call the sort function sort(float_arr, float_arr+num) Call the print function print(float_arr, num) Stop Live Demo #include <bits/stdc++.h> using namespace std; // creating variable of template class template <class T> void print(T arr[], int size) { for (size_t i = 0; i < size; ++i) cout << arr[i] << " "; cout << endl; } int main() { int num = 6; int arr[num] = { 10, 90, 1, 2, 3 }; sort(arr, arr + num); print(arr, num); string str[num] = { "tutorials point is best", "tutorials point", "www.tutorialspoint.com" }; sort(str, str + num); print(str, num); float float_arr[num] = { 32.0, 12.76, 10.00 }; sort(float_arr, float_arr+num); print(float_arr, num); return 0; } 0 1 2 3 10 90 tutorials point tutorials point is best www.tutorialspoint.com 10 12.76 32
[ { "code": null, "e": 1287, "s": 1062, "text": "We are given with the values of different datatypes like it can be of type integer, float, string, bool, etc. and the task is to sort the variables of any data type using one common method or function and display the result." }, { "code": null, "e": 1509, "s": 1287, "text": "In C++, we can use std::sort to sort any type of array which is available in C++ standard template library(STL). By default sort function sorts the array element in ascending order. Sort() function takes three arguments −" }, { "code": null, "e": 1585, "s": 1509, "text": "Start element in the array list i.e. from where you want to start your sort" }, { "code": null, "e": 1664, "s": 1585, "text": "End element in the array list i.e. till where you want your sorting to be done" }, { "code": null, "e": 1791, "s": 1664, "text": "Change the default setting of sort function to descending order by passing the greater() function to sort in descending order." }, { "code": null, "e": 2110, "s": 1791, "text": "Input-: int arr[] = { 2, 1, 5, 4, 6, 3}\nOutput-: 1, 2, 3, 4, 5, 6\n\nInput-: float arr[] = { 30.0, 21.1, 29.0, 45.0}\nOutput-: 21.1, 29.0, 30.0, 45.0\n\nInput-: string str = {\"tutorials point is best\", \"tutorials point\", \"www.tutorialspoint.com\"}\nOutput-: tutorials point tutorials point is best www.tutorialspoint.com" }, { "code": null, "e": 2163, "s": 2112, "text": "Approach used in the below program is as follows −" }, { "code": null, "e": 2241, "s": 2163, "text": "Input the variables of different data types like integer, float, string, etc." }, { "code": null, "e": 2316, "s": 2241, "text": "Apply the sort() function that will sort the elements of any type of array" }, { "code": null, "e": 2334, "s": 2316, "text": "Print the results" }, { "code": null, "e": 3247, "s": 2334, "text": "Start\nStep 1-> create template class for operating upon different type of data Template <class T>\nStep 2-> Create function to display the sorted array of any data type\n void print(T arr[], int size)\n Loop For size_t i = 0 and i < size and ++i\n print arr[i]\n End\nStep 3-> In main()\n Declare variable for size of an array int num = 6\n Create an array of type integer int arr[num] = { 10, 90, 1, 2, 3 }\n Call the sort function sort(arr, arr + num)\n Call the print function print(arr, num)\n Create an array of type string string str[num] = { \"tutorials point is best\", \"tutorials point\", \"www.tutorialspoint.com\" }\n Call the sort function sort(str, str + num)\n Call the print function print(str, num)\n Create an array of type float float float_arr[num] = { 32.0, 12.76, 10.00 }\n Call the sort function sort(float_arr, float_arr+num)\n Call the print function print(float_arr, num)\nStop" }, { "code": null, "e": 3258, "s": 3247, "text": " Live Demo" }, { "code": null, "e": 3866, "s": 3258, "text": "#include <bits/stdc++.h>\nusing namespace std;\n// creating variable of template class\ntemplate <class T>\nvoid print(T arr[], int size) {\n for (size_t i = 0; i < size; ++i) \n cout << arr[i] << \" \"; \n cout << endl;\n}\nint main() {\n int num = 6;\n int arr[num] = { 10, 90, 1, 2, 3 };\n sort(arr, arr + num);\n print(arr, num);\n string str[num] = { \"tutorials point is best\", \"tutorials point\", \"www.tutorialspoint.com\" };\n sort(str, str + num);\n print(str, num);\n float float_arr[num] = { 32.0, 12.76, 10.00 };\n sort(float_arr, float_arr+num);\n print(float_arr, num);\n return 0;\n} " }, { "code": null, "e": 3971, "s": 3866, "text": "0 1 2 3 10 90\ntutorials point tutorials point is best www.tutorialspoint.com\n10 12.76 32" } ]
Add more than one shadow to a text with CSS
Add the comma-separated list of shadows to add more than one shadow, with the text-shadow property. You can try to run the following to learn how to add multiple shadows in a single line Example Live Demo <!DOCTYPE html> <html> <head> <style> h1 { text-shadow: 0 0 3px red, 0 0 4px green, 0 0 5px blue; } </style> </head> <body> <h1>Heading One</h1> <p>Above heading has multiple text shadow effects.</p> </body> </html>
[ { "code": null, "e": 1249, "s": 1062, "text": "Add the comma-separated list of shadows to add more than one shadow, with the text-shadow property. You can try to run the following to learn how to add multiple shadows in a single line" }, { "code": null, "e": 1257, "s": 1249, "text": "Example" }, { "code": null, "e": 1267, "s": 1257, "text": "Live Demo" }, { "code": null, "e": 1549, "s": 1267, "text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n h1 {\n text-shadow: 0 0 3px red, 0 0 4px green, 0 0 5px blue;\n }\n </style>\n </head>\n <body>\n <h1>Heading One</h1>\n <p>Above heading has multiple text shadow effects.</p>\n </body>\n</html>" } ]
Scala List iterator() method with example - GeeksforGeeks
29 Jul, 2019 The iterator method is utilized to give an iterator. Method Definition: def iterator: Iterator[A] Return Type: It returns a non-empty iterator for non-empty list and returns an empty iterator for empty list. Example #1: // Scala program of iterator// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list val m1 = List(1, 2, 3, 4, 5) // Applying iterator method val result = m1.iterator // Displays output println(result) }} non-empty iterator Example #2: // Scala program of iterator// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating an empty list val m1 = List() // Applying iterator method val result = m1.iterator // Displays output println(result) }} empty iterator Scala Scala-list Scala-Method Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Scala Map Scala List contains() method with example Scala Lists Scala Tutorial – Learn Scala with Step By Step Guide Throw Keyword in Scala Scala | Arrays How to get the first element of List in Scala Lambda Expression in Scala Enumeration in Scala Scala String replace() method with example
[ { "code": null, "e": 23856, "s": 23828, "text": "\n29 Jul, 2019" }, { "code": null, "e": 23909, "s": 23856, "text": "The iterator method is utilized to give an iterator." }, { "code": null, "e": 23954, "s": 23909, "text": "Method Definition: def iterator: Iterator[A]" }, { "code": null, "e": 24064, "s": 23954, "text": "Return Type: It returns a non-empty iterator for non-empty list and returns an empty iterator for empty list." }, { "code": null, "e": 24076, "s": 24064, "text": "Example #1:" }, { "code": "// Scala program of iterator// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list val m1 = List(1, 2, 3, 4, 5) // Applying iterator method val result = m1.iterator // Displays output println(result) }}", "e": 24423, "s": 24076, "text": null }, { "code": null, "e": 24443, "s": 24423, "text": "non-empty iterator\n" }, { "code": null, "e": 24455, "s": 24443, "text": "Example #2:" }, { "code": "// Scala program of iterator// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating an empty list val m1 = List() // Applying iterator method val result = m1.iterator // Displays output println(result) }}", "e": 24793, "s": 24455, "text": null }, { "code": null, "e": 24809, "s": 24793, "text": "empty iterator\n" }, { "code": null, "e": 24815, "s": 24809, "text": "Scala" }, { "code": null, "e": 24826, "s": 24815, "text": "Scala-list" }, { "code": null, "e": 24839, "s": 24826, "text": "Scala-Method" }, { "code": null, "e": 24845, "s": 24839, "text": "Scala" }, { "code": null, "e": 24943, "s": 24845, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24952, "s": 24943, "text": "Comments" }, { "code": null, "e": 24965, "s": 24952, "text": "Old Comments" }, { "code": null, "e": 24975, "s": 24965, "text": "Scala Map" }, { "code": null, "e": 25017, "s": 24975, "text": "Scala List contains() method with example" }, { "code": null, "e": 25029, "s": 25017, "text": "Scala Lists" }, { "code": null, "e": 25082, "s": 25029, "text": "Scala Tutorial – Learn Scala with Step By Step Guide" }, { "code": null, "e": 25105, "s": 25082, "text": "Throw Keyword in Scala" }, { "code": null, "e": 25120, "s": 25105, "text": "Scala | Arrays" }, { "code": null, "e": 25166, "s": 25120, "text": "How to get the first element of List in Scala" }, { "code": null, "e": 25193, "s": 25166, "text": "Lambda Expression in Scala" }, { "code": null, "e": 25214, "s": 25193, "text": "Enumeration in Scala" } ]
Calculate difference between adjacent elements in given list using Python
In this article we will see how we create a new list from a given list by subtracting the values in the adjacent elements of the list. We have various approaches to do that. In this approach we iterate through list elements by subtracting the values using their index positions and appending the result of each subtraction to a new list. We use the range and len function to keep track of how many iterations to do. Live Demo listA= [25, 97, 13, 62, 14, 102] print("Given list:\n",listA) list_with_diff = [] for n in range(1, len(listA)): list_with_diff.append(listA[n] - listA[n-1]) print("Difference between adjacent elements in the list: \n", list_with_diff) Running the above code gives us the following result − Given list: [25, 97, 13, 62, 14, 102] Difference between adjacent elements in the list: [72, -84, 49, -48, 88] In the next approach we create a for loop to find the difference between the adjacent elements and keep appending the result to a new list. Live Demo listA= [25, 97, 13, 62, 14, 102] print("Given list:\n",listA) list_with_diff = [] for i, j in zip(listA[0::], listA[1::]): list_with_diff.append(j - i) print("Difference between adjacent elements in the list: \n", list_with_diff) Running the above code gives us the following result − Given list: [25, 97, 13, 62, 14, 102] Difference between adjacent elements in the list: [72, -84, 49, -48, 88]
[ { "code": null, "e": 1236, "s": 1062, "text": "In this article we will see how we create a new list from a given list by subtracting the values in the adjacent elements of the list. We have various approaches to do that." }, { "code": null, "e": 1478, "s": 1236, "text": "In this approach we iterate through list elements by subtracting the values using their index positions and appending the result of each subtraction to a new list. We use the range and len function to keep track of how many iterations to do." }, { "code": null, "e": 1489, "s": 1478, "text": " Live Demo" }, { "code": null, "e": 1732, "s": 1489, "text": "listA= [25, 97, 13, 62, 14, 102]\n\nprint(\"Given list:\\n\",listA)\nlist_with_diff = []\nfor n in range(1, len(listA)):\n list_with_diff.append(listA[n] - listA[n-1])\nprint(\"Difference between adjacent elements in the list: \\n\",\n list_with_diff)" }, { "code": null, "e": 1787, "s": 1732, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1898, "s": 1787, "text": "Given list:\n[25, 97, 13, 62, 14, 102]\nDifference between adjacent elements in the list:\n[72, -84, 49, -48, 88]" }, { "code": null, "e": 2038, "s": 1898, "text": "In the next approach we create a for loop to find the difference between the adjacent elements and keep appending the result to a new list." }, { "code": null, "e": 2049, "s": 2038, "text": " Live Demo" }, { "code": null, "e": 2286, "s": 2049, "text": "listA= [25, 97, 13, 62, 14, 102]\n\nprint(\"Given list:\\n\",listA)\nlist_with_diff = []\nfor i, j in zip(listA[0::], listA[1::]):\n list_with_diff.append(j - i)\nprint(\"Difference between adjacent elements in the list: \\n\",\n list_with_diff)" }, { "code": null, "e": 2341, "s": 2286, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2452, "s": 2341, "text": "Given list:\n[25, 97, 13, 62, 14, 102]\nDifference between adjacent elements in the list:\n[72, -84, 49, -48, 88]" } ]
ByteBuffer rewind() methods in Java with Examples - GeeksforGeeks
16 Jul, 2019 The rewind() method of java.nio.ByteBuffer Class is used to rewind this buffer. The position is set to zero and the mark is discarded. Invoke this method before a sequence of channel-write or get operations, assuming that the limit has already been set appropriately. Invoking this method neither changes nor discards the mark’s value. Syntax: public ByteBuffer rewind() Return Value: This method returns this buffer. Below are the examples to illustrate the rewind() method: Examples 1: // Java program to demonstrate// rewind() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // defining and allocating ByteBuffer // using allocate() method ByteBuffer byteBuffer = ByteBuffer.allocate(4); // put byte value in byteBuffer // using put() method byteBuffer.put((byte)20); byteBuffer.put((byte)'a'); // print the byte buffer System.out.println("Buffer before operation: " + Arrays.toString(byteBuffer.array()) + "\nPosition: " + byteBuffer.position() + "\nLimit: " + byteBuffer.limit()); // rewind the Buffer // using rewind() method byteBuffer.rewind(); // print the bytebuffer System.out.println("\nBuffer after operation: " + Arrays.toString(byteBuffer.array()) + "\nPosition: " + byteBuffer.position() + "\nLimit: " + byteBuffer.limit()); }} Buffer before operation: [20, 97, 0, 0] Position: 2 Limit: 4 Buffer after operation: [20, 97, 0, 0] Position: 0 Limit: 4 Examples 2: // Java program to demonstrate// rewind() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // defining and allocating ByteBuffer // using allocate() method ByteBuffer byteBuffer = ByteBuffer.allocate(5); // put byte value in byteBuffer // using put() method byteBuffer.put((byte)20); byteBuffer.put((byte)30); byteBuffer.put((byte)40); // mark will be going to discarded by rewind() byteBuffer.mark(); // print the buffer System.out.println("Buffer before operation: " + Arrays.toString(byteBuffer.array()) + "\nPosition: " + byteBuffer.position() + "\nLimit: " + byteBuffer.limit()); // Rewind the Buffer // using rewind() method byteBuffer.rewind(); // print the buffer System.out.println("\nBuffer after operation: " + Arrays.toString(byteBuffer.array()) + "\nPosition: " + byteBuffer.position() + "\nLimit: " + byteBuffer.limit()); }} Buffer before operation: [20, 30, 40, 0, 0] Position: 3 Limit: 5 Buffer after operation: [20, 30, 40, 0, 0] Position: 0 Limit: 5 Reference: https://docs.oracle.com/javase/9/docs/api/java/nio/ByteBuffer.html#rewind– Java-ByteBuffer Java-Functions Java-NIO package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments HashMap in Java with Examples Initialize an ArrayList in Java Interfaces in Java ArrayList in Java How to iterate any Map in Java Multidimensional Arrays in Java Singleton Class in Java Stack Class in Java Set in Java Multithreading in Java
[ { "code": null, "e": 24522, "s": 24494, "text": "\n16 Jul, 2019" }, { "code": null, "e": 24858, "s": 24522, "text": "The rewind() method of java.nio.ByteBuffer Class is used to rewind this buffer. The position is set to zero and the mark is discarded. Invoke this method before a sequence of channel-write or get operations, assuming that the limit has already been set appropriately. Invoking this method neither changes nor discards the mark’s value." }, { "code": null, "e": 24866, "s": 24858, "text": "Syntax:" }, { "code": null, "e": 24893, "s": 24866, "text": "public ByteBuffer rewind()" }, { "code": null, "e": 24940, "s": 24893, "text": "Return Value: This method returns this buffer." }, { "code": null, "e": 24998, "s": 24940, "text": "Below are the examples to illustrate the rewind() method:" }, { "code": null, "e": 25010, "s": 24998, "text": "Examples 1:" }, { "code": "// Java program to demonstrate// rewind() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // defining and allocating ByteBuffer // using allocate() method ByteBuffer byteBuffer = ByteBuffer.allocate(4); // put byte value in byteBuffer // using put() method byteBuffer.put((byte)20); byteBuffer.put((byte)'a'); // print the byte buffer System.out.println(\"Buffer before operation: \" + Arrays.toString(byteBuffer.array()) + \"\\nPosition: \" + byteBuffer.position() + \"\\nLimit: \" + byteBuffer.limit()); // rewind the Buffer // using rewind() method byteBuffer.rewind(); // print the bytebuffer System.out.println(\"\\nBuffer after operation: \" + Arrays.toString(byteBuffer.array()) + \"\\nPosition: \" + byteBuffer.position() + \"\\nLimit: \" + byteBuffer.limit()); }}", "e": 26096, "s": 25010, "text": null }, { "code": null, "e": 26219, "s": 26096, "text": "Buffer before operation: [20, 97, 0, 0]\nPosition: 2\nLimit: 4\n\nBuffer after operation: [20, 97, 0, 0]\nPosition: 0\nLimit: 4\n" }, { "code": null, "e": 26231, "s": 26219, "text": "Examples 2:" }, { "code": "// Java program to demonstrate// rewind() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // defining and allocating ByteBuffer // using allocate() method ByteBuffer byteBuffer = ByteBuffer.allocate(5); // put byte value in byteBuffer // using put() method byteBuffer.put((byte)20); byteBuffer.put((byte)30); byteBuffer.put((byte)40); // mark will be going to discarded by rewind() byteBuffer.mark(); // print the buffer System.out.println(\"Buffer before operation: \" + Arrays.toString(byteBuffer.array()) + \"\\nPosition: \" + byteBuffer.position() + \"\\nLimit: \" + byteBuffer.limit()); // Rewind the Buffer // using rewind() method byteBuffer.rewind(); // print the buffer System.out.println(\"\\nBuffer after operation: \" + Arrays.toString(byteBuffer.array()) + \"\\nPosition: \" + byteBuffer.position() + \"\\nLimit: \" + byteBuffer.limit()); }}", "e": 27422, "s": 26231, "text": null }, { "code": null, "e": 27553, "s": 27422, "text": "Buffer before operation: [20, 30, 40, 0, 0]\nPosition: 3\nLimit: 5\n\nBuffer after operation: [20, 30, 40, 0, 0]\nPosition: 0\nLimit: 5\n" }, { "code": null, "e": 27639, "s": 27553, "text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/nio/ByteBuffer.html#rewind–" }, { "code": null, "e": 27655, "s": 27639, "text": "Java-ByteBuffer" }, { "code": null, "e": 27670, "s": 27655, "text": "Java-Functions" }, { "code": null, "e": 27687, "s": 27670, "text": "Java-NIO package" }, { "code": null, "e": 27692, "s": 27687, "text": "Java" }, { "code": null, "e": 27697, "s": 27692, "text": "Java" }, { "code": null, "e": 27795, "s": 27697, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27804, "s": 27795, "text": "Comments" }, { "code": null, "e": 27817, "s": 27804, "text": "Old Comments" }, { "code": null, "e": 27847, "s": 27817, "text": "HashMap in Java with Examples" }, { "code": null, "e": 27879, "s": 27847, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 27898, "s": 27879, "text": "Interfaces in Java" }, { "code": null, "e": 27916, "s": 27898, "text": "ArrayList in Java" }, { "code": null, "e": 27947, "s": 27916, "text": "How to iterate any Map in Java" }, { "code": null, "e": 27979, "s": 27947, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 28003, "s": 27979, "text": "Singleton Class in Java" }, { "code": null, "e": 28023, "s": 28003, "text": "Stack Class in Java" }, { "code": null, "e": 28035, "s": 28023, "text": "Set in Java" } ]
How to press ENTER inside an edit box in Selenium?
Selenium gives Enum Key macros to perform the enter action. import org.openqa.selenium.By; import org.openqa.selenium.Keys; 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 PressEnter { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); String url = " https://www.tutorialspoint.com/index.htm"; driver.get(url); driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS); // Keys.ENTER passed through sendKeys() method driver.findElement(By.className("gsc-input")).sendKeys("Keys.ENTER"); driver.close(); } }
[ { "code": null, "e": 1122, "s": 1062, "text": "Selenium gives Enum Key macros to perform the enter action." }, { "code": null, "e": 1911, "s": 1122, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.Keys;\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 PressEnter {\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 String url = \" https://www.tutorialspoint.com/index.htm\";\n driver.get(url);\n driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);\n // Keys.ENTER passed through sendKeys() method\n driver.findElement(By.className(\"gsc-input\")).sendKeys(\"Keys.ENTER\");\n driver.close();\n }\n}" } ]
Python - Tkinter Message
This widget provides a multiline and noneditable object that displays texts, automatically breaking lines and justifying their contents. Its functionality is very similar to the one provided by the Label widget, except that it can also automatically wrap the text, maintaining a given width or aspect ratio. Here is the simple syntax to create this widget − w = Message ( master, option, ... ) master − This represents the parent window. master − This represents the parent window. options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas. options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas. anchor This options controls where the text is positioned if the widget has more space than the text needs. The default is anchor=CENTER, which centers the text in the available space. bg The normal background color displayed behind the label and indicator. bitmap Set this option equal to a bitmap or image object and the label will display that graphic. bd The size of the border around the indicator. Default is 2 pixels. cursor If you set this option to a cursor name (arrow, dot etc.), the mouse cursor will change to that pattern when it is over the checkbutton. font If you are displaying text in this label (with the text or textvariable option, the font option specifies in what font that text will be displayed. fg If you are displaying text or a bitmap in this label, this option specifies the color of the text. If you are displaying a bitmap, this is the color that will appear at the position of the 1-bits in the bitmap. height The vertical dimension of the new frame. image To display a static image in the label widget, set this option to an image object. justify Specifies how multiple lines of text will be aligned with respect to each other: LEFT for flush left, CENTER for centered (the default), or RIGHT for right-justified. padx Extra space added to the left and right of the text within the widget. Default is 1. pady Extra space added above and below the text within the widget. Default is 1. relief Specifies the appearance of a decorative border around the label. The default is FLAT; for other values. text To display one or more lines of text in a label widget, set this option to a string containing the text. Internal newlines ("\n") will force a line break. textvariable To slave the text displayed in a label widget to a control variable of class StringVar, set this option to that variable. underline You can display an underline (_) below the nth letter of the text, counting from 0, by setting this option to n. The default is underline=-1, which means no underlining. width Width of the label in characters (not pixels!). If this option is not set, the label will be sized to fit its contents. wraplength You can limit the number of characters in each line by setting this option to the desired number. The default value, 0, means that lines will be broken only at newlines. Try the following example yourself − from Tkinter import * root = Tk() var = StringVar() label = Message( root, textvariable=var, relief=RAISED ) var.set("Hey!? How are you doing?") label.pack() root.mainloop() When the above code is executed, it produces the following result − 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2381, "s": 2244, "text": "This widget provides a multiline and noneditable object that displays texts, automatically breaking lines and justifying their contents." }, { "code": null, "e": 2552, "s": 2381, "text": "Its functionality is very similar to the one provided by the Label widget, except that it can also automatically wrap the text, maintaining a given width or aspect ratio." }, { "code": null, "e": 2602, "s": 2552, "text": "Here is the simple syntax to create this widget −" }, { "code": null, "e": 2639, "s": 2602, "text": "w = Message ( master, option, ... )\n" }, { "code": null, "e": 2683, "s": 2639, "text": "master − This represents the parent window." }, { "code": null, "e": 2727, "s": 2683, "text": "master − This represents the parent window." }, { "code": null, "e": 2867, "s": 2727, "text": "options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas." }, { "code": null, "e": 3007, "s": 2867, "text": "options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas." }, { "code": null, "e": 3014, "s": 3007, "text": "anchor" }, { "code": null, "e": 3192, "s": 3014, "text": "This options controls where the text is positioned if the widget has more space than the text needs. The default is anchor=CENTER, which centers the text in the available space." }, { "code": null, "e": 3195, "s": 3192, "text": "bg" }, { "code": null, "e": 3265, "s": 3195, "text": "The normal background color displayed behind the label and indicator." }, { "code": null, "e": 3272, "s": 3265, "text": "bitmap" }, { "code": null, "e": 3363, "s": 3272, "text": "Set this option equal to a bitmap or image object and the label will display that graphic." }, { "code": null, "e": 3367, "s": 3363, "text": "bd " }, { "code": null, "e": 3433, "s": 3367, "text": "The size of the border around the indicator. Default is 2 pixels." }, { "code": null, "e": 3440, "s": 3433, "text": "cursor" }, { "code": null, "e": 3577, "s": 3440, "text": "If you set this option to a cursor name (arrow, dot etc.), the mouse cursor will change to that pattern when it is over the checkbutton." }, { "code": null, "e": 3582, "s": 3577, "text": "font" }, { "code": null, "e": 3730, "s": 3582, "text": "If you are displaying text in this label (with the text or textvariable option, the font option specifies in what font that text will be displayed." }, { "code": null, "e": 3734, "s": 3730, "text": "fg " }, { "code": null, "e": 3945, "s": 3734, "text": "If you are displaying text or a bitmap in this label, this option specifies the color of the text. If you are displaying a bitmap, this is the color that will appear at the position of the 1-bits in the bitmap." }, { "code": null, "e": 3952, "s": 3945, "text": "height" }, { "code": null, "e": 3994, "s": 3952, "text": "The vertical dimension of the new frame. " }, { "code": null, "e": 4000, "s": 3994, "text": "image" }, { "code": null, "e": 4083, "s": 4000, "text": "To display a static image in the label widget, set this option to an image object." }, { "code": null, "e": 4091, "s": 4083, "text": "justify" }, { "code": null, "e": 4258, "s": 4091, "text": "Specifies how multiple lines of text will be aligned with respect to each other: LEFT for flush left, CENTER for centered (the default), or RIGHT for right-justified." }, { "code": null, "e": 4263, "s": 4258, "text": "padx" }, { "code": null, "e": 4348, "s": 4263, "text": "Extra space added to the left and right of the text within the widget. Default is 1." }, { "code": null, "e": 4353, "s": 4348, "text": "pady" }, { "code": null, "e": 4429, "s": 4353, "text": "Extra space added above and below the text within the widget. Default is 1." }, { "code": null, "e": 4436, "s": 4429, "text": "relief" }, { "code": null, "e": 4541, "s": 4436, "text": "Specifies the appearance of a decorative border around the label. The default is FLAT; for other values." }, { "code": null, "e": 4546, "s": 4541, "text": "text" }, { "code": null, "e": 4701, "s": 4546, "text": "To display one or more lines of text in a label widget, set this option to a string containing the text. Internal newlines (\"\\n\") will force a line break." }, { "code": null, "e": 4714, "s": 4701, "text": "textvariable" }, { "code": null, "e": 4836, "s": 4714, "text": "To slave the text displayed in a label widget to a control variable of class StringVar, set this option to that variable." }, { "code": null, "e": 4846, "s": 4836, "text": "underline" }, { "code": null, "e": 5016, "s": 4846, "text": "You can display an underline (_) below the nth letter of the text, counting from 0, by setting this option to n. The default is underline=-1, which means no underlining." }, { "code": null, "e": 5022, "s": 5016, "text": "width" }, { "code": null, "e": 5142, "s": 5022, "text": "Width of the label in characters (not pixels!). If this option is not set, the label will be sized to fit its contents." }, { "code": null, "e": 5153, "s": 5142, "text": "wraplength" }, { "code": null, "e": 5323, "s": 5153, "text": "You can limit the number of characters in each line by setting this option to the desired number. The default value, 0, means that lines will be broken only at newlines." }, { "code": null, "e": 5360, "s": 5323, "text": "Try the following example yourself −" }, { "code": null, "e": 5536, "s": 5360, "text": "from Tkinter import *\n\nroot = Tk()\nvar = StringVar()\nlabel = Message( root, textvariable=var, relief=RAISED )\n\nvar.set(\"Hey!? How are you doing?\")\nlabel.pack()\nroot.mainloop()" }, { "code": null, "e": 5605, "s": 5536, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 5642, "s": 5605, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 5658, "s": 5642, "text": " Malhar Lathkar" }, { "code": null, "e": 5691, "s": 5658, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 5710, "s": 5691, "text": " Arnab Chakraborty" }, { "code": null, "e": 5745, "s": 5710, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 5767, "s": 5745, "text": " In28Minutes Official" }, { "code": null, "e": 5801, "s": 5767, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 5829, "s": 5801, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5864, "s": 5829, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 5878, "s": 5864, "text": " Lets Kode It" }, { "code": null, "e": 5911, "s": 5878, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 5928, "s": 5911, "text": " Abhilash Nelson" }, { "code": null, "e": 5935, "s": 5928, "text": " Print" }, { "code": null, "e": 5946, "s": 5935, "text": " Add Notes" } ]
Containerize Your Application With Docker | Towards Data Science
Let’s say that you want to deploy an application to a server. In your local system, the application works just fine without any problem. But once you’ve deployed the application into a server, boom! Your application doesn’t work. Many factors can make this happen. It could be the operating system compatibility or different library versions. Therefore, your application is never being deployed, and you will get a headache just because of that. How can we remove the headache just because of the incompatibility problem? Docker comes to save you! This article will show you how to use Docker to containerize your application so you can run them on any servers regardless of their operating system inside of them. Without further, let’s get started! Before we get into the implementation, let me explain to you about Docker. Docker is a platform for deploying applications. It works by isolating the application into an image. The image will be run by a container, where it contains the operating system and supporting software. Because of that isolation, we don’t have to worry about software installation and its version. You can run the application through a container regardless of the operating system and the software inside your computer. Therefore, you can focus on developing your applications and deploy them straightly. After you understand the concept of Docker, now let’s get into the implementation. There are several steps that we will do: Install DockerCreate a file called DockerfileBuild the imageRun the image Install Docker Create a file called Dockerfile Build the image Run the image The first step that we can do is to install the docker application. You can download Docker here and make sure to pick the right one based on your operating system. After you install Docker, now let’s test whether the Docker is already installed on your computer. You can run command ‘docker’ like this preview below: If your computer shows a prompt like above, we can assure you that Docker is already installed on your computer. Now let’s get into the next step. After you install Docker, the next step is to create a file called Dockerfile. Dockerfile is a script for building a docker image. It consists of instructions to set up the image ranging from installing libraries to run our project. In this case, I’ve created an API that is based on the Flask library. This API will be used as the connector between the user and the machine learning model to return a prediction result. Here is the code of the API: For creating the Dockerfile, make sure that the file is located at the same location as your application and the machine learning model folder. In my case, the folder location looks like this: | app.py| Dockerfile| requirements.txt|+---resnet50_food_model| | saved_model.pb| || +---assets| +---variables| variables.data-00000-of-00001| variables.index Inside the folder, we have app.py for running my application, requirements.txt that contains the list of packages that we will use, the model folder that consists of the pre-trained model, and the Dockerfile for building a docker image. Please remember that when you create the Dockerfile, make sure that you don’t give any extension after the file name. You must write ‘Dockerfile’ only. Now let’s write our Dockerfile script. Here is the script inside the Dockerfile: Let me explain each line of the script: The ‘FROM’ instruction will take a docker image from a docker registry. The image will contain the operating system and also the Python. The ‘WORKDIR’ instruction will set the default working directory that we will use to run the application. The ‘COPY’ instruction will copy every single file inside the current directory into the new working directory. The ‘RUN’ instruction will run a command. In this case, the ‘pip install’ command. The ‘EXPOSE’ instruction will expose port 5000 as the connector to the docker image. Finally, the ‘CMD’ instruction will run a command. In this case, the ‘flask run’ command. Side Note: The ‘CMD’ instruction has the same function as the ‘RUN’ instruction, but they are different based on their purpose. The ‘CMD’ instruction is used for running a command when you start running the docker image. Meanwhile, the ‘RUN’ instruction is used for running a command while you are building the docker image. After you create the docker image, the next step is to build the image. To build the image, it’s really simple. All you need to do is to run the ‘docker build’ command like this: docker build -t my-image . As you can see above, I give the ‘-t’ tag beside the ‘docker build’ command. The ‘-t’ tag takes two arguments. They are the image name and also the dot character, which represents all files inside the folder. Here is the preview when we are building the docker image (It will take a long time, so be patient) : Let’s run the ‘docker images’ command to display the existing images that are already built. Here is the preview of the result: As you can see from above, the image already exists. Now the next step is to run the docker image on our computer. To run the image, you can use the command ‘docker run’ like this, docker run -dp 5000:5000 my-image Let’s wait for a while for 3 to 5 minutes. To know whether our image is already running, we can use the ‘docker ps -a’ command to check all running images. Here is the preview: As you can see from above, the image is already up about a minute. It means that the image is already running at port 5000. Now let’s access the image using localhost:5000 or 127.0.0.1:5000. Here is the preview: As you can see from above, our container has run successfully on our computer. Because you set the ‘-d’ parameter, you cannot show the log of the container. To check activities on a container, you can use ‘docker logs’ for doing that. Also, please set the container id beside it. You can see the container id from the ‘docker ps -a’ command. The command looks like this: docker logs bff6d3c8e2da Here is what the log preview looks like: If you want to stop the container, you can use the ‘docker kill’ command and set the container id beside it. Here is the command to stop the docker command: docker kill bff6d3c8e2da After you stop the container, it will look like this, Yes, our container has already terminated. Well done! You have learned how to containerize your application as a docker image. I hope this article helps you to build your own docker image on your project. If you are interested in this article, you can follow me on Medium to get articles like this. If you have any questions or want to say hi, you can connect with me on LinkedIn. Thank you for reading my article! [1] https://docs.docker.com/[2] https://nickjanetakis.com/blog/docker-tip-7-the-difference-between-run-and-cmd
[ { "code": null, "e": 276, "s": 46, "text": "Let’s say that you want to deploy an application to a server. In your local system, the application works just fine without any problem. But once you’ve deployed the application into a server, boom! Your application doesn’t work." }, { "code": null, "e": 492, "s": 276, "text": "Many factors can make this happen. It could be the operating system compatibility or different library versions. Therefore, your application is never being deployed, and you will get a headache just because of that." }, { "code": null, "e": 594, "s": 492, "text": "How can we remove the headache just because of the incompatibility problem? Docker comes to save you!" }, { "code": null, "e": 796, "s": 594, "text": "This article will show you how to use Docker to containerize your application so you can run them on any servers regardless of their operating system inside of them. Without further, let’s get started!" }, { "code": null, "e": 1075, "s": 796, "text": "Before we get into the implementation, let me explain to you about Docker. Docker is a platform for deploying applications. It works by isolating the application into an image. The image will be run by a container, where it contains the operating system and supporting software." }, { "code": null, "e": 1377, "s": 1075, "text": "Because of that isolation, we don’t have to worry about software installation and its version. You can run the application through a container regardless of the operating system and the software inside your computer. Therefore, you can focus on developing your applications and deploy them straightly." }, { "code": null, "e": 1501, "s": 1377, "text": "After you understand the concept of Docker, now let’s get into the implementation. There are several steps that we will do:" }, { "code": null, "e": 1575, "s": 1501, "text": "Install DockerCreate a file called DockerfileBuild the imageRun the image" }, { "code": null, "e": 1590, "s": 1575, "text": "Install Docker" }, { "code": null, "e": 1622, "s": 1590, "text": "Create a file called Dockerfile" }, { "code": null, "e": 1638, "s": 1622, "text": "Build the image" }, { "code": null, "e": 1652, "s": 1638, "text": "Run the image" }, { "code": null, "e": 1817, "s": 1652, "text": "The first step that we can do is to install the docker application. You can download Docker here and make sure to pick the right one based on your operating system." }, { "code": null, "e": 1970, "s": 1817, "text": "After you install Docker, now let’s test whether the Docker is already installed on your computer. You can run command ‘docker’ like this preview below:" }, { "code": null, "e": 2117, "s": 1970, "text": "If your computer shows a prompt like above, we can assure you that Docker is already installed on your computer. Now let’s get into the next step." }, { "code": null, "e": 2350, "s": 2117, "text": "After you install Docker, the next step is to create a file called Dockerfile. Dockerfile is a script for building a docker image. It consists of instructions to set up the image ranging from installing libraries to run our project." }, { "code": null, "e": 2567, "s": 2350, "text": "In this case, I’ve created an API that is based on the Flask library. This API will be used as the connector between the user and the machine learning model to return a prediction result. Here is the code of the API:" }, { "code": null, "e": 2760, "s": 2567, "text": "For creating the Dockerfile, make sure that the file is located at the same location as your application and the machine learning model folder. In my case, the folder location looks like this:" }, { "code": null, "e": 2955, "s": 2760, "text": "| app.py| Dockerfile| requirements.txt|+---resnet50_food_model| | saved_model.pb| || +---assets| +---variables| variables.data-00000-of-00001| variables.index" }, { "code": null, "e": 3192, "s": 2955, "text": "Inside the folder, we have app.py for running my application, requirements.txt that contains the list of packages that we will use, the model folder that consists of the pre-trained model, and the Dockerfile for building a docker image." }, { "code": null, "e": 3344, "s": 3192, "text": "Please remember that when you create the Dockerfile, make sure that you don’t give any extension after the file name. You must write ‘Dockerfile’ only." }, { "code": null, "e": 3425, "s": 3344, "text": "Now let’s write our Dockerfile script. Here is the script inside the Dockerfile:" }, { "code": null, "e": 3465, "s": 3425, "text": "Let me explain each line of the script:" }, { "code": null, "e": 3602, "s": 3465, "text": "The ‘FROM’ instruction will take a docker image from a docker registry. The image will contain the operating system and also the Python." }, { "code": null, "e": 3708, "s": 3602, "text": "The ‘WORKDIR’ instruction will set the default working directory that we will use to run the application." }, { "code": null, "e": 3820, "s": 3708, "text": "The ‘COPY’ instruction will copy every single file inside the current directory into the new working directory." }, { "code": null, "e": 3903, "s": 3820, "text": "The ‘RUN’ instruction will run a command. In this case, the ‘pip install’ command." }, { "code": null, "e": 3988, "s": 3903, "text": "The ‘EXPOSE’ instruction will expose port 5000 as the connector to the docker image." }, { "code": null, "e": 4078, "s": 3988, "text": "Finally, the ‘CMD’ instruction will run a command. In this case, the ‘flask run’ command." }, { "code": null, "e": 4206, "s": 4078, "text": "Side Note: The ‘CMD’ instruction has the same function as the ‘RUN’ instruction, but they are different based on their purpose." }, { "code": null, "e": 4299, "s": 4206, "text": "The ‘CMD’ instruction is used for running a command when you start running the docker image." }, { "code": null, "e": 4403, "s": 4299, "text": "Meanwhile, the ‘RUN’ instruction is used for running a command while you are building the docker image." }, { "code": null, "e": 4582, "s": 4403, "text": "After you create the docker image, the next step is to build the image. To build the image, it’s really simple. All you need to do is to run the ‘docker build’ command like this:" }, { "code": null, "e": 4609, "s": 4582, "text": "docker build -t my-image ." }, { "code": null, "e": 4818, "s": 4609, "text": "As you can see above, I give the ‘-t’ tag beside the ‘docker build’ command. The ‘-t’ tag takes two arguments. They are the image name and also the dot character, which represents all files inside the folder." }, { "code": null, "e": 4920, "s": 4818, "text": "Here is the preview when we are building the docker image (It will take a long time, so be patient) :" }, { "code": null, "e": 5048, "s": 4920, "text": "Let’s run the ‘docker images’ command to display the existing images that are already built. Here is the preview of the result:" }, { "code": null, "e": 5229, "s": 5048, "text": "As you can see from above, the image already exists. Now the next step is to run the docker image on our computer. To run the image, you can use the command ‘docker run’ like this," }, { "code": null, "e": 5263, "s": 5229, "text": "docker run -dp 5000:5000 my-image" }, { "code": null, "e": 5440, "s": 5263, "text": "Let’s wait for a while for 3 to 5 minutes. To know whether our image is already running, we can use the ‘docker ps -a’ command to check all running images. Here is the preview:" }, { "code": null, "e": 5652, "s": 5440, "text": "As you can see from above, the image is already up about a minute. It means that the image is already running at port 5000. Now let’s access the image using localhost:5000 or 127.0.0.1:5000. Here is the preview:" }, { "code": null, "e": 5809, "s": 5652, "text": "As you can see from above, our container has run successfully on our computer. Because you set the ‘-d’ parameter, you cannot show the log of the container." }, { "code": null, "e": 6023, "s": 5809, "text": "To check activities on a container, you can use ‘docker logs’ for doing that. Also, please set the container id beside it. You can see the container id from the ‘docker ps -a’ command. The command looks like this:" }, { "code": null, "e": 6048, "s": 6023, "text": "docker logs bff6d3c8e2da" }, { "code": null, "e": 6089, "s": 6048, "text": "Here is what the log preview looks like:" }, { "code": null, "e": 6246, "s": 6089, "text": "If you want to stop the container, you can use the ‘docker kill’ command and set the container id beside it. Here is the command to stop the docker command:" }, { "code": null, "e": 6271, "s": 6246, "text": "docker kill bff6d3c8e2da" }, { "code": null, "e": 6325, "s": 6271, "text": "After you stop the container, it will look like this," }, { "code": null, "e": 6368, "s": 6325, "text": "Yes, our container has already terminated." }, { "code": null, "e": 6530, "s": 6368, "text": "Well done! You have learned how to containerize your application as a docker image. I hope this article helps you to build your own docker image on your project." }, { "code": null, "e": 6706, "s": 6530, "text": "If you are interested in this article, you can follow me on Medium to get articles like this. If you have any questions or want to say hi, you can connect with me on LinkedIn." }, { "code": null, "e": 6740, "s": 6706, "text": "Thank you for reading my article!" } ]
How to turn on Flash light programmatically in android?
This example demonstrates how do I turn on Flash light programatically 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:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical"> <ToggleButton android:id="@+id/onOffFlashlight" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textOn="Turn Off" android:textOff="Turn On" android:checked="false" android:text="Turn On/Off Camera LED/ Flashlight Android" /> </LinearLayout> Step 3 − Add the following code to src/MainActivity.java import android.content.Context; import android.content.DialogInterface; import android.content.pm.PackageManager; import android.hardware.camera2.CameraAccessException; import android.hardware.camera2.CameraManager; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.widget.CompoundButton; import android.widget.ToggleButton; public class MainActivity extends AppCompatActivity { private CameraManager mCameraManager; private String mCameraId; private ToggleButton toggleButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); boolean isFlashAvailable = getApplicationContext().getPackageManager() .hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT); if (!isFlashAvailable) { showNoFlashError(); } mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE); try { mCameraId = mCameraManager.getCameraIdList()[0]; } catch (CameraAccessException e) { e.printStackTrace(); } toggleButton = findViewById(R.id.onOffFlashlight); toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { switchFlashLight(isChecked); } }); } public void showNoFlashError() { AlertDialog alert = new AlertDialog.Builder(this) .create(); alert.setTitle("Oops!"); alert.setMessage("Flash not available in this device..."); alert.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }); alert.show(); } public void switchFlashLight(boolean status) { try { mCameraManager.setTorchMode(mCameraId, status); } catch (CameraAccessException e) { e.printStackTrace(); } } } Step 4 - Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <uses-permission android:name="android.permission.CAMERA" /> <uses-feature android:name="android.hardware.camera.flash" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run Icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
[ { "code": null, "e": 1145, "s": 1062, "text": "This example demonstrates how do I turn on Flash light programatically in android." }, { "code": null, "e": 1274, "s": 1145, "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": 1339, "s": 1274, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1913, "s": 1339, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:gravity=\"center\"\n android:orientation=\"vertical\">\n\n <ToggleButton\n android:id=\"@+id/onOffFlashlight\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:textOn=\"Turn Off\"\n android:textOff=\"Turn On\"\n android:checked=\"false\"\n android:text=\"Turn On/Off Camera LED/ Flashlight Android\" />\n</LinearLayout>" }, { "code": null, "e": 1970, "s": 1913, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 4115, "s": 1970, "text": "import android.content.Context;\nimport android.content.DialogInterface;\nimport android.content.pm.PackageManager;\nimport android.hardware.camera2.CameraAccessException;\nimport android.hardware.camera2.CameraManager;\nimport android.os.Bundle;\nimport android.support.v7.app.AlertDialog;\nimport android.support.v7.app.AppCompatActivity;\nimport android.widget.CompoundButton;\nimport android.widget.ToggleButton;\n\npublic class MainActivity extends AppCompatActivity {\n\n private CameraManager mCameraManager;\n private String mCameraId;\n private ToggleButton toggleButton;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n boolean isFlashAvailable = getApplicationContext().getPackageManager()\n .hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT);\n\n if (!isFlashAvailable) {\n showNoFlashError();\n }\n\n mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);\n try {\n mCameraId = mCameraManager.getCameraIdList()[0];\n } catch (CameraAccessException e) {\n e.printStackTrace();\n }\n\n toggleButton = findViewById(R.id.onOffFlashlight);\n toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {\n @Override\n public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {\n switchFlashLight(isChecked);\n }\n });\n }\n\n public void showNoFlashError() {\n AlertDialog alert = new AlertDialog.Builder(this)\n .create();\n alert.setTitle(\"Oops!\");\n alert.setMessage(\"Flash not available in this device...\");\n alert.setButton(DialogInterface.BUTTON_POSITIVE, \"OK\", new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int which) {\n finish();\n }\n });\n alert.show();\n }\n\n public void switchFlashLight(boolean status) {\n try {\n mCameraManager.setTorchMode(mCameraId, status);\n } catch (CameraAccessException e) {\n e.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 4170, "s": 4115, "text": "Step 4 - Add the following code to androidManifest.xml" }, { "code": null, "e": 4974, "s": 4170, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.sample\">\n\n <uses-permission android:name=\"android.permission.CAMERA\" />\n <uses-feature android:name=\"android.hardware.camera.flash\" />\n\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 5321, "s": 4974, "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 –" } ]
CSS Image Opacity / Transparency
The opacity property specifies the opacity/transparency of an element. The opacity property can take a value from 0.0 - 1.0. The lower value, the more transparent: opacity 0.2 opacity 0.5 opacity 1(default) The opacity property is often used together with the :hover selector to change the opacity on mouse-over: The first CSS block is similar to the code in Example 1. In addition, we have added what should happen when a user hovers over one of the images. In this case we want the image to NOT be transparent when the user hovers over it. The CSS for this is opacity:1;. When the mouse pointer moves away from the image, the image will be transparent again. An example of reversed hover effect: When using the opacity property to add transparency to the background of an element, all of its child elements inherit the same transparency. This can make the text inside a fully transparent element hard to read: opacity 1 opacity 0.6 opacity 0.3 opacity 0.1 If you do not want to apply opacity to child elements, like in our example above, use RGBA color values. The following example sets the opacity for the background color and not the text: 100% opacity 60% opacity 30% opacity 10% opacity You learned from our CSS Colors Chapter, that you can use RGB as a color value. In addition to RGB, you can use an RGB color value with an alpha channel (RGBA) - which specifies the opacity for a color. An RGBA color value is specified with: rgba(red, green, blue, alpha). The alpha parameter is a number between 0.0 (fully transparent) and 1.0 (fully opaque). Tip: You will learn more about RGBA Colors in our CSS Colors Chapter. This is some text that is placed in the transparent box. First, we create a <div> element (class="background") with a background image, and a border. Then we create another <div> (class="transbox") inside the first <div>. The <div class="transbox"> have a background color, and a border - the div is transparent. Inside the transparent <div>, we add some text inside a <p> element. Use CSS to set the transparency of the image to 50%. <style> img { : ; } </style> <body> <img src="klematis.jpg" width="150" height="113"> </body> 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": 71, "s": 0, "text": "The opacity property specifies the opacity/transparency of an element." }, { "code": null, "e": 164, "s": 71, "text": "The opacity property can take a value from 0.0 - 1.0. The lower value, the more transparent:" }, { "code": null, "e": 176, "s": 164, "text": "opacity 0.2" }, { "code": null, "e": 188, "s": 176, "text": "opacity 0.5" }, { "code": null, "e": 207, "s": 188, "text": "opacity 1(default)" }, { "code": null, "e": 314, "s": 207, "text": "The opacity property is often used together with the :hover \nselector to change the opacity on mouse-over:" }, { "code": null, "e": 575, "s": 314, "text": "The first CSS block is similar to the code in Example 1. In addition, we have added what should happen when a user hovers over one of the images. In this case we want the image to NOT be transparent when the user hovers over it. The CSS for this is opacity:1;." }, { "code": null, "e": 662, "s": 575, "text": "When the mouse pointer moves away from the image, the image will be transparent again." }, { "code": null, "e": 699, "s": 662, "text": "An example of reversed hover effect:" }, { "code": null, "e": 914, "s": 699, "text": "When using the opacity property to add transparency to the background of an element, all of its child elements \ninherit the same transparency. This can make the text inside a fully transparent element hard to read:" }, { "code": null, "e": 924, "s": 914, "text": "opacity 1" }, { "code": null, "e": 936, "s": 924, "text": "opacity 0.6" }, { "code": null, "e": 948, "s": 936, "text": "opacity 0.3" }, { "code": null, "e": 960, "s": 948, "text": "opacity 0.1" }, { "code": null, "e": 1148, "s": 960, "text": "If you do not want to apply opacity to child elements, like in our example above, use RGBA color values. \nThe following example sets the opacity for the background color and not the text:" }, { "code": null, "e": 1161, "s": 1148, "text": "100% opacity" }, { "code": null, "e": 1173, "s": 1161, "text": "60% opacity" }, { "code": null, "e": 1185, "s": 1173, "text": "30% opacity" }, { "code": null, "e": 1197, "s": 1185, "text": "10% opacity" }, { "code": null, "e": 1401, "s": 1197, "text": "You learned from our CSS Colors Chapter, that you can use RGB as a color value. In addition to RGB, \nyou can use an RGB color value with an alpha channel (RGBA) - which specifies the opacity for a color." }, { "code": null, "e": 1560, "s": 1401, "text": "An RGBA color value is specified with: rgba(red, green, blue, alpha). The \nalpha parameter is a number between 0.0 (fully transparent) and 1.0 (fully opaque)." }, { "code": null, "e": 1630, "s": 1560, "text": "Tip: You will learn more about RGBA Colors in our CSS Colors Chapter." }, { "code": null, "e": 1687, "s": 1630, "text": "This is some text that is placed in the transparent box." }, { "code": null, "e": 1781, "s": 1687, "text": "First, we create a <div> element (class=\"background\") with a background image, and a border.\n" }, { "code": null, "e": 1854, "s": 1781, "text": "Then we create another <div> (class=\"transbox\") inside the first <div>. " }, { "code": null, "e": 1948, "s": 1854, "text": "The \n<div class=\"transbox\"> have a background color, and a border - \nthe div is transparent. " }, { "code": null, "e": 2018, "s": 1948, "text": "Inside the transparent \n<div>, we add some text inside a <p> element." }, { "code": null, "e": 2071, "s": 2018, "text": "Use CSS to set the transparency of the image to 50%." }, { "code": null, "e": 2171, "s": 2071, "text": "<style>\nimg {\n : ;\n}\n</style>\n\n<body>\n <img src=\"klematis.jpg\" width=\"150\" height=\"113\">\n</body>\n" }, { "code": null, "e": 2190, "s": 2171, "text": "Start the Exercise" }, { "code": null, "e": 2223, "s": 2190, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 2265, "s": 2223, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 2372, "s": 2265, "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": 2391, "s": 2372, "text": "[email protected]" } ]
Data Ops – Git Actions & Terraform for Data Engineers & Scientists — GCP/AWS/Azure | by Gagandeep Singh | Towards Data Science
I strongly believe in POCing a new design or code template and get it review by other engineers because you never know what efficient nuances you are missing and it is always good to have a fresh set of eyes reviewing the code. And I tend to make POC as near to MVP (Minimum viable product) as possible to make myself and the team more confident of the design and to not waste any time in Regression testing later. It also helps in estimating my delivery task better and more accurately. But issues arise when I have to be dependent upon the DevOps team to ‘Infrastructure as code’ (IAC) my project in the dev environment. In the Prod environment, it is desirable to involve them in DevOps the infrastructure based on the best practices they have learned but in Dev, it can derail your MVP by just waiting for them to prioritize your task. So a couple of years ago I started learning DevOps/DataOps and I started with Cloudformation (CFN) and Atlassian Bamboo since I was mostly working on AWS and the organization was using Bamboo. But lately, I got the chance to get my hands dirty in Terraform (TF) and Github Actions, because I was required to work on GCP, and dear oh dear it is way too easy to grasp and good to learn because with TF and Actions you can deploy in any cloud. And for a Data Engineer or Scientist or Analyst, it becomes really handy if you know an IAC tool. Since Github Actions sit closer to your code, it becomes all the more convenient for me. So, I will break this down into 3 easy sections: Integrating TF cloud to GithubGithub Actions workflow to run TF stepsOverview of TF files based on Best Practices Integrating TF cloud to Github Github Actions workflow to run TF steps Overview of TF files based on Best Practices Step 1: First thing first, TF has a community version so go ahead and create an account there. Here is the link: https://www.terraform.io/cloud. It will ask you to confirm your email address and everything so I am assuming that is done at the end of this step. Also, to complete the steps, it would be really great if you have your own account in the GCP or for that matter in any of the cloud. And your own Github account. Step 2: TF has its hierarchy where each Organization has multiple workspaces and each Workspace has a one-to-one mapping with your IAC Github branch in repo where you will be pushing the updated Terraform files (Best practice). Files are written in Hashicorp Configuration Language (HCL) which is somewhat similar to YAML. So the idea is, whenever you will push a new update (or merge a PR) to a Github branch, Github-actions will execute and run the plan with a new changeset on TF cloud. Since TF cloud is linked to GCP (later), it will update the resource in GCP. Create an organization and workspace inside of it in your Terraform community account. Step 3: Assumingly, you have your own GCP account, create a service account in your project where you want the resource to be deployed, copy its key and put it in environment variable as GOOGLE_CREDENTIALS in Terraform variable. If you are using AWS then you need to put AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY. This GCP Service account will be used to deploy the resource so it should have an Edit role or access level that has authority to deploy the resource. You can also create a secret in Github secrets as shown below and pass the Credentials from there by using ${{ secrets.GOOGLE_CREDENTIALS }} in Github Actions as I did below. Step 4: While creating a workspace, it will let you choose the github repo so that it can authenticate with it internally otherwise you have to generate a token in Terraform and save it in Github secrets to be used in ‘Setup Terraform’ step in Github actions. The following Github actions script needs to be put in .github/workflow/ folder as anyname.yml. This has sequential steps in a particular job on what to do when someone pushes a new change in the repo. In the following, github actions will use bash in ubuntu-latest to checkout the code, setup terraform and run terraform init, plan and apply. name: 'Terraform CI'on: push: branches: - main pull_request:jobs: terraform: name: 'Terraform' runs-on: ubuntu-latest# Use the Bash shell regardless whether the GitHub Actions runner is ubuntu-latest, macos-latest, or windows-latest defaults: run: shell: bashsteps: # Checkout the repository to the GitHub Actions runner - name: Checkout uses: actions/checkout@v2# Install the latest version of Terraform CLI and configure the Terraform CLI configuration file with a Terraform Cloud user API token - name: Setup Terraform uses: hashicorp/setup-terraform@v1# Initialize a new or existing Terraform working directory by creating initial files, loading any remote state, downloading modules, etc. - name: Terraform Init run: terraform init env: GOOGLE_CREDENTIALS: ${{ secrets.GOOGLE_CREDENTIALS }}# Checks that all Terraform configuration files adhere to a canonical format# - name: Terraform Format# run: terraform fmt -check# Generates an execution plan for Terraform - name: Terraform Plan run: terraform plan env: GOOGLE_CREDENTIALS: ${{ secrets.GOOGLE_CREDENTIALS }}# On push to main, build or change infrastructure according to Terraform configuration files # && github.event_name == 'push' # Note: It is recommended to set up a required "strict" status check in your repository for "Terraform Cloud". See the documentation on "strict" required status checks for more information: https://help.github.com/en/github/administering-a-repository/types-of-required-status-checks - name: Terraform Apply if: github.ref == 'refs/heads/master' run: terraform apply -auto-approve env: GOOGLE_CREDENTIALS: ${{ secrets.GOOGLE_CREDENTIALS }} Now terraform only reads those files that have .tf extension to it or .tfvars but there are some files that it needs to be named as is whereas others are just resource abstraction and will be executed in the no order unless you mention the dependencies using depends_on. Main.tf, variables.tf and terraform.tfvars are the files that need to be created with the same name. main.tf: All the resources can be mentioned here with its appropriate configuration values. So for example if you want to create a storage bucket then it can be written in HCL as below: resource “google_storage_bucket” “bucket” { name = “dev-bucket-random-12345”} variables.tf: As the name suggests, it has variables like below with its default value which you want to re-use in other resources or .tf file like ${var.region}. This is more like a convention to put the variables in different variables.tf file but you can put it in main.tf too. variable “region” { type = string default = “australia-southeast1”} terraform.tfvars: This will have the actual values of the variables defined above. Essentially, if region is not mentioned below then it will take the above default value. project_id = “bstate-xxxx-yyyy”region = “australia-southeast1” The rest of the files are to abstract different types of resources into different files. For example networks.tf will have VPC and Subnet resources, stackdriver.tf will have alerts and monitoring dashboards, dataproc.tf will have cluster and nodes resources in it and similarly for firewalls, GKE, etc. For all those who don’t know, TF and CFN have documentation where these predefined functions or Resource configurations are there to help us understand what options mean. Following is of GCP: https://registry.terraform.io/providers/hashicorp/google/latest/docs In the following example, a monitoring channel is created for the Stackdriver alerts. All the fields are self-explanatory and come from the GCP Terraform documentation and with the help of the output variable ‘gsingh_id’, you can directly use it in any .tf file or if you don’t want to specify the output, you can directly use it like this: google_monitoring_notification_channel.gsingh resource "google_monitoring_notification_channel" "gsingh" { display_name = "[email protected]" type = "email" labels = { email_address = "[email protected]" }}output "gsingh_id" { value = "${google_monitoring_notification_channel.gsingh.name}"} Below a Subnet is getting created and VPC is specified as a dependency for the subnet in a similar fashion. resource "google_compute_subnetwork" "vpc_subnetwork" { name = "subnet-01" network = google_compute_network.vpc_network.self_link private_ip_google_access = true ip_cidr_range = "10.xx.xx.xx/19" region = "australia-southeast1" depends_on = [ google_compute_network.vpc_network, ]} Now as explained earlier, whenever you push a new change to this repo, Git actions will checkout the code from the master branch and run Terraform Init, Plan and Apply to deploy the changes in the cloud. In the next couple of days, I will be publishing a series of articles on how to Deploy a Flink application on GKE cluster through Git actions which will also let you know how to build a Scala app using Git Actions. So stay tuned.
[ { "code": null, "e": 1012, "s": 172, "text": "I strongly believe in POCing a new design or code template and get it review by other engineers because you never know what efficient nuances you are missing and it is always good to have a fresh set of eyes reviewing the code. And I tend to make POC as near to MVP (Minimum viable product) as possible to make myself and the team more confident of the design and to not waste any time in Regression testing later. It also helps in estimating my delivery task better and more accurately. But issues arise when I have to be dependent upon the DevOps team to ‘Infrastructure as code’ (IAC) my project in the dev environment. In the Prod environment, it is desirable to involve them in DevOps the infrastructure based on the best practices they have learned but in Dev, it can derail your MVP by just waiting for them to prioritize your task." }, { "code": null, "e": 1640, "s": 1012, "text": "So a couple of years ago I started learning DevOps/DataOps and I started with Cloudformation (CFN) and Atlassian Bamboo since I was mostly working on AWS and the organization was using Bamboo. But lately, I got the chance to get my hands dirty in Terraform (TF) and Github Actions, because I was required to work on GCP, and dear oh dear it is way too easy to grasp and good to learn because with TF and Actions you can deploy in any cloud. And for a Data Engineer or Scientist or Analyst, it becomes really handy if you know an IAC tool. Since Github Actions sit closer to your code, it becomes all the more convenient for me." }, { "code": null, "e": 1689, "s": 1640, "text": "So, I will break this down into 3 easy sections:" }, { "code": null, "e": 1803, "s": 1689, "text": "Integrating TF cloud to GithubGithub Actions workflow to run TF stepsOverview of TF files based on Best Practices" }, { "code": null, "e": 1834, "s": 1803, "text": "Integrating TF cloud to Github" }, { "code": null, "e": 1874, "s": 1834, "text": "Github Actions workflow to run TF steps" }, { "code": null, "e": 1919, "s": 1874, "text": "Overview of TF files based on Best Practices" }, { "code": null, "e": 2343, "s": 1919, "text": "Step 1: First thing first, TF has a community version so go ahead and create an account there. Here is the link: https://www.terraform.io/cloud. It will ask you to confirm your email address and everything so I am assuming that is done at the end of this step. Also, to complete the steps, it would be really great if you have your own account in the GCP or for that matter in any of the cloud. And your own Github account." }, { "code": null, "e": 2910, "s": 2343, "text": "Step 2: TF has its hierarchy where each Organization has multiple workspaces and each Workspace has a one-to-one mapping with your IAC Github branch in repo where you will be pushing the updated Terraform files (Best practice). Files are written in Hashicorp Configuration Language (HCL) which is somewhat similar to YAML. So the idea is, whenever you will push a new update (or merge a PR) to a Github branch, Github-actions will execute and run the plan with a new changeset on TF cloud. Since TF cloud is linked to GCP (later), it will update the resource in GCP." }, { "code": null, "e": 2997, "s": 2910, "text": "Create an organization and workspace inside of it in your Terraform community account." }, { "code": null, "e": 3313, "s": 2997, "text": "Step 3: Assumingly, you have your own GCP account, create a service account in your project where you want the resource to be deployed, copy its key and put it in environment variable as GOOGLE_CREDENTIALS in Terraform variable. If you are using AWS then you need to put AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY." }, { "code": null, "e": 3464, "s": 3313, "text": "This GCP Service account will be used to deploy the resource so it should have an Edit role or access level that has authority to deploy the resource." }, { "code": null, "e": 3639, "s": 3464, "text": "You can also create a secret in Github secrets as shown below and pass the Credentials from there by using ${{ secrets.GOOGLE_CREDENTIALS }} in Github Actions as I did below." }, { "code": null, "e": 3899, "s": 3639, "text": "Step 4: While creating a workspace, it will let you choose the github repo so that it can authenticate with it internally otherwise you have to generate a token in Terraform and save it in Github secrets to be used in ‘Setup Terraform’ step in Github actions." }, { "code": null, "e": 4243, "s": 3899, "text": "The following Github actions script needs to be put in .github/workflow/ folder as anyname.yml. This has sequential steps in a particular job on what to do when someone pushes a new change in the repo. In the following, github actions will use bash in ubuntu-latest to checkout the code, setup terraform and run terraform init, plan and apply." }, { "code": null, "e": 6004, "s": 4243, "text": "name: 'Terraform CI'on: push: branches: - main pull_request:jobs: terraform: name: 'Terraform' runs-on: ubuntu-latest# Use the Bash shell regardless whether the GitHub Actions runner is ubuntu-latest, macos-latest, or windows-latest defaults: run: shell: bashsteps: # Checkout the repository to the GitHub Actions runner - name: Checkout uses: actions/checkout@v2# Install the latest version of Terraform CLI and configure the Terraform CLI configuration file with a Terraform Cloud user API token - name: Setup Terraform uses: hashicorp/setup-terraform@v1# Initialize a new or existing Terraform working directory by creating initial files, loading any remote state, downloading modules, etc. - name: Terraform Init run: terraform init env: GOOGLE_CREDENTIALS: ${{ secrets.GOOGLE_CREDENTIALS }}# Checks that all Terraform configuration files adhere to a canonical format# - name: Terraform Format# run: terraform fmt -check# Generates an execution plan for Terraform - name: Terraform Plan run: terraform plan env: GOOGLE_CREDENTIALS: ${{ secrets.GOOGLE_CREDENTIALS }}# On push to main, build or change infrastructure according to Terraform configuration files # && github.event_name == 'push' # Note: It is recommended to set up a required \"strict\" status check in your repository for \"Terraform Cloud\". See the documentation on \"strict\" required status checks for more information: https://help.github.com/en/github/administering-a-repository/types-of-required-status-checks - name: Terraform Apply if: github.ref == 'refs/heads/master' run: terraform apply -auto-approve env: GOOGLE_CREDENTIALS: ${{ secrets.GOOGLE_CREDENTIALS }}" }, { "code": null, "e": 6376, "s": 6004, "text": "Now terraform only reads those files that have .tf extension to it or .tfvars but there are some files that it needs to be named as is whereas others are just resource abstraction and will be executed in the no order unless you mention the dependencies using depends_on. Main.tf, variables.tf and terraform.tfvars are the files that need to be created with the same name." }, { "code": null, "e": 6562, "s": 6376, "text": "main.tf: All the resources can be mentioned here with its appropriate configuration values. So for example if you want to create a storage bucket then it can be written in HCL as below:" }, { "code": null, "e": 6644, "s": 6562, "text": "resource “google_storage_bucket” “bucket” { name = “dev-bucket-random-12345”}" }, { "code": null, "e": 6925, "s": 6644, "text": "variables.tf: As the name suggests, it has variables like below with its default value which you want to re-use in other resources or .tf file like ${var.region}. This is more like a convention to put the variables in different variables.tf file but you can put it in main.tf too." }, { "code": null, "e": 7001, "s": 6925, "text": "variable “region” { type = string default = “australia-southeast1”}" }, { "code": null, "e": 7173, "s": 7001, "text": "terraform.tfvars: This will have the actual values of the variables defined above. Essentially, if region is not mentioned below then it will take the above default value." }, { "code": null, "e": 7236, "s": 7173, "text": "project_id = “bstate-xxxx-yyyy”region = “australia-southeast1”" }, { "code": null, "e": 7539, "s": 7236, "text": "The rest of the files are to abstract different types of resources into different files. For example networks.tf will have VPC and Subnet resources, stackdriver.tf will have alerts and monitoring dashboards, dataproc.tf will have cluster and nodes resources in it and similarly for firewalls, GKE, etc." }, { "code": null, "e": 7800, "s": 7539, "text": "For all those who don’t know, TF and CFN have documentation where these predefined functions or Resource configurations are there to help us understand what options mean. Following is of GCP: https://registry.terraform.io/providers/hashicorp/google/latest/docs" }, { "code": null, "e": 8187, "s": 7800, "text": "In the following example, a monitoring channel is created for the Stackdriver alerts. All the fields are self-explanatory and come from the GCP Terraform documentation and with the help of the output variable ‘gsingh_id’, you can directly use it in any .tf file or if you don’t want to specify the output, you can directly use it like this: google_monitoring_notification_channel.gsingh" }, { "code": null, "e": 8433, "s": 8187, "text": "resource \"google_monitoring_notification_channel\" \"gsingh\" { display_name = \"[email protected]\" type = \"email\" labels = { email_address = \"[email protected]\" }}output \"gsingh_id\" { value = \"${google_monitoring_notification_channel.gsingh.name}\"}" }, { "code": null, "e": 8541, "s": 8433, "text": "Below a Subnet is getting created and VPC is specified as a dependency for the subnet in a similar fashion." }, { "code": null, "e": 8854, "s": 8541, "text": "resource \"google_compute_subnetwork\" \"vpc_subnetwork\" { name = \"subnet-01\" network = google_compute_network.vpc_network.self_link private_ip_google_access = true ip_cidr_range = \"10.xx.xx.xx/19\" region = \"australia-southeast1\" depends_on = [ google_compute_network.vpc_network, ]}" } ]
Scikit Learn - Multinomial Naà ̄ve Bayes
It is another useful Naïve Bayes classifier. It assumes that the features are drawn from a simple Multinomial distribution. The Scikit-learn provides sklearn.naive_bayes.MultinomialNB to implement the Multinomial Naïve Bayes algorithm for classification. Following table consist the parameters used by sklearn.naive_bayes.MultinomialNB method − alpha − float, optional, default = 1.0 It represents the additive smoothing parameter. If you choose 0 as its value, then there will be no smoothing. fit_prior − Boolean, optional, default = true It tells the model that whether to learn class prior probabilities or not. The default value is True but if set to False, the algorithms will use a uniform prior. class_prior − array-like, size(n_classes,), optional, Default = None This parameter represents the prior probabilities of each class. Following table consist the attributes used by sklearn.naive_bayes.MultinomialNB method − class_log_prior_ − array, shape(n_classes,) It provides the smoothed log probability for every class. class_count_ − array, shape(n_classes,) It provides the actual number of training samples encountered for each class. intercept_ − array, shape (n_classes,) These are the Mirrors class_log_prior_ for interpreting MultinomilaNB model as a linear model. feature_log_prob_ − array, shape (n_classes, n_features) It gives the empirical log probability of features given a class P(features⏐Y). coef_ − array, shape (n_classes, n_features) These are the Mirrors feature_log_prior_ for interpreting MultinomilaNB model as a linear model. feature_count_ − array, shape (n_classes, n_features) It provides the actual number of training samples encountered for each (class,feature). The methods of sklearn.naive_bayes. MultinomialNB are same as we have used in sklearn.naive_bayes.GaussianNB. The Python script below will use sklearn.naive_bayes.GaussianNB method to construct Gaussian Naïve Bayes Classifier from our data set − import numpy as np X = np.random.randint(8, size = (8, 100)) y = np.array([1, 2, 3, 4, 5, 6, 7, 8]) from sklearn.naive_bayes import MultinomialNB MNBclf = MultinomialNB() MNBclf.fit(X, y) MultinomialNB(alpha = 1.0, class_prior = None, fit_prior = True) Now, once fitted we can predict the new value aby using predict() method as follows − print((MNBclf.predict(X[4:5])) [5] 11 Lectures 2 hours PARTHA MAJUMDAR Print Add Notes Bookmark this page
[ { "code": null, "e": 2478, "s": 2221, "text": "It is another useful Naïve Bayes classifier. It assumes that the features are drawn from a simple Multinomial distribution. The Scikit-learn provides sklearn.naive_bayes.MultinomialNB to implement the Multinomial Naïve Bayes algorithm for classification." }, { "code": null, "e": 2568, "s": 2478, "text": "Following table consist the parameters used by sklearn.naive_bayes.MultinomialNB method −" }, { "code": null, "e": 2607, "s": 2568, "text": "alpha − float, optional, default = 1.0" }, { "code": null, "e": 2718, "s": 2607, "text": "It represents the additive smoothing parameter. If you choose 0 as its value, then there will be no smoothing." }, { "code": null, "e": 2764, "s": 2718, "text": "fit_prior − Boolean, optional, default = true" }, { "code": null, "e": 2927, "s": 2764, "text": "It tells the model that whether to learn class prior probabilities or not. The default value is True but if set to False, the algorithms will use a uniform prior." }, { "code": null, "e": 2996, "s": 2927, "text": "class_prior − array-like, size(n_classes,), optional, Default = None" }, { "code": null, "e": 3061, "s": 2996, "text": "This parameter represents the prior probabilities of each class." }, { "code": null, "e": 3151, "s": 3061, "text": "Following table consist the attributes used by sklearn.naive_bayes.MultinomialNB method −" }, { "code": null, "e": 3195, "s": 3151, "text": "class_log_prior_ − array, shape(n_classes,)" }, { "code": null, "e": 3253, "s": 3195, "text": "It provides the smoothed log probability for every class." }, { "code": null, "e": 3293, "s": 3253, "text": "class_count_ − array, shape(n_classes,)" }, { "code": null, "e": 3371, "s": 3293, "text": "It provides the actual number of training samples encountered for each class." }, { "code": null, "e": 3410, "s": 3371, "text": "intercept_ − array, shape (n_classes,)" }, { "code": null, "e": 3505, "s": 3410, "text": "These are the Mirrors class_log_prior_ for interpreting MultinomilaNB model as a linear model." }, { "code": null, "e": 3562, "s": 3505, "text": "feature_log_prob_ − array, shape (n_classes, n_features)" }, { "code": null, "e": 3642, "s": 3562, "text": "It gives the empirical log probability of features given a class P(features⏐Y)." }, { "code": null, "e": 3687, "s": 3642, "text": "coef_ − array, shape (n_classes, n_features)" }, { "code": null, "e": 3784, "s": 3687, "text": "These are the Mirrors feature_log_prior_ for interpreting MultinomilaNB model as a linear model." }, { "code": null, "e": 3838, "s": 3784, "text": "feature_count_ − array, shape (n_classes, n_features)" }, { "code": null, "e": 3926, "s": 3838, "text": "It provides the actual number of training samples encountered for each (class,feature)." }, { "code": null, "e": 4036, "s": 3926, "text": "The methods of sklearn.naive_bayes. MultinomialNB are same as we have used in sklearn.naive_bayes.GaussianNB." }, { "code": null, "e": 4173, "s": 4036, "text": "The Python script below will use sklearn.naive_bayes.GaussianNB method to construct Gaussian Naïve Bayes Classifier from our data set −" }, { "code": null, "e": 4362, "s": 4173, "text": "import numpy as np\nX = np.random.randint(8, size = (8, 100))\ny = np.array([1, 2, 3, 4, 5, 6, 7, 8])\n\nfrom sklearn.naive_bayes import MultinomialNB\nMNBclf = MultinomialNB()\nMNBclf.fit(X, y)" }, { "code": null, "e": 4427, "s": 4362, "text": "MultinomialNB(alpha = 1.0, class_prior = None, fit_prior = True)" }, { "code": null, "e": 4513, "s": 4427, "text": "Now, once fitted we can predict the new value aby using predict() method as follows −" }, { "code": null, "e": 4544, "s": 4513, "text": "print((MNBclf.predict(X[4:5]))" }, { "code": null, "e": 4548, "s": 4544, "text": "[5]" }, { "code": null, "e": 4581, "s": 4548, "text": "\n 11 Lectures \n 2 hours \n" }, { "code": null, "e": 4598, "s": 4581, "text": " PARTHA MAJUMDAR" }, { "code": null, "e": 4605, "s": 4598, "text": " Print" }, { "code": null, "e": 4616, "s": 4605, "text": " Add Notes" } ]
How to compare dates in JavaScript?
Dates can be compared easily in javascript. The dates can belong to any frame i.e past, present and future. Past dates can be compared to future or future dates can be compared to the present. In the following example, a date in the year 2000 is compared with today's date and the respective message is displayed in the output. Live Demo <html> <body> <p id="compare"></p> <script> var today = new Date(); var otherday = new Date(); otherday.setFullYear(2000, 2, 14); if (otherday > today) { var msg = "The date you provided is a future date "; } else { var msg = "The date you provided is a past date"; } document.getElementById("compare").innerHTML = msg; </script> </body> </html> The date you provided is a past date In the following example, a date in the year 2900 is compared with today's date and the respective message is displayed in the output. Live Demo <html> <body> <p id="compare"> </p> <script> var today = new Date(); var otherday = new Date(); otherday.setFullYear(2900, 2, 14); if (otherday > today) { var msg = "The date you provided is a future date "; } else { var msg = "The date you provided is a past date"; } document.getElementById("compare").innerHTML = msg; </script> </body> </html> The date you provided is a future date
[ { "code": null, "e": 1256, "s": 1062, "text": "Dates can be compared easily in javascript. The dates can belong to any frame i.e past, present and future. Past dates can be compared to future or future dates can be compared to the present. " }, { "code": null, "e": 1392, "s": 1256, "text": "In the following example, a date in the year 2000 is compared with today's date and the respective message is displayed in the output. " }, { "code": null, "e": 1402, "s": 1392, "text": "Live Demo" }, { "code": null, "e": 1785, "s": 1402, "text": "<html>\n<body>\n <p id=\"compare\"></p>\n<script>\n var today = new Date();\n var otherday = new Date();\n otherday.setFullYear(2000, 2, 14);\n if (otherday > today) {\n var msg = \"The date you provided is a future date \";\n } else {\n var msg = \"The date you provided is a past date\";\n }\n document.getElementById(\"compare\").innerHTML = msg;\n</script>\n</body>\n</html>" }, { "code": null, "e": 1822, "s": 1785, "text": "The date you provided is a past date" }, { "code": null, "e": 1958, "s": 1822, "text": "In the following example, a date in the year 2900 is compared with today's date and the respective message is displayed in the output. " }, { "code": null, "e": 1968, "s": 1958, "text": "Live Demo" }, { "code": null, "e": 2352, "s": 1968, "text": "<html>\n<body>\n <p id=\"compare\"> </p>\n<script>\n var today = new Date();\n var otherday = new Date();\n otherday.setFullYear(2900, 2, 14);\n if (otherday > today) {\n var msg = \"The date you provided is a future date \";\n } else {\n var msg = \"The date you provided is a past date\";\n }\n document.getElementById(\"compare\").innerHTML = msg;\n</script>\n</body>\n</html>" }, { "code": null, "e": 2391, "s": 2352, "text": "The date you provided is a future date" } ]
Elixir - Environment
In order to run Elixir, you need to set it up locally on your system. To install Elixir, you will first require Erlang. On some platforms, Elixir packages come with Erlang in them. Let us now understand the installation of Elixir in different Operating Systems. To install Elixir on windows, download installer from https://repo.hex.pm/elixirwebsetup.exe and simply click Next to proceed through all steps. You will have it on your local system. If you have any problems while installing it, you can check this page for more info. If you have Homebrew installed, make sure that it is the latest version. For updating, use the following command − brew update Now, install Elixir using the command given below − brew install elixir The steps to install Elixir in an Ubuntu/Debian setup is as follows − Add Erlang Solutions repo − wget https://packages.erlang-solutions.com/erlang-solutions_1.0_all.deb && sudo dpkg -i erlang-solutions_1.0_all.deb sudo apt-get update Install the Erlang/OTP platform and all of its applications − sudo apt-get install esl-erlang Install Elixir − sudo apt-get install elixir If you have any other Linux distribution, please visit this page to set up elixir on your local system. To test the Elixir setup on your system, open your terminal and enter iex in it. It will open the interactive elixir shell like the following − Erlang/OTP 19 [erts-8.0] [source-6dc93c1] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false] Interactive Elixir (1.3.1) - press Ctrl+C to exit (type h() ENTER for help) iex(1)> Elixir is now successfully set up on your system. 35 Lectures 3 hours Pranjal Srivastava 54 Lectures 6 hours Pranjal Srivastava, Harshit Srivastava 80 Lectures 9.5 hours Pranjal Srivastava 43 Lectures 4 hours Mohammad Nauman Print Add Notes Bookmark this page
[ { "code": null, "e": 2252, "s": 2182, "text": "In order to run Elixir, you need to set it up locally on your system." }, { "code": null, "e": 2363, "s": 2252, "text": "To install Elixir, you will first require Erlang. On some platforms, Elixir packages come with Erlang in them." }, { "code": null, "e": 2444, "s": 2363, "text": "Let us now understand the installation of Elixir in different Operating Systems." }, { "code": null, "e": 2628, "s": 2444, "text": "To install Elixir on windows, download installer from https://repo.hex.pm/elixirwebsetup.exe and simply click Next to proceed through all steps. You will have it on your local system." }, { "code": null, "e": 2713, "s": 2628, "text": "If you have any problems while installing it, you can check this page for more info." }, { "code": null, "e": 2828, "s": 2713, "text": "If you have Homebrew installed, make sure that it is the latest version. For updating, use the following command −" }, { "code": null, "e": 2841, "s": 2828, "text": "brew update\n" }, { "code": null, "e": 2893, "s": 2841, "text": "Now, install Elixir using the command given below −" }, { "code": null, "e": 2914, "s": 2893, "text": "brew install elixir\n" }, { "code": null, "e": 2984, "s": 2914, "text": "The steps to install Elixir in an Ubuntu/Debian setup is as follows −" }, { "code": null, "e": 3012, "s": 2984, "text": "Add Erlang Solutions repo −" }, { "code": null, "e": 3153, "s": 3012, "text": "wget https://packages.erlang-solutions.com/erlang-solutions_1.0_all.deb && sudo \ndpkg -i erlang-solutions_1.0_all.deb \nsudo apt-get update \n" }, { "code": null, "e": 3215, "s": 3153, "text": "Install the Erlang/OTP platform and all of its applications −" }, { "code": null, "e": 3249, "s": 3215, "text": "sudo apt-get install esl-erlang \n" }, { "code": null, "e": 3266, "s": 3249, "text": "Install Elixir −" }, { "code": null, "e": 3295, "s": 3266, "text": "sudo apt-get install elixir\n" }, { "code": null, "e": 3399, "s": 3295, "text": "If you have any other Linux distribution, please visit this page to set up elixir on your local system." }, { "code": null, "e": 3543, "s": 3399, "text": "To test the Elixir setup on your system, open your terminal and enter iex in it. It will open the interactive elixir shell like the following −" }, { "code": null, "e": 3740, "s": 3543, "text": "Erlang/OTP 19 [erts-8.0] [source-6dc93c1] [64-bit] \n[smp:4:4] [async-threads:10] [hipe] [kernel-poll:false] \n\nInteractive Elixir (1.3.1) - press Ctrl+C to exit (type h() ENTER for help) \niex(1)>\n" }, { "code": null, "e": 3790, "s": 3740, "text": "Elixir is now successfully set up on your system." }, { "code": null, "e": 3823, "s": 3790, "text": "\n 35 Lectures \n 3 hours \n" }, { "code": null, "e": 3843, "s": 3823, "text": " Pranjal Srivastava" }, { "code": null, "e": 3876, "s": 3843, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 3916, "s": 3876, "text": " Pranjal Srivastava, Harshit Srivastava" }, { "code": null, "e": 3951, "s": 3916, "text": "\n 80 Lectures \n 9.5 hours \n" }, { "code": null, "e": 3971, "s": 3951, "text": " Pranjal Srivastava" }, { "code": null, "e": 4004, "s": 3971, "text": "\n 43 Lectures \n 4 hours \n" }, { "code": null, "e": 4021, "s": 4004, "text": " Mohammad Nauman" }, { "code": null, "e": 4028, "s": 4021, "text": " Print" }, { "code": null, "e": 4039, "s": 4028, "text": " Add Notes" } ]
Computer vision and the ultimate pong AI | by Robin T. White, PhD | Towards Data Science
One of my favourite YouTuber’s, CodeBullet, once attempted to create a pong AI to rule them all. Sadly he ran into troubles, not because he isn’t capable but I don’t think his experience at the time had much in the way of computer vision. He is absolutely hilarious and I highly recommend you watch him (parental advisory is advised) if you are at all considering reading the rest of this post. Also he is a genius at what he does. Love you mate. See his video here. This seemed like a really fun and simple task so I had to give it a go. In this post I will outline some of the considerations I took that may help if you wish to work on any similar project, and I think I will try my hand at a few more of these, so if you like this type of thing consider following me. The nice thing about using computer vision is that I can just use a already built game and process the images. Having said that, we will be using the same game version as the one CodeBullet was using from ponggame.org. It also has a 2 player mode so I can play against my own AI; which I did, and it was hard... First things first, getting the screen. I wanted to make sure my frame rate was as fast as possible and for this I found MSS to be a great python package. With this I was easily maxing out at 60 fps and comparing this to PIL I was only getting about 20 fps. It returns as a numpy array so my life was complete. Working our way in order of simplicity, we need to define the paddle locations. This could be done in a few different ways but I thought the most obvious was to mask the area for each paddle and run connected components to find the paddle object. Here is a snippet of that code: def get_objects_in_masked_region(img, vertices, connectivity = 8): ''':return connected components with stats in masked region [0] retval number of total labels 0 is background [1] labels image [2] stats[0] leftmostx, [1] topmosty, [2] horizontal size, [3] vertical size, [4] area [3] centroids ''' mask = np.zeros_like(img) # fill the mask cv2.fillPoly(mask, [vertices], 255) # now only show the area that is the mask mask = cv2.bitwise_and(img, mask) conn = cv2.connectedComponentsWithStats(mask, connectivity, cv2.CV_16U) return conn In the above, ‘vertices’ is just a list of the coordinates that define the masked region. Once I have the object within each region I can get their centroid position or the bounding box. One thing to note is that OpenCV includes the background as the 0'th object in any connected component list, so in this case I always grabbed the second largest object. The result is below — the paddle on the right with the green centroid is the player / soon-to-be AI controlled paddle. Now that we have our output, we need an input. For this I turned to a useful package and someone else’s code — thanks StackOverflow. It uses ctypes to simulate keyboard presses and in this case, the game is played using the ‘k’ and ‘m’ keys. I got the Scan Codes here. After testing that it worked by just randomly moving up and down, we are good to start tracking. Next up is to identify and track the pong. Again, this could have been handled in several ways — one of which could have been to do object detection by using a template, however instead I again went with connected components and object properties, namely the area of the pong since it is the only object with it’s dimensions. I knew I would run into issues whenever the pong crossed or touched any of the other white objects but I also figured this was fine so long as I could track it the majority of the time. After all, it moves in a straight line. If you watch the video below you will see how the red circle marking the pong flickers. That is because it only finds it about 1 in every 2 frames. At 60 fps this really doesn’t matter. At this point we already have a working AI. If we just move the player paddle such that it is at the same y-position as the pong, it does a fairly good job. However, it does run into problems when the pong gets a good bounce going. The paddle is just too slow to keep up and needs to instead predict where the pong will be instead of just moving to where it currently is. This has already been implemented in the clips above but below is a comparison of the two methods. The difference isn’t huge but it is definitely a more consistent win with the right AI. To do this I first created a list of the positions for the pong. I kept this list at a length of just 5 for averaging sake, but more or less could be done. Probably don’t want more otherwise it takes longer to figure out it has changed directions. After getting the list of positions I used simple vector averaging to smooth out and obtain the direction vector — shown by the green arrow. This was also normalized to be a unit vector and then multiplied by a length for visualization purposes. Casting the ray is just an extension of this — making the forward projection longer. I then checked if the future positions were outside the boundary of the top and bottom area. If so, it just projects the position back into the play area. For the left and right sides, it calculates where that intersection will occur with the paddle x-position and fixes the x- and y-position to that point. This makes sure the paddle is targeting to the correct position. Without this it would often move too far. Here is the code for defining the ray that predicts the future position of the pong: def pong_ray(pong_pos, dir_vec, l_paddle, r_paddle, boundaries, steps = 250): future_pts_list = [] for i in range(steps): x_tmp = int(i * dir_vect[0] + pong_pos[0]) y_tmp = int(i * dir_vect[1] + pong_pos[1]) if y_tmp > boundaries[3]: #bottom y_end = int(2*boundaries[3] - y_tmp) x_end = x_tmp elif y_tmp < boundaries[2]: #top y_end = int(-1*y_tmp) x_end = x_tmp else: y_end = y_tmp ##stop where paddle can reach if x_tmp > r_paddle[0]: #right x_end = int(boundaries[1]) y_end = int(pong_pos[1] + ((boundaries[1] - pong_pos[0])/dir_vec[0])*dir_vec[1]) elif x_tmp < boundaries[0]: #left x_end = int(boundaries[0]) y_end = int(pong_pos[1] + ((boundaries[0] - pong_pos[0]) / dir_vec[0]) * dir_vec[1]) else: x_end = x_tmp end_pos = (x_end, y_end) future_pts_list.append(end_pos) return future_pts_list In the above the perhaps less obvious calculation is determining the intercept of left or right positions for the paddles to target. We do this essentially by similar triangles with the diagram and equation show below. We know the intercept with the x-position of the paddle which is given in boundaries. We can then calculate how far the pong will travel and add that to the current y-position. The paddles, although look straight, actually have a rebound surface that is curved. That is, if you hit the ball with the paddle towards the ends it will bounce as if the paddle was angled. I therefore allowed the paddle to hit at the edges which adds some offense to the AI, causing the pong to fly around. Although designed for this particular implementation of pong, the same concepts and code could be used for any version — it just comes down to changing some of the pre-processing steps. Of course, another method is to use machine learning through reinforcement learning or just simple conv net, but I like this classical approach; at least in this instance where I don’t need robust generality or difficult image processing steps. As I mentioned, this version of pong is 2 player, and I honestly cannot beat my own AI... If you any part of this post provided some useful information or just a bit of inspiration please follow me for more. You can find the source code on my github. Link to my other posts: Minecraft Mapper — Computer Vision and OCR to grab positions from screenshots and plot
[ { "code": null, "e": 638, "s": 171, "text": "One of my favourite YouTuber’s, CodeBullet, once attempted to create a pong AI to rule them all. Sadly he ran into troubles, not because he isn’t capable but I don’t think his experience at the time had much in the way of computer vision. He is absolutely hilarious and I highly recommend you watch him (parental advisory is advised) if you are at all considering reading the rest of this post. Also he is a genius at what he does. Love you mate. See his video here." }, { "code": null, "e": 942, "s": 638, "text": "This seemed like a really fun and simple task so I had to give it a go. In this post I will outline some of the considerations I took that may help if you wish to work on any similar project, and I think I will try my hand at a few more of these, so if you like this type of thing consider following me." }, { "code": null, "e": 1254, "s": 942, "text": "The nice thing about using computer vision is that I can just use a already built game and process the images. Having said that, we will be using the same game version as the one CodeBullet was using from ponggame.org. It also has a 2 player mode so I can play against my own AI; which I did, and it was hard..." }, { "code": null, "e": 1565, "s": 1254, "text": "First things first, getting the screen. I wanted to make sure my frame rate was as fast as possible and for this I found MSS to be a great python package. With this I was easily maxing out at 60 fps and comparing this to PIL I was only getting about 20 fps. It returns as a numpy array so my life was complete." }, { "code": null, "e": 1844, "s": 1565, "text": "Working our way in order of simplicity, we need to define the paddle locations. This could be done in a few different ways but I thought the most obvious was to mask the area for each paddle and run connected components to find the paddle object. Here is a snippet of that code:" }, { "code": null, "e": 2421, "s": 1844, "text": "def get_objects_in_masked_region(img, vertices, connectivity = 8): ''':return connected components with stats in masked region [0] retval number of total labels 0 is background [1] labels image [2] stats[0] leftmostx, [1] topmosty, [2] horizontal size, [3] vertical size, [4] area [3] centroids ''' mask = np.zeros_like(img) # fill the mask cv2.fillPoly(mask, [vertices], 255) # now only show the area that is the mask mask = cv2.bitwise_and(img, mask) conn = cv2.connectedComponentsWithStats(mask, connectivity, cv2.CV_16U) return conn" }, { "code": null, "e": 2896, "s": 2421, "text": "In the above, ‘vertices’ is just a list of the coordinates that define the masked region. Once I have the object within each region I can get their centroid position or the bounding box. One thing to note is that OpenCV includes the background as the 0'th object in any connected component list, so in this case I always grabbed the second largest object. The result is below — the paddle on the right with the green centroid is the player / soon-to-be AI controlled paddle." }, { "code": null, "e": 3262, "s": 2896, "text": "Now that we have our output, we need an input. For this I turned to a useful package and someone else’s code — thanks StackOverflow. It uses ctypes to simulate keyboard presses and in this case, the game is played using the ‘k’ and ‘m’ keys. I got the Scan Codes here. After testing that it worked by just randomly moving up and down, we are good to start tracking." }, { "code": null, "e": 4000, "s": 3262, "text": "Next up is to identify and track the pong. Again, this could have been handled in several ways — one of which could have been to do object detection by using a template, however instead I again went with connected components and object properties, namely the area of the pong since it is the only object with it’s dimensions. I knew I would run into issues whenever the pong crossed or touched any of the other white objects but I also figured this was fine so long as I could track it the majority of the time. After all, it moves in a straight line. If you watch the video below you will see how the red circle marking the pong flickers. That is because it only finds it about 1 in every 2 frames. At 60 fps this really doesn’t matter." }, { "code": null, "e": 4471, "s": 4000, "text": "At this point we already have a working AI. If we just move the player paddle such that it is at the same y-position as the pong, it does a fairly good job. However, it does run into problems when the pong gets a good bounce going. The paddle is just too slow to keep up and needs to instead predict where the pong will be instead of just moving to where it currently is. This has already been implemented in the clips above but below is a comparison of the two methods." }, { "code": null, "e": 5053, "s": 4471, "text": "The difference isn’t huge but it is definitely a more consistent win with the right AI. To do this I first created a list of the positions for the pong. I kept this list at a length of just 5 for averaging sake, but more or less could be done. Probably don’t want more otherwise it takes longer to figure out it has changed directions. After getting the list of positions I used simple vector averaging to smooth out and obtain the direction vector — shown by the green arrow. This was also normalized to be a unit vector and then multiplied by a length for visualization purposes." }, { "code": null, "e": 5638, "s": 5053, "text": "Casting the ray is just an extension of this — making the forward projection longer. I then checked if the future positions were outside the boundary of the top and bottom area. If so, it just projects the position back into the play area. For the left and right sides, it calculates where that intersection will occur with the paddle x-position and fixes the x- and y-position to that point. This makes sure the paddle is targeting to the correct position. Without this it would often move too far. Here is the code for defining the ray that predicts the future position of the pong:" }, { "code": null, "e": 6631, "s": 5638, "text": "def pong_ray(pong_pos, dir_vec, l_paddle, r_paddle, boundaries, steps = 250): future_pts_list = [] for i in range(steps): x_tmp = int(i * dir_vect[0] + pong_pos[0]) y_tmp = int(i * dir_vect[1] + pong_pos[1]) if y_tmp > boundaries[3]: #bottom y_end = int(2*boundaries[3] - y_tmp) x_end = x_tmp elif y_tmp < boundaries[2]: #top y_end = int(-1*y_tmp) x_end = x_tmp else: y_end = y_tmp ##stop where paddle can reach if x_tmp > r_paddle[0]: #right x_end = int(boundaries[1]) y_end = int(pong_pos[1] + ((boundaries[1] - pong_pos[0])/dir_vec[0])*dir_vec[1]) elif x_tmp < boundaries[0]: #left x_end = int(boundaries[0]) y_end = int(pong_pos[1] + ((boundaries[0] - pong_pos[0]) / dir_vec[0]) * dir_vec[1]) else: x_end = x_tmp end_pos = (x_end, y_end) future_pts_list.append(end_pos) return future_pts_list" }, { "code": null, "e": 7027, "s": 6631, "text": "In the above the perhaps less obvious calculation is determining the intercept of left or right positions for the paddles to target. We do this essentially by similar triangles with the diagram and equation show below. We know the intercept with the x-position of the paddle which is given in boundaries. We can then calculate how far the pong will travel and add that to the current y-position." }, { "code": null, "e": 7336, "s": 7027, "text": "The paddles, although look straight, actually have a rebound surface that is curved. That is, if you hit the ball with the paddle towards the ends it will bounce as if the paddle was angled. I therefore allowed the paddle to hit at the edges which adds some offense to the AI, causing the pong to fly around." }, { "code": null, "e": 7857, "s": 7336, "text": "Although designed for this particular implementation of pong, the same concepts and code could be used for any version — it just comes down to changing some of the pre-processing steps. Of course, another method is to use machine learning through reinforcement learning or just simple conv net, but I like this classical approach; at least in this instance where I don’t need robust generality or difficult image processing steps. As I mentioned, this version of pong is 2 player, and I honestly cannot beat my own AI..." }, { "code": null, "e": 7975, "s": 7857, "text": "If you any part of this post provided some useful information or just a bit of inspiration please follow me for more." }, { "code": null, "e": 8018, "s": 7975, "text": "You can find the source code on my github." }, { "code": null, "e": 8042, "s": 8018, "text": "Link to my other posts:" } ]
Check if a graph is strongly connected - Set 1 (Kosaraju using DFS) in C++
Suppose we have a graph. We have to check whether the graph is strongly connected or not using Kosaraju algorithm. A graph is said to be strongly connected, if any two vertices has path between them, then the graph is connected. An undirected graph is strongly connected graph. Some undirected graph may be connected but not strongly connected. This is an example of strongly connected graph. This is an example of connected, but not strongly connected graph. Here we will see, how to check a graph is strongly connected or not using the following steps of Kosaraju algorithm. Steps − Mark all nodes as not visited Mark all nodes as not visited Start DFS traversal from any arbitrary vertex u. If the DFS fails to visit all nodes, then return false. Start DFS traversal from any arbitrary vertex u. If the DFS fails to visit all nodes, then return false. Reverse all edges of the graph Reverse all edges of the graph Set all vertices as not visited nodes again Set all vertices as not visited nodes again Start DFS traversal from that vertex u. If the DFS fails to visit all nodes, then return false. otherwise true. Start DFS traversal from that vertex u. If the DFS fails to visit all nodes, then return false. otherwise true. Live Demo #include <iostream> #include <list> #include <stack> using namespace std; class Graph { int V; list<int> *adj; void dfs(int v, bool visited[]); public: Graph(int V) { this->V = V; adj = new list<int>[V]; } ~Graph() { delete [] adj; } void addEdge(int v, int w); bool isStronglyConnected(); Graph reverseArc(); }; void Graph::dfs(int v, bool visited[]) { visited[v] = true; list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) dfs(*i, visited); } Graph Graph::reverseArc() { Graph graph(V); for (int v = 0; v < V; v++) { list<int>::iterator i; for(i = adj[v].begin(); i != adj[v].end(); ++i) graph.adj[*i].push_back(v); } return graph; } void Graph::addEdge(int u, int v) { adj[u].push_back(v); } bool Graph::isStronglyConnected() { bool visited[V]; for (int i = 0; i < V; i++) visited[i] = false; dfs(0, visited); for (int i = 0; i < V; i++) if (visited[i] == false) return false; Graph graph = reverseArc(); for(int i = 0; i < V; i++) visited[i] = false; graph.dfs(0, visited); for (int i = 0; i < V; i++) if (visited[i] == false) return false; return true; } int main() { Graph graph(5); graph.addEdge(0, 1); graph.addEdge(1, 2); graph.addEdge(2, 3); graph.addEdge(3, 0); graph.addEdge(2, 4); graph.addEdge(4, 2); graph.isStronglyConnected()? cout << "This is strongly connected" : cout << "This is not strongly connected"; } This is strongly connected
[ { "code": null, "e": 1340, "s": 1062, "text": "Suppose we have a graph. We have to check whether the graph is strongly connected or not using Kosaraju algorithm. A graph is said to be strongly connected, if any two vertices has path between them, then the graph is connected. An undirected graph is strongly connected graph." }, { "code": null, "e": 1455, "s": 1340, "text": "Some undirected graph may be connected but not strongly connected. This is an example of strongly connected graph." }, { "code": null, "e": 1522, "s": 1455, "text": "This is an example of connected, but not strongly connected graph." }, { "code": null, "e": 1639, "s": 1522, "text": "Here we will see, how to check a graph is strongly connected or not using the following steps of Kosaraju algorithm." }, { "code": null, "e": 1647, "s": 1639, "text": "Steps −" }, { "code": null, "e": 1677, "s": 1647, "text": "Mark all nodes as not visited" }, { "code": null, "e": 1707, "s": 1677, "text": "Mark all nodes as not visited" }, { "code": null, "e": 1812, "s": 1707, "text": "Start DFS traversal from any arbitrary vertex u. If the DFS fails to visit all nodes, then return false." }, { "code": null, "e": 1917, "s": 1812, "text": "Start DFS traversal from any arbitrary vertex u. If the DFS fails to visit all nodes, then return false." }, { "code": null, "e": 1948, "s": 1917, "text": "Reverse all edges of the graph" }, { "code": null, "e": 1979, "s": 1948, "text": "Reverse all edges of the graph" }, { "code": null, "e": 2023, "s": 1979, "text": "Set all vertices as not visited nodes again" }, { "code": null, "e": 2067, "s": 2023, "text": "Set all vertices as not visited nodes again" }, { "code": null, "e": 2179, "s": 2067, "text": "Start DFS traversal from that vertex u. If the DFS fails to visit all nodes, then return false. otherwise true." }, { "code": null, "e": 2291, "s": 2179, "text": "Start DFS traversal from that vertex u. If the DFS fails to visit all nodes, then return false. otherwise true." }, { "code": null, "e": 2302, "s": 2291, "text": " Live Demo" }, { "code": null, "e": 3844, "s": 2302, "text": "#include <iostream>\n#include <list>\n#include <stack>\nusing namespace std;\nclass Graph {\n int V;\n list<int> *adj;\n void dfs(int v, bool visited[]);\n public:\n Graph(int V) {\n this->V = V;\n adj = new list<int>[V];\n }\n ~Graph() {\n delete [] adj;\n }\n void addEdge(int v, int w);\n bool isStronglyConnected();\n Graph reverseArc();\n};\nvoid Graph::dfs(int v, bool visited[]) {\n visited[v] = true;\n list<int>::iterator i;\n for (i = adj[v].begin(); i != adj[v].end(); ++i)\n if (!visited[*i])\n dfs(*i, visited);\n}\nGraph Graph::reverseArc() {\n Graph graph(V);\n for (int v = 0; v < V; v++) {\n list<int>::iterator i;\n for(i = adj[v].begin(); i != adj[v].end(); ++i)\n graph.adj[*i].push_back(v);\n }\n return graph;\n}\nvoid Graph::addEdge(int u, int v) {\n adj[u].push_back(v);\n}\nbool Graph::isStronglyConnected() {\n bool visited[V];\n for (int i = 0; i < V; i++)\n visited[i] = false;\n dfs(0, visited);\n for (int i = 0; i < V; i++)\n if (visited[i] == false)\n return false;\n Graph graph = reverseArc();\n for(int i = 0; i < V; i++)\n visited[i] = false;\n graph.dfs(0, visited);\n for (int i = 0; i < V; i++)\n if (visited[i] == false)\n return false;\n return true;\n}\nint main() {\n Graph graph(5);\n graph.addEdge(0, 1);\n graph.addEdge(1, 2);\n graph.addEdge(2, 3);\n graph.addEdge(3, 0);\n graph.addEdge(2, 4);\n graph.addEdge(4, 2);\n graph.isStronglyConnected()? cout << \"This is strongly connected\" : cout << \"This is not strongly connected\";\n}" }, { "code": null, "e": 3871, "s": 3844, "text": "This is strongly connected" } ]
How to Monitor a Thread's Status in Java? - GeeksforGeeks
30 Sep, 2021 The Java language support thread synchronization through the use of monitors. A monitor is associated with a specific data item and functions as a lock on that data. When a thread holds the monitor for some data item, other threads are locked out and cannot inspect or modify the data. In order to monitor a thread’s status Java have predefined currentThread.getName() method that is extended by Thread Class.The getName() method of java.lang.reflect.Method class is used to get the name of the entity, as a String, that entity can be class, interface, array, enum, method, etc. of the class object. The getName() method of java.lang.reflect. Method class is helpful to get the name of methods, as a String. To get name of all methods of a class, get all the methods of that class object. Then call getName() on those method objects. Syntax: public String getName() Return Value: It returns the name of the method, as String. Example: Java // Java Program to Monitor a Thread's Status // Class 1// Helper classclass MyThread extends Thread { // Initially initializing states using boolean methods boolean waiting = true; boolean ready = false; // Constructor of this class MyThread() {} // Methods of this class are as follows: // Method 1 synchronized void startWait() { try { while (!ready) wait(); } catch (InterruptedException exc) { System.out.println("wait() interrupted"); } } // Method 2 synchronized void notice() { ready = true; notify(); } // Method 3 // To run threads when called using start() public void run() { // Getting the name of current thread // using currentThread() and getName() methods String thrdName = Thread.currentThread().getName(); // Print the corresponding thread System.out.println(thrdName + " starting."); // While the thread is in waiting state while (waiting) System.out.println("waiting:" + waiting); // Display message System.out.println("waiting..."); // calling the Method1 startWait(); // Try block to check for exceptions try { // Making thread to pause execution for a // certain time of 1 second using sleep() method Thread.sleep(1000); } // Catch block to handle the exceptions catch (Exception exc) { // Display if interrupted System.out.println(thrdName + " interrupted."); } // Else display the thread is terminated. System.out.println(thrdName + " terminating."); }} // Class 2// Main classpublic class GFG { // Method 1 // To get the thread status static void showThreadStatus(Thread thrd) { System.out.println(thrd.getName() + " Alive:=" + thrd.isAlive() + " State:=" + thrd.getState()); } // Method 2 // Main driver method public static void main(String args[]) throws Exception { // Creating an object of our thread class // in the main() method MyThread thrd = new MyThread(); // Setting the name for the threads // using setname() method thrd.setName("MyThread #1"); // getting the status of current thread showThreadStatus(thrd); // Starting the thread which automatically invokes // the run() method for the thread thrd.start(); // Similarly repeating the same Thread.sleep(50); showThreadStatus(thrd); // hee notice we change the flag value // thai is no more in waiting state now thrd.waiting = false; Thread.sleep(50); showThreadStatus(thrd); thrd.notice(); Thread.sleep(50); showThreadStatus(thrd); // Till thread is alive while (thrd.isAlive()) // Print the statement System.out.println("alive"); // Callin the method showThreadStatus(thrd); }} Output: anikakapoor simranarora5sos Java-Multithreading Picked Java Java Programs 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 Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java? Iterate through List in Java
[ { "code": null, "e": 25347, "s": 25319, "text": "\n30 Sep, 2021" }, { "code": null, "e": 26181, "s": 25347, "text": "The Java language support thread synchronization through the use of monitors. A monitor is associated with a specific data item and functions as a lock on that data. When a thread holds the monitor for some data item, other threads are locked out and cannot inspect or modify the data. In order to monitor a thread’s status Java have predefined currentThread.getName() method that is extended by Thread Class.The getName() method of java.lang.reflect.Method class is used to get the name of the entity, as a String, that entity can be class, interface, array, enum, method, etc. of the class object. The getName() method of java.lang.reflect. Method class is helpful to get the name of methods, as a String. To get name of all methods of a class, get all the methods of that class object. Then call getName() on those method objects." }, { "code": null, "e": 26189, "s": 26181, "text": "Syntax:" }, { "code": null, "e": 26213, "s": 26189, "text": "public String getName()" }, { "code": null, "e": 26273, "s": 26213, "text": "Return Value: It returns the name of the method, as String." }, { "code": null, "e": 26282, "s": 26273, "text": "Example:" }, { "code": null, "e": 26287, "s": 26282, "text": "Java" }, { "code": "// Java Program to Monitor a Thread's Status // Class 1// Helper classclass MyThread extends Thread { // Initially initializing states using boolean methods boolean waiting = true; boolean ready = false; // Constructor of this class MyThread() {} // Methods of this class are as follows: // Method 1 synchronized void startWait() { try { while (!ready) wait(); } catch (InterruptedException exc) { System.out.println(\"wait() interrupted\"); } } // Method 2 synchronized void notice() { ready = true; notify(); } // Method 3 // To run threads when called using start() public void run() { // Getting the name of current thread // using currentThread() and getName() methods String thrdName = Thread.currentThread().getName(); // Print the corresponding thread System.out.println(thrdName + \" starting.\"); // While the thread is in waiting state while (waiting) System.out.println(\"waiting:\" + waiting); // Display message System.out.println(\"waiting...\"); // calling the Method1 startWait(); // Try block to check for exceptions try { // Making thread to pause execution for a // certain time of 1 second using sleep() method Thread.sleep(1000); } // Catch block to handle the exceptions catch (Exception exc) { // Display if interrupted System.out.println(thrdName + \" interrupted.\"); } // Else display the thread is terminated. System.out.println(thrdName + \" terminating.\"); }} // Class 2// Main classpublic class GFG { // Method 1 // To get the thread status static void showThreadStatus(Thread thrd) { System.out.println(thrd.getName() + \" Alive:=\" + thrd.isAlive() + \" State:=\" + thrd.getState()); } // Method 2 // Main driver method public static void main(String args[]) throws Exception { // Creating an object of our thread class // in the main() method MyThread thrd = new MyThread(); // Setting the name for the threads // using setname() method thrd.setName(\"MyThread #1\"); // getting the status of current thread showThreadStatus(thrd); // Starting the thread which automatically invokes // the run() method for the thread thrd.start(); // Similarly repeating the same Thread.sleep(50); showThreadStatus(thrd); // hee notice we change the flag value // thai is no more in waiting state now thrd.waiting = false; Thread.sleep(50); showThreadStatus(thrd); thrd.notice(); Thread.sleep(50); showThreadStatus(thrd); // Till thread is alive while (thrd.isAlive()) // Print the statement System.out.println(\"alive\"); // Callin the method showThreadStatus(thrd); }}", "e": 29415, "s": 26287, "text": null }, { "code": null, "e": 29423, "s": 29415, "text": "Output:" }, { "code": null, "e": 29435, "s": 29423, "text": "anikakapoor" }, { "code": null, "e": 29451, "s": 29435, "text": "simranarora5sos" }, { "code": null, "e": 29471, "s": 29451, "text": "Java-Multithreading" }, { "code": null, "e": 29478, "s": 29471, "text": "Picked" }, { "code": null, "e": 29483, "s": 29478, "text": "Java" }, { "code": null, "e": 29497, "s": 29483, "text": "Java Programs" }, { "code": null, "e": 29502, "s": 29497, "text": "Java" }, { "code": null, "e": 29600, "s": 29502, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29615, "s": 29600, "text": "Stream In Java" }, { "code": null, "e": 29636, "s": 29615, "text": "Constructors in Java" }, { "code": null, "e": 29655, "s": 29636, "text": "Exceptions in Java" }, { "code": null, "e": 29685, "s": 29655, "text": "Functional Interfaces in Java" }, { "code": null, "e": 29731, "s": 29685, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 29757, "s": 29731, "text": "Java Programming Examples" }, { "code": null, "e": 29791, "s": 29757, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 29838, "s": 29791, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 29870, "s": 29838, "text": "How to Iterate HashMap in Java?" } ]
Flood fill Algorithm | Practice | GeeksforGeeks
An image is represented by a 2-D array of integers, each integer representing the pixel value of the image. Given a coordinate (sr, sc) representing the starting pixel (row and column) of the flood fill, and a pixel value newColor, "flood fill" the image. To perform a "flood fill", consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color as the starting pixel), and so on. Replace the color of all of the aforementioned pixels with the newColor. Example 1: Input: image = {{1,1,1},{1,1,0},{1,0,1}}, sr = 1, sc = 1, newColor = 2. Output: {{2,2,2},{2,2,0},{2,0,1}} Explanation: From the center of the image (with position (sr, sc) = (1, 1)), all pixels connected by a path of the same color as the starting pixel are colored with the new color.Note the bottom corner is not colored 2, because it is not 4-directionally connected to the starting pixel. Your Task: You don't need to read or print anyhting. Your task is to complete the function floodFill() which takes image, sr, sc and newColor as input paramater and returns the image after flood filling. Expected Time Compelxity: O(n*m) Expected Space Complexity: O(n*m) 0 bokonist6 days ago C++, Simple recursion with no helper functions. TC: O(n*m), SC: stack size, O(n*m). . . vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) { // Code here int n= image.size(); int m= image[0].size(); if(sr>=n || sr<0 || sc>=m || sc<0 || image[sr][sc]==newColor) return image; int oldColor= image[sr][sc]; image[sr][sc]= -1; if(sr-1 >=0 && image[sr-1][sc]==oldColor) floodFill(image, sr-1,sc, newColor); if(sr+1 <n && image[sr+1][sc]==oldColor) floodFill(image, sr+1,sc,newColor); if(sc-1 >=0 && image[sr][sc-1]==oldColor) floodFill(image, sr,sc-1,newColor); if(sc+1 <m && image[sr][sc+1]==oldColor) floodFill(image,sr,sc+1,newColor); image[sr][sc]= newColor; return image; } 0 sharadyaduvanshi2 weeks ago bool issafe(vector<vector<int>>& image,int n,int m,int i,int j,vector<vector<int>>&vis,int newColor,int src) { if(i < 0 || i >= n || j < 0 || j >= m || image[i][j] != src || vis[i][j] == 1 ) return false; return true; } void helper(vector<vector<int>>& image,int n,int m, int i, int j, int newColor,vector<vector<int>>&vis,int src) { if(i == n && j == m) return ; image[i][j] = newColor; vis[i][j] = 1; if(issafe(image,n,m,i,j-1,vis,newColor,src)) //left { helper(image,n,m,i,j-1,newColor,vis,src); } if(issafe(image,n,m,i,j+1,vis,newColor,src)) //right { helper(image,n,m,i,j+1,newColor,vis,src); } if(issafe(image,n,m,i-1,j,vis,newColor,src)) //up { helper(image,n,m,i-1,j,newColor,vis,src); } if(issafe(image,n,m,i+1,j,vis,newColor,src)) //down { helper(image,n,m,i+1,j,newColor,vis,src); } vis[i][j] = 0; // return ; } vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) { // Code here int n = image.size(); int m = image[0].size(); vector<vector<int>>vis(n+1,vector<int>(m+1,0)); int src = image[sr][sc]; image[sr][sc] = newColor; helper(image,n,m,sr,sc,newColor,vis,src); return image; } 0 naveenapatnaik3 weeks ago JAVA SOLUTION!! public int[][] floodFill(int[][] image, int sr, int sc, int newColor) { // Code here int oldColor = image[sr][sc]; if(oldColor == newColor){ return image; } fill(image, sr, sc, oldColor, newColor); return image; } public void fill(int[][] image, int sr, int sc, int oldColor, int newColor){ if(sr<0 || sc<0 || sr>=image.length || sc>=image[0].length || image[sr][sc]!=oldColor){ return; } image[sr][sc] = newColor; fill(image, sr-1, sc, oldColor, newColor); fill(image, sr+1, sc, oldColor, newColor); fill(image, sr, sc-1, oldColor, newColor); fill(image, sr, sc+1, oldColor, newColor); } 0 itvictoralfonsoflores1 month ago This is my solution, i accept comments. class Solution{ public int[][] floodFill(int[][] image, int sr, int sc, int newColor) { int color = image[sr][sc]; if(color == newColor) { return image; } image = recurse(image, sr, sc, color, newColor); return image; // Code here } private int[][] recurse(int[][] image, int sr, int sc, int oldColor, int newColor) { if(image[sr][sc] == oldColor){ image[sr][sc] = newColor; if(sr + 1 < image.length) image = recurse(image,sr+1,sc,oldColor,newColor); if(sr-1 >= 0) image = recurse(image,sr-1,sc,oldColor,newColor); if(sc+1 < image[0].length) image = recurse(image,sr,sc+1,oldColor,newColor); if(sc-1 >= 0) image = recurse(image,sr,sc-1,oldColor,newColor); } return image; } } 0 seagullcode1 month ago void solve(vector<vector<int>>& image, int sr, int sc, int newColor, vector<vector<int>> &vis, int init){ if(sr<0 || sr>=image.size() || sc<0 || sc>=image[0].size() || vis[sr][sc] || image[sr][sc]!=init){ return; } vis[sr][sc]=1; image[sr][sc]=newColor; solve(image,sr+1,sc,newColor,vis,init); solve(image,sr-1,sc,newColor,vis,init); solve(image,sr,sc+1,newColor,vis,init); solve(image,sr,sc-1,newColor,vis,init); } public: vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) { // Code here int init = image[sr][sc]; vector<vector<int>> vis(image.size(),vector<int>(image[0].size(),0)); solve(image,sr,sc,newColor,vis,init); return image; }}; 0 stanislaslegendre1 month ago simple Java solution class Solution { public int[][] floodFill(int[][] image, int sr, int sc, int newColor) { int oldColor = image[sr][sc]; if(oldColor == newColor) return image; recurse(image, sr, sc, oldColor, newColor); return image; } private void flood(int[][] image, int sr, int sc, int oldColor, int newColor) { if(sr > image.length -1 || sc > image[0].length -1 || sr <0 || sc < 0) return; if(image[sr][sc] != oldColor) return; recurse(image, sr, sc, oldColor, newColor); } private void recurse(int[][] image, int sr, int sc, int oldColor, int newColor ) { image[sr][sc] = newColor; flood(image, sr +1, sc, oldColor, newColor); flood(image, sr -1, sc, oldColor, newColor); flood(image, sr , sc +1, oldColor, newColor); flood(image, sr , sc -1, oldColor, newColor); } } 0 geminicode2 months ago don't think we need extra space!! here is my python solution def floodFill(self, image, sr, sc, newColor): #Code here oldc = image[sr][sc] move = [[0,1],[1,0],[0,-1],[-1,0]] def dfs(r,c): if image[r][c] == newColor: return image[r][c] = newColor for i in move: if r + i[0] >= 0 and r + i[0] < len(image) and c + i[1] >= 0 and\ c+ i[1] < len (image[0]) and image[r+i[0]][c+i[1]] == oldc: dfs(r+i[0],c+i[1]) dfs(sr,sc) return image 0 agrawalvanisha102 months ago Someone pls tell the mistake...it is showing segmentation fault, I have already added the condition, if image[sr][sc]==newColor then return. int distx[4]={0,0,1,-1}; int disty[4]={1,-1,0,0}; vector<vector<int>> changeColor(vector<vector<int>>& image, int &sr, int &sc, int newColor,int n,int m) { static int givenColor=image[sr][sc]; image[sr][sc]=newColor; for(int i=0;i<4;i++) { if(sr+distx[i]>=0 && sc+disty[i]>=0 && sr+distx[i]<n && sc+disty[i]<m && image[sr+distx[i]][sc+disty[i]]==givenColor) { int x=sr+distx[i]; int y=sc+disty[i]; changeColor(image,x,y,newColor,n,m); } } return image; } vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) { // Code here int n=image.size(); if(n==0) return image; int m=image[0].size(); if(image[sr][sc]==newColor) return image; return changeColor(image,sr,sc,newColor,n,m); } 0 amoghagarwal05032 months ago Ezz Ezz 0 bishtkunal092 months ago vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) { queue<pair<int,int>> q; int r=image.size(); int c=image[0].size(); vector<vector<int>> vis(r,vector<int>(c,0)); q.push({sr,sc}); int p=image[sr][sc]; image[sr][sc]=newColor; int dx[]={0,0,1,-1}; int dy[]={1,-1,0,0}; while(!q.empty()){ int k=q.size(); while(k--){ int x=q.front().first; int y=q.front().second; q.pop(); image[x][y]=newColor; for(int i=0;i<4;i++){ if(x+dx[i]>=r||x+dx[i]<0||y+dy[i]<0||y+dy[i]>=c||vis[x+dx[i]][y+dy[i]]==1){ continue; } if(image[x+dx[i]][y+dy[i]]==p){ vis[x+dx[i]][y+dy[i]]=1; q.push({x+dx[i],y+dy[i]}); } } } } return image; } 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": 346, "s": 238, "text": "An image is represented by a 2-D array of integers, each integer representing the pixel value of the image." }, { "code": null, "e": 494, "s": 346, "text": "Given a coordinate (sr, sc) representing the starting pixel (row and column) of the flood fill, and a pixel value newColor, \"flood fill\" the image." }, { "code": null, "e": 847, "s": 494, "text": "To perform a \"flood fill\", consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color as the starting pixel), and so on. Replace the color of all of the aforementioned pixels with the newColor." }, { "code": null, "e": 858, "s": 847, "text": "Example 1:" }, { "code": null, "e": 1257, "s": 858, "text": "Input: image = {{1,1,1},{1,1,0},{1,0,1}},\nsr = 1, sc = 1, newColor = 2.\nOutput: {{2,2,2},{2,2,0},{2,0,1}}\nExplanation: From the center of the image \n(with position (sr, sc) = (1, 1)), all \npixels connected by a path of the same color\nas the starting pixel are colored with the new \ncolor.Note the bottom corner is not colored 2, \nbecause it is not 4-directionally connected to \nthe starting pixel.\n" }, { "code": null, "e": 1465, "s": 1259, "text": "Your Task:\nYou don't need to read or print anyhting. Your task is to complete the function floodFill() which takes image, sr, sc and newColor as input paramater and returns the image after flood filling.\n " }, { "code": null, "e": 1534, "s": 1465, "text": "Expected Time Compelxity: O(n*m)\nExpected Space Complexity: O(n*m)\n " }, { "code": null, "e": 1536, "s": 1534, "text": "0" }, { "code": null, "e": 1555, "s": 1536, "text": "bokonist6 days ago" }, { "code": null, "e": 1604, "s": 1555, "text": "C++, Simple recursion with no helper functions. " }, { "code": null, "e": 1617, "s": 1604, "text": "TC: O(n*m), " }, { "code": null, "e": 1641, "s": 1617, "text": "SC: stack size, O(n*m)." }, { "code": null, "e": 1643, "s": 1641, "text": "." }, { "code": null, "e": 1645, "s": 1643, "text": "." }, { "code": null, "e": 2350, "s": 1645, "text": "vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) \n{\n // Code here \n int n= image.size();\n int m= image[0].size();\n if(sr>=n || sr<0 || sc>=m || sc<0 || image[sr][sc]==newColor)\n return image;\n \n int oldColor= image[sr][sc];\n image[sr][sc]= -1;\n \n if(sr-1 >=0 && image[sr-1][sc]==oldColor) floodFill(image, sr-1,sc, newColor);\n if(sr+1 <n && image[sr+1][sc]==oldColor) floodFill(image, sr+1,sc,newColor);\n if(sc-1 >=0 && image[sr][sc-1]==oldColor) floodFill(image, sr,sc-1,newColor);\n if(sc+1 <m && image[sr][sc+1]==oldColor) floodFill(image,sr,sc+1,newColor);\n \n image[sr][sc]= newColor;\n return image;\n \n}" }, { "code": null, "e": 2352, "s": 2350, "text": "0" }, { "code": null, "e": 2380, "s": 2352, "text": "sharadyaduvanshi2 weeks ago" }, { "code": null, "e": 3833, "s": 2380, "text": " bool issafe(vector<vector<int>>& image,int n,int m,int i,int j,vector<vector<int>>&vis,int newColor,int src) { if(i < 0 || i >= n || j < 0 || j >= m || image[i][j] != src || vis[i][j] == 1 ) return false; return true; } void helper(vector<vector<int>>& image,int n,int m, int i, int j, int newColor,vector<vector<int>>&vis,int src) { if(i == n && j == m) return ; image[i][j] = newColor; vis[i][j] = 1; if(issafe(image,n,m,i,j-1,vis,newColor,src)) //left { helper(image,n,m,i,j-1,newColor,vis,src); } if(issafe(image,n,m,i,j+1,vis,newColor,src)) //right { helper(image,n,m,i,j+1,newColor,vis,src); } if(issafe(image,n,m,i-1,j,vis,newColor,src)) //up { helper(image,n,m,i-1,j,newColor,vis,src); } if(issafe(image,n,m,i+1,j,vis,newColor,src)) //down { helper(image,n,m,i+1,j,newColor,vis,src); } vis[i][j] = 0; // return ; } vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) { // Code here int n = image.size(); int m = image[0].size(); vector<vector<int>>vis(n+1,vector<int>(m+1,0)); int src = image[sr][sc]; image[sr][sc] = newColor; helper(image,n,m,sr,sc,newColor,vis,src); return image; }" }, { "code": null, "e": 3835, "s": 3833, "text": "0" }, { "code": null, "e": 3861, "s": 3835, "text": "naveenapatnaik3 weeks ago" }, { "code": null, "e": 3877, "s": 3861, "text": "JAVA SOLUTION!!" }, { "code": null, "e": 4590, "s": 3877, "text": "public int[][] floodFill(int[][] image, int sr, int sc, int newColor) { // Code here int oldColor = image[sr][sc]; if(oldColor == newColor){ return image; } fill(image, sr, sc, oldColor, newColor); return image; } public void fill(int[][] image, int sr, int sc, int oldColor, int newColor){ if(sr<0 || sc<0 || sr>=image.length || sc>=image[0].length || image[sr][sc]!=oldColor){ return; } image[sr][sc] = newColor; fill(image, sr-1, sc, oldColor, newColor); fill(image, sr+1, sc, oldColor, newColor); fill(image, sr, sc-1, oldColor, newColor); fill(image, sr, sc+1, oldColor, newColor); }" }, { "code": null, "e": 4592, "s": 4590, "text": "0" }, { "code": null, "e": 4625, "s": 4592, "text": "itvictoralfonsoflores1 month ago" }, { "code": null, "e": 4665, "s": 4625, "text": "This is my solution, i accept comments." }, { "code": null, "e": 5574, "s": 4667, "text": "class Solution{ public int[][] floodFill(int[][] image, int sr, int sc, int newColor) { int color = image[sr][sc]; if(color == newColor) { return image; } image = recurse(image, sr, sc, color, newColor); return image; // Code here } private int[][] recurse(int[][] image, int sr, int sc, int oldColor, int newColor) { if(image[sr][sc] == oldColor){ image[sr][sc] = newColor; if(sr + 1 < image.length) image = recurse(image,sr+1,sc,oldColor,newColor); if(sr-1 >= 0) image = recurse(image,sr-1,sc,oldColor,newColor); if(sc+1 < image[0].length) image = recurse(image,sr,sc+1,oldColor,newColor); if(sc-1 >= 0) image = recurse(image,sr,sc-1,oldColor,newColor); } return image; } }" }, { "code": null, "e": 5576, "s": 5574, "text": "0" }, { "code": null, "e": 5599, "s": 5576, "text": "seagullcode1 month ago" }, { "code": null, "e": 6426, "s": 5599, "text": " void solve(vector<vector<int>>& image, int sr, int sc, int newColor, vector<vector<int>> &vis, int init){ if(sr<0 || sr>=image.size() || sc<0 || sc>=image[0].size() || vis[sr][sc] || image[sr][sc]!=init){ return; } vis[sr][sc]=1; image[sr][sc]=newColor; solve(image,sr+1,sc,newColor,vis,init); solve(image,sr-1,sc,newColor,vis,init); solve(image,sr,sc+1,newColor,vis,init); solve(image,sr,sc-1,newColor,vis,init); } public: vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) { // Code here int init = image[sr][sc]; vector<vector<int>> vis(image.size(),vector<int>(image[0].size(),0)); solve(image,sr,sc,newColor,vis,init); return image; }};" }, { "code": null, "e": 6428, "s": 6426, "text": "0" }, { "code": null, "e": 6457, "s": 6428, "text": "stanislaslegendre1 month ago" }, { "code": null, "e": 6478, "s": 6457, "text": "simple Java solution" }, { "code": null, "e": 7379, "s": 6480, "text": "class Solution\n{\n public int[][] floodFill(int[][] image, int sr, int sc, int newColor)\n {\n int oldColor = image[sr][sc];\n if(oldColor == newColor) return image;\n recurse(image, sr, sc, oldColor, newColor);\n return image;\n }\n \n private void flood(int[][] image, int sr, int sc, int oldColor, int newColor) {\n if(sr > image.length -1 || sc > image[0].length -1 || sr <0 || sc < 0) return;\n if(image[sr][sc] != oldColor) return;\n recurse(image, sr, sc, oldColor, newColor);\n \n }\n \n private void recurse(int[][] image, int sr, int sc, int oldColor, int newColor ) {\n image[sr][sc] = newColor;\n flood(image, sr +1, sc, oldColor, newColor);\n flood(image, sr -1, sc, oldColor, newColor);\n flood(image, sr , sc +1, oldColor, newColor);\n flood(image, sr , sc -1, oldColor, newColor);\n }\n}" }, { "code": null, "e": 7381, "s": 7379, "text": "0" }, { "code": null, "e": 7404, "s": 7381, "text": "geminicode2 months ago" }, { "code": null, "e": 7465, "s": 7404, "text": "don't think we need extra space!! here is my python solution" }, { "code": null, "e": 7903, "s": 7465, "text": "def floodFill(self, image, sr, sc, newColor):\n #Code here\n \n oldc = image[sr][sc]\n move = [[0,1],[1,0],[0,-1],[-1,0]]\n def dfs(r,c):\n if image[r][c] == newColor:\n return\n image[r][c] = newColor\n for i in move:\n if r + i[0] >= 0 and r + i[0] < len(image) and c + i[1] >= 0 and\\\n c+ i[1] < len (image[0]) and image[r+i[0]][c+i[1]] == oldc:\n dfs(r+i[0],c+i[1])\n dfs(sr,sc)\n return image" }, { "code": null, "e": 7905, "s": 7903, "text": "0" }, { "code": null, "e": 7934, "s": 7905, "text": "agrawalvanisha102 months ago" }, { "code": null, "e": 8075, "s": 7934, "text": "Someone pls tell the mistake...it is showing segmentation fault, I have already added the condition, if image[sr][sc]==newColor then return." }, { "code": null, "e": 8129, "s": 8077, "text": "int distx[4]={0,0,1,-1}; int disty[4]={1,-1,0,0};" }, { "code": null, "e": 8239, "s": 8131, "text": "vector<vector<int>> changeColor(vector<vector<int>>& image, int &sr, int &sc, int newColor,int n,int m) {" }, { "code": null, "e": 8673, "s": 8239, "text": " static int givenColor=image[sr][sc]; image[sr][sc]=newColor; for(int i=0;i<4;i++) { if(sr+distx[i]>=0 && sc+disty[i]>=0 && sr+distx[i]<n && sc+disty[i]<m && image[sr+distx[i]][sc+disty[i]]==givenColor) { int x=sr+distx[i]; int y=sc+disty[i]; changeColor(image,x,y,newColor,n,m); } } return image; }" }, { "code": null, "e": 8993, "s": 8675, "text": "vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) { // Code here int n=image.size(); if(n==0) return image; int m=image[0].size(); if(image[sr][sc]==newColor) return image; return changeColor(image,sr,sc,newColor,n,m); } " }, { "code": null, "e": 8995, "s": 8993, "text": "0" }, { "code": null, "e": 9024, "s": 8995, "text": "amoghagarwal05032 months ago" }, { "code": null, "e": 9028, "s": 9024, "text": "Ezz" }, { "code": null, "e": 9032, "s": 9028, "text": "Ezz" }, { "code": null, "e": 9034, "s": 9032, "text": "0" }, { "code": null, "e": 9059, "s": 9034, "text": "bishtkunal092 months ago" }, { "code": null, "e": 10122, "s": 9059, "text": " vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) { queue<pair<int,int>> q; int r=image.size(); int c=image[0].size(); vector<vector<int>> vis(r,vector<int>(c,0)); q.push({sr,sc}); int p=image[sr][sc]; image[sr][sc]=newColor; int dx[]={0,0,1,-1}; int dy[]={1,-1,0,0}; while(!q.empty()){ int k=q.size(); while(k--){ int x=q.front().first; int y=q.front().second; q.pop(); image[x][y]=newColor; for(int i=0;i<4;i++){ if(x+dx[i]>=r||x+dx[i]<0||y+dy[i]<0||y+dy[i]>=c||vis[x+dx[i]][y+dy[i]]==1){ continue; } if(image[x+dx[i]][y+dy[i]]==p){ vis[x+dx[i]][y+dy[i]]=1; q.push({x+dx[i],y+dy[i]}); } } } } return image; }" }, { "code": null, "e": 10268, "s": 10122, "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": 10304, "s": 10268, "text": " Login to access your submissions. " }, { "code": null, "e": 10314, "s": 10304, "text": "\nProblem\n" }, { "code": null, "e": 10324, "s": 10314, "text": "\nContest\n" }, { "code": null, "e": 10387, "s": 10324, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 10535, "s": 10387, "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": 10743, "s": 10535, "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": 10849, "s": 10743, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Pie Charts in Python. Creating Pie Charts in Python | by Sadrach Pierre, Ph.D. | Towards Data Science
A pie chart is a type of data visualization that is used to illustrate numerical proportions in data. The python library ‘matplotlib’ provides many useful tools for creating beautiful visualizations, including pie charts. In this post, we will discuss how to use ‘matplotlib’ to create pie charts in python. Let’s get started! For our purposes, we will be using the Netflix Movies and TV Shows data set, which can be found here. To start, let’s read the data into a Pandas data frame; import pandas as pd df = pd.read_csv("netflix_titles.csv") Next, let’s print the first five rows of data using the ‘.head()’ method: print(df.head()) As we can see, the data contains columns with various categorical values. Pie charts typically show relative proportions of different categories in a data set. For our pie chart visualizations, the ‘rating’, ‘country’ ,and ‘type’ columns are good examples of data with categorical values we can group and visualize. To get an idea of the distribution in categorical values for these columns, we can use the ‘Counter’ method from the collections module. Let’s apply the ‘Counter’ method to the ‘type’ column: from collections import Counterprint(Counter(df['type'])) Let’s also look at the ‘rating’ column: print(Counter(df['rating'])) Now, let’s proceed by grouping our data by the number of values for each ‘type’ category: title_type = df.groupby('type').agg('count')print(title_type) Next, let’s import a few modules from ‘matplotlib’: import matplotlib.ticker as tickerimport matplotlib.cm as cmimport matplotlib as mplfrom matplotlib.gridspec import GridSpecimport matplotlib.pyplot as plt Now, let’s sort the indices and counts for our aggregated types: type_labels = title_type.show_id.sort_values().index type_counts = title_type.show_id.sort_values() We then specify the figure details: plt.figure(1, figsize=(20,10)) the_grid = GridSpec(2, 2) and specify the color map information: cmap = plt.get_cmap('Spectral')colors = [cmap(i) for i in np.linspace(0, 1, 8)] Finally, let’s plot our pie chart: plt.subplot(the_grid[0, 1], aspect=1, title='Types of Netflix Titles')type_show_ids = plt.pie(type_counts, labels=type_labels, autopct='%1.1f%%', shadow=True, colors=colors)plt.show() We see that most of the Netflix titles in this data set are movies. We can also generate a pie chart for the ratings. Let’s aggregate by rating: title_rating = df.groupby('rating').agg('count')rating_labels = title_rating.show_id.sort_values().index rating_counts = title_rating.show_id.sort_values() And plot our chart: plt.figure(1, figsize=(40,20))the_grid = GridSpec(2, 2)cmap = plt.get_cmap('Spectral')colors = [cmap(i) for i in np.linspace(0, 1, 8)]plt.subplot(the_grid[0, 1], aspect=1, title='Ratings of Netflix Titles')type_show_ids = plt.pie(rating_counts, labels=rating_labels, autopct='%1.1f%%', shadow=True, colors=colors)plt.show() We see ‘TV-14’ and ‘TV-MA’ are the most common ratings in the data. A drawback of pie charts is that they become less useful the more categories present within a column. For example, in our ratings pie chart the ‘G’, ‘NC-17’, and ‘UR’ ratings overlap which doesn’t look visually pleasing. You can imagine that this gets worse with an increasing number of categories. To resolve this, let’s define a function that calculate the 75th percentile and groups the lesser counts together in an ‘other’ category: def group_lower_ranking_values(column): rating_counts = df.groupby(column).agg('count') pct_value = rating_counts[lambda x: x.columns[0]].quantile(.75) values_below_pct_value = rating_counts[lambda x: x.columns[0]].loc[lambda s: s < pct_value].index.values def fix_values(row): if row[column] in values_below_pct_value: row[column] = 'Other' return row rating_grouped = df.apply(fix_values, axis=1).groupby(column).agg('count') return rating_grouped We can now aggregate our data using this function: rating_grouped = group_lower_ranking_values('rating')rating_labels = rating_grouped.show_id.sort_values().index rating_counts = rating_grouped.show_id.sort_values() And plot the result: plt.subplot(the_grid[0, 1], aspect=1, title='Rating of Netflix Titles')type_show_ids = plt.pie(rating_counts, labels=rating_labels, autopct='%1.1f%%', shadow=True, colors=colors)plt.show() We see this looks much better than the previous plot. Let’s do the same for the country column. Here, we will consider the 99th percentile: def group_lower_ranking_values(column): ... pct_value = rating_counts[lambda x: x.columns[0]].quantile(.99) ... return rating_groupedcountry_grouped = group_lower_ranking_values('country')country_labels = country_grouped.show_id.sort_values().index country_counts = country_grouped.show_id.sort_values()plt.subplot(the_grid[0, 1], aspect=1, title='Country of Netflix Titles')type_show_ids = plt.pie(country_counts, labels=country_labels, autopct='%1.1f%%', shadow=True, colors=colors)plt.show() I’ll stop here but feel free to play around with the code yourself. To summarize, in this post we discussed how to create pie charts in python. We showed to represent proportions of categories corresponding to title types, ratings and countries for Netflix titles. We also showed how to resolve the issue of visualizing a column with too many category types by calculating the highest ranking categories and grouping the lower values into a single ‘other’ group. I hope you found this post interesting/useful. The code from this post is available on GitHub. Thank you for reading!
[ { "code": null, "e": 480, "s": 172, "text": "A pie chart is a type of data visualization that is used to illustrate numerical proportions in data. The python library ‘matplotlib’ provides many useful tools for creating beautiful visualizations, including pie charts. In this post, we will discuss how to use ‘matplotlib’ to create pie charts in python." }, { "code": null, "e": 499, "s": 480, "text": "Let’s get started!" }, { "code": null, "e": 601, "s": 499, "text": "For our purposes, we will be using the Netflix Movies and TV Shows data set, which can be found here." }, { "code": null, "e": 657, "s": 601, "text": "To start, let’s read the data into a Pandas data frame;" }, { "code": null, "e": 716, "s": 657, "text": "import pandas as pd df = pd.read_csv(\"netflix_titles.csv\")" }, { "code": null, "e": 790, "s": 716, "text": "Next, let’s print the first five rows of data using the ‘.head()’ method:" }, { "code": null, "e": 807, "s": 790, "text": "print(df.head())" }, { "code": null, "e": 1123, "s": 807, "text": "As we can see, the data contains columns with various categorical values. Pie charts typically show relative proportions of different categories in a data set. For our pie chart visualizations, the ‘rating’, ‘country’ ,and ‘type’ columns are good examples of data with categorical values we can group and visualize." }, { "code": null, "e": 1315, "s": 1123, "text": "To get an idea of the distribution in categorical values for these columns, we can use the ‘Counter’ method from the collections module. Let’s apply the ‘Counter’ method to the ‘type’ column:" }, { "code": null, "e": 1373, "s": 1315, "text": "from collections import Counterprint(Counter(df['type']))" }, { "code": null, "e": 1413, "s": 1373, "text": "Let’s also look at the ‘rating’ column:" }, { "code": null, "e": 1442, "s": 1413, "text": "print(Counter(df['rating']))" }, { "code": null, "e": 1532, "s": 1442, "text": "Now, let’s proceed by grouping our data by the number of values for each ‘type’ category:" }, { "code": null, "e": 1594, "s": 1532, "text": "title_type = df.groupby('type').agg('count')print(title_type)" }, { "code": null, "e": 1646, "s": 1594, "text": "Next, let’s import a few modules from ‘matplotlib’:" }, { "code": null, "e": 1802, "s": 1646, "text": "import matplotlib.ticker as tickerimport matplotlib.cm as cmimport matplotlib as mplfrom matplotlib.gridspec import GridSpecimport matplotlib.pyplot as plt" }, { "code": null, "e": 1867, "s": 1802, "text": "Now, let’s sort the indices and counts for our aggregated types:" }, { "code": null, "e": 1967, "s": 1867, "text": "type_labels = title_type.show_id.sort_values().index type_counts = title_type.show_id.sort_values()" }, { "code": null, "e": 2003, "s": 1967, "text": "We then specify the figure details:" }, { "code": null, "e": 2060, "s": 2003, "text": "plt.figure(1, figsize=(20,10)) the_grid = GridSpec(2, 2)" }, { "code": null, "e": 2099, "s": 2060, "text": "and specify the color map information:" }, { "code": null, "e": 2179, "s": 2099, "text": "cmap = plt.get_cmap('Spectral')colors = [cmap(i) for i in np.linspace(0, 1, 8)]" }, { "code": null, "e": 2214, "s": 2179, "text": "Finally, let’s plot our pie chart:" }, { "code": null, "e": 2398, "s": 2214, "text": "plt.subplot(the_grid[0, 1], aspect=1, title='Types of Netflix Titles')type_show_ids = plt.pie(type_counts, labels=type_labels, autopct='%1.1f%%', shadow=True, colors=colors)plt.show()" }, { "code": null, "e": 2543, "s": 2398, "text": "We see that most of the Netflix titles in this data set are movies. We can also generate a pie chart for the ratings. Let’s aggregate by rating:" }, { "code": null, "e": 2699, "s": 2543, "text": "title_rating = df.groupby('rating').agg('count')rating_labels = title_rating.show_id.sort_values().index rating_counts = title_rating.show_id.sort_values()" }, { "code": null, "e": 2719, "s": 2699, "text": "And plot our chart:" }, { "code": null, "e": 3043, "s": 2719, "text": "plt.figure(1, figsize=(40,20))the_grid = GridSpec(2, 2)cmap = plt.get_cmap('Spectral')colors = [cmap(i) for i in np.linspace(0, 1, 8)]plt.subplot(the_grid[0, 1], aspect=1, title='Ratings of Netflix Titles')type_show_ids = plt.pie(rating_counts, labels=rating_labels, autopct='%1.1f%%', shadow=True, colors=colors)plt.show()" }, { "code": null, "e": 3548, "s": 3043, "text": "We see ‘TV-14’ and ‘TV-MA’ are the most common ratings in the data. A drawback of pie charts is that they become less useful the more categories present within a column. For example, in our ratings pie chart the ‘G’, ‘NC-17’, and ‘UR’ ratings overlap which doesn’t look visually pleasing. You can imagine that this gets worse with an increasing number of categories. To resolve this, let’s define a function that calculate the 75th percentile and groups the lesser counts together in an ‘other’ category:" }, { "code": null, "e": 4042, "s": 3548, "text": "def group_lower_ranking_values(column): rating_counts = df.groupby(column).agg('count') pct_value = rating_counts[lambda x: x.columns[0]].quantile(.75) values_below_pct_value = rating_counts[lambda x: x.columns[0]].loc[lambda s: s < pct_value].index.values def fix_values(row): if row[column] in values_below_pct_value: row[column] = 'Other' return row rating_grouped = df.apply(fix_values, axis=1).groupby(column).agg('count') return rating_grouped" }, { "code": null, "e": 4093, "s": 4042, "text": "We can now aggregate our data using this function:" }, { "code": null, "e": 4258, "s": 4093, "text": "rating_grouped = group_lower_ranking_values('rating')rating_labels = rating_grouped.show_id.sort_values().index rating_counts = rating_grouped.show_id.sort_values()" }, { "code": null, "e": 4279, "s": 4258, "text": "And plot the result:" }, { "code": null, "e": 4468, "s": 4279, "text": "plt.subplot(the_grid[0, 1], aspect=1, title='Rating of Netflix Titles')type_show_ids = plt.pie(rating_counts, labels=rating_labels, autopct='%1.1f%%', shadow=True, colors=colors)plt.show()" }, { "code": null, "e": 4608, "s": 4468, "text": "We see this looks much better than the previous plot. Let’s do the same for the country column. Here, we will consider the 99th percentile:" }, { "code": null, "e": 5115, "s": 4608, "text": "def group_lower_ranking_values(column): ... pct_value = rating_counts[lambda x: x.columns[0]].quantile(.99) ... return rating_groupedcountry_grouped = group_lower_ranking_values('country')country_labels = country_grouped.show_id.sort_values().index country_counts = country_grouped.show_id.sort_values()plt.subplot(the_grid[0, 1], aspect=1, title='Country of Netflix Titles')type_show_ids = plt.pie(country_counts, labels=country_labels, autopct='%1.1f%%', shadow=True, colors=colors)plt.show()" }, { "code": null, "e": 5183, "s": 5115, "text": "I’ll stop here but feel free to play around with the code yourself." } ]
2D Vector of Pairs in C++ with Examples - GeeksforGeeks
19 Dec, 2021 What is Vector? In C++, a vector is similar to dynamic arrays with the ability to resize itself automatically. Vector elements are stored in contiguous memory locations so that they can be accessed and traversed using iterators. Some of the functions associated with a vector: begin(): Returns an iterator pointing to the first element in the vector end(): Returns an iterator pointing to the theoretical element that follows the last element in the vector rbegin(): Returns a reverse iterator pointing to the last element in the vector (reverse beginning). It moves from last to first element size(): Returns the number of elements in the vector. empty(): Returns whether the vector is empty. push_back(): It pushes the elements into a vector from the back pop_back(): It is used to pop or remove elements from a vector from the back. insert(): It inserts new elements before the element at the specified position What is 2D vector? In C++, a 2D vector is a vector of vectors which means that each element of a 2D vector is a vector itself. It is the same as a matrix implemented with the help of vectors. Some of the functions associated with a 2D vector: size(): Returns the number of elements in the 2D vector. empty(): Returns whether the 2D vector is empty. push_back(): It pushes a vector into a 2D vector from the back. pop_back(): It is used to pop or remove elements from a 2D vector from the back. What is Pair? Utility header in C++ provides us pair container. A pair consists of two data elements or objects. The first element is referenced as ‘first’ and the second element as ‘second’ and the order is fixed (first, second). Pair is used to combine together two values that may be different in type. Pair provides a way to store two heterogeneous objects as a single unit. Pair can be assigned, copied, and compared. The array of objects allocated in a map or hash_map is of type ‘pair’ by default in which all the ‘first’ elements are unique keys associated with their ‘second’ value objects. To access the elements, we use variable name followed by dot operator followed by the keyword first or second. How to access a Pair? To access elements of a pair use the dot (.) operator. Syntax: auto fistElement = myPair.first; auto fistElement = myPair.second; 2D Vector of Pairs A 2D vector of pairs or vector of vectors of pairs is a vector in which each element is a vector of pairs itself. Syntax: vector<vector<pair<dataType1, dataType2>> myContainer Here, dataType1 and dataType2 can be similar or dissimilar data types. Example 1: In the below C++ program, a vector of vectors of pairs of type {int, string} is used. C++ // C++ program to demonstrate the // working of vector of vectors // of pairs#include <bits/stdc++.h>using namespace std; // Function to print 2D vector elementsvoid print(vector<vector<pair<int, string>>> &myContainer){ // Iterating over 2D vector elements for(auto currentVector: myContainer) { // Each element of the 2D vector // is a vector itself vector<pair<int, string>> myVector = currentVector; // Iterating over the the vector // elements cout << "[ "; for(auto pr: myVector) { // Print the element cout << "{"; cout << pr.first << " , " << pr.second; cout << "} "; } cout << "]\n"; }} // Driver codeint main() { // Declaring a 2D vector of pairs vector<vector<pair<int, string>>> myContainer; // Initializing vectors of pairs // Pairs are of type {int, string} vector<pair<int, string>> vect1 = {{0, "GeeksforGeeks"}, {1, "GFG"}, {2, "Computer Science"}}; vector<pair<int, string>> vect2 = {{0, "C#"}, {1, "C"}, {2, "C++"}}; vector<pair<int, string>> vect3 = {{0, "HTML"}, {1, "CSS"}, {2, "Javascript"}}; vector<pair<int, string>> vect4 = {{0, "R"}, {1, "Swift"}, {2, "Python"}}; // Inserting vectors in the // 2D vector myContainer.push_back(vect1); myContainer.push_back(vect2); myContainer.push_back(vect3); myContainer.push_back(vect4); // Calling print function print(myContainer); return 0;} Output: [ {0 , GeeksforGeeks} {1 , GFG} {2 , Computer Science} ][ {0 , C#} {1 , C} {2 , C++} ][ {0 , HTML} {1 , CSS} {2 , Javascript} ][ {0 , R} {1 , Swift} {2 , Python} ] Example 2: In the below C++ program, a vector of vectors of pairs of type {char, bool} is used. C++ // C++ program to demonstrate the // working of vector of vectors // of pairs#include <bits/stdc++.h>using namespace std; // Function to print 2D vector elementsvoid print(vector<vector<pair<char, bool>>> &myContainer){ // Iterating over 2D vector elements for(auto currentVector: myContainer) { // Each element of the 2D vector is // a vector itself vector<pair<char, bool>> myVector = currentVector; // Iterating over the the vector // elements cout << "[ "; for(auto pr: myVector) { // Print the element cout << "{"; cout << pr.first << " , " << pr.second; cout << "} "; } cout << "]\n"; }} // Driver codeint main() { // Declaring a 2D vector of pairs // Pairs are of type {char, bool} vector<vector<pair<char, bool>>> myContainer; // Initializing vectors of pairs vector<pair<char, bool>> vect1 = {{'G', 0}, {'e', 0}, {'e', 0}, {'k', 0}}; vector<pair<char, bool>> vect2 = {{'G', 1}, {'e', 1}, {'e', 1}, {'k', 1}}; vector<pair<char, bool>> vect3 = {{'G', 0}, {'e', 0}, {'e', 0}, {'k', 1}}; vector<pair<char, bool>> vect4 = {{'G', 0}, {'e', 1}, {'e', 0}, {'k', 1}}; // Inserting vectors in the 2D vector myContainer.push_back(vect1); myContainer.push_back(vect2); myContainer.push_back(vect3); myContainer.push_back(vect4); print(myContainer); return 0;} Output: [ {G , 0} {e , 0} {e , 0} {k , 0} ][ {G , 1} {e , 1} {e , 1} {k , 1} ][ {G , 0} {e , 0} {e , 0} {k , 1} ][ {G , 0} {e , 1} {e , 0} {k , 1} ] cpp-pair cpp-vector C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Friend class and function in C++ Sorting a vector in C++ std::string class in C++ Inline Functions in C++ Pair in C++ Standard Template Library (STL) Array of Strings in C++ (5 Different Ways to Create) Convert string to char array in C++ Destructors in C++
[ { "code": null, "e": 25479, "s": 25451, "text": "\n19 Dec, 2021" }, { "code": null, "e": 25495, "s": 25479, "text": "What is Vector?" }, { "code": null, "e": 25708, "s": 25495, "text": "In C++, a vector is similar to dynamic arrays with the ability to resize itself automatically. Vector elements are stored in contiguous memory locations so that they can be accessed and traversed using iterators." }, { "code": null, "e": 25756, "s": 25708, "text": "Some of the functions associated with a vector:" }, { "code": null, "e": 25829, "s": 25756, "text": "begin(): Returns an iterator pointing to the first element in the vector" }, { "code": null, "e": 25936, "s": 25829, "text": "end(): Returns an iterator pointing to the theoretical element that follows the last element in the vector" }, { "code": null, "e": 26073, "s": 25936, "text": "rbegin(): Returns a reverse iterator pointing to the last element in the vector (reverse beginning). It moves from last to first element" }, { "code": null, "e": 26127, "s": 26073, "text": "size(): Returns the number of elements in the vector." }, { "code": null, "e": 26173, "s": 26127, "text": "empty(): Returns whether the vector is empty." }, { "code": null, "e": 26237, "s": 26173, "text": "push_back(): It pushes the elements into a vector from the back" }, { "code": null, "e": 26315, "s": 26237, "text": "pop_back(): It is used to pop or remove elements from a vector from the back." }, { "code": null, "e": 26394, "s": 26315, "text": "insert(): It inserts new elements before the element at the specified position" }, { "code": null, "e": 26413, "s": 26394, "text": "What is 2D vector?" }, { "code": null, "e": 26586, "s": 26413, "text": "In C++, a 2D vector is a vector of vectors which means that each element of a 2D vector is a vector itself. It is the same as a matrix implemented with the help of vectors." }, { "code": null, "e": 26637, "s": 26586, "text": "Some of the functions associated with a 2D vector:" }, { "code": null, "e": 26694, "s": 26637, "text": "size(): Returns the number of elements in the 2D vector." }, { "code": null, "e": 26743, "s": 26694, "text": "empty(): Returns whether the 2D vector is empty." }, { "code": null, "e": 26807, "s": 26743, "text": "push_back(): It pushes a vector into a 2D vector from the back." }, { "code": null, "e": 26888, "s": 26807, "text": "pop_back(): It is used to pop or remove elements from a 2D vector from the back." }, { "code": null, "e": 26902, "s": 26888, "text": "What is Pair?" }, { "code": null, "e": 27001, "s": 26902, "text": "Utility header in C++ provides us pair container. A pair consists of two data elements or objects." }, { "code": null, "e": 27119, "s": 27001, "text": "The first element is referenced as ‘first’ and the second element as ‘second’ and the order is fixed (first, second)." }, { "code": null, "e": 27267, "s": 27119, "text": "Pair is used to combine together two values that may be different in type. Pair provides a way to store two heterogeneous objects as a single unit." }, { "code": null, "e": 27488, "s": 27267, "text": "Pair can be assigned, copied, and compared. The array of objects allocated in a map or hash_map is of type ‘pair’ by default in which all the ‘first’ elements are unique keys associated with their ‘second’ value objects." }, { "code": null, "e": 27599, "s": 27488, "text": "To access the elements, we use variable name followed by dot operator followed by the keyword first or second." }, { "code": null, "e": 27621, "s": 27599, "text": "How to access a Pair?" }, { "code": null, "e": 27676, "s": 27621, "text": "To access elements of a pair use the dot (.) operator." }, { "code": null, "e": 27684, "s": 27676, "text": "Syntax:" }, { "code": null, "e": 27717, "s": 27684, "text": "auto fistElement = myPair.first;" }, { "code": null, "e": 27751, "s": 27717, "text": "auto fistElement = myPair.second;" }, { "code": null, "e": 27770, "s": 27751, "text": "2D Vector of Pairs" }, { "code": null, "e": 27885, "s": 27770, "text": "A 2D vector of pairs or vector of vectors of pairs is a vector in which each element is a vector of pairs itself. " }, { "code": null, "e": 27893, "s": 27885, "text": "Syntax:" }, { "code": null, "e": 27947, "s": 27893, "text": "vector<vector<pair<dataType1, dataType2>> myContainer" }, { "code": null, "e": 27953, "s": 27947, "text": "Here," }, { "code": null, "e": 28018, "s": 27953, "text": "dataType1 and dataType2 can be similar or dissimilar data types." }, { "code": null, "e": 28115, "s": 28018, "text": "Example 1: In the below C++ program, a vector of vectors of pairs of type {int, string} is used." }, { "code": null, "e": 28119, "s": 28115, "text": "C++" }, { "code": "// C++ program to demonstrate the // working of vector of vectors // of pairs#include <bits/stdc++.h>using namespace std; // Function to print 2D vector elementsvoid print(vector<vector<pair<int, string>>> &myContainer){ // Iterating over 2D vector elements for(auto currentVector: myContainer) { // Each element of the 2D vector // is a vector itself vector<pair<int, string>> myVector = currentVector; // Iterating over the the vector // elements cout << \"[ \"; for(auto pr: myVector) { // Print the element cout << \"{\"; cout << pr.first << \" , \" << pr.second; cout << \"} \"; } cout << \"]\\n\"; }} // Driver codeint main() { // Declaring a 2D vector of pairs vector<vector<pair<int, string>>> myContainer; // Initializing vectors of pairs // Pairs are of type {int, string} vector<pair<int, string>> vect1 = {{0, \"GeeksforGeeks\"}, {1, \"GFG\"}, {2, \"Computer Science\"}}; vector<pair<int, string>> vect2 = {{0, \"C#\"}, {1, \"C\"}, {2, \"C++\"}}; vector<pair<int, string>> vect3 = {{0, \"HTML\"}, {1, \"CSS\"}, {2, \"Javascript\"}}; vector<pair<int, string>> vect4 = {{0, \"R\"}, {1, \"Swift\"}, {2, \"Python\"}}; // Inserting vectors in the // 2D vector myContainer.push_back(vect1); myContainer.push_back(vect2); myContainer.push_back(vect3); myContainer.push_back(vect4); // Calling print function print(myContainer); return 0;}", "e": 29573, "s": 28119, "text": null }, { "code": null, "e": 29581, "s": 29573, "text": "Output:" }, { "code": null, "e": 29761, "s": 29581, "text": "[ {0 , GeeksforGeeks} {1 , GFG} {2 , Computer Science} ][ {0 , C#} {1 , C} {2 , C++} ][ {0 , HTML} {1 , CSS} {2 , Javascript} ][ {0 , R} {1 , Swift} {2 , Python} ]" }, { "code": null, "e": 29857, "s": 29761, "text": "Example 2: In the below C++ program, a vector of vectors of pairs of type {char, bool} is used." }, { "code": null, "e": 29861, "s": 29857, "text": "C++" }, { "code": "// C++ program to demonstrate the // working of vector of vectors // of pairs#include <bits/stdc++.h>using namespace std; // Function to print 2D vector elementsvoid print(vector<vector<pair<char, bool>>> &myContainer){ // Iterating over 2D vector elements for(auto currentVector: myContainer) { // Each element of the 2D vector is // a vector itself vector<pair<char, bool>> myVector = currentVector; // Iterating over the the vector // elements cout << \"[ \"; for(auto pr: myVector) { // Print the element cout << \"{\"; cout << pr.first << \" , \" << pr.second; cout << \"} \"; } cout << \"]\\n\"; }} // Driver codeint main() { // Declaring a 2D vector of pairs // Pairs are of type {char, bool} vector<vector<pair<char, bool>>> myContainer; // Initializing vectors of pairs vector<pair<char, bool>> vect1 = {{'G', 0}, {'e', 0}, {'e', 0}, {'k', 0}}; vector<pair<char, bool>> vect2 = {{'G', 1}, {'e', 1}, {'e', 1}, {'k', 1}}; vector<pair<char, bool>> vect3 = {{'G', 0}, {'e', 0}, {'e', 0}, {'k', 1}}; vector<pair<char, bool>> vect4 = {{'G', 0}, {'e', 1}, {'e', 0}, {'k', 1}}; // Inserting vectors in the 2D vector myContainer.push_back(vect1); myContainer.push_back(vect2); myContainer.push_back(vect3); myContainer.push_back(vect4); print(myContainer); return 0;}", "e": 31262, "s": 29861, "text": null }, { "code": null, "e": 31270, "s": 31262, "text": "Output:" }, { "code": null, "e": 31431, "s": 31270, "text": "[ {G , 0} {e , 0} {e , 0} {k , 0} ][ {G , 1} {e , 1} {e , 1} {k , 1} ][ {G , 0} {e , 0} {e , 0} {k , 1} ][ {G , 0} {e , 1} {e , 0} {k , 1} ]" }, { "code": null, "e": 31440, "s": 31431, "text": "cpp-pair" }, { "code": null, "e": 31451, "s": 31440, "text": "cpp-vector" }, { "code": null, "e": 31455, "s": 31451, "text": "C++" }, { "code": null, "e": 31459, "s": 31455, "text": "CPP" }, { "code": null, "e": 31557, "s": 31459, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31585, "s": 31557, "text": "Operator Overloading in C++" }, { "code": null, "e": 31605, "s": 31585, "text": "Polymorphism in C++" }, { "code": null, "e": 31638, "s": 31605, "text": "Friend class and function in C++" }, { "code": null, "e": 31662, "s": 31638, "text": "Sorting a vector in C++" }, { "code": null, "e": 31687, "s": 31662, "text": "std::string class in C++" }, { "code": null, "e": 31711, "s": 31687, "text": "Inline Functions in C++" }, { "code": null, "e": 31755, "s": 31711, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 31808, "s": 31755, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 31844, "s": 31808, "text": "Convert string to char array in C++" } ]
ML | Models Score and Error - GeeksforGeeks
02 Aug, 2019 In Machine Learning one of the main task is to model the data and predict the output using various Classification and Regression Algorithms. But since there are so many Algorithms, it is really difficult to choose the one for predicting the final data. So we need to compare our models and choose the one with the highest accuracy. Using the sklearn library we can find out the scores of our ML Model and thus choose the algorithm with a higher score to predict our output. Another good way is to calculate errors such as mean absolute error and mean squared error and try to minimize them to better our models. Mean Absolute Error(MAE): It is the mean of all absolute error Mean Squared Error (MSE) It is the mean of square of all errors. Here, we are using Titanic dataset as our input for Classification problem and modelling our data with Logistic Regression and KNN only. Although, you can also model with other algorithms. You can find the dataset here # importing librariesimport numpy as npimport sklearnfrom sklearn import metricsimport pandas as pd from sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LogisticRegressionfrom sklearn.neighbors import KNeighborsClassifier data = pd.read_csv("gfg_data") x = data[['Pclass', 'Sex', 'Age', 'Parch', 'Embarked', 'Fare', 'Has_Cabin', 'FamilySize', 'title', 'IsAlone']] y = data[['Survived']] X_train, X_test, Y_train, Y_test = train_test_split(x, y,test_size = 0.3, random_state = None) # logistic Regressionlr = LogisticRegression()lr.fit(X_train, Y_train) Y_pred = lr.predict(X_test) LogReg = round(lr.score(X_test, Y_test), 2) mae_lr = round(metrics.mean_absolute_error(Y_test, Y_pred), 4)mse_lr = round(metrics.mean_squared_error(Y_test, Y_pred), 4) # KNNknn = KNeighborsClassifier(n_neighbors = 2)knn.fit(X_train, Y_train) Y_pred = knn.predict(X_test) KNN = round(knn.score(X_test, Y_test), 2) mae_knn = metrics.mean_absolute_error(Y_test, Y_pred)mse_knn = metrics.mean_squared_error(Y_test, Y_pred) compare_models = pd.DataFrame( { 'Model' : ['LogReg', 'KNN'], 'Score' : [LogReg, KNN], 'MAE' : [mae_lr, mae_knn], 'MSE' : [mse_lr, mse_knn] }) print(compare_models) Output: We can now see the score and error of our models and compare them. Score of Logistic Regression is greater then KNN and error is also less. Thus, Logistic Regression will be the right choice for our model. Machine Learning Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Support Vector Machine Algorithm Intuition of Adam Optimizer Introduction to Recurrent Neural Network Singular Value Decomposition (SVD) k-nearest neighbor algorithm in Python CNN | Introduction to Pooling Layer Python | Decision Tree Regression using sklearn Bagging vs Boosting in Machine Learning Python | Stemming words with NLTK DBSCAN Clustering in ML | Density based clustering
[ { "code": null, "e": 24467, "s": 24439, "text": "\n02 Aug, 2019" }, { "code": null, "e": 24799, "s": 24467, "text": "In Machine Learning one of the main task is to model the data and predict the output using various Classification and Regression Algorithms. But since there are so many Algorithms, it is really difficult to choose the one for predicting the final data. So we need to compare our models and choose the one with the highest accuracy." }, { "code": null, "e": 25079, "s": 24799, "text": "Using the sklearn library we can find out the scores of our ML Model and thus choose the algorithm with a higher score to predict our output. Another good way is to calculate errors such as mean absolute error and mean squared error and try to minimize them to better our models." }, { "code": null, "e": 25142, "s": 25079, "text": "Mean Absolute Error(MAE): It is the mean of all absolute error" }, { "code": null, "e": 25207, "s": 25142, "text": "Mean Squared Error (MSE) It is the mean of square of all errors." }, { "code": null, "e": 25426, "s": 25207, "text": "Here, we are using Titanic dataset as our input for Classification problem and modelling our data with Logistic Regression and KNN only. Although, you can also model with other algorithms. You can find the dataset here" }, { "code": "# importing librariesimport numpy as npimport sklearnfrom sklearn import metricsimport pandas as pd from sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LogisticRegressionfrom sklearn.neighbors import KNeighborsClassifier data = pd.read_csv(\"gfg_data\") x = data[['Pclass', 'Sex', 'Age', 'Parch', 'Embarked', 'Fare', 'Has_Cabin', 'FamilySize', 'title', 'IsAlone']] y = data[['Survived']] X_train, X_test, Y_train, Y_test = train_test_split(x, y,test_size = 0.3, random_state = None) # logistic Regressionlr = LogisticRegression()lr.fit(X_train, Y_train) Y_pred = lr.predict(X_test) LogReg = round(lr.score(X_test, Y_test), 2) mae_lr = round(metrics.mean_absolute_error(Y_test, Y_pred), 4)mse_lr = round(metrics.mean_squared_error(Y_test, Y_pred), 4) # KNNknn = KNeighborsClassifier(n_neighbors = 2)knn.fit(X_train, Y_train) Y_pred = knn.predict(X_test) KNN = round(knn.score(X_test, Y_test), 2) mae_knn = metrics.mean_absolute_error(Y_test, Y_pred)mse_knn = metrics.mean_squared_error(Y_test, Y_pred) compare_models = pd.DataFrame( { 'Model' : ['LogReg', 'KNN'], 'Score' : [LogReg, KNN], 'MAE' : [mae_lr, mae_knn], 'MSE' : [mse_lr, mse_knn] }) print(compare_models)", "e": 26685, "s": 25426, "text": null }, { "code": null, "e": 26693, "s": 26685, "text": "Output:" }, { "code": null, "e": 26899, "s": 26693, "text": "We can now see the score and error of our models and compare them. Score of Logistic Regression is greater then KNN and error is also less. Thus, Logistic Regression will be the right choice for our model." }, { "code": null, "e": 26916, "s": 26899, "text": "Machine Learning" }, { "code": null, "e": 26933, "s": 26916, "text": "Machine Learning" }, { "code": null, "e": 27031, "s": 26933, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27064, "s": 27031, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 27092, "s": 27064, "text": "Intuition of Adam Optimizer" }, { "code": null, "e": 27133, "s": 27092, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 27168, "s": 27133, "text": "Singular Value Decomposition (SVD)" }, { "code": null, "e": 27207, "s": 27168, "text": "k-nearest neighbor algorithm in Python" }, { "code": null, "e": 27243, "s": 27207, "text": "CNN | Introduction to Pooling Layer" }, { "code": null, "e": 27291, "s": 27243, "text": "Python | Decision Tree Regression using sklearn" }, { "code": null, "e": 27331, "s": 27291, "text": "Bagging vs Boosting in Machine Learning" }, { "code": null, "e": 27365, "s": 27331, "text": "Python | Stemming words with NLTK" } ]
CSS | @import rule - GeeksforGeeks
07 Jan, 2019 The @import rule is used to import one style sheet into another style sheet. This rule also support media queries so that the user can import the media-dependent style sheet. The @import rule must be declared at the top of the document after any @charset declaration. Syntax: @import url|string list-of-mediaqueries; Property Values: url|string: A url or a string represents the location of the resource to be imported. The url may be relative or absolute list-of-mediaqueries: The list of media queries condition the application of the CSS rules defined in the linked URL Example: Consider the two CSS files as shown below. icss.css@import url("i1css.css"); h1 { color: #00ff00; } @import url("i1css.css"); h1 { color: #00ff00; } i1css.cssh1 { text-decoration: underline; font-size:60px; } p { padding-left: 20px; font-size: 60px; } h1 { text-decoration: underline; font-size:60px; } p { padding-left: 20px; font-size: 60px; } Link the first CSS file icss.css in the below HTML file and see the output. <!DOCTYPE html><html><head> <title>WebPage</title> <link href="icss.css" rel="stylesheet"></head> <body> <h1>GeeksforGeeks</h1> <p>A computer science portal for geeks</p></body></html> Output: Supported Browsers:The browsers supported by @import rule are listed below: Google Chrome Internet Explorer 5.5 Firefox Safari Opera CSS-Basics CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to create footer to stay at the bottom of a Web page? How to apply style to parent if it has child with CSS? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24186, "s": 24158, "text": "\n07 Jan, 2019" }, { "code": null, "e": 24454, "s": 24186, "text": "The @import rule is used to import one style sheet into another style sheet. This rule also support media queries so that the user can import the media-dependent style sheet. The @import rule must be declared at the top of the document after any @charset declaration." }, { "code": null, "e": 24462, "s": 24454, "text": "Syntax:" }, { "code": null, "e": 24504, "s": 24462, "text": "@import url|string list-of-mediaqueries;\n" }, { "code": null, "e": 24521, "s": 24504, "text": "Property Values:" }, { "code": null, "e": 24643, "s": 24521, "text": "url|string: A url or a string represents the location of the resource to be imported. The url may be relative or absolute" }, { "code": null, "e": 24760, "s": 24643, "text": "list-of-mediaqueries: The list of media queries condition the application of the CSS rules defined in the linked URL" }, { "code": null, "e": 24812, "s": 24760, "text": "Example: Consider the two CSS files as shown below." }, { "code": null, "e": 24874, "s": 24812, "text": "icss.css@import url(\"i1css.css\");\nh1 {\n color: #00ff00;\n}\n" }, { "code": null, "e": 24928, "s": 24874, "text": "@import url(\"i1css.css\");\nh1 {\n color: #00ff00;\n}\n" }, { "code": null, "e": 25045, "s": 24928, "text": "i1css.cssh1 {\n text-decoration: underline;\n font-size:60px;\n}\n\np {\n padding-left: 20px;\n font-size: 60px;\n}\n" }, { "code": null, "e": 25153, "s": 25045, "text": "h1 {\n text-decoration: underline;\n font-size:60px;\n}\n\np {\n padding-left: 20px;\n font-size: 60px;\n}\n" }, { "code": null, "e": 25229, "s": 25153, "text": "Link the first CSS file icss.css in the below HTML file and see the output." }, { "code": "<!DOCTYPE html><html><head> <title>WebPage</title> <link href=\"icss.css\" rel=\"stylesheet\"></head> <body> <h1>GeeksforGeeks</h1> <p>A computer science portal for geeks</p></body></html> ", "e": 25447, "s": 25229, "text": null }, { "code": null, "e": 25455, "s": 25447, "text": "Output:" }, { "code": null, "e": 25531, "s": 25455, "text": "Supported Browsers:The browsers supported by @import rule are listed below:" }, { "code": null, "e": 25545, "s": 25531, "text": "Google Chrome" }, { "code": null, "e": 25567, "s": 25545, "text": "Internet Explorer 5.5" }, { "code": null, "e": 25575, "s": 25567, "text": "Firefox" }, { "code": null, "e": 25582, "s": 25575, "text": "Safari" }, { "code": null, "e": 25588, "s": 25582, "text": "Opera" }, { "code": null, "e": 25599, "s": 25588, "text": "CSS-Basics" }, { "code": null, "e": 25603, "s": 25599, "text": "CSS" }, { "code": null, "e": 25620, "s": 25603, "text": "Web Technologies" }, { "code": null, "e": 25718, "s": 25620, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25768, "s": 25718, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 25830, "s": 25768, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 25878, "s": 25830, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 25936, "s": 25878, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 25991, "s": 25936, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 26031, "s": 25991, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 26064, "s": 26031, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26109, "s": 26064, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 26152, "s": 26109, "text": "How to fetch data from an API in ReactJS ?" } ]
Semaphores in Kotlin - GeeksforGeeks
28 Feb, 2022 Semaphore is a set of permits. Assume it as a box that has the tokens(permits) for attending(performing) a task. Threads have access to Semaphore but not those permits. Depending on the number of permits, and when a thread arrives at the semaphore, a permit is given. If a Thread arrives when there are no permits available, it has to wait until a permit is assigned to it. Only then a task can be performed. So basically, A Semaphore is used in Multi-Threading or a Multi-Threaded application. There can be multiple processes running in an application. The use of Semaphore is to restrict or control access to any common resource by multiple threads(processes). Semaphore by definition is used for signaling from one task to another. They allow flexible source management. Threads arriving at Semaphore for the resources.Semaphore assigning Permits to the Threads and halts the rest of the Threads if falls short of Permits. The process of assigning Permit to a Thread is called Acquiring.Previously running Threads release the Permits when the task is completed. These Permits are now assigned to the halted Threads. This process where the Threads submit back the Permit is called Releasing. Threads arriving at Semaphore for the resources. Semaphore assigning Permits to the Threads and halts the rest of the Threads if falls short of Permits. The process of assigning Permit to a Thread is called Acquiring. Previously running Threads release the Permits when the task is completed. These Permits are now assigned to the halted Threads. This process where the Threads submit back the Permit is called Releasing. The program below is in Kotlin, an example where a Semaphore is used for running some activity in a Multi-Threaded process: The Semaphore is assigned a Permit value of 2 which means at a time only 2 Threads can run. The Threads declared in the below code have a Sleep Activity of 10 seconds (10000 Millisecs) which means a Permit is acquired by any of the Threads for 10 seconds. A print function is declared to print “.” to represent that Thread Activity is finished and the Permit is released. Since there is no priority assigned to any of the Threads, a NORM_PRIORITY(Default Priority = 5) to all the Threads and Preference would be given to the Thread that arrives first. import java.util.concurrent.Semaphore val s = Semaphore(2) val t1 = Thread(Runnable { s.acquireUninterruptibly() print("t1") Thread.sleep(10000) print(".") s.release()}) val t2 = Thread(Runnable { s.acquireUninterruptibly() print("t2") Thread.sleep(10000) print(".") s.release()}) val t3 = Thread(Runnable { s.acquireUninterruptibly() print("t3") Thread.sleep(10000) print(".") s.release()}) val t4 = Thread(Runnable { s.acquireUninterruptibly() print("t4") Thread.sleep(10000) print(".") s.release()}) t1.start()t2.start()t3.start()t4.start() Output: t1t2..t3t4.. Here 2 dots i.e. in the output “..” represents 10 seconds wait(Thread.sleep) between permit acquire and permit release. Note: Setting Priority to the Threads is possible. In such a case, the Threads are in Priority order and likewise, Permits are assigned to them. Multiple Semaphores can be declared depending upon the number of resources required by the process. nikhatkhan11 Kotlin Operating Systems Operating Systems 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 Retrofit with Kotlin Coroutine in Android Kotlin Android Tutorial Kotlin when expression Banker's Algorithm in Operating System Types of Operating Systems Page Replacement Algorithms in Operating Systems Program for FCFS CPU Scheduling | Set 1 Paging in Operating System
[ { "code": null, "e": 25413, "s": 25385, "text": "\n28 Feb, 2022" }, { "code": null, "e": 25822, "s": 25413, "text": "Semaphore is a set of permits. Assume it as a box that has the tokens(permits) for attending(performing) a task. Threads have access to Semaphore but not those permits. Depending on the number of permits, and when a thread arrives at the semaphore, a permit is given. If a Thread arrives when there are no permits available, it has to wait until a permit is assigned to it. Only then a task can be performed." }, { "code": null, "e": 26187, "s": 25822, "text": "So basically, A Semaphore is used in Multi-Threading or a Multi-Threaded application. There can be multiple processes running in an application. The use of Semaphore is to restrict or control access to any common resource by multiple threads(processes). Semaphore by definition is used for signaling from one task to another. They allow flexible source management." }, { "code": null, "e": 26607, "s": 26187, "text": "Threads arriving at Semaphore for the resources.Semaphore assigning Permits to the Threads and halts the rest of the Threads if falls short of Permits. The process of assigning Permit to a Thread is called Acquiring.Previously running Threads release the Permits when the task is completed. These Permits are now assigned to the halted Threads. This process where the Threads submit back the Permit is called Releasing." }, { "code": null, "e": 26656, "s": 26607, "text": "Threads arriving at Semaphore for the resources." }, { "code": null, "e": 26825, "s": 26656, "text": "Semaphore assigning Permits to the Threads and halts the rest of the Threads if falls short of Permits. The process of assigning Permit to a Thread is called Acquiring." }, { "code": null, "e": 27029, "s": 26825, "text": "Previously running Threads release the Permits when the task is completed. These Permits are now assigned to the halted Threads. This process where the Threads submit back the Permit is called Releasing." }, { "code": null, "e": 27153, "s": 27029, "text": "The program below is in Kotlin, an example where a Semaphore is used for running some activity in a Multi-Threaded process:" }, { "code": null, "e": 27245, "s": 27153, "text": "The Semaphore is assigned a Permit value of 2 which means at a time only 2 Threads can run." }, { "code": null, "e": 27409, "s": 27245, "text": "The Threads declared in the below code have a Sleep Activity of 10 seconds (10000 Millisecs) which means a Permit is acquired by any of the Threads for 10 seconds." }, { "code": null, "e": 27525, "s": 27409, "text": "A print function is declared to print “.” to represent that Thread Activity is finished and the Permit is released." }, { "code": null, "e": 27705, "s": 27525, "text": "Since there is no priority assigned to any of the Threads, a NORM_PRIORITY(Default Priority = 5) to all the Threads and Preference would be given to the Thread that arrives first." }, { "code": "import java.util.concurrent.Semaphore val s = Semaphore(2) val t1 = Thread(Runnable { s.acquireUninterruptibly() print(\"t1\") Thread.sleep(10000) print(\".\") s.release()}) val t2 = Thread(Runnable { s.acquireUninterruptibly() print(\"t2\") Thread.sleep(10000) print(\".\") s.release()}) val t3 = Thread(Runnable { s.acquireUninterruptibly() print(\"t3\") Thread.sleep(10000) print(\".\") s.release()}) val t4 = Thread(Runnable { s.acquireUninterruptibly() print(\"t4\") Thread.sleep(10000) print(\".\") s.release()}) t1.start()t2.start()t3.start()t4.start()", "e": 28317, "s": 27705, "text": null }, { "code": null, "e": 28325, "s": 28317, "text": "Output:" }, { "code": null, "e": 28339, "s": 28325, "text": "t1t2..t3t4..\n" }, { "code": null, "e": 28459, "s": 28339, "text": "Here 2 dots i.e. in the output “..” represents 10 seconds wait(Thread.sleep) between permit acquire and permit release." }, { "code": null, "e": 28704, "s": 28459, "text": "Note: Setting Priority to the Threads is possible. In such a case, the Threads are in Priority order and likewise, Permits are assigned to them. Multiple Semaphores can be declared depending upon the number of resources required by the process." }, { "code": null, "e": 28717, "s": 28704, "text": "nikhatkhan11" }, { "code": null, "e": 28724, "s": 28717, "text": "Kotlin" }, { "code": null, "e": 28742, "s": 28724, "text": "Operating Systems" }, { "code": null, "e": 28760, "s": 28742, "text": "Operating Systems" }, { "code": null, "e": 28858, "s": 28760, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28901, "s": 28858, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 28932, "s": 28901, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 28974, "s": 28932, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 28998, "s": 28974, "text": "Kotlin Android Tutorial" }, { "code": null, "e": 29021, "s": 28998, "text": "Kotlin when expression" }, { "code": null, "e": 29060, "s": 29021, "text": "Banker's Algorithm in Operating System" }, { "code": null, "e": 29087, "s": 29060, "text": "Types of Operating Systems" }, { "code": null, "e": 29136, "s": 29087, "text": "Page Replacement Algorithms in Operating Systems" }, { "code": null, "e": 29176, "s": 29136, "text": "Program for FCFS CPU Scheduling | Set 1" } ]
Java fall through switch statements
Following rules govern the fall through the behavior of switch statement. When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached. When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached. When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement. When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement. Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached. Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached. Live Demo public class Test { public static void main(String args[]) { // char grade = args[0].charAt(0); char grade = 'C'; switch(grade) { case 'A' : System.out.println("Excellent!"); break; case 'B' : case 'C' : System.out.println("Well done"); break; case 'D' : System.out.println("You passed"); case 'F' : System.out.println("Better try again"); break; default : System.out.println("Invalid grade"); } System.out.println("Your grade is " + grade); } } Compile and run the above program using various command line arguments. This will produce the following result − Well done Your grade is C
[ { "code": null, "e": 1137, "s": 1062, "text": " Following rules govern the fall through the behavior of switch statement." }, { "code": null, "e": 1277, "s": 1137, "text": "When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached." }, { "code": null, "e": 1417, "s": 1277, "text": "When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached." }, { "code": null, "e": 1554, "s": 1417, "text": "When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement." }, { "code": null, "e": 1691, "s": 1554, "text": "When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement." }, { "code": null, "e": 1837, "s": 1691, "text": "Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached." }, { "code": null, "e": 1983, "s": 1837, "text": "Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached." }, { "code": null, "e": 1993, "s": 1983, "text": "Live Demo" }, { "code": null, "e": 2627, "s": 1993, "text": "public class Test {\n\n public static void main(String args[]) {\n // char grade = args[0].charAt(0);\n char grade = 'C';\n\n switch(grade) {\n case 'A' :\n System.out.println(\"Excellent!\");\n break;\n case 'B' :\n case 'C' :\n System.out.println(\"Well done\");\n break;\n case 'D' :\n System.out.println(\"You passed\");\n case 'F' :\n System.out.println(\"Better try again\");\n break;\n default :\n System.out.println(\"Invalid grade\");\n }\n System.out.println(\"Your grade is \" + grade);\n }\n}" }, { "code": null, "e": 2740, "s": 2627, "text": "Compile and run the above program using various command line arguments. This will produce the following result −" }, { "code": null, "e": 2766, "s": 2740, "text": "Well done\nYour grade is C" } ]
Console.SetBufferSize() Method in C# - GeeksforGeeks
14 Mar, 2019 Console.SetBufferSize(Int32, Int32) Method is used to set the height and width of the screen buffer area to the specified values. Syntax: public static void SetBufferSize(int width, int height); Parameters:width: It sets the width of the buffer area measured in the form of columns.height: It sets the height of the buffer area measured in the form of rows. Return value: The new size of the buffer screen. Exceptions: ArgumentOutOfRangeException: If the height or width is less than or equal to zero Or height or width is greater than or equal to MaxValue. Also, if the width is less than WindowLeft + WindowWidth or height is less than WindowTop + WindowHeight then we will get the same exception. IOException: If an I/O error occurred. Note: As you will see via the horizontal and the vertical scrollbars in the below examples, as we give different dimensions, we get differently sized windows. Example 1: // C# program to demonstrate// the SetBufferSize Methodusing System;using System.Text;using System.IO; class GFG { // Main Method public static void Main() { // using the method Console.SetBufferSize(800, 800); Console.WriteLine("Start"); while (true) { Console.WriteLine("Great Geek's Example!!!"); } } // end Main} Output: Example 2: // C# program to demonstrate// the SetBufferSize Methodusing System;using System.Text;using System.IO; class GFG { // Main Method public static void Main() { Console.SetBufferSize(0, 80); Console.WriteLine("Great Geek's Example!!!"); Console.WriteLine("The Width's value is too less!"); } // end Main} Example 3: // C# program to demonstrate// the SetBufferSize Methodusing System;using System.Text;using System.IO; class GFG { // Main Method public static void Main() { Console.SetBufferSize(8000, -80); Console.WriteLine("Great Geek's Example!!!"); Console.WriteLine("The negativity of this height is unbearable!"); } // end Main} Reference: https://docs.microsoft.com/en-us/dotnet/api/system.console.setbuffersize?view=netframework-4.7.2 CSharp-Console-Class CSharp-method Picked C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Extension Method in C# HashSet in C# with Examples Partial Classes in C# Top 50 C# Interview Questions & Answers C# | How to insert an element in an Array? C# | List Class C# | Inheritance Lambda Expressions in C# Linked List Implementation in C# Convert String to Character Array in C#
[ { "code": null, "e": 24302, "s": 24274, "text": "\n14 Mar, 2019" }, { "code": null, "e": 24432, "s": 24302, "text": "Console.SetBufferSize(Int32, Int32) Method is used to set the height and width of the screen buffer area to the specified values." }, { "code": null, "e": 24497, "s": 24432, "text": "Syntax: public static void SetBufferSize(int width, int height);" }, { "code": null, "e": 24660, "s": 24497, "text": "Parameters:width: It sets the width of the buffer area measured in the form of columns.height: It sets the height of the buffer area measured in the form of rows." }, { "code": null, "e": 24709, "s": 24660, "text": "Return value: The new size of the buffer screen." }, { "code": null, "e": 24721, "s": 24709, "text": "Exceptions:" }, { "code": null, "e": 25002, "s": 24721, "text": "ArgumentOutOfRangeException: If the height or width is less than or equal to zero Or height or width is greater than or equal to MaxValue. Also, if the width is less than WindowLeft + WindowWidth or height is less than WindowTop + WindowHeight then we will get the same exception." }, { "code": null, "e": 25041, "s": 25002, "text": "IOException: If an I/O error occurred." }, { "code": null, "e": 25200, "s": 25041, "text": "Note: As you will see via the horizontal and the vertical scrollbars in the below examples, as we give different dimensions, we get differently sized windows." }, { "code": null, "e": 25211, "s": 25200, "text": "Example 1:" }, { "code": "// C# program to demonstrate// the SetBufferSize Methodusing System;using System.Text;using System.IO; class GFG { // Main Method public static void Main() { // using the method Console.SetBufferSize(800, 800); Console.WriteLine(\"Start\"); while (true) { Console.WriteLine(\"Great Geek's Example!!!\"); } } // end Main}", "e": 25600, "s": 25211, "text": null }, { "code": null, "e": 25608, "s": 25600, "text": "Output:" }, { "code": null, "e": 25619, "s": 25608, "text": "Example 2:" }, { "code": "// C# program to demonstrate// the SetBufferSize Methodusing System;using System.Text;using System.IO; class GFG { // Main Method public static void Main() { Console.SetBufferSize(0, 80); Console.WriteLine(\"Great Geek's Example!!!\"); Console.WriteLine(\"The Width's value is too less!\"); } // end Main}", "e": 25957, "s": 25619, "text": null }, { "code": null, "e": 25968, "s": 25957, "text": "Example 3:" }, { "code": "// C# program to demonstrate// the SetBufferSize Methodusing System;using System.Text;using System.IO; class GFG { // Main Method public static void Main() { Console.SetBufferSize(8000, -80); Console.WriteLine(\"Great Geek's Example!!!\"); Console.WriteLine(\"The negativity of this height is unbearable!\"); } // end Main}", "e": 26324, "s": 25968, "text": null }, { "code": null, "e": 26335, "s": 26324, "text": "Reference:" }, { "code": null, "e": 26432, "s": 26335, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.console.setbuffersize?view=netframework-4.7.2" }, { "code": null, "e": 26453, "s": 26432, "text": "CSharp-Console-Class" }, { "code": null, "e": 26467, "s": 26453, "text": "CSharp-method" }, { "code": null, "e": 26474, "s": 26467, "text": "Picked" }, { "code": null, "e": 26477, "s": 26474, "text": "C#" }, { "code": null, "e": 26575, "s": 26477, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26584, "s": 26575, "text": "Comments" }, { "code": null, "e": 26597, "s": 26584, "text": "Old Comments" }, { "code": null, "e": 26620, "s": 26597, "text": "Extension Method in C#" }, { "code": null, "e": 26648, "s": 26620, "text": "HashSet in C# with Examples" }, { "code": null, "e": 26670, "s": 26648, "text": "Partial Classes in C#" }, { "code": null, "e": 26710, "s": 26670, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 26753, "s": 26710, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 26769, "s": 26753, "text": "C# | List Class" }, { "code": null, "e": 26786, "s": 26769, "text": "C# | Inheritance" }, { "code": null, "e": 26811, "s": 26786, "text": "Lambda Expressions in C#" }, { "code": null, "e": 26844, "s": 26811, "text": "Linked List Implementation in C#" } ]
Erlang - Logical Operators
Following are the logical operators available in Erlang. The following code snippet shows how the various operators can be used. -module(helloworld). -export([start/0]). start() -> io:fwrite("~w~n",[true or false]), io:fwrite("~w~n",[true and false]), io:fwrite("~w~n",[true xor false]), io:fwrite("~w~n",[not false]). The output of the above program will be − true false true true Print Add Notes Bookmark this page
[ { "code": null, "e": 2358, "s": 2301, "text": "Following are the logical operators available in Erlang." }, { "code": null, "e": 2430, "s": 2358, "text": "The following code snippet shows how the various operators can be used." }, { "code": null, "e": 2640, "s": 2430, "text": "-module(helloworld). \n-export([start/0]). \n\nstart() -> \n io:fwrite(\"~w~n\",[true or false]), \n io:fwrite(\"~w~n\",[true and false]), \n io:fwrite(\"~w~n\",[true xor false]), \n io:fwrite(\"~w~n\",[not false])." }, { "code": null, "e": 2682, "s": 2640, "text": "The output of the above program will be −" }, { "code": null, "e": 2704, "s": 2682, "text": "true\nfalse\ntrue\ntrue\n" }, { "code": null, "e": 2711, "s": 2704, "text": " Print" }, { "code": null, "e": 2722, "s": 2711, "text": " Add Notes" } ]
Deep Learning and LSTM based Malware Classification | by Ferhat Ozgur Catak | Towards Data Science
Malware development has seen diversity in terms of architecture and features. This advancement in the competencies of malware poses a severe threat and opens new research dimensions in malware detection. This study is focused on metamorphic malware that is the most advanced member of the malware family. It is quite impossible for anti-virus applications using traditional signature-based methods to detect metamorphic malware, which makes it difficult to classify this type of malware accordingly. Recent research literature about malware detection and classification discusses this issue related to malware behaviour. Cite The Work If you find this implementation useful please cite it: @article{10.7717/peerj-cs.285,title = {Deep learning based Sequential model for malware analysis using Windows exe API Calls},author = {Catak, Ferhat Ozgur and Yazı, Ahmet Faruk and Elezaj, Ogerta and Ahmed, Javed},year = 2020,month = jul,keywords = {Malware analysis, Sequential models, Network security, Long-short-term memory, Malware dataset},volume = 6,pages = {e285},journal = {PeerJ Computer Science},issn = {2376-5992},url = {https://doi.org/10.7717/peerj-cs.285},doi = {10.7717/peerj-cs.285}} You can access the dataset from my My GitHub Repository. Malicious software, commonly known as malware, is any software intentionally designed to cause damage to computer systems and compromise user security. An application or code is considered malware if it secretly acts against the interests of the computer user and performs malicious activities. Malware targets various platforms such as servers, personal computers, mobile phones, and cameras to gain unauthorized access, steal personal data, and disrupt the normal function of the system. One approach to deal with malware protection problem is by identifying the malicious software and evaluating its behaviour. Usually, this problem is solved through the analysis of malware behaviour. This field closely follows the model of malicious software family, which also reflects the pattern of malicious behaviour. There are very few studies that have demonstrated the methods of classification according to the malware families. All operating system API calls made to act by any software show the overall direction of this program. Whether this program is a malware or not can be learned by examining these actions in-depth. If it is malware, then what is its malware family. The malware-made operating system API call is a data attribute, and the sequence in which those API calls are generated is also critical to detect the malware family. Performing specific API calls is a particular order that represents a behaviour. One of the deep learning methods LSTM (long-short term memory) has been commonly used in the processing of such time-sequential data. This research has two main objectives; first, we created a relevant dataset, and then, using this dataset, we did a comparative study using various machine learning to detect and classify malware automatically based on their types. One of the most important contributions of this work is the new Windows PE Malware API sequence dataset, which contains malware analysis information. There are 7107 malware from different classes in this dataset. The Cuckoo Sandbox application, as explained above, is used to obtain the Windows API call sequences of malicious software, and VirusTotal Service is used to detect the classes of malware. The following figure illustrates the system architecture used to collect the data and to classify them using LSTM algorithms. Our system consists of three main parts, data collection, data pre-processing and analyses, and data classification. The following steps were followed when creating the dataset. Cuckoo Sandbox application is installed on a computer running Ubuntu Linux distribution. The analysis machine was run as a virtual server to run and analyze malware. The Windows operating system is installed on this server. We import the usual standard libraries to build an LSTM model to detect the malware. import pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsfrom sklearn.preprocessing import LabelEncoderfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import confusion_matrixfrom keras.preprocessing.text import Tokenizerfrom keras.layers import LSTM, Dense, Dropout, Embeddingfrom keras.preprocessing import sequencefrom keras.utils import np_utilsfrom keras.models import Sequentialfrom keras.layers import SpatialDropout1Dfrom mlxtend.plotting import plot_confusion_matrix In this work, we will use standard our malware dataset to show the results. You can access the dataset from My GitHub Repository. We need to merge the call and the label datasets. malware_calls_df = pd.read_csv("calls.zip", compression="zip", sep="\t", names=["API_Calls"])malware_labels_df = pd.read_csv("types.zip", compression="zip", sep="\t", names=["API_Labels"])malware_calls_df["API_Labels"] = malware_labels_df.API_Labelsmalware_calls_df["API_Calls"] = malware_calls_df.API_Calls.apply(lambda x: " ".join(x.split(",")))malware_calls_df["API_Labels"] = malware_calls_df.API_Labels.apply(lambda x: 1 if x == "Virus" else 0) Let’s analyze the class distribution sns.countplot(malware_calls_df.API_Labels)plt.xlabel('Labels')plt.title('Class distribution')plt.savefig("class_distribution.png")plt.show() Now we can create our sequence matrix. In order to build an LSTM model, you need to create a tokenization based sequence matrix as the input dataset max_words = 800max_len = 100X = malware_calls_df.API_CallsY = malware_calls_df.API_Labels.astype('category').cat.codestok = Tokenizer(num_words=max_words)tok.fit_on_texts(X)print('Found %s unique tokens.' % len(tok.word_index))X = tok.texts_to_sequences(X.values)X = sequence.pad_sequences(X, maxlen=max_len)print('Shape of data tensor:', X.shape)X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.15)le = LabelEncoder()Y_train_enc = le.fit_transform(Y_train)Y_train_enc = np_utils.to_categorical(Y_train_enc)Y_test_enc = le.transform(Y_test)Y_test_enc = np_utils.to_categorical(Y_test_enc)Found 278 unique tokens.Shape of data tensor: (7107, 100) The LSTM based classification model is then given for example as exercise here: def malware_model(act_func="softsign"): model = Sequential() model.add(Embedding(max_words, 300, input_length=max_len)) model.add(SpatialDropout1D(0.1)) model.add(LSTM(32, dropout=0.1, recurrent_dropout=0.1, return_sequences=True, activation=act_func)) model.add(LSTM(32, dropout=0.1, activation=act_func, return_sequences=True)) model.add(LSTM(32, dropout=0.1, activation=act_func)) model.add(Dense(128, activation=act_func)) model.add(Dropout(0.1)) model.add(Dense(256, activation=act_func)) model.add(Dropout(0.1)) model.add(Dense(128, activation=act_func)) model.add(Dropout(0.1)) model.add(Dense(1, name='out_layer', activation="linear")) return model The next step is to train the model. I trained and saved my model. Because of the dataset, the training stage takes lots of time. In order to reduce the execution time, you can load my previous trained model from the GitHub repository. model = malware_model()print(model.summary())model.compile(loss='mse', optimizer="rmsprop", metrics=['accuracy'])filepath = "lstm-malware-model.hdf5"model.load_weights(filepath)history = model.fit(X_train, Y_train, batch_size=1000, epochs=10, validation_data=(X_test, Y_test), verbose=1)Model: "sequential"_________________________________________________________________Layer (type) Output Shape Param # =================================================================embedding (Embedding) (None, 100, 300) 240000 _________________________________________________________________spatial_dropout1d (SpatialDr (None, 100, 300) 0 _________________________________________________________________lstm (LSTM) (None, 100, 32) 42624 _________________________________________________________________lstm_1 (LSTM) (None, 100, 32) 8320 _________________________________________________________________lstm_2 (LSTM) (None, 32) 8320 _________________________________________________________________dense (Dense) (None, 128) 4224 _________________________________________________________________dropout (Dropout) (None, 128) 0 _________________________________________________________________dense_1 (Dense) (None, 256) 33024 _________________________________________________________________dropout_1 (Dropout) (None, 256) 0 _________________________________________________________________dense_2 (Dense) (None, 128) 32896 _________________________________________________________________dropout_2 (Dropout) (None, 128) 0 _________________________________________________________________out_layer (Dense) (None, 1) 129 =================================================================Total params: 369,537Trainable params: 369,537Non-trainable params: 0_________________________________________________________________NoneEpoch 1/107/7 [==============================] - 22s 3s/step - loss: 0.0486 - accuracy: 0.9487 - val_loss: 0.0311 - val_accuracy: 0.9672Epoch 2/107/7 [==============================] - 21s 3s/step - loss: 0.0378 - accuracy: 0.9591 - val_loss: 0.0302 - val_accuracy: 0.9672Epoch 3/107/7 [==============================] - 21s 3s/step - loss: 0.0364 - accuracy: 0.9604 - val_loss: 0.0362 - val_accuracy: 0.9625Epoch 4/107/7 [==============================] - 20s 3s/step - loss: 0.0378 - accuracy: 0.9593 - val_loss: 0.0328 - val_accuracy: 0.9616Epoch 5/107/7 [==============================] - 22s 3s/step - loss: 0.0365 - accuracy: 0.9609 - val_loss: 0.0351 - val_accuracy: 0.9606Epoch 6/107/7 [==============================] - 21s 3s/step - loss: 0.0369 - accuracy: 0.9601 - val_loss: 0.0369 - val_accuracy: 0.9606Epoch 7/107/7 [==============================] - 22s 3s/step - loss: 0.0371 - accuracy: 0.9594 - val_loss: 0.0395 - val_accuracy: 0.9625Epoch 8/107/7 [==============================] - 22s 3s/step - loss: 0.0378 - accuracy: 0.9601 - val_loss: 0.0365 - val_accuracy: 0.9588Epoch 9/107/7 [==============================] - 22s 3s/step - loss: 0.0358 - accuracy: 0.9618 - val_loss: 0.0440 - val_accuracy: 0.9456Epoch 10/107/7 [==============================] - 21s 3s/step - loss: 0.0373 - accuracy: 0.9589 - val_loss: 0.0354 - val_accuracy: 0.9644 Now, we have finished the training phase of the LSTM model. We can evaluate our model’s classification performance using the confusion matrix. According to the confusion matrix, the modelâ€TMs classification performance quite good. y_test_pred = model.predict_classes(X_test)cm = confusion_matrix(Y_test, y_test_pred)plot_confusion_matrix(conf_mat=cm, show_absolute=True, show_normed=True, colorbar=True)plt.savefig("confusion_matrix.png")plt.show() Let’s continue with the training history of our model. plt.plot(history.history['accuracy'])plt.plot(history.history['val_accuracy'])plt.title('model accuracy')plt.ylabel('accuracy')plt.xlabel('epoch')plt.legend(['train', 'test'], loc='upper left')plt.grid()plt.savefig("accuracy.png")plt.show()plt.plot(history.history['loss'])plt.plot(history.history['val_loss'])plt.title('model loss')plt.ylabel('loss')plt.xlabel('epoch')plt.legend(['train', 'test'], loc='upper left')plt.grid()plt.savefig("loss.png")plt.show() The purpose of this study was to create an LSTM based malware detection model using my previous malware dataset. Although our dataset contains instances that belong to some malware families with unbalanced distribution, we have shown that this problem does not affect classification performance.
[ { "code": null, "e": 793, "s": 172, "text": "Malware development has seen diversity in terms of architecture and features. This advancement in the competencies of malware poses a severe threat and opens new research dimensions in malware detection. This study is focused on metamorphic malware that is the most advanced member of the malware family. It is quite impossible for anti-virus applications using traditional signature-based methods to detect metamorphic malware, which makes it difficult to classify this type of malware accordingly. Recent research literature about malware detection and classification discusses this issue related to malware behaviour." }, { "code": null, "e": 862, "s": 793, "text": "Cite The Work If you find this implementation useful please cite it:" }, { "code": null, "e": 1364, "s": 862, "text": "@article{10.7717/peerj-cs.285,title = {Deep learning based Sequential model for malware analysis using Windows exe API Calls},author = {Catak, Ferhat Ozgur and Yazı, Ahmet Faruk and Elezaj, Ogerta and Ahmed, Javed},year = 2020,month = jul,keywords = {Malware analysis, Sequential models, Network security, Long-short-term memory, Malware dataset},volume = 6,pages = {e285},journal = {PeerJ Computer Science},issn = {2376-5992},url = {https://doi.org/10.7717/peerj-cs.285},doi = {10.7717/peerj-cs.285}}" }, { "code": null, "e": 1421, "s": 1364, "text": "You can access the dataset from my My GitHub Repository." }, { "code": null, "e": 1911, "s": 1421, "text": "Malicious software, commonly known as malware, is any software intentionally designed to cause damage to computer systems and compromise user security. An application or code is considered malware if it secretly acts against the interests of the computer user and performs malicious activities. Malware targets various platforms such as servers, personal computers, mobile phones, and cameras to gain unauthorized access, steal personal data, and disrupt the normal function of the system." }, { "code": null, "e": 2348, "s": 1911, "text": "One approach to deal with malware protection problem is by identifying the malicious software and evaluating its behaviour. Usually, this problem is solved through the analysis of malware behaviour. This field closely follows the model of malicious software family, which also reflects the pattern of malicious behaviour. There are very few studies that have demonstrated the methods of classification according to the malware families." }, { "code": null, "e": 2977, "s": 2348, "text": "All operating system API calls made to act by any software show the overall direction of this program. Whether this program is a malware or not can be learned by examining these actions in-depth. If it is malware, then what is its malware family. The malware-made operating system API call is a data attribute, and the sequence in which those API calls are generated is also critical to detect the malware family. Performing specific API calls is a particular order that represents a behaviour. One of the deep learning methods LSTM (long-short term memory) has been commonly used in the processing of such time-sequential data." }, { "code": null, "e": 3209, "s": 2977, "text": "This research has two main objectives; first, we created a relevant dataset, and then, using this dataset, we did a comparative study using various machine learning to detect and classify malware automatically based on their types." }, { "code": null, "e": 3611, "s": 3209, "text": "One of the most important contributions of this work is the new Windows PE Malware API sequence dataset, which contains malware analysis information. There are 7107 malware from different classes in this dataset. The Cuckoo Sandbox application, as explained above, is used to obtain the Windows API call sequences of malicious software, and VirusTotal Service is used to detect the classes of malware." }, { "code": null, "e": 3737, "s": 3611, "text": "The following figure illustrates the system architecture used to collect the data and to classify them using LSTM algorithms." }, { "code": null, "e": 3854, "s": 3737, "text": "Our system consists of three main parts, data collection, data pre-processing and analyses, and data classification." }, { "code": null, "e": 3915, "s": 3854, "text": "The following steps were followed when creating the dataset." }, { "code": null, "e": 4139, "s": 3915, "text": "Cuckoo Sandbox application is installed on a computer running Ubuntu Linux distribution. The analysis machine was run as a virtual server to run and analyze malware. The Windows operating system is installed on this server." }, { "code": null, "e": 4224, "s": 4139, "text": "We import the usual standard libraries to build an LSTM model to detect the malware." }, { "code": null, "e": 4738, "s": 4224, "text": "import pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsfrom sklearn.preprocessing import LabelEncoderfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import confusion_matrixfrom keras.preprocessing.text import Tokenizerfrom keras.layers import LSTM, Dense, Dropout, Embeddingfrom keras.preprocessing import sequencefrom keras.utils import np_utilsfrom keras.models import Sequentialfrom keras.layers import SpatialDropout1Dfrom mlxtend.plotting import plot_confusion_matrix" }, { "code": null, "e": 4918, "s": 4738, "text": "In this work, we will use standard our malware dataset to show the results. You can access the dataset from My GitHub Repository. We need to merge the call and the label datasets." }, { "code": null, "e": 5429, "s": 4918, "text": "malware_calls_df = pd.read_csv(\"calls.zip\", compression=\"zip\", sep=\"\\t\", names=[\"API_Calls\"])malware_labels_df = pd.read_csv(\"types.zip\", compression=\"zip\", sep=\"\\t\", names=[\"API_Labels\"])malware_calls_df[\"API_Labels\"] = malware_labels_df.API_Labelsmalware_calls_df[\"API_Calls\"] = malware_calls_df.API_Calls.apply(lambda x: \" \".join(x.split(\",\")))malware_calls_df[\"API_Labels\"] = malware_calls_df.API_Labels.apply(lambda x: 1 if x == \"Virus\" else 0)" }, { "code": null, "e": 5466, "s": 5429, "text": "Let’s analyze the class distribution" }, { "code": null, "e": 5607, "s": 5466, "text": "sns.countplot(malware_calls_df.API_Labels)plt.xlabel('Labels')plt.title('Class distribution')plt.savefig(\"class_distribution.png\")plt.show()" }, { "code": null, "e": 5756, "s": 5607, "text": "Now we can create our sequence matrix. In order to build an LSTM model, you need to create a tokenization based sequence matrix as the input dataset" }, { "code": null, "e": 6474, "s": 5756, "text": "max_words = 800max_len = 100X = malware_calls_df.API_CallsY = malware_calls_df.API_Labels.astype('category').cat.codestok = Tokenizer(num_words=max_words)tok.fit_on_texts(X)print('Found %s unique tokens.' % len(tok.word_index))X = tok.texts_to_sequences(X.values)X = sequence.pad_sequences(X, maxlen=max_len)print('Shape of data tensor:', X.shape)X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.15)le = LabelEncoder()Y_train_enc = le.fit_transform(Y_train)Y_train_enc = np_utils.to_categorical(Y_train_enc)Y_test_enc = le.transform(Y_test)Y_test_enc = np_utils.to_categorical(Y_test_enc)Found 278 unique tokens.Shape of data tensor: (7107, 100)" }, { "code": null, "e": 6554, "s": 6474, "text": "The LSTM based classification model is then given for example as exercise here:" }, { "code": null, "e": 7271, "s": 6554, "text": "def malware_model(act_func=\"softsign\"): model = Sequential() model.add(Embedding(max_words, 300, input_length=max_len)) model.add(SpatialDropout1D(0.1)) model.add(LSTM(32, dropout=0.1, recurrent_dropout=0.1, return_sequences=True, activation=act_func)) model.add(LSTM(32, dropout=0.1, activation=act_func, return_sequences=True)) model.add(LSTM(32, dropout=0.1, activation=act_func)) model.add(Dense(128, activation=act_func)) model.add(Dropout(0.1)) model.add(Dense(256, activation=act_func)) model.add(Dropout(0.1)) model.add(Dense(128, activation=act_func)) model.add(Dropout(0.1)) model.add(Dense(1, name='out_layer', activation=\"linear\")) return model" }, { "code": null, "e": 7507, "s": 7271, "text": "The next step is to train the model. I trained and saved my model. Because of the dataset, the training stage takes lots of time. In order to reduce the execution time, you can load my previous trained model from the GitHub repository." }, { "code": null, "e": 11100, "s": 7507, "text": "model = malware_model()print(model.summary())model.compile(loss='mse', optimizer=\"rmsprop\", metrics=['accuracy'])filepath = \"lstm-malware-model.hdf5\"model.load_weights(filepath)history = model.fit(X_train, Y_train, batch_size=1000, epochs=10, validation_data=(X_test, Y_test), verbose=1)Model: \"sequential\"_________________________________________________________________Layer (type) Output Shape Param # =================================================================embedding (Embedding) (None, 100, 300) 240000 _________________________________________________________________spatial_dropout1d (SpatialDr (None, 100, 300) 0 _________________________________________________________________lstm (LSTM) (None, 100, 32) 42624 _________________________________________________________________lstm_1 (LSTM) (None, 100, 32) 8320 _________________________________________________________________lstm_2 (LSTM) (None, 32) 8320 _________________________________________________________________dense (Dense) (None, 128) 4224 _________________________________________________________________dropout (Dropout) (None, 128) 0 _________________________________________________________________dense_1 (Dense) (None, 256) 33024 _________________________________________________________________dropout_1 (Dropout) (None, 256) 0 _________________________________________________________________dense_2 (Dense) (None, 128) 32896 _________________________________________________________________dropout_2 (Dropout) (None, 128) 0 _________________________________________________________________out_layer (Dense) (None, 1) 129 =================================================================Total params: 369,537Trainable params: 369,537Non-trainable params: 0_________________________________________________________________NoneEpoch 1/107/7 [==============================] - 22s 3s/step - loss: 0.0486 - accuracy: 0.9487 - val_loss: 0.0311 - val_accuracy: 0.9672Epoch 2/107/7 [==============================] - 21s 3s/step - loss: 0.0378 - accuracy: 0.9591 - val_loss: 0.0302 - val_accuracy: 0.9672Epoch 3/107/7 [==============================] - 21s 3s/step - loss: 0.0364 - accuracy: 0.9604 - val_loss: 0.0362 - val_accuracy: 0.9625Epoch 4/107/7 [==============================] - 20s 3s/step - loss: 0.0378 - accuracy: 0.9593 - val_loss: 0.0328 - val_accuracy: 0.9616Epoch 5/107/7 [==============================] - 22s 3s/step - loss: 0.0365 - accuracy: 0.9609 - val_loss: 0.0351 - val_accuracy: 0.9606Epoch 6/107/7 [==============================] - 21s 3s/step - loss: 0.0369 - accuracy: 0.9601 - val_loss: 0.0369 - val_accuracy: 0.9606Epoch 7/107/7 [==============================] - 22s 3s/step - loss: 0.0371 - accuracy: 0.9594 - val_loss: 0.0395 - val_accuracy: 0.9625Epoch 8/107/7 [==============================] - 22s 3s/step - loss: 0.0378 - accuracy: 0.9601 - val_loss: 0.0365 - val_accuracy: 0.9588Epoch 9/107/7 [==============================] - 22s 3s/step - loss: 0.0358 - accuracy: 0.9618 - val_loss: 0.0440 - val_accuracy: 0.9456Epoch 10/107/7 [==============================] - 21s 3s/step - loss: 0.0373 - accuracy: 0.9589 - val_loss: 0.0354 - val_accuracy: 0.9644" }, { "code": null, "e": 11333, "s": 11100, "text": "Now, we have finished the training phase of the LSTM model. We can evaluate our model’s classification performance using the confusion matrix. According to the confusion matrix, the modelâ€TMs classification performance quite good." }, { "code": null, "e": 11614, "s": 11333, "text": "y_test_pred = model.predict_classes(X_test)cm = confusion_matrix(Y_test, y_test_pred)plot_confusion_matrix(conf_mat=cm, show_absolute=True, show_normed=True, colorbar=True)plt.savefig(\"confusion_matrix.png\")plt.show()" }, { "code": null, "e": 11669, "s": 11614, "text": "Let’s continue with the training history of our model." }, { "code": null, "e": 12130, "s": 11669, "text": "plt.plot(history.history['accuracy'])plt.plot(history.history['val_accuracy'])plt.title('model accuracy')plt.ylabel('accuracy')plt.xlabel('epoch')plt.legend(['train', 'test'], loc='upper left')plt.grid()plt.savefig(\"accuracy.png\")plt.show()plt.plot(history.history['loss'])plt.plot(history.history['val_loss'])plt.title('model loss')plt.ylabel('loss')plt.xlabel('epoch')plt.legend(['train', 'test'], loc='upper left')plt.grid()plt.savefig(\"loss.png\")plt.show()" } ]
Frequency Modulation (FM) using MATLAB - GeeksforGeeks
02 Sep, 2020 Frequency modulation is the encoding of data in a carrier wave by changing the immediate frequency of the wave. In other words in frequency modulation, the frequency, as opposed to the amplitude of the carrier wave, is made to change in relation to the differing amplitude of the modulating signal. We will be using the fmmod() function to get Frequency Modulation of a signal. Syntax: a = fmmod(x, fc, fs, fdev) Parameters: x is input sinusoidal message signal fc is carrier frequency fc is carrier frequency, fdev is frequency deviation Spectrum: Code: % Sampling Frequencyfs = 400; % Carrier Frequencyfc = 200; % Time Durationtime = (0:1/fs:0.2)'; % Create two sinusoidal signal with frequencies 30 Hz and 60 Hzx = sin(2*pi*30*time)+2*sin(2*pi*60*time); % Frequency Deviation fDev = 50; % Frequency modulate xy = fmmod(x,fc,fs,fDev); % plottingplot(time,x,'c',time,y,'b--')xlabel('Time (s)')ylabel('Amplitude')legend('Original Signal','Modulated Signal') Output: MATLAB Advanced Computer Subject Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Linear Regression Decision Tree Copying Files to and from Docker Containers System Design Tutorial Python | Decision tree implementation Decision Tree Introduction with example Reinforcement learning ML | Underfitting and Overfitting Clustering in Machine Learning How to Run a Python Script using Docker?
[ { "code": null, "e": 24664, "s": 24636, "text": "\n02 Sep, 2020" }, { "code": null, "e": 24963, "s": 24664, "text": "Frequency modulation is the encoding of data in a carrier wave by changing the immediate frequency of the wave. In other words in frequency modulation, the frequency, as opposed to the amplitude of the carrier wave, is made to change in relation to the differing amplitude of the modulating signal." }, { "code": null, "e": 25042, "s": 24963, "text": "We will be using the fmmod() function to get Frequency Modulation of a signal." }, { "code": null, "e": 25077, "s": 25042, "text": "Syntax: a = fmmod(x, fc, fs, fdev)" }, { "code": null, "e": 25089, "s": 25077, "text": "Parameters:" }, { "code": null, "e": 25126, "s": 25089, "text": "x is input sinusoidal message signal" }, { "code": null, "e": 25150, "s": 25126, "text": "fc is carrier frequency" }, { "code": null, "e": 25175, "s": 25150, "text": "fc is carrier frequency," }, { "code": null, "e": 25203, "s": 25175, "text": "fdev is frequency deviation" }, { "code": null, "e": 25213, "s": 25203, "text": "Spectrum:" }, { "code": null, "e": 25219, "s": 25213, "text": "Code:" }, { "code": "% Sampling Frequencyfs = 400; % Carrier Frequencyfc = 200; % Time Durationtime = (0:1/fs:0.2)'; % Create two sinusoidal signal with frequencies 30 Hz and 60 Hzx = sin(2*pi*30*time)+2*sin(2*pi*60*time); % Frequency Deviation fDev = 50; % Frequency modulate xy = fmmod(x,fc,fs,fDev); % plottingplot(time,x,'c',time,y,'b--')xlabel('Time (s)')ylabel('Amplitude')legend('Original Signal','Modulated Signal')", "e": 25639, "s": 25219, "text": null }, { "code": null, "e": 25647, "s": 25639, "text": "Output:" }, { "code": null, "e": 25654, "s": 25647, "text": "MATLAB" }, { "code": null, "e": 25680, "s": 25654, "text": "Advanced Computer Subject" }, { "code": null, "e": 25778, "s": 25680, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25801, "s": 25778, "text": "ML | Linear Regression" }, { "code": null, "e": 25815, "s": 25801, "text": "Decision Tree" }, { "code": null, "e": 25859, "s": 25815, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 25882, "s": 25859, "text": "System Design Tutorial" }, { "code": null, "e": 25920, "s": 25882, "text": "Python | Decision tree implementation" }, { "code": null, "e": 25960, "s": 25920, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 25983, "s": 25960, "text": "Reinforcement learning" }, { "code": null, "e": 26017, "s": 25983, "text": "ML | Underfitting and Overfitting" }, { "code": null, "e": 26048, "s": 26017, "text": "Clustering in Machine Learning" } ]
Fidget Spinner using Python - GeeksforGeeks
30 Jun, 2021 Prerequisite: Turtle Programming in Python In this article, we are going to create Fidget Spinner using the Python turtle module. It is a Python feature like a drawing board, which lets us command a turtle to draw all over it! We can use functions like turtle.forward() and turtle.right() which can move the turtle around. Step 1: Drawing the fidget spinner Here in this piece of code, we will initialize the state of the fidget spinner, angles for rotating it in both clockwise and anticlockwise direction and make the colored graphics required to make the fidget spinner. Python3 # initial state of spinner is null (stable)state= {'turn':0 } # Draw fidget spinnerdef spin(): clear() # Angle of fidget spinner angle = state['turn']/10 right(angle) # move the turtle forward by specified # distance forward(100) # draw a dot with diameter 120 using colour # red dot(120, 'red') # move the turtle backward by specified # distance back(100) "second dot" right(120) forward(100) dot(120, 'blue') back(100) "third dot" right(120) forward(100) dot(120, 'green') back(100) right(120) update() Output: Step 2: Animating the fidget spinner In this step, we will call a function animate() which will animate the fidget spinner by seeing if the state is greater than 0 then decrement one from it decreases and call the spin function again. After that, a timer is installed which will call the animate function again after 20 milliseconds Python3 # Animate fidget spinnerdef animate(): if state['turn'] > 0: state['turn'] -= 1 spin() ontimer(animate, 20) Step 3: Moving the fidget spinner, setting up the window, and tracing the spinner back to its original position Here we will define the flick function which will move the fidget spinner by increasing its state to 40, also we will set up a window and its background color, we will use a tracer that brings back the fidget spinner into its initial state after completing its rotation and after that, we will define the width and color of our fidget spinner and at last, we will define the key for moving the fidget spinner. Python3 # Flick fidget spinnerdef flick(): # acceleration of spinner state['turn'] += 40 # setup window screensetup(600, 400, 370, 0)bgcolor("black") tracer(False)'''tracer brings back the fidget spinner into its initial stateafter completing the rotation''' # wing of fidget spinnerwidth(60)color("orange") # keyboard key for the rotation of spinneronkey(flick, 'space') listen()animate()done() Below is the complete implementation: Python3 # import object from module turtlefrom turtle import * # initial state of spinner is null (stable)state= {'turn':0 } # Draw fidget spinnerdef spin(): clear() # Angle of fidget spinner angle = state['turn']/10 # To rotate in clock wise we use right # for Anticlockwise rotation we use left right(angle) # move the turtle forward by specified distance forward(100) # draw a dot with diameter 120 using colour red dot(120, 'red') # move the turtle backward by specified distance back(100) "second dot" right(120) forward(100) dot(120, 'blue') back(100) "third dot" right(120) forward(100) dot(120, 'green') back(100) right(120) update() # Animate fidget spinnerdef animate(): if state['turn']>0: state['turn']-=1 spin() ontimer(animate, 20) # Flick fidget spinnerdef flick(): state['turn']+=40 #acceleration of spinner # setup window screensetup(600, 400, 370, 0)bgcolor("black") tracer(False) # wing of fidget spinnerwidth(60)color("orange") # keyboard key for the rotation of spinneronkey(flick,'space') listen()animate()done() Output: Python-turtle Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Defaultdict in Python Python | os.path.join() method Python | Get unique values from a list Selecting rows in pandas DataFrame based on conditions Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n30 Jun, 2021" }, { "code": null, "e": 24335, "s": 24292, "text": "Prerequisite: Turtle Programming in Python" }, { "code": null, "e": 24616, "s": 24335, "text": "In this article, we are going to create Fidget Spinner using the Python turtle module. It is a Python feature like a drawing board, which lets us command a turtle to draw all over it! We can use functions like turtle.forward() and turtle.right() which can move the turtle around. " }, { "code": null, "e": 24651, "s": 24616, "text": "Step 1: Drawing the fidget spinner" }, { "code": null, "e": 24867, "s": 24651, "text": "Here in this piece of code, we will initialize the state of the fidget spinner, angles for rotating it in both clockwise and anticlockwise direction and make the colored graphics required to make the fidget spinner." }, { "code": null, "e": 24875, "s": 24867, "text": "Python3" }, { "code": "# initial state of spinner is null (stable)state= {'turn':0 } # Draw fidget spinnerdef spin(): clear() # Angle of fidget spinner angle = state['turn']/10 right(angle) # move the turtle forward by specified # distance forward(100) # draw a dot with diameter 120 using colour # red dot(120, 'red') # move the turtle backward by specified # distance back(100) \"second dot\" right(120) forward(100) dot(120, 'blue') back(100) \"third dot\" right(120) forward(100) dot(120, 'green') back(100) right(120) update()", "e": 25472, "s": 24875, "text": null }, { "code": null, "e": 25480, "s": 25472, "text": "Output:" }, { "code": null, "e": 25517, "s": 25480, "text": "Step 2: Animating the fidget spinner" }, { "code": null, "e": 25813, "s": 25517, "text": "In this step, we will call a function animate() which will animate the fidget spinner by seeing if the state is greater than 0 then decrement one from it decreases and call the spin function again. After that, a timer is installed which will call the animate function again after 20 milliseconds" }, { "code": null, "e": 25821, "s": 25813, "text": "Python3" }, { "code": "# Animate fidget spinnerdef animate(): if state['turn'] > 0: state['turn'] -= 1 spin() ontimer(animate, 20)", "e": 25947, "s": 25821, "text": null }, { "code": null, "e": 26059, "s": 25947, "text": "Step 3: Moving the fidget spinner, setting up the window, and tracing the spinner back to its original position" }, { "code": null, "e": 26469, "s": 26059, "text": "Here we will define the flick function which will move the fidget spinner by increasing its state to 40, also we will set up a window and its background color, we will use a tracer that brings back the fidget spinner into its initial state after completing its rotation and after that, we will define the width and color of our fidget spinner and at last, we will define the key for moving the fidget spinner." }, { "code": null, "e": 26477, "s": 26469, "text": "Python3" }, { "code": "# Flick fidget spinnerdef flick(): # acceleration of spinner state['turn'] += 40 # setup window screensetup(600, 400, 370, 0)bgcolor(\"black\") tracer(False)'''tracer brings back the fidget spinner into its initial stateafter completing the rotation''' # wing of fidget spinnerwidth(60)color(\"orange\") # keyboard key for the rotation of spinneronkey(flick, 'space') listen()animate()done()", "e": 26884, "s": 26477, "text": null }, { "code": null, "e": 26922, "s": 26884, "text": "Below is the complete implementation:" }, { "code": null, "e": 26930, "s": 26922, "text": "Python3" }, { "code": "# import object from module turtlefrom turtle import * # initial state of spinner is null (stable)state= {'turn':0 } # Draw fidget spinnerdef spin(): clear() # Angle of fidget spinner angle = state['turn']/10 # To rotate in clock wise we use right # for Anticlockwise rotation we use left right(angle) # move the turtle forward by specified distance forward(100) # draw a dot with diameter 120 using colour red dot(120, 'red') # move the turtle backward by specified distance back(100) \"second dot\" right(120) forward(100) dot(120, 'blue') back(100) \"third dot\" right(120) forward(100) dot(120, 'green') back(100) right(120) update() # Animate fidget spinnerdef animate(): if state['turn']>0: state['turn']-=1 spin() ontimer(animate, 20) # Flick fidget spinnerdef flick(): state['turn']+=40 #acceleration of spinner # setup window screensetup(600, 400, 370, 0)bgcolor(\"black\") tracer(False) # wing of fidget spinnerwidth(60)color(\"orange\") # keyboard key for the rotation of spinneronkey(flick,'space') listen()animate()done()", "e": 28083, "s": 26930, "text": null }, { "code": null, "e": 28091, "s": 28083, "text": "Output:" }, { "code": null, "e": 28105, "s": 28091, "text": "Python-turtle" }, { "code": null, "e": 28112, "s": 28105, "text": "Python" }, { "code": null, "e": 28210, "s": 28112, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28242, "s": 28210, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28298, "s": 28242, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28340, "s": 28298, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28382, "s": 28340, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28404, "s": 28382, "text": "Defaultdict in Python" }, { "code": null, "e": 28435, "s": 28404, "text": "Python | os.path.join() method" }, { "code": null, "e": 28474, "s": 28435, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28529, "s": 28474, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 28558, "s": 28529, "text": "Create a directory in Python" } ]
How to convert std::string to LPCWSTR in C++?
In this section we will see how to convert C++ wide string (std::wstring) to LPCWSTR. The LPCWSTR is the (Long Pointer to Constant Wide STRing). It is basically the string with wide characters. So by converting wide string to wide character array we can get LPCWSTR. This LPCWSTR is Microsoft defined. So to use them we have to include Windows.h header file into our program. To convert std::wstring to wide character array type string, we can use the function called c_str() to make it C like string and point to wide character string. #include<iostream> #include<Windows.h> using namespace std; main(){ wstring my_str = L"Hello World"; LPCWSTR wide_string ; //define an array with size of my_str + 1 wide_string = my_str.c_str(); wcout << "my_str is : " << my_str <<endl; wcout << "Wide String is : " << wide_string <<endl; } my_str is : Hello World Wide String is : Hello World
[ { "code": null, "e": 1438, "s": 1062, "text": "In this section we will see how to convert C++ wide string (std::wstring) to LPCWSTR. The LPCWSTR is the (Long Pointer to Constant Wide STRing). It is basically the string with wide characters. So by converting wide string to wide character array we can get LPCWSTR. This LPCWSTR is Microsoft defined. So to use them we have to include Windows.h header file into our program." }, { "code": null, "e": 1599, "s": 1438, "text": "To convert std::wstring to wide character array type string, we can use the function called c_str() to make it C like string and point to wide character string." }, { "code": null, "e": 1905, "s": 1599, "text": "#include<iostream>\n#include<Windows.h>\nusing namespace std;\nmain(){\n wstring my_str = L\"Hello World\";\n LPCWSTR wide_string ; //define an array with size of my_str + 1\n wide_string = my_str.c_str();\n wcout << \"my_str is : \" << my_str <<endl;\n wcout << \"Wide String is : \" << wide_string <<endl;\n}" }, { "code": null, "e": 1958, "s": 1905, "text": "my_str is : Hello World\nWide String is : Hello World" } ]
Abstractive Summarization for Data Augmentation | by Aaron Briel | Towards Data Science
Imbalanced class distribution is a common problem in Machine Learning. I was recently confronted with this issue when training a sentiment classification model. Certain categories were far more prevalent than others and the predictive quality of the model suffered. The first technique I used to address this was random under-sampling, wherein I randomly sampled a subset of rows from each category up to a ceiling threshold. I selected a ceiling that reasonably balanced the upper 3 classes. Although a small improvement was observed, the model was still far from optimal. I needed a way to deal with the under-represented classes. I could not rely on traditional techniques used in multi-class classification such as sample and class weighting, as I was working with a multi-label dataset. It became evident that I would need to leverage oversampling in this situation. A technique such as SMOTE (Synthetic Minority Over-sampling Technique) can be effective for oversampling, although the problem again becomes a bit more difficult with multi-label datasets. MLSMOTE (Multi-Label Synthetic Minority Over-sampling Technique) has been proposed [1], but the high dimensional nature of the numerical vectors created from text can sometimes make other forms of data augmentation more appealing. If you decided to read this article, it is safe to assume that you are aware of the latest advances in Natural Language Processing bequeathed by the mighty Transformers. The exceptional developers at Hugging Face in particular have opened the door to this world through their open source contributions. One of their more recent releases implements a breakthrough in Transfer Learning called the Text-to-Text Transfer Transformer or T5 model, originally presented by Raffel et. al. in their paper Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer [2]. T5 allows us to execute various NLP tasks by specifying prefixes to the input text. In my case, I was interested in Abstractive Summarization, so I made use of the summarize prefix. Abstractive Summarization put simplistically is a technique by which a chunk of text is fed to an NLP model and a novel summary of that text is returned. This should not be confused with Extractive Summarization, where sentences are embedded and a clustering algorithm is executed to find those closest to the clusters’ centroids — namely, existing sentences are returned. Abstractive Summarization seemed particularly appealing as a Data Augmentation technique because of its ability to generate novel yet realistic sentences of text. Here are the steps I took to use Abstractive Summarization for Data Augmentation, including code segments illustrating the solution. I first needed to determine how many rows each under-represented class required. The number of rows to add for each feature is thus calculated with a ceiling threshold, and we refer to these as the append_counts. Features with counts above the ceiling are not appended. In particular, if a given feature has 1000 rows and the ceiling is 100, its append count will be 0. The following methods trivially achieve this in the situation where features have been one-hot encoded: def get_feature_counts(self, df): shape_array = {} for feature in self.features: shape_array[feature] = df[feature].sum() return shape_arraydef get_append_counts(self, df): append_counts = {} feature_counts = self.get_feature_counts(df) for feature in self.features: if feature_counts[feature] >= self.threshold: count = 0 else: count = self.threshold - feature_counts[feature] append_counts[feature] = count return append_counts For each feature, a loop is completed from an append index range to the append count specified for that given feature. This append_index variable along with a tasks array are introduced to allow for multi-processing which we will discuss shortly. counts = self.get_append_counts(self.df)# Create append dataframe with length of all rows to be appendedself.df_append = pd.DataFrame( index=np.arange(sum(counts.values())), columns=self.df.columns)# Creating array of tasks for multiprocessingtasks = []# set all feature values to 0for feature in self.features: self.df_append[feature] = 0for feature in self.features: num_to_append = counts[feature] for num in range( self.append_index, self.append_index + num_to_append ): tasks.append( self.process_abstractive_summarization(feature, num) ) # Updating index for insertion into shared appended dataframe # to preserve indexing for multiprocessing self.append_index += num_to_append An Abstractive Summarization is calculated for a specified size subset of all rows that uniquely have the given feature, and is added to the append DataFrame with its respective feature one-hot encoded. df_feature = self.df[ (self.df[feature] == 1) & (self.df[self.features].sum(axis=1) == 1)]df_sample = df_feature.sample(self.num_samples, replace=True)text_to_summarize = ' '.join( df_sample[:self.num_samples]['review_text'])new_text = self.get_abstractive_summarization(text_to_summarize)self.df_append.at[num, 'text'] = new_textself.df_append.at[num, feature] = 1 The Abstractive Summarization itself is generated in the following way: t5_prepared_text = "summarize: " + text_to_summarizeif self.device.type == 'cpu': tokenized_text = self.tokenizer.encode( t5_prepared_text, return_tensors=self.return_tensors).to(self.device)else: tokenized_text = self.tokenizer.encode( t5_prepared_text, return_tensors=self.return_tensors)summary_ids = self.model.generate( tokenized_text, num_beams=self.num_beams, no_repeat_ngram_size=self.no_repeat_ngram_size, min_length=self.min_length, max_length=self.max_length, early_stopping=self.early_stopping)output = self.tokenizer.decode( summary_ids[0], skip_special_tokens=self.skip_special_tokens) In initial tests the summarization calls to the T5 model were extremely time-consuming, reaching up to 25 seconds even on a GCP instance with an NVIDIA Tesla P100. Clearly this needed to be addressed to make this a feasible solution for data augmentation. I introduced a multiprocessing option, whereby the calls to Abstractive Summarization are stored in a task array later passed to a sub-routine that runs the calls in parallel using the multiprocessing library. This resulted in an exponential decrease in runtime. I must thank David Foster for his succinct stackoverflow contribution [3]! running_tasks = [Process(target=task) for task in tasks]for running_task in running_tasks: running_task.start()for running_task in running_tasks: running_task.join() To make things easier for everybody I packaged this into a library called absum. Installing is possible through pip:pip install absum. One can also download directly from the repository. Running the code on your own dataset is then simply a matter of importing the library’s Augmentor class and running its abs_sum_augment method as follows: import pandas as pdfrom absum import Augmentorcsv = 'path_to_csv'df = pd.read_csv(csv)augmentor = Augmentor(df)df_augmented = augmentor.abs_sum_augment()df_augmented.to_csv( csv.replace('.csv', '-augmented.csv'), encoding='utf-8', index=False) absum uses the Hugging Face T5 model by default, but is designed in a modular way to allow you to use any pre-trained or out-of-the-box Transformer models capable of Abstractive Summarization. It is format agnostic, expecting only a DataFrame containing text and one-hot encoded features. If additional columns are present that you do not wish to be considered, you have the option to pass in specific one-hot encoded features as a comma-separated string to the features parameter. Also of special note are the min_length and max_length parameters, which determine the size of the resulting summarizations. One trick I found useful is to find the average character count of the text data you’re working with and start with something a bit lower for the minimum length while slightly padding it for the maximum. All available parameters are detailed in the documentation. Feel free to add any suggestions for improvement in the comments or even better yet in a PR. Happy coding! [1] F. Chartea, A.Riverab, M. del Jesus, F. Herreraac, MLSMOTE: Approaching imbalanced multilabel learning through synthetic instance generation (2015), Knowledge-Based Systems, Volume 89, November 2015, Pages 385–397 [2] C. Raffel, N. Shazeer, A. Roberts, K. Lee, S. Narang, M. Matena, Y. Zhou, W. Li, P. Liu, Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer, Journal of Machine Learning Research, 21, June 2020. [3] D. Foster, Python: How can I run python functions in parallel? Retrieved from stackoverflow.com, 7/27/2020.
[ { "code": null, "e": 745, "s": 171, "text": "Imbalanced class distribution is a common problem in Machine Learning. I was recently confronted with this issue when training a sentiment classification model. Certain categories were far more prevalent than others and the predictive quality of the model suffered. The first technique I used to address this was random under-sampling, wherein I randomly sampled a subset of rows from each category up to a ceiling threshold. I selected a ceiling that reasonably balanced the upper 3 classes. Although a small improvement was observed, the model was still far from optimal." }, { "code": null, "e": 1043, "s": 745, "text": "I needed a way to deal with the under-represented classes. I could not rely on traditional techniques used in multi-class classification such as sample and class weighting, as I was working with a multi-label dataset. It became evident that I would need to leverage oversampling in this situation." }, { "code": null, "e": 1463, "s": 1043, "text": "A technique such as SMOTE (Synthetic Minority Over-sampling Technique) can be effective for oversampling, although the problem again becomes a bit more difficult with multi-label datasets. MLSMOTE (Multi-Label Synthetic Minority Over-sampling Technique) has been proposed [1], but the high dimensional nature of the numerical vectors created from text can sometimes make other forms of data augmentation more appealing." }, { "code": null, "e": 2046, "s": 1463, "text": "If you decided to read this article, it is safe to assume that you are aware of the latest advances in Natural Language Processing bequeathed by the mighty Transformers. The exceptional developers at Hugging Face in particular have opened the door to this world through their open source contributions. One of their more recent releases implements a breakthrough in Transfer Learning called the Text-to-Text Transfer Transformer or T5 model, originally presented by Raffel et. al. in their paper Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer [2]." }, { "code": null, "e": 2228, "s": 2046, "text": "T5 allows us to execute various NLP tasks by specifying prefixes to the input text. In my case, I was interested in Abstractive Summarization, so I made use of the summarize prefix." }, { "code": null, "e": 2764, "s": 2228, "text": "Abstractive Summarization put simplistically is a technique by which a chunk of text is fed to an NLP model and a novel summary of that text is returned. This should not be confused with Extractive Summarization, where sentences are embedded and a clustering algorithm is executed to find those closest to the clusters’ centroids — namely, existing sentences are returned. Abstractive Summarization seemed particularly appealing as a Data Augmentation technique because of its ability to generate novel yet realistic sentences of text." }, { "code": null, "e": 2897, "s": 2764, "text": "Here are the steps I took to use Abstractive Summarization for Data Augmentation, including code segments illustrating the solution." }, { "code": null, "e": 3371, "s": 2897, "text": "I first needed to determine how many rows each under-represented class required. The number of rows to add for each feature is thus calculated with a ceiling threshold, and we refer to these as the append_counts. Features with counts above the ceiling are not appended. In particular, if a given feature has 1000 rows and the ceiling is 100, its append count will be 0. The following methods trivially achieve this in the situation where features have been one-hot encoded:" }, { "code": null, "e": 3872, "s": 3371, "text": "def get_feature_counts(self, df): shape_array = {} for feature in self.features: shape_array[feature] = df[feature].sum() return shape_arraydef get_append_counts(self, df): append_counts = {} feature_counts = self.get_feature_counts(df) for feature in self.features: if feature_counts[feature] >= self.threshold: count = 0 else: count = self.threshold - feature_counts[feature] append_counts[feature] = count return append_counts" }, { "code": null, "e": 4119, "s": 3872, "text": "For each feature, a loop is completed from an append index range to the append count specified for that given feature. This append_index variable along with a tasks array are introduced to allow for multi-processing which we will discuss shortly." }, { "code": null, "e": 4878, "s": 4119, "text": "counts = self.get_append_counts(self.df)# Create append dataframe with length of all rows to be appendedself.df_append = pd.DataFrame( index=np.arange(sum(counts.values())), columns=self.df.columns)# Creating array of tasks for multiprocessingtasks = []# set all feature values to 0for feature in self.features: self.df_append[feature] = 0for feature in self.features: num_to_append = counts[feature] for num in range( self.append_index, self.append_index + num_to_append ): tasks.append( self.process_abstractive_summarization(feature, num) ) # Updating index for insertion into shared appended dataframe # to preserve indexing for multiprocessing self.append_index += num_to_append" }, { "code": null, "e": 5081, "s": 4878, "text": "An Abstractive Summarization is calculated for a specified size subset of all rows that uniquely have the given feature, and is added to the append DataFrame with its respective feature one-hot encoded." }, { "code": null, "e": 5456, "s": 5081, "text": "df_feature = self.df[ (self.df[feature] == 1) & (self.df[self.features].sum(axis=1) == 1)]df_sample = df_feature.sample(self.num_samples, replace=True)text_to_summarize = ' '.join( df_sample[:self.num_samples]['review_text'])new_text = self.get_abstractive_summarization(text_to_summarize)self.df_append.at[num, 'text'] = new_textself.df_append.at[num, feature] = 1" }, { "code": null, "e": 5528, "s": 5456, "text": "The Abstractive Summarization itself is generated in the following way:" }, { "code": null, "e": 6186, "s": 5528, "text": "t5_prepared_text = \"summarize: \" + text_to_summarizeif self.device.type == 'cpu': tokenized_text = self.tokenizer.encode( t5_prepared_text, return_tensors=self.return_tensors).to(self.device)else: tokenized_text = self.tokenizer.encode( t5_prepared_text, return_tensors=self.return_tensors)summary_ids = self.model.generate( tokenized_text, num_beams=self.num_beams, no_repeat_ngram_size=self.no_repeat_ngram_size, min_length=self.min_length, max_length=self.max_length, early_stopping=self.early_stopping)output = self.tokenizer.decode( summary_ids[0], skip_special_tokens=self.skip_special_tokens)" }, { "code": null, "e": 6442, "s": 6186, "text": "In initial tests the summarization calls to the T5 model were extremely time-consuming, reaching up to 25 seconds even on a GCP instance with an NVIDIA Tesla P100. Clearly this needed to be addressed to make this a feasible solution for data augmentation." }, { "code": null, "e": 6780, "s": 6442, "text": "I introduced a multiprocessing option, whereby the calls to Abstractive Summarization are stored in a task array later passed to a sub-routine that runs the calls in parallel using the multiprocessing library. This resulted in an exponential decrease in runtime. I must thank David Foster for his succinct stackoverflow contribution [3]!" }, { "code": null, "e": 6952, "s": 6780, "text": "running_tasks = [Process(target=task) for task in tasks]for running_task in running_tasks: running_task.start()for running_task in running_tasks: running_task.join()" }, { "code": null, "e": 7139, "s": 6952, "text": "To make things easier for everybody I packaged this into a library called absum. Installing is possible through pip:pip install absum. One can also download directly from the repository." }, { "code": null, "e": 7294, "s": 7139, "text": "Running the code on your own dataset is then simply a matter of importing the library’s Augmentor class and running its abs_sum_augment method as follows:" }, { "code": null, "e": 7549, "s": 7294, "text": "import pandas as pdfrom absum import Augmentorcsv = 'path_to_csv'df = pd.read_csv(csv)augmentor = Augmentor(df)df_augmented = augmentor.abs_sum_augment()df_augmented.to_csv( csv.replace('.csv', '-augmented.csv'), encoding='utf-8', index=False)" }, { "code": null, "e": 8031, "s": 7549, "text": "absum uses the Hugging Face T5 model by default, but is designed in a modular way to allow you to use any pre-trained or out-of-the-box Transformer models capable of Abstractive Summarization. It is format agnostic, expecting only a DataFrame containing text and one-hot encoded features. If additional columns are present that you do not wish to be considered, you have the option to pass in specific one-hot encoded features as a comma-separated string to the features parameter." }, { "code": null, "e": 8420, "s": 8031, "text": "Also of special note are the min_length and max_length parameters, which determine the size of the resulting summarizations. One trick I found useful is to find the average character count of the text data you’re working with and start with something a bit lower for the minimum length while slightly padding it for the maximum. All available parameters are detailed in the documentation." }, { "code": null, "e": 8527, "s": 8420, "text": "Feel free to add any suggestions for improvement in the comments or even better yet in a PR. Happy coding!" }, { "code": null, "e": 8745, "s": 8527, "text": "[1] F. Chartea, A.Riverab, M. del Jesus, F. Herreraac, MLSMOTE: Approaching imbalanced multilabel learning through synthetic instance generation (2015), Knowledge-Based Systems, Volume 89, November 2015, Pages 385–397" }, { "code": null, "e": 8974, "s": 8745, "text": "[2] C. Raffel, N. Shazeer, A. Roberts, K. Lee, S. Narang, M. Matena, Y. Zhou, W. Li, P. Liu, Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer, Journal of Machine Learning Research, 21, June 2020." } ]
NHibernate - Basic CRUD Operations
In this chapter, we will cover the basic CRUD operations. Now that our system is ready to start, as we have successfully implemented our domain Student class, we have also defined the mapping files and configured NHibernate. We can now use some queries to perform CRUD operations. As you can see that we have no data in our Student table in NHibernateDemoDB database. So to add some data, we need to perform the Add/Create operation as shown below. using (var session = sefact.OpenSession()) { using (var tx = session.BeginTransaction()) { var student1 = new Student { ID = 1, FirstMidName = "Allan", LastName = "Bommer" }; var student2 = new Student { ID = 2, FirstMidName = "Jerry", LastName = "Lewis" }; session.Save(student1); session.Save(student2); tx.Commit(); } Console.ReadLine(); } As you can see that we have created two students and then call the Save() method of the OpenSession and then call the Commit() of the BeginTransaction. Here is the complete implementation in Program.cs file using NHibernate.Cfg; using NHibernate.Dialect; using NHibernate.Driver; using System; using System.Linq; using System.Reflection; namespace NHibernateDemoApp { class Program { static void Main(string[] args) { var cfg = new Configuration(); String Data Source = asia13797\\sqlexpress; String Initial Catalog = NHibernateDemoDB; String Integrated Security = True; String Connect Timeout = 15; String Encrypt = False; String TrustServerCertificate = False; String ApplicationIntent = ReadWrite; String MultiSubnetFailover = False; cfg.DataBaseIntegration(x = > { x.ConnectionString = "Data Source + Initial Catalog + Integrated Security + Connect Timeout + Encrypt + TrustServerCertificate + ApplicationIntent + MultiSubnetFailover"; x.Driver<SqlClientDriver>(); x.Dialect<MsSql2008Dialect>(); }); cfg.AddAssembly(Assembly.GetExecutingAssembly()); var sefact = cfg.BuildSessionFactory(); using (var session = sefact.OpenSession()) { using (var tx = session.BeginTransaction()) { var student1 = new Student { ID = 1, FirstMidName = "Allan", LastName = "Bommer" }; var student2 = new Student { ID = 2, FirstMidName = "Jerry", LastName = "Lewis" }; session.Save(student1); session.Save(student2); tx.Commit(); } Console.ReadLine(); } } } } Now let’s run this application and then go to the SQL Server Object Explorer and refresh your database. You will see that the above two students are now added to the Student table in NHibernateDemoDB database. You can see that now we have two records in our student table. To read these records from the table, we need to call the CreateCriteria() of OpenSession as shown in the following code. using (var session = sefact.OpenSession()) { using (var tx = session.BeginTransaction()) { var students = session.CreateCriteria<Student>().List<Student>(); foreach (var student in students) { Console.WriteLine("{0} \t{1} \t{2}", student.ID,student.FirstMidName, student.LastName); } tx.Commit(); } Console.ReadLine(); } So if you want the list of record then we can just simply say list of type Student. Now use the foreach through all of the students and say print the ID, FirstMidName and LastName on the console. Now, let’s run this application again and you will see the following output on the console window. 1 Allan Bommer 2 Jerry Lewis You can also retrieve any record by specifying the ID in the Get() method of OpenSession using the following code. using (var session = sefact.OpenSession()) { using (var tx = session.BeginTransaction()) { var students = session.CreateCriteria<Student>().List<Student>(); foreach (var student in students) { Console.WriteLine("{0} \t{1} \t{2}", student.ID, student.FirstMidName, student.LastName); } var stdnt = session.Get<Student>(1); Console.WriteLine("Retrieved by ID"); Console.WriteLine("{0} \t{1} \t{2}", stdnt.ID, stdnt.FirstMidName, stdnt.LastName); tx.Commit(); } Console.ReadLine(); } Now when you run your application, you will see the following output. 1 Allan Bommer 2 Jerry Lewis Retrieved by ID 1 Allan Bommer To update record in the table, we need to first fetch that particular record and then update that record by calling the Update() method of OpenSession as shown in the following code. using (var session = sefact.OpenSession()) { using (var tx = session.BeginTransaction()) { var students = session.CreateCriteria<Student>().List<Student>(); foreach (var student in students) { Console.WriteLine("{0} \t{1} \t{2}", student.ID, student.FirstMidName, student.LastName); } var stdnt = session.Get<Student>(1); Console.WriteLine("Retrieved by ID"); Console.WriteLine("{0} \t{1} \t{2}", stdnt.ID, stdnt.FirstMidName, stdnt.LastName); Console.WriteLine("Update the last name of ID = {0}", stdnt.ID); stdnt.LastName = "Donald"; session.Update(stdnt); Console.WriteLine("\nFetch the complete list again\n"); foreach (var student in students) { Console.WriteLine("{0} \t{1} \t{2}", student.ID, student.FirstMidName, student.LastName); } tx.Commit(); } Console.ReadLine(); } Now when you run your application, you will see the following output. 1 Allan Bommer 2 Jerry Lewis Retrieved by ID 1 Allan Bommer Update the last name of ID = 1 Fetch the complete list again 1 Allan Donald 2 Jerry Lewis As you can see, LastName of ID equal 1 is updated from Bommer to Donald. To delete any record from the table, we need to first fetch that particular record and then delete that record by calling the Delete() method of OpenSession as shown in the following code. using (var session = sefact.OpenSession()) { using (var tx = session.BeginTransaction()) { var students = session.CreateCriteria<Student>().List<Student>(); foreach (var student in students) { Console.WriteLine("{0} \t{1} \t{2}", student.ID, student.FirstMidName, student.LastName); } var stdnt = session.Get<Student>(1); Console.WriteLine("Retrieved by ID"); Console.WriteLine("{0} \t{1} \t{2}", stdnt.ID, stdnt.FirstMidName, stdnt.LastName); Console.WriteLine("Delete the record which has ID = {0}", stdnt.ID); session.Delete(stdnt); Console.WriteLine("\nFetch the complete list again\n"); foreach (var student in students) { Console.WriteLine("{0} \t{1} \t{2}", student.ID, student.FirstMidName, student.LastName); } tx.Commit(); } Console.ReadLine(); } Now when you run your application, you will see the following output. 1 Allan Donald 2 Jerry Lewis Retrieved by ID 1 Allan Bommer Delete the record which has ID = 1 Fetch the complete list again 2 Jerry Lewis As you can see that the record which has ID equal to 1 is no longer available in the database. You can also see the database in the SQL Server Object Explorer. Print Add Notes Bookmark this page
[ { "code": null, "e": 2614, "s": 2333, "text": "In this chapter, we will cover the basic CRUD operations. Now that our system is ready to start, as we have successfully implemented our domain Student class, we have also defined the mapping files and configured NHibernate. We can now use some queries to perform CRUD operations." }, { "code": null, "e": 2701, "s": 2614, "text": "As you can see that we have no data in our Student table in NHibernateDemoDB database." }, { "code": null, "e": 2782, "s": 2701, "text": "So to add some data, we need to perform the Add/Create operation as shown below." }, { "code": null, "e": 3272, "s": 2782, "text": "using (var session = sefact.OpenSession()) { \n\n using (var tx = session.BeginTransaction()) { \n \n var student1 = new Student { \n ID = 1, \n FirstMidName = \"Allan\", \n LastName = \"Bommer\" \n }; \n \n var student2 = new Student { \n ID = 2, \n FirstMidName = \"Jerry\", \n LastName = \"Lewis\" \n }; \n \n session.Save(student1); \n session.Save(student2); \n tx.Commit(); \n } \n \n Console.ReadLine(); \n}" }, { "code": null, "e": 3479, "s": 3272, "text": "As you can see that we have created two students and then call the Save() method of the OpenSession and then call the Commit() of the BeginTransaction. Here is the complete implementation in Program.cs file" }, { "code": null, "e": 5277, "s": 3479, "text": "using NHibernate.Cfg; \nusing NHibernate.Dialect; \nusing NHibernate.Driver; \n\nusing System; \nusing System.Linq; \nusing System.Reflection;\n\nnamespace NHibernateDemoApp { \n \n class Program { \n \n static void Main(string[] args) { \n var cfg = new Configuration();\n\t\t\t\n String Data Source = asia13797\\\\sqlexpress;\n String Initial Catalog = NHibernateDemoDB;\n String Integrated Security = True;\n String Connect Timeout = 15;\n String Encrypt = False;\n String TrustServerCertificate = False;\n String ApplicationIntent = ReadWrite;\n String MultiSubnetFailover = False;\n\t\t\t\n cfg.DataBaseIntegration(x = > { x.ConnectionString = \"Data Source + \n Initial Catalog + Integrated Security + Connect Timeout + Encrypt +\n TrustServerCertificate + ApplicationIntent + MultiSubnetFailover\"; \n\n x.Driver<SqlClientDriver>(); \n x.Dialect<MsSql2008Dialect>(); \n }); \n \n cfg.AddAssembly(Assembly.GetExecutingAssembly()); \n var sefact = cfg.BuildSessionFactory(); \n\t\t\t\n using (var session = sefact.OpenSession()) { \n\t\t\t\n using (var tx = session.BeginTransaction()) { \n \n var student1 = new Student { \n ID = 1, \n FirstMidName = \"Allan\", \n LastName = \"Bommer\" \n }; \n\n var student2 = new Student { \n ID = 2, \n FirstMidName = \"Jerry\", \n LastName = \"Lewis\" \n }; \n \n session.Save(student1); \n session.Save(student2); \n tx.Commit();\n } \n \n Console.ReadLine(); \n } \n } \n } \n}" }, { "code": null, "e": 5487, "s": 5277, "text": "Now let’s run this application and then go to the SQL Server Object Explorer and refresh your database. You will see that the above two students are now added to the Student table in NHibernateDemoDB database." }, { "code": null, "e": 5672, "s": 5487, "text": "You can see that now we have two records in our student table. To read these records from the table, we need to call the CreateCriteria() of OpenSession as shown in the following code." }, { "code": null, "e": 6079, "s": 5672, "text": "using (var session = sefact.OpenSession()) { \n \n using (var tx = session.BeginTransaction()) { \n var students = session.CreateCriteria<Student>().List<Student>(); \n \n foreach (var student in students) { \n Console.WriteLine(\"{0} \\t{1} \\t{2}\", \n student.ID,student.FirstMidName, student.LastName); \n } \n \n tx.Commit(); \n } \n \n Console.ReadLine(); \n}" }, { "code": null, "e": 6163, "s": 6079, "text": "So if you want the list of record then we can just simply say list of type Student." }, { "code": null, "e": 6374, "s": 6163, "text": "Now use the foreach through all of the students and say print the ID, FirstMidName and LastName on the console. Now, let’s run this application again and you will see the following output on the console window." }, { "code": null, "e": 6404, "s": 6374, "text": "1 Allan Bommer\n2 Jerry Lewis\n" }, { "code": null, "e": 6519, "s": 6404, "text": "You can also retrieve any record by specifying the ID in the Get() method of OpenSession using the following code." }, { "code": null, "e": 7113, "s": 6519, "text": "using (var session = sefact.OpenSession()) { \n \n using (var tx = session.BeginTransaction()) { \n var students = session.CreateCriteria<Student>().List<Student>(); \n \n foreach (var student in students) { \n Console.WriteLine(\"{0} \\t{1} \\t{2}\", student.ID, \n student.FirstMidName, student.LastName); \n }\n \n var stdnt = session.Get<Student>(1); \n Console.WriteLine(\"Retrieved by ID\"); \n Console.WriteLine(\"{0} \\t{1} \\t{2}\", stdnt.ID, \n stdnt.FirstMidName, stdnt.LastName); \n tx.Commit();\n } \n\t\n Console.ReadLine(); \n}" }, { "code": null, "e": 7183, "s": 7113, "text": "Now when you run your application, you will see the following output." }, { "code": null, "e": 7244, "s": 7183, "text": "1 Allan Bommer\n2 Jerry Lewis\nRetrieved by ID\n1 Allan Bommer\n" }, { "code": null, "e": 7427, "s": 7244, "text": "To update record in the table, we need to first fetch that particular record and then update that record by calling the Update() method of OpenSession as shown in the following code." }, { "code": null, "e": 8392, "s": 7427, "text": "using (var session = sefact.OpenSession()) { \n\n using (var tx = session.BeginTransaction()) { \n var students = session.CreateCriteria<Student>().List<Student>(); \n \n foreach (var student in students) { \n Console.WriteLine(\"{0} \\t{1} \\t{2}\", student.ID, \n student.FirstMidName, student.LastName); \n }\n \n var stdnt = session.Get<Student>(1); \n Console.WriteLine(\"Retrieved by ID\"); \n Console.WriteLine(\"{0} \\t{1} \\t{2}\", stdnt.ID, stdnt.FirstMidName, stdnt.LastName);\n \n Console.WriteLine(\"Update the last name of ID = {0}\", stdnt.ID); \n stdnt.LastName = \"Donald\"; \n session.Update(stdnt); \n Console.WriteLine(\"\\nFetch the complete list again\\n\"); \n \n foreach (var student in students) { \n Console.WriteLine(\"{0} \\t{1} \\t{2}\", student.ID, \n student.FirstMidName, student.LastName); \n } \n \n tx.Commit();\n } \n \n Console.ReadLine();\n}" }, { "code": null, "e": 8462, "s": 8392, "text": "Now when you run your application, you will see the following output." }, { "code": null, "e": 8613, "s": 8462, "text": "1 Allan Bommer\n2 Jerry Lewis\nRetrieved by ID\n1 Allan Bommer\nUpdate the last name of ID = 1\nFetch the complete list again\n1 Allan Donald\n2 Jerry Lewis\n" }, { "code": null, "e": 8686, "s": 8613, "text": "As you can see, LastName of ID equal 1 is updated from Bommer to Donald." }, { "code": null, "e": 8875, "s": 8686, "text": "To delete any record from the table, we need to first fetch that particular record and then delete that record by calling the Delete() method of OpenSession as shown in the following code." }, { "code": null, "e": 9811, "s": 8875, "text": "using (var session = sefact.OpenSession()) { \n \n using (var tx = session.BeginTransaction()) { \n var students = session.CreateCriteria<Student>().List<Student>();\n \n foreach (var student in students) { \n Console.WriteLine(\"{0} \\t{1} \\t{2}\", student.ID, \n student.FirstMidName, student.LastName); \n }\n \n var stdnt = session.Get<Student>(1); \n Console.WriteLine(\"Retrieved by ID\"); \n Console.WriteLine(\"{0} \\t{1} \\t{2}\", stdnt.ID, stdnt.FirstMidName, stdnt.LastName);\n \n Console.WriteLine(\"Delete the record which has ID = {0}\", stdnt.ID); \n session.Delete(stdnt);\n Console.WriteLine(\"\\nFetch the complete list again\\n\"); \n \n foreach (var student in students) { \n Console.WriteLine(\"{0} \\t{1} \\t{2}\", student.ID, student.FirstMidName, \n student.LastName); \n } \n \n tx.Commit();\n } \n\t\n Console.ReadLine(); \n}" }, { "code": null, "e": 9881, "s": 9811, "text": "Now when you run your application, you will see the following output." }, { "code": null, "e": 10021, "s": 9881, "text": "1 Allan Donald\n2 Jerry Lewis\nRetrieved by ID\n1 Allan Bommer\nDelete the record which has ID = 1\nFetch the complete list again\n2 Jerry Lewis\n" }, { "code": null, "e": 10181, "s": 10021, "text": "As you can see that the record which has ID equal to 1 is no longer available in the database. You can also see the database in the SQL Server Object Explorer." }, { "code": null, "e": 10188, "s": 10181, "text": " Print" }, { "code": null, "e": 10199, "s": 10188, "text": " Add Notes" } ]
How to install a windows service using windows command prompt in C#?
Step 1 − Create a new windows service application. Step 2 − For running a Windows Service, you need to install the Installer, which registers it with the Service Control Manager. Right click on the Service1.cs[Design] and Add Installer. Step 3 − Right click on the ProjectInstaller.cs [Design] and select the view code. using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration.Install; using System.Linq; using System.Threading.Tasks; namespace DemoWindowsService{ [RunInstaller(true)] public partial class ProjectInstaller : System.Configuration.Install.Installer{ public ProjectInstaller(){ InitializeComponent(); } } } Press F12 and go to the implementation of the InitializeComponent class. Add the service name and description which will be the name of the windows service during installation. private void InitializeComponent(){ this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller(); this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller(); // // serviceProcessInstaller1 // this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalService; this.serviceProcessInstaller1.Password = null; this.serviceProcessInstaller1.Username = null; // // serviceInstaller1 // this.serviceInstaller1.Description = "My Demo Service"; this.serviceInstaller1.ServiceName = "DemoService"; // // ProjectInstaller // this.Installers.AddRange(new System.Configuration.Install.Installer[] { this.serviceProcessInstaller1, this.serviceInstaller1}); } Step 4 − Now let us add below logic to write log data in the text file in the Service1.cs class. using System; using System.IO; using System.ServiceProcess; using System.Timers; namespace DemoWindowsService{ public partial class Service1 : ServiceBase{ Timer timer = new Timer(); public Service1(){ InitializeComponent(); } protected override void OnStart(string[] args){ WriteToFile("Service started at " + DateTime.Now); timer.Elapsed += new ElapsedEventHandler(OnElapsedTime); timer.Interval = 5000; timer.Enabled = true; } protected override void OnStop(){ WriteToFile("Service stopped at " + DateTime.Now); } private void OnElapsedTime(object source, ElapsedEventArgs e){ WriteToFile("Service recall at " + DateTime.Now); } public void WriteToFile(string Message){ string path = @"D:\Demo"; if (!Directory.Exists(path)){ Directory.CreateDirectory(path); } string filepath = @"D:\Demo\Log.txt"; if (!File.Exists(filepath)){ using (StreamWriter sw = File.CreateText(filepath)){ sw.WriteLine(Message); } } else { using (StreamWriter sw = File.AppendText(filepath)){ sw.WriteLine(Message); } } } } } Step 5 (Installation) − Now we will install our windows service using command prompt. Open the command prompt as administrator and provide the below command. cd C:\Windows\Microsoft.NET\Framework\v4.0.30319 Open the folder where our windows service exe file is present and run the below command. InstallUtil.exe C:\Users\[UserName] source\repos\DemoWindowsService\DemoWindowsService\bin\Debug\ DemoWindowsService.exe Now open Services from the windows application menu. We could see that our windows service is installed and started running as expected. Below output shows that the service is running and wiring the log to the text file as expected.
[ { "code": null, "e": 1071, "s": 1062, "text": "Step 1 −" }, { "code": null, "e": 1113, "s": 1071, "text": "Create a new windows service application." }, { "code": null, "e": 1122, "s": 1113, "text": "Step 2 −" }, { "code": null, "e": 1299, "s": 1122, "text": "For running a Windows Service, you need to install the Installer, which registers it\nwith the Service Control Manager. Right click on the Service1.cs[Design] and Add\nInstaller." }, { "code": null, "e": 1308, "s": 1299, "text": "Step 3 −" }, { "code": null, "e": 1382, "s": 1308, "text": "Right click on the ProjectInstaller.cs [Design] and select the view code." }, { "code": null, "e": 1787, "s": 1382, "text": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Configuration.Install;\nusing System.Linq;\nusing System.Threading.Tasks;\nnamespace DemoWindowsService{\n [RunInstaller(true)]\n public partial class ProjectInstaller : System.Configuration.Install.Installer{\n public ProjectInstaller(){\n InitializeComponent();\n }\n }\n}" }, { "code": null, "e": 1964, "s": 1787, "text": "Press F12 and go to the implementation of the InitializeComponent class. Add the\nservice name and description which will be the name of the windows service during\ninstallation." }, { "code": null, "e": 2730, "s": 1964, "text": "private void InitializeComponent(){\n this.serviceProcessInstaller1 = new\n System.ServiceProcess.ServiceProcessInstaller();\n this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller();\n //\n // serviceProcessInstaller1\n //\n this.serviceProcessInstaller1.Account =\n System.ServiceProcess.ServiceAccount.LocalService;\n this.serviceProcessInstaller1.Password = null;\n this.serviceProcessInstaller1.Username = null;\n //\n // serviceInstaller1\n //\n this.serviceInstaller1.Description = \"My Demo Service\";\n this.serviceInstaller1.ServiceName = \"DemoService\";\n //\n // ProjectInstaller\n //\n this.Installers.AddRange(new System.Configuration.Install.Installer[] {\n this.serviceProcessInstaller1,\n this.serviceInstaller1});\n}" }, { "code": null, "e": 2739, "s": 2730, "text": "Step 4 −" }, { "code": null, "e": 2827, "s": 2739, "text": "Now let us add below logic to write log data in the text file in the Service1.cs class." }, { "code": null, "e": 4119, "s": 2827, "text": "using System;\nusing System.IO;\nusing System.ServiceProcess;\nusing System.Timers;\nnamespace DemoWindowsService{\n public partial class Service1 : ServiceBase{\n Timer timer = new Timer();\n public Service1(){\n InitializeComponent();\n }\n protected override void OnStart(string[] args){\n WriteToFile(\"Service started at \" + DateTime.Now);\n timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);\n timer.Interval = 5000;\n timer.Enabled = true;\n }\n protected override void OnStop(){\n WriteToFile(\"Service stopped at \" + DateTime.Now);\n }\n private void OnElapsedTime(object source, ElapsedEventArgs e){\n WriteToFile(\"Service recall at \" + DateTime.Now);\n }\n public void WriteToFile(string Message){\n string path = @\"D:\\Demo\";\n if (!Directory.Exists(path)){\n Directory.CreateDirectory(path);\n }\n string filepath = @\"D:\\Demo\\Log.txt\";\n if (!File.Exists(filepath)){\n using (StreamWriter sw = File.CreateText(filepath)){\n sw.WriteLine(Message);\n }\n } else {\n using (StreamWriter sw = File.AppendText(filepath)){\n sw.WriteLine(Message);\n }\n }\n }\n }\n}" }, { "code": null, "e": 4143, "s": 4119, "text": "Step 5 (Installation) −" }, { "code": null, "e": 4277, "s": 4143, "text": "Now we will install our windows service using command prompt. Open the command\nprompt as administrator and provide the below command." }, { "code": null, "e": 4326, "s": 4277, "text": "cd C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319" }, { "code": null, "e": 4415, "s": 4326, "text": "Open the folder where our windows service exe file is present and run the below\ncommand." }, { "code": null, "e": 4536, "s": 4415, "text": "InstallUtil.exe C:\\Users\\[UserName]\nsource\\repos\\DemoWindowsService\\DemoWindowsService\\bin\\Debug\\\nDemoWindowsService.exe" }, { "code": null, "e": 4589, "s": 4536, "text": "Now open Services from the windows application menu." }, { "code": null, "e": 4673, "s": 4589, "text": "We could see that our windows service is installed and started running as expected." }, { "code": null, "e": 4769, "s": 4673, "text": "Below output shows that the service is running and wiring the log to the text file as\nexpected." } ]
Forward List in C++ | Set 1 (Introduction and Important Functions) - GeeksforGeeks
17 Jan, 2022 Forward list in STL implements singly linked list. Introduced from C++11, forward list are more useful than other containers in insertion, removal, and moving operations (like sort) and allow time constant insertion and removal of elements. It differs from the list by the fact that the forward list keeps track of the location of only the next element while the list keeps track of both the next and previous elements, thus increasing the storage space required to store each element. The drawback of a forward list is that it cannot be iterated backward and its individual elements cannot be accessed directly. Forward List is preferred over the list when only forward traversal is required (same as the singly linked list is preferred over doubly linked list) as we can save space. Some example cases are, chaining in hashing, adjacency list representation of the graph, etc. Operations on Forward List: 1. assign(): This function is used to assign values to the forward list, its other variant is used to assign repeated elements. CPP // C++ code to demonstrate forward list// and assign()#include <forward_list>#include <iostream>using namespace std; // Driver Codeint main(){ // Declaring forward list forward_list<int> flist1; // Declaring another forward list forward_list<int> flist2; // Assigning values using assign() flist1.assign({ 1, 2, 3 }); // Assigning repeating values using assign() // 5 elements with value 10 flist2.assign(5, 10); // Displaying forward lists cout << "The elements of first forward list are : "; for (int& a : flist1) cout << a << " "; cout << endl; cout << "The elements of second forward list are : "; for (int& b : flist2) cout << b << " "; cout << endl; return 0;} The elements of first forward list are : 1 2 3 The elements of second forward list are : 10 10 10 10 10 2. push_front(): This function is used to insert the element at the first position on forward list. The value from this function is copied to the space before first element in the container. The size of forward list increases by 1. 3. emplace_front(): This function is similar to the previous function but in this no copying operation occurs, the element is created directly at the memory before the first element of the forward list. 4. pop_front(): This function is used to delete the first element of the list. CPP // C++ code to demonstrate working of// push_front(), emplace_front() and pop_front()#include <forward_list>#include <iostream>using namespace std; // Driver Codeint main(){ // Initializing forward list forward_list<int> flist = { 10, 20, 30, 40, 50 }; // Inserting value using push_front() // Inserts 60 at front flist.push_front(60); // Displaying the forward list cout << "The forward list after push_front operation : "; for (int& c : flist) cout << c << " "; cout << endl; // Inserting value using emplace_front() // Inserts 70 at front flist.emplace_front(70); // Displaying the forward list cout << "The forward list after emplace_front " "operation : "; for (int& c : flist) cout << c << " "; cout << endl; // Deleting first value using pop_front() // Pops 70 flist.pop_front(); // Displaying the forward list cout << "The forward list after pop_front operation : "; for (int& c : flist) cout << c << " "; cout << endl; return 0;} The forward list after push_front operation : 60 10 20 30 40 50 The forward list after emplace_front operation : 70 60 10 20 30 40 50 The forward list after pop_front operation : 60 10 20 30 40 50 5. insert_after(): This function gives us a choice to insert elements at any position in forward list. The arguments in this function are copied at the desired position. 6. emplace_after(): This function also does the same operation as the above function but the elements are directly made without any copy operation. 7. erase_after(): This function is used to erase elements from a particular position in the forward list. CPP // C++ code to demonstrate working of// insert_after(), emplace_after()// and erase_after()#include <forward_list>#include <iostream>using namespace std; // Driver Codeint main(){ // Initializing forward list forward_list<int> flist = { 10, 20, 30 }; // Declaring a forward list iterator forward_list<int>::iterator ptr; // Inserting value using insert_after() // starts insertion from second position ptr = flist.insert_after(flist.begin(), { 1, 2, 3 }); // Displaying the forward list cout << "The forward list after insert_after operation " ": "; for (int& c : flist) cout << c << " "; cout << endl; // Inserting value using emplace_after() // inserts 2 after ptr ptr = flist.emplace_after(ptr, 2); // Displaying the forward list cout << "The forward list after emplace_after " "operation : "; for (int& c : flist) cout << c << " "; cout << endl; // Deleting value using erase.after Deleted 2 // after ptr ptr = flist.erase_after(ptr); // Displaying the forward list cout << "The forward list after erase_after operation " ": "; for (int& c : flist) cout << c << " "; cout << endl; return 0;} The forward list after insert_after operation : 10 1 2 3 20 30 The forward list after emplace_after operation : 10 1 2 3 2 20 30 The forward list after erase_after operation : 10 1 2 3 2 30 8. remove(): This function removes the particular element from the forward list mentioned in its argument. 9. remove_if(): This function removes according to the condition in its argument. CPP // C++ code to demonstrate// working of remove() and// remove_if()#include <forward_list>#include <iostream>using namespace std; // Driver Codeint main(){ // Initializing forward list forward_list<int> flist = { 10, 20, 30, 25, 40, 40 }; // Removing element using remove() // Removes all occurrences of 40 flist.remove(40); // Displaying the forward list cout << "The forward list after remove operation : "; for (int& c : flist) cout << c << " "; cout << endl; // Removing according to condition. Removes // elements greater than 20. Removes 25 and 30 flist.remove_if([](int x) { return x > 20; }); // Displaying the forward list cout << "The forward list after remove_if operation : "; for (int& c : flist) cout << c << " "; cout << endl; return 0;} The forward list after remove operation : 10 20 30 25 The forward list after remove_if operation : 10 20 10. splice_after(): This function transfers elements from one forward list to other. CPP // C++ code to demonstrate working of// splice_after()#include <forward_list> // for splice_after()#include <iostream>using namespace std; // Driver Codeint main(){ // Initializing forward list forward_list<int> flist1 = { 10, 20, 30 }; // Initializing second list forward_list<int> flist2 = { 40, 50, 60 }; // Shifting elements from first to second // forward list after 1st position flist2.splice_after(flist2.begin(), flist1); // Displaying the forward list cout << "The forward list after splice_after operation " ": "; for (int& c : flist2) cout << c << " "; cout << endl; return 0;} The forward list after splice_after operation : 40 10 20 30 50 60 Method Definition For Second Set Refer to this Article – Forward List in C++ | Set 2 (Manipulating Functions) This article is contributed by Manjeet 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. bslapa anshikajain26 CPP-Library STL C Language C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments rand() and srand() in C/C++ Left Shift and Right Shift Operators in C/C++ fork() in C Command line arguments in C/C++ Substring in C++ Initialize a vector in C++ (6 different ways) Map in C++ Standard Template Library (STL) Inheritance in C++ Constructors in C++ C++ Classes and Objects
[ { "code": null, "e": 24205, "s": 24177, "text": "\n17 Jan, 2022" }, { "code": null, "e": 24447, "s": 24205, "text": "Forward list in STL implements singly linked list. Introduced from C++11, forward list are more useful than other containers in insertion, removal, and moving operations (like sort) and allow time constant insertion and removal of elements. " }, { "code": null, "e": 24820, "s": 24447, "text": "It differs from the list by the fact that the forward list keeps track of the location of only the next element while the list keeps track of both the next and previous elements, thus increasing the storage space required to store each element. The drawback of a forward list is that it cannot be iterated backward and its individual elements cannot be accessed directly. " }, { "code": null, "e": 25086, "s": 24820, "text": "Forward List is preferred over the list when only forward traversal is required (same as the singly linked list is preferred over doubly linked list) as we can save space. Some example cases are, chaining in hashing, adjacency list representation of the graph, etc." }, { "code": null, "e": 25244, "s": 25086, "text": "Operations on Forward List: 1. assign(): This function is used to assign values to the forward list, its other variant is used to assign repeated elements. " }, { "code": null, "e": 25248, "s": 25244, "text": "CPP" }, { "code": "// C++ code to demonstrate forward list// and assign()#include <forward_list>#include <iostream>using namespace std; // Driver Codeint main(){ // Declaring forward list forward_list<int> flist1; // Declaring another forward list forward_list<int> flist2; // Assigning values using assign() flist1.assign({ 1, 2, 3 }); // Assigning repeating values using assign() // 5 elements with value 10 flist2.assign(5, 10); // Displaying forward lists cout << \"The elements of first forward list are : \"; for (int& a : flist1) cout << a << \" \"; cout << endl; cout << \"The elements of second forward list are : \"; for (int& b : flist2) cout << b << \" \"; cout << endl; return 0;}", "e": 25986, "s": 25248, "text": null }, { "code": null, "e": 26092, "s": 25986, "text": "The elements of first forward list are : 1 2 3 \nThe elements of second forward list are : 10 10 10 10 10 " }, { "code": null, "e": 26324, "s": 26092, "text": "2. push_front(): This function is used to insert the element at the first position on forward list. The value from this function is copied to the space before first element in the container. The size of forward list increases by 1." }, { "code": null, "e": 26527, "s": 26324, "text": "3. emplace_front(): This function is similar to the previous function but in this no copying operation occurs, the element is created directly at the memory before the first element of the forward list." }, { "code": null, "e": 26608, "s": 26527, "text": "4. pop_front(): This function is used to delete the first element of the list. " }, { "code": null, "e": 26612, "s": 26608, "text": "CPP" }, { "code": "// C++ code to demonstrate working of// push_front(), emplace_front() and pop_front()#include <forward_list>#include <iostream>using namespace std; // Driver Codeint main(){ // Initializing forward list forward_list<int> flist = { 10, 20, 30, 40, 50 }; // Inserting value using push_front() // Inserts 60 at front flist.push_front(60); // Displaying the forward list cout << \"The forward list after push_front operation : \"; for (int& c : flist) cout << c << \" \"; cout << endl; // Inserting value using emplace_front() // Inserts 70 at front flist.emplace_front(70); // Displaying the forward list cout << \"The forward list after emplace_front \" \"operation : \"; for (int& c : flist) cout << c << \" \"; cout << endl; // Deleting first value using pop_front() // Pops 70 flist.pop_front(); // Displaying the forward list cout << \"The forward list after pop_front operation : \"; for (int& c : flist) cout << c << \" \"; cout << endl; return 0;}", "e": 27669, "s": 26612, "text": null }, { "code": null, "e": 27869, "s": 27669, "text": "The forward list after push_front operation : 60 10 20 30 40 50 \nThe forward list after emplace_front operation : 70 60 10 20 30 40 50 \nThe forward list after pop_front operation : 60 10 20 30 40 50 " }, { "code": null, "e": 28039, "s": 27869, "text": "5. insert_after(): This function gives us a choice to insert elements at any position in forward list. The arguments in this function are copied at the desired position." }, { "code": null, "e": 28187, "s": 28039, "text": "6. emplace_after(): This function also does the same operation as the above function but the elements are directly made without any copy operation." }, { "code": null, "e": 28294, "s": 28187, "text": "7. erase_after(): This function is used to erase elements from a particular position in the forward list. " }, { "code": null, "e": 28298, "s": 28294, "text": "CPP" }, { "code": "// C++ code to demonstrate working of// insert_after(), emplace_after()// and erase_after()#include <forward_list>#include <iostream>using namespace std; // Driver Codeint main(){ // Initializing forward list forward_list<int> flist = { 10, 20, 30 }; // Declaring a forward list iterator forward_list<int>::iterator ptr; // Inserting value using insert_after() // starts insertion from second position ptr = flist.insert_after(flist.begin(), { 1, 2, 3 }); // Displaying the forward list cout << \"The forward list after insert_after operation \" \": \"; for (int& c : flist) cout << c << \" \"; cout << endl; // Inserting value using emplace_after() // inserts 2 after ptr ptr = flist.emplace_after(ptr, 2); // Displaying the forward list cout << \"The forward list after emplace_after \" \"operation : \"; for (int& c : flist) cout << c << \" \"; cout << endl; // Deleting value using erase.after Deleted 2 // after ptr ptr = flist.erase_after(ptr); // Displaying the forward list cout << \"The forward list after erase_after operation \" \": \"; for (int& c : flist) cout << c << \" \"; cout << endl; return 0;}", "e": 29534, "s": 28298, "text": null }, { "code": null, "e": 29727, "s": 29534, "text": "The forward list after insert_after operation : 10 1 2 3 20 30 \nThe forward list after emplace_after operation : 10 1 2 3 2 20 30 \nThe forward list after erase_after operation : 10 1 2 3 2 30 " }, { "code": null, "e": 29834, "s": 29727, "text": "8. remove(): This function removes the particular element from the forward list mentioned in its argument." }, { "code": null, "e": 29917, "s": 29834, "text": "9. remove_if(): This function removes according to the condition in its argument. " }, { "code": null, "e": 29921, "s": 29917, "text": "CPP" }, { "code": "// C++ code to demonstrate// working of remove() and// remove_if()#include <forward_list>#include <iostream>using namespace std; // Driver Codeint main(){ // Initializing forward list forward_list<int> flist = { 10, 20, 30, 25, 40, 40 }; // Removing element using remove() // Removes all occurrences of 40 flist.remove(40); // Displaying the forward list cout << \"The forward list after remove operation : \"; for (int& c : flist) cout << c << \" \"; cout << endl; // Removing according to condition. Removes // elements greater than 20. Removes 25 and 30 flist.remove_if([](int x) { return x > 20; }); // Displaying the forward list cout << \"The forward list after remove_if operation : \"; for (int& c : flist) cout << c << \" \"; cout << endl; return 0;}", "e": 30743, "s": 29921, "text": null }, { "code": null, "e": 30850, "s": 30743, "text": "The forward list after remove operation : 10 20 30 25 \nThe forward list after remove_if operation : 10 20 " }, { "code": null, "e": 30937, "s": 30850, "text": "10. splice_after(): This function transfers elements from one forward list to other. " }, { "code": null, "e": 30941, "s": 30937, "text": "CPP" }, { "code": "// C++ code to demonstrate working of// splice_after()#include <forward_list> // for splice_after()#include <iostream>using namespace std; // Driver Codeint main(){ // Initializing forward list forward_list<int> flist1 = { 10, 20, 30 }; // Initializing second list forward_list<int> flist2 = { 40, 50, 60 }; // Shifting elements from first to second // forward list after 1st position flist2.splice_after(flist2.begin(), flist1); // Displaying the forward list cout << \"The forward list after splice_after operation \" \": \"; for (int& c : flist2) cout << c << \" \"; cout << endl; return 0;}", "e": 31588, "s": 30941, "text": null }, { "code": null, "e": 31655, "s": 31588, "text": "The forward list after splice_after operation : 40 10 20 30 50 60 " }, { "code": null, "e": 31662, "s": 31655, "text": "Method" }, { "code": null, "e": 31673, "s": 31662, "text": "Definition" }, { "code": null, "e": 31765, "s": 31673, "text": "For Second Set Refer to this Article – Forward List in C++ | Set 2 (Manipulating Functions)" }, { "code": null, "e": 32188, "s": 31765, "text": "This article is contributed by Manjeet 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. " }, { "code": null, "e": 32195, "s": 32188, "text": "bslapa" }, { "code": null, "e": 32209, "s": 32195, "text": "anshikajain26" }, { "code": null, "e": 32221, "s": 32209, "text": "CPP-Library" }, { "code": null, "e": 32225, "s": 32221, "text": "STL" }, { "code": null, "e": 32236, "s": 32225, "text": "C Language" }, { "code": null, "e": 32240, "s": 32236, "text": "C++" }, { "code": null, "e": 32244, "s": 32240, "text": "STL" }, { "code": null, "e": 32248, "s": 32244, "text": "CPP" }, { "code": null, "e": 32346, "s": 32248, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32355, "s": 32346, "text": "Comments" }, { "code": null, "e": 32368, "s": 32355, "text": "Old Comments" }, { "code": null, "e": 32396, "s": 32368, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 32442, "s": 32396, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 32454, "s": 32442, "text": "fork() in C" }, { "code": null, "e": 32486, "s": 32454, "text": "Command line arguments in C/C++" }, { "code": null, "e": 32503, "s": 32486, "text": "Substring in C++" }, { "code": null, "e": 32549, "s": 32503, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 32592, "s": 32549, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 32611, "s": 32592, "text": "Inheritance in C++" }, { "code": null, "e": 32631, "s": 32611, "text": "Constructors in C++" } ]
GATE-CS-2014-(Set-1) - GeeksforGeeks
10 Nov, 2021 A says that strategies are now available for eliminating psychiatric illnesses but it is mentioned in the very first line that the geneticists are very close but the strategy is not available till now. So, A is incorrect. The given data says that the geneticists are working on the genetic roots of psychiatric illnesses such as depression and schizophrenia, which implies that these two diseases have genetic basis. Thus, B is the correct option. C says that all human diseases can be traced back to genes and how they are expressed, but the data given in the question talks about psychiatric illnesses such as depression and schizophrenia only. So, C is also incorrect. D says that in future, genetics will be the only relevant field for identifying psychiatric illnesses, which cannot be inferred from the given data. So, D is also incorrect. One way single person fare is 100. Therefore 2 way is 200. For 5 persons it is 200 x 5 = 1000 Now 1st discount is of 10 % on total fare, which is 100( 10 % of 1000). And as the group is of more than 4, an additional discount of 5 % on total fare, which is 50( 5 % of 1000). Hence total discount is equal to 100 + 50 = 150. Therefore tickets are charged at Rs 1000 - 150 = 850. No. of respondents do not own scooter = No. of persons who have car alone + No. of persons who don't have both. In men, 40 + 20 = 60 and In women 34 + 50 = 84. Total 60 + 84 = 144 . Now the percentage is, (144/300) *100 = 48 Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Must Do Coding Questions for Product Based Companies Difference between var, let and const keywords in JavaScript Array of Objects in C++ with Examples How to Convert Categorical Variable to Numeric in Pandas? How to Replace Values in Column Based on Condition in Pandas? C Program to read contents of Whole File How to Replace Values in a List in Python? How to Read Text Files with Pandas? Python Data Structures and Algorithms Different ways to iterate over a set in C++
[ { "code": null, "e": 27610, "s": 27582, "text": "\n10 Nov, 2021" }, { "code": null, "e": 27832, "s": 27610, "text": "A says that strategies are now available for eliminating psychiatric illnesses but it is mentioned in the very first line that the geneticists are very close but the strategy is not available till now. So, A is incorrect." }, { "code": null, "e": 28058, "s": 27832, "text": "The given data says that the geneticists are working on the genetic roots of psychiatric illnesses such as depression and schizophrenia, which implies that these two diseases have genetic basis. Thus, B is the correct option." }, { "code": null, "e": 28282, "s": 28058, "text": "C says that all human diseases can be traced back to genes and how they are expressed, but the data given in the question talks about psychiatric illnesses such as depression and schizophrenia only. So, C is also incorrect." }, { "code": null, "e": 28456, "s": 28282, "text": "D says that in future, genetics will be the only relevant field for identifying psychiatric illnesses, which cannot be inferred from the given data. So, D is also incorrect." }, { "code": null, "e": 28840, "s": 28456, "text": "One way single person fare is 100. Therefore 2 way\nis 200.\n\nFor 5 persons it is 200 x 5 = 1000\n\nNow 1st discount is of 10 % on total fare, which is\n100( 10 % of 1000). And as the group is of more than 4, \nan additional discount of 5 % on total fare, which is \n50( 5 % of 1000).\n\nHence total discount is equal to 100 + 50 = 150.\n\nTherefore tickets are charged at Rs 1000 - 150 = 850. " }, { "code": null, "e": 29115, "s": 28840, "text": "No. of respondents do not own scooter = \n No. of persons who have car alone + \n No. of persons who don't have both.\nIn men, 40 + 20 = 60 and\nIn women 34 + 50 = 84.\nTotal 60 + 84 = 144 .\nNow the percentage is, (144/300) *100 = 48" }, { "code": null, "e": 29213, "s": 29115, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 29266, "s": 29213, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 29327, "s": 29266, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29365, "s": 29327, "text": "Array of Objects in C++ with Examples" }, { "code": null, "e": 29423, "s": 29365, "text": "How to Convert Categorical Variable to Numeric in Pandas?" }, { "code": null, "e": 29485, "s": 29423, "text": "How to Replace Values in Column Based on Condition in Pandas?" }, { "code": null, "e": 29526, "s": 29485, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 29569, "s": 29526, "text": "How to Replace Values in a List in Python?" }, { "code": null, "e": 29605, "s": 29569, "text": "How to Read Text Files with Pandas?" }, { "code": null, "e": 29643, "s": 29605, "text": "Python Data Structures and Algorithms" } ]
Create a simple Numpy Jupyter Notebook using Docker
Machine learning and Data Science have certainly become the new buzzword. Organizations are now trying to adopt Data Analytics and Machine learning techniques to predict their sales and to increase their revenue. No doubt, specializing machine learning techniques would surely give you an upperhand in today’s corporate world. If you want to build a machine learning model in a dynamic and contained environment, there can be no better option than using Docker containers. You can build and run your Machine Learning models easily inside Docker Containers with the help of Jupyter Notebooks. In fact, the packed environment of a Docker Container provides better version control of your python or R libraries and packages that you would be using in your Machine Learning project. In this article, we will discuss how to create a simple Numpy Jupyter Notebook inside a Docker Container. Following the same template, you can easily install other useful libraries and packages and include them in your Machine Learning project through Jupyter Notebooks. Assuming that you have Docker installed on your system, let’s go ahead and see how to run a Jupyter Notebook inside the Docker Container. To start with, run the Docker Jupyter image by pulling it directly from Docker Registry. You can use the following command to run the Jupyter image. sudo docker run −d −p 8888:8888 jupyter/scipy-notebook To check whether the Docker Container is running or not, you can use the following command − sudo docker ps −a Copy the Container Id of the Jupyter Container. After that, you need to get the Token associated with the Jupyter Notebook running inside the Docker Container. To do this, you can use the following command − sudo docker exec <container−id> jupyter notebook list http://localhost:8888/?token=a37c45becfd981ffeb2fdca9b82419bd697e9 a8b4b5bf25b :: /home/raunak This will generate a localhost URL along with the token Id. Copy the URL upto token Id and fire up your browser and open that link. The Notebook is being served inside the Docker Container and the port 8888 of the Docker Container is exposed to the port 8888 of the host machine. Hence, you can access the URL inside your host machine. This will open up the Notebook in the browser. All the basic Machine Learning packages such as Numpy, scipy, etc. is already included inside the Docker Container. Create a new Python3 Notebook and give it a name. Inside the notebook, type the following command. import numpy as np np.mgrid[0:3, 0:3] Execute the notebook cell. You should see a matrix output. Now, save the notebook. Stop the Docker Container and start it again to check whether the Jupyter Notebook still exists or not. sudo docker ps −a sudo docker stop <container−id> sudo docker start <container−id> You will find that the Jupyter Notebook you had created earlier still exists inside the Docker Container. To conclude, it’s obvious that grabbing a skill such as Machine Learning or Data Science would surely boost your academic or corporate career however building projects using Machine Learning and deploying or running them inside Docker Containers not only gives you a perfect container and packaged environment, but it also helps you to ease up the process of training huge models as it provides you with ample resources and saves your system from taking up the load while you perform other tasks. In this article, we saw the steps to run a Jupyter image from the Docker registry, how to access the notebook in the browser on your local machine, ran a numpy code snippet and verified whether the notebook persists on restarting the Container or not.
[ { "code": null, "e": 1535, "s": 1062, "text": "Machine learning and Data Science have certainly become the new buzzword. Organizations are now trying to adopt Data Analytics and Machine learning techniques to predict their sales and to increase their revenue. No doubt, specializing machine learning techniques would surely give you an upperhand in today’s corporate world. If you want to build a machine learning model in a dynamic and contained environment, there can be no better option than using Docker containers." }, { "code": null, "e": 1841, "s": 1535, "text": "You can build and run your Machine Learning models easily inside Docker Containers with the help of Jupyter Notebooks. In fact, the packed environment of a Docker Container provides better version control of your python or R libraries and packages that you would be using in your Machine Learning project." }, { "code": null, "e": 2112, "s": 1841, "text": "In this article, we will discuss how to create a simple Numpy Jupyter Notebook inside a Docker Container. Following the same template, you can easily install other useful libraries and packages and include them in your Machine Learning project through Jupyter Notebooks." }, { "code": null, "e": 2250, "s": 2112, "text": "Assuming that you have Docker installed on your system, let’s go ahead and see how to run a Jupyter Notebook inside the Docker Container." }, { "code": null, "e": 2399, "s": 2250, "text": "To start with, run the Docker Jupyter image by pulling it directly from Docker Registry. You can use the following command to run the Jupyter image." }, { "code": null, "e": 2454, "s": 2399, "text": "sudo docker run −d −p 8888:8888 jupyter/scipy-notebook" }, { "code": null, "e": 2547, "s": 2454, "text": "To check whether the Docker Container is running or not, you can use the following command −" }, { "code": null, "e": 2565, "s": 2547, "text": "sudo docker ps −a" }, { "code": null, "e": 2613, "s": 2565, "text": "Copy the Container Id of the Jupyter Container." }, { "code": null, "e": 2773, "s": 2613, "text": "After that, you need to get the Token associated with the Jupyter Notebook running inside the Docker Container. To do this, you can use the following command −" }, { "code": null, "e": 2827, "s": 2773, "text": "sudo docker exec <container−id> jupyter notebook list" }, { "code": null, "e": 2922, "s": 2827, "text": "http://localhost:8888/?token=a37c45becfd981ffeb2fdca9b82419bd697e9\na8b4b5bf25b :: /home/raunak" }, { "code": null, "e": 3305, "s": 2922, "text": "This will generate a localhost URL along with the token Id. Copy the URL upto token Id and fire up your browser and open that link. The Notebook is being served inside the Docker Container and the port 8888 of the Docker Container is exposed to the port 8888 of the host machine. Hence, you can access the URL inside your host machine. This will open up the Notebook in the browser." }, { "code": null, "e": 3421, "s": 3305, "text": "All the basic Machine Learning packages such as Numpy, scipy, etc. is already included inside the Docker Container." }, { "code": null, "e": 3520, "s": 3421, "text": "Create a new Python3 Notebook and give it a name. Inside the notebook, type the following command." }, { "code": null, "e": 3558, "s": 3520, "text": "import numpy as np\nnp.mgrid[0:3, 0:3]" }, { "code": null, "e": 3641, "s": 3558, "text": "Execute the notebook cell. You should see a matrix output. Now, save the notebook." }, { "code": null, "e": 3745, "s": 3641, "text": "Stop the Docker Container and start it again to check whether the Jupyter Notebook still exists or not." }, { "code": null, "e": 3828, "s": 3745, "text": "sudo docker ps −a\nsudo docker stop <container−id>\nsudo docker start <container−id>" }, { "code": null, "e": 3934, "s": 3828, "text": "You will find that the Jupyter Notebook you had created earlier still exists inside the Docker Container." }, { "code": null, "e": 4431, "s": 3934, "text": "To conclude, it’s obvious that grabbing a skill such as Machine Learning or Data Science would surely boost your academic or corporate career however building projects using Machine Learning and deploying or running them inside Docker Containers not only gives you a perfect container and packaged environment, but it also helps you to ease up the process of training huge models as it provides you with ample resources and saves your system from taking up the load while you perform other tasks." }, { "code": null, "e": 4683, "s": 4431, "text": "In this article, we saw the steps to run a Jupyter image from the Docker registry, how to access the notebook in the browser on your local machine, ran a numpy code snippet and verified whether the notebook persists on restarting the Container or not." } ]
How to display NA frequency for a ggplot2 graph using color brewer in R?
To display NA frequency for a ggplot2 graph using color brewer in R, we can follow the below steps − First of all, create a data frame. Then, create the chart with default colors. After that, use scale_colour_brewer function to create the bar chart and set the color of NA values bar with na.value. Let's create a data frame as shown below − Live Demo Group<-c("A","B","C",NA) Count<-c(24,21,27,25) df<-data.frame(Group,Count) df On executing, the above script generates the below output(this output will vary on your system due to randomization) − Group Count 1 A 24 2 B 21 3 C 27 4 <NA> 25 Loading ggplot2 package and creating the bar for the data in df − Group<-c("A","B","C",NA) Count<-c(24,21,27,25) df<-data.frame(Group,Count) library(ggplot2) ggplot(df,aes(Group,Count,fill=Group))+geom_bar(stat="identity") Use scale_colour_brewer function of ggplot2 package to create the bar chart and set the color of NA values bar to red with na.value as shown below − Group<-c("A","B","C",NA) Count<-c(24,21,27,25) df<-data.frame(Group,Count) library(ggplot2) ggplot(df,aes(Group,Count,fill=Group))+geom_bar(stat="identity")+scale_fill_brewer(pa lette="Accent",na.value="red")
[ { "code": null, "e": 1163, "s": 1062, "text": "To display NA frequency for a ggplot2 graph using color brewer in R, we can follow the below steps −" }, { "code": null, "e": 1198, "s": 1163, "text": "First of all, create a data frame." }, { "code": null, "e": 1242, "s": 1198, "text": "Then, create the chart with default colors." }, { "code": null, "e": 1361, "s": 1242, "text": "After that, use scale_colour_brewer function to create the bar chart and set the color of NA values bar with na.value." }, { "code": null, "e": 1404, "s": 1361, "text": "Let's create a data frame as shown below −" }, { "code": null, "e": 1415, "s": 1404, "text": " Live Demo" }, { "code": null, "e": 1493, "s": 1415, "text": "Group<-c(\"A\",\"B\",\"C\",NA)\nCount<-c(24,21,27,25)\ndf<-data.frame(Group,Count)\ndf" }, { "code": null, "e": 1612, "s": 1493, "text": "On executing, the above script generates the below output(this output will vary on your system due to randomization) −" }, { "code": null, "e": 1675, "s": 1612, "text": " Group Count\n1 A 24\n2 B 21\n3 C 27\n4 <NA> 25" }, { "code": null, "e": 1741, "s": 1675, "text": "Loading ggplot2 package and creating the bar for the data in df −" }, { "code": null, "e": 1898, "s": 1741, "text": "Group<-c(\"A\",\"B\",\"C\",NA)\nCount<-c(24,21,27,25)\ndf<-data.frame(Group,Count)\nlibrary(ggplot2)\nggplot(df,aes(Group,Count,fill=Group))+geom_bar(stat=\"identity\")" }, { "code": null, "e": 2047, "s": 1898, "text": "Use scale_colour_brewer function of ggplot2 package to create the bar chart and set the color of NA values bar to red with na.value as shown below −" }, { "code": null, "e": 2256, "s": 2047, "text": "Group<-c(\"A\",\"B\",\"C\",NA)\nCount<-c(24,21,27,25)\ndf<-data.frame(Group,Count)\nlibrary(ggplot2)\nggplot(df,aes(Group,Count,fill=Group))+geom_bar(stat=\"identity\")+scale_fill_brewer(pa\nlette=\"Accent\",na.value=\"red\")" } ]
C# program to iterate over a string array with for loop
Create a string array − string[] str = new string[] { "Videos", "Tutorials", "Tools", "InterviewQA" }; Loop until the length of the array − for (int i = 0; i < str.Length; i++) { string res = str[i]; Console.WriteLine(res); } Here is the complete code − Live Demo using System; public class Demo { public static void Main() { string[] str = new string[] { "Videos", "Tutorials", "Tools", "InterviewQA" }; Console.WriteLine("String Array..."); for (int i = 0; i < str.Length; i++) { string res = str[i]; Console.WriteLine(res); } } } String Array... Videos Tutorials Tools InterviewQA
[ { "code": null, "e": 1086, "s": 1062, "text": "Create a string array −" }, { "code": null, "e": 1177, "s": 1086, "text": "string[] str = new string[] {\n \"Videos\",\n \"Tutorials\",\n \"Tools\",\n \"InterviewQA\"\n};" }, { "code": null, "e": 1214, "s": 1177, "text": "Loop until the length of the array −" }, { "code": null, "e": 1306, "s": 1214, "text": "for (int i = 0; i < str.Length; i++) {\n string res = str[i];\n Console.WriteLine(res);\n}" }, { "code": null, "e": 1334, "s": 1306, "text": "Here is the complete code −" }, { "code": null, "e": 1345, "s": 1334, "text": " Live Demo" }, { "code": null, "e": 1709, "s": 1345, "text": "using System;\n\npublic class Demo {\n public static void Main() {\n string[] str = new string[] {\n \"Videos\",\n \"Tutorials\",\n \"Tools\",\n \"InterviewQA\"\n };\n \n Console.WriteLine(\"String Array...\");\n for (int i = 0; i < str.Length; i++) {\n string res = str[i];\n Console.WriteLine(res);\n }\n }\n}" }, { "code": null, "e": 1760, "s": 1709, "text": "String Array...\nVideos\nTutorials\nTools\nInterviewQA" } ]
CakePHP - Session Management
Session allows us to manage unique users across requests, and stores data for specific users. Session data can be accessible anywhere, anyplace, where you have access to request object, i.e., sessions are accessible from controllers, views, helpers, cells, and components. Session object can be created by executing the following code. $session = $this->request->session(); To write something in session, we can use the write() session method. Session::write($key, $value) The above method will take two arguments, the value and the key under, which the value will be stored. $session->write('name', 'Virat Gandhi'); To retrieve stored data from session, we can use the read() session method. Session::read($key) The above function will take only one argument, that is the key of the value, which was used at the time of writing session data. Once the correct key was provided, then the function will return its value. $session->read('name'); When you want to check whether, particular data exists in the session or not, then you can use the check() session method. Session::check($key) The above function will take only key as the argument. if ($session->check('name')) { // name exists and is not null. } To delete data from session, we can use the delete() session method to delete the data. Session::delete($key) The above function will take only key of the value to be deleted from session. $session->delete('name'); When you want to read and then delete data from session then, we can use the consume() session method. static Session::consume($key) The above function will take only key as argument. $session->consume('name'); We need to destroy a user session, when the user logs out from the site and to destroy the session the destroy() method is used. Session::destroy() $session->destroy(); Destroying session will remove all session data from server, but will not remove session cookie. In a situation, where you want to renew user session then, we can use the renew() session method. Session::renew() $session->renew(); Make changes in the config/routes.php file as shown in the following program. config/routes.php <?php use Cake\Http\Middleware\CsrfProtectionMiddleware; use Cake\Routing\Route\DashedRoute; use Cake\Routing\RouteBuilder; $routes->setRouteClass(DashedRoute::class); $routes->scope('/', function (RouteBuilder $builder) { $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([ 'httpOnly' => true, ])); $builder->applyMiddleware('csrf'); //$builder->connect('/pages',['controller'=>'Pages','action'=>'display', 'home']); $builder->connect('/session-object',['controller'=>'Sessions','action'=>'index']); $builder->connect('/session-read',['controller'=>'Sessions','action'=>'retrieve_session_data']); $builder->connect('/session-write',['controller'=>'Sessions','action'=> 'write_session_data']); $builder->connect('/session-check',['controller'=>'Sessions','action'=>'check_session_data']); $builder->connect('/session-delete',['controller'=>'Sessions','action'=>'delete_session_data']); $builder->connect('/session-destroy',['controller'=>'Sessions','action'=>'destroy_session_data']); $builder->fallbacks(); }); Create a SessionsController.php file at src/Controller/SessionsController.php. Copy the following code in the controller file src/Controller/SessionsController.php <?php namespace App\Controller; use App\Controller\AppController; class SessionsController extends AppController { public function retrieveSessionData() { //create session object $session = $this->request->getSession(); //read data from session $name = $session->read('name'); $this->set('name',$name); } public function writeSessionData(){ //create session object $session = $this->request->getSession(); //write data in session $session->write('name','Virat Gandhi'); } public function checkSessionData(){ //create session object $session = $this->request->getSession(); //check session data $name = $session->check('name'); $address = $session->check('address'); $this->set('name',$name); $this->set('address',$address); } public function deleteSessionData(){ //create session object $session = $this->request->getSession(); //delete session data $session->delete('name'); } public function destroySessionData(){ //create session object $session = $this->request->getSession(); //destroy session $session->destroy(); } } ?> Create a directory Sessions at src/Template and under that directory create a View file called write_session_data.php. Copy the following code in that file. src/Template/Sessions/write_session_data.php The data has been written in session. Create another View file called retrieve_session_data.php under the same Sessions directory and copy the following code in that file. src/Template/Sessions/retrieve_session_data.php Here is the data from session. Name: <?=$name;?> Create another View file called check_session_data.ctp under the same Sessions directory and copy the following code in that file. src/Template/Sessions/check_session_data.ctp <?php if($name): ?> name exists in the session. <?php else: ?> name doesn't exist in the database <?php endif;?> <?php if($address): ?> address exists in the session. <?php else: ?> address doesn't exist in the database <?php endif;?> Create another View file called delete_session_data.ctp, under the same Sessions directory and copy the following code in that file. src/Template/Sessions/delete_session_data.ctp Data deleted from session. Create another View file called destroy_session_data.ctp, under the same Sessions directory and copy the following code in that file. src/Template/Sessions/destroy_session_data.ctp Session Destroyed. Execute the above example by visiting the following URL. This URL will help you write data in session. http://localhost/cakephp4/session-write Visit the following URL to read session data − http://localhost/cakephp4/session-read Visit the following URL to check session data − http://localhost/cakephp4/session-check Visit the following URL to delete session data − http://localhost/cakephp4/session-delete Visit the Visit the following URL to destroy session data − http://localhost/cakephp4/session-destroy Print Add Notes Bookmark this page
[ { "code": null, "e": 2515, "s": 2242, "text": "Session allows us to manage unique users across requests, and stores data for specific users. Session data can be accessible anywhere, anyplace, where you have access to request object, i.e., sessions are accessible from controllers, views, helpers, cells, and components." }, { "code": null, "e": 2578, "s": 2515, "text": "Session object can be created by executing the following code." }, { "code": null, "e": 2617, "s": 2578, "text": "$session = $this->request->session();\n" }, { "code": null, "e": 2687, "s": 2617, "text": "To write something in session, we can use the write() session method." }, { "code": null, "e": 2717, "s": 2687, "text": "Session::write($key, $value)\n" }, { "code": null, "e": 2820, "s": 2717, "text": "The above method will take two arguments, the value and the key under, which the value will be stored." }, { "code": null, "e": 2862, "s": 2820, "text": "$session->write('name', 'Virat Gandhi');\n" }, { "code": null, "e": 2938, "s": 2862, "text": "To retrieve stored data from session, we can use the read() session method." }, { "code": null, "e": 2959, "s": 2938, "text": "Session::read($key)\n" }, { "code": null, "e": 3165, "s": 2959, "text": "The above function will take only one argument, that is the key of the value, which was used at the time of writing session data. Once the correct key was provided, then the function will return its value." }, { "code": null, "e": 3190, "s": 3165, "text": "$session->read('name');\n" }, { "code": null, "e": 3313, "s": 3190, "text": "When you want to check whether, particular data exists in the session or not, then you can use the check() session method." }, { "code": null, "e": 3335, "s": 3313, "text": "Session::check($key)\n" }, { "code": null, "e": 3390, "s": 3335, "text": "The above function will take only key as the argument." }, { "code": null, "e": 3459, "s": 3390, "text": "if ($session->check('name')) {\n // name exists and is not null.\n}\n" }, { "code": null, "e": 3547, "s": 3459, "text": "To delete data from session, we can use the delete() session method to delete the data." }, { "code": null, "e": 3570, "s": 3547, "text": "Session::delete($key)\n" }, { "code": null, "e": 3649, "s": 3570, "text": "The above function will take only key of the value to be deleted from session." }, { "code": null, "e": 3676, "s": 3649, "text": "$session->delete('name');\n" }, { "code": null, "e": 3779, "s": 3676, "text": "When you want to read and then delete data from session then, we can use the consume() session method." }, { "code": null, "e": 3810, "s": 3779, "text": "static Session::consume($key)\n" }, { "code": null, "e": 3861, "s": 3810, "text": "The above function will take only key as argument." }, { "code": null, "e": 3889, "s": 3861, "text": "$session->consume('name');\n" }, { "code": null, "e": 4018, "s": 3889, "text": "We need to destroy a user session, when the user logs out from the site and to destroy the session the destroy() method is used." }, { "code": null, "e": 4038, "s": 4018, "text": "Session::destroy()\n" }, { "code": null, "e": 4060, "s": 4038, "text": "$session->destroy();\n" }, { "code": null, "e": 4157, "s": 4060, "text": "Destroying session will remove all session data from server, but will not remove session cookie." }, { "code": null, "e": 4255, "s": 4157, "text": "In a situation, where you want to renew user session then, we can use the renew() session method." }, { "code": null, "e": 4273, "s": 4255, "text": "Session::renew()\n" }, { "code": null, "e": 4293, "s": 4273, "text": "$session->renew();\n" }, { "code": null, "e": 4371, "s": 4293, "text": "Make changes in the config/routes.php file as shown in the following program." }, { "code": null, "e": 4389, "s": 4371, "text": "config/routes.php" }, { "code": null, "e": 5456, "s": 4389, "text": "<?php\nuse Cake\\Http\\Middleware\\CsrfProtectionMiddleware;\nuse Cake\\Routing\\Route\\DashedRoute;\nuse Cake\\Routing\\RouteBuilder;\n$routes->setRouteClass(DashedRoute::class);\n$routes->scope('/', function (RouteBuilder $builder) {\n $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([\n 'httpOnly' => true,\n ]));\n $builder->applyMiddleware('csrf');\n //$builder->connect('/pages',['controller'=>'Pages','action'=>'display', 'home']);\n $builder->connect('/session-object',['controller'=>'Sessions','action'=>'index']);\n $builder->connect('/session-read',['controller'=>'Sessions','action'=>'retrieve_session_data']);\n $builder->connect('/session-write',['controller'=>'Sessions','action'=> 'write_session_data']);\n $builder->connect('/session-check',['controller'=>'Sessions','action'=>'check_session_data']);\n $builder->connect('/session-delete',['controller'=>'Sessions','action'=>'delete_session_data']);\n $builder->connect('/session-destroy',['controller'=>'Sessions','action'=>'destroy_session_data']);\n $builder->fallbacks();\n});" }, { "code": null, "e": 5583, "s": 5456, "text": "Create a SessionsController.php file at src/Controller/SessionsController.php. Copy the following code in the controller file" }, { "code": null, "e": 5621, "s": 5583, "text": "src/Controller/SessionsController.php" }, { "code": null, "e": 6825, "s": 5621, "text": "<?php\nnamespace App\\Controller;\nuse App\\Controller\\AppController;\n class SessionsController extends AppController {\n public function retrieveSessionData() {\n //create session object\n $session = $this->request->getSession();\n //read data from session\n $name = $session->read('name');\n $this->set('name',$name);\n }\n public function writeSessionData(){\n //create session object\n $session = $this->request->getSession();\n //write data in session\n $session->write('name','Virat Gandhi');\n }\n public function checkSessionData(){\n //create session object\n $session = $this->request->getSession();\n //check session data\n $name = $session->check('name');\n $address = $session->check('address');\n $this->set('name',$name);\n $this->set('address',$address);\n }\n public function deleteSessionData(){\n //create session object\n $session = $this->request->getSession();\n //delete session data\n $session->delete('name');\n }\n public function destroySessionData(){\n //create session object\n $session = $this->request->getSession();\n //destroy session\n $session->destroy();\n }\n}\n?>" }, { "code": null, "e": 6982, "s": 6825, "text": "Create a directory Sessions at src/Template and under that directory create a View file called write_session_data.php. Copy the following code in that file." }, { "code": null, "e": 7027, "s": 6982, "text": "src/Template/Sessions/write_session_data.php" }, { "code": null, "e": 7066, "s": 7027, "text": "The data has been written in session.\n" }, { "code": null, "e": 7200, "s": 7066, "text": "Create another View file called retrieve_session_data.php under the same Sessions directory and copy the following code in that file." }, { "code": null, "e": 7248, "s": 7200, "text": "src/Template/Sessions/retrieve_session_data.php" }, { "code": null, "e": 7298, "s": 7248, "text": "Here is the data from session.\nName: <?=$name;?>\n" }, { "code": null, "e": 7429, "s": 7298, "text": "Create another View file called check_session_data.ctp under the same Sessions directory and copy the following code in that file." }, { "code": null, "e": 7474, "s": 7429, "text": "src/Template/Sessions/check_session_data.ctp" }, { "code": null, "e": 7709, "s": 7474, "text": "<?php if($name): ?>\nname exists in the session.\n<?php else: ?>\nname doesn't exist in the database\n<?php endif;?>\n<?php if($address): ?>\naddress exists in the session.\n<?php else: ?>\naddress doesn't exist in the database\n<?php endif;?>" }, { "code": null, "e": 7842, "s": 7709, "text": "Create another View file called delete_session_data.ctp, under the same Sessions directory and copy the following code in that file." }, { "code": null, "e": 7888, "s": 7842, "text": "src/Template/Sessions/delete_session_data.ctp" }, { "code": null, "e": 7916, "s": 7888, "text": "Data deleted from session.\n" }, { "code": null, "e": 8050, "s": 7916, "text": "Create another View file called destroy_session_data.ctp, under the same Sessions directory and copy the following code in that file." }, { "code": null, "e": 8097, "s": 8050, "text": "src/Template/Sessions/destroy_session_data.ctp" }, { "code": null, "e": 8117, "s": 8097, "text": "Session Destroyed.\n" }, { "code": null, "e": 8220, "s": 8117, "text": "Execute the above example by visiting the following URL. This URL will help you write data in session." }, { "code": null, "e": 8260, "s": 8220, "text": "http://localhost/cakephp4/session-write" }, { "code": null, "e": 8346, "s": 8260, "text": "Visit the following URL to read session data − http://localhost/cakephp4/session-read" }, { "code": null, "e": 8434, "s": 8346, "text": "Visit the following URL to check session data − http://localhost/cakephp4/session-check" }, { "code": null, "e": 8534, "s": 8434, "text": "Visit the following URL to delete session data − http://localhost/cakephp4/session-delete Visit the" }, { "code": null, "e": 8626, "s": 8534, "text": "Visit the following URL to destroy session data − http://localhost/cakephp4/session-destroy" }, { "code": null, "e": 8633, "s": 8626, "text": " Print" }, { "code": null, "e": 8644, "s": 8633, "text": " Add Notes" } ]
3 ways to interpretate your NLP model to management and customer | by Edward Ma | Towards Data Science
Machine Learning (ML) and Artificial Intelligence (AI) changed the landscape in doing business. Lots of company hire data scientist (I am one of them:)) to deliver a data product. It is absolute easy to deliver a engine with “high” accuracy (Here is the reason why I double quoted). If somebody ask about reason, we can say that the model is black box or it is a statistical calculation few year ago but we cannot say that anymore nowadays. We also need to convince product team and management to trust our model but we cannot simply say that the engine “learnt” from data or it is a black box which cannot be explained as well. Of course, we may not need to explain model in some special scenario. For example, you do not want to explain the fraud detection model to public. Otherwise, public can find a way to “hack” the system. After reading this article, you will understand: What is model interpretation? Why do we need to interpretate model? Interpreting NLP model Take Away Reference Model interpretation means providing reason and the logic behind in order to enable the accountability and transparency on model. There are many types of model interpretations which including: During exploratory data analysis (EDA), we may apply principal component analysis (PCA) or t-Distributed Stochastic Neighbor Embedding (t-SNE) to understand about the feature After built model, we will use various metric to measure classification and regression model. Accuracy, precision and recall used in classification while mean squared error (MSE) used in regression. This kind of metric help us to understand the model performance Besides performance, static feature summary such as feature importance can be retrieved from model. However, it only exist in those decision tree base algorithm such as Random Forest and XGBoost. When evaluating model, we want to know why we predict it wrongly. We can leverage library to explain it so that we can fix it. Before explaining the model, we can first understand the criteria of model interpretation: Interpretability Intrinsic: We do not need to train another model to explain the target. For example, it is using decision tree or liner model Post hoc: The model belongs to black-box model which we need to use another model to interpret it. We will focus on this area in the following part Approach Model-specific: Some tools are limited to specific model such as liner model and neural network model. Model-agnostic: On the other hand, some tools able to explain any model by building write-box model. Level Global: Explain the overall model such as feature weight. This one give you a in general model behavior Local: Explain the specific prediction result. As mentioned before, we should explain in most of the scenario because: Accountability. Model should has a accountability to provide a correct (relatively) answer to consumer. As a model author, we should validate model features to guarantee it help on make a correct decision but not including as much feature as we can. Transparency. Machine learning is not a black box and we should provide the model transparency to customer and management. So that they know why you are doing. Just like open source, people are willing to use open source much more as they know what you are doing. Trustability. It is the basic requirement if consumer want to use the classification or prediction result. Most of the time, use has some domain knowledge such as trader need to understand why you provide the decision for buy/ sell particular stock. As you know, I mainly focus on NLP. Therefore, I only demonstrate the capability of interpreting NLP model although the following library can also explain other problems such as regression and image. For the following demonstration, I did NOT do any preprocessing for the sake of keeping it easy to understand. In real life business problem, we should do the preprocessing all the time. Otherwise, garbage in garbage out. Several libraries helps to explain model which including Explain Like I am Five (ELI5), Local Interpretable Model-agnostic Explanations (LIME) [1] and Skater. Library: I will demonstrate how we can use ELI5 and LIME. How about Skater? Stay tuned, will explain reason why I do not use it in NLP. Algorithm: In the following demonstration, it will include linear model (Logistic Regression in scikit-learn), ensemble model (Random Forest in scikit-learn, XGBoost) and deep learning model(self build word embedding in keras). For word embedding, you can check out my previous post for detail. ELI5 ELI5 provides both global model interpretation and local model interpretation. You may simply consider the global model interpretation as a feature importance but it not only support decision tree algorithm such as Radom Forest and XGBoost but also all sci-kit learn estimators. ELI5 author introduces it as Permutation Importance for global interpretation. To calculate the score, feature (a word) will be replaced by other word (noise) and predicting it. The idea is that feature importance [2]can be deduced by getting how much score decrease when a particular word is not provided. For example, “I like apple”. It will may changed to “I like orange” and then it will classify the newly created record to understand how “apple” is important. Of course, we need to assume the replaced word (e.g. orange) is noise and it should not provide major change on score. for pipeline in pipelines: print('Estimator: %s' % (pipeline['name'])) labels = pipeline['pipeline'].classes_.tolist() if pipeline['name'] in ['Logistic Regression', 'Random Forest']: estimator = pipeline['pipeline'] elif pipeline['name'] == 'XGBoost Classifier': estimator = pipeline['pipeline'].steps[1][1].get_booster()# Not support Keras# elif pipeline['name'] == 'keras':# estimator = pipeline['pipeline'] else: continue IPython.display.display( eli5.show_weights(estimator=estimator, top=10, target_names=labels, vec=vec)) The above figure means that, if input includes “keith”, then score of y=0 increase 2.138. Another case is “the”, it will decrease score -0.731 and -1.387 in y=1 and y=2 respectively. For local model interpretation, ELI5 use LIME algorithm. The display format is different from LIME but using same idea. number_of_sample = 1sample_ids = [random.randint(0, len(x_test) -1 ) for p in range(0, number_of_sample)]for idx in sample_ids: print('Index: %d' % (idx))# print('Index: %d, Feature: %s' % (idx, x_test[idx])) for pipeline in pipelines: if pipeline['name'] in ['Logistic Regression', 'Random Forest']: estimator = pipeline['pipeline'].steps[1][1] elif pipeline['name'] == 'XGBoost Classifier': estimator = pipeline['pipeline'].steps[1][1].get_booster() # Not support Keras# elif pipeline['name'] == 'Keras':# estimator = pipeline['pipeline'].model else: continueIPython.display.display( eli5.show_prediction(estimator, x_test[idx], top=10, vec=vec, target_names=labels)) ELI5 explains the test data and deciding that it may be y=0 and the probabilty is 0.031. It also highlight some high positive score and negative score words. LIME As the name mentioned, LIME focus on local model interpretable and model-agnostic part only. Passing trained model and target record to LIME library. A liner bag-of-words model will be created and providing lots of generated record for training a white box model. The while box model work as a binary classifier indicating the impact of word existence. For example, “I like apple”. It will may changed to “I like” and then it will classify the newly created record to understand how “apple” is important. So no matter what is the provided model is, it can also explain the model by generating records. No matter it is scikit-learn library, XGBoost or even Keras word embedding model. In my sample code, I implemented Keras in sci-kit learn API interface so that I can also use LIME to explain Keras’s word embedding model. number_of_sample = 1sample_ids = [random.randint(0, len(x_test) -1 ) for p in range(0, number_of_sample)]for idx in sample_ids: print('Index: %d' % (idx))# print('Index: %d, Feature: %s' % (idx, x_test[idx])) for pipeline in pipelines: print('-' * 50) print('Estimator: %s' % (pipeline['name'])) print('True Label: %s, Predicted Label: %s' % (y_test[idx], pipeline['pipeline'].predict([x_test[idx]])[0])) labels = pipeline['pipeline'].classes_.tolist() explainer = LimeTextExplainer(class_names=labels) exp = explainer.explain_instance(x_test[idx], pipeline['pipeline'].predict_proba, num_features=6, top_labels=5) IPython.display.display(exp.show_in_notebook(text=True)) # break# break LIME builds binary classifiers so we can see that it represent whether it is 0, 9, 15 classes with weight and highlighting high positive and negative score words. Skater For global interpretation, Skater provides feature importance and partial dependence approaches. Tried several time and cannot find a way to provide sci-kit learn pipeline package. Have to convert raw text to numpy format and passing the model separately. Second thing is that it takes about 2 minutes to prepare the feature importance when there is about 800 unique words. %matplotlib inlineimport warningswarnings.filterwarnings('ignore')import matplotlib.pyplot as pltfrom skater.model import InMemoryModelfrom skater.core.explanations import Interpretationtransfromed_x_test = vec.transform(x_test[:2]).toarray()interpreter = Interpretation(transfromed_x_test, feature_names=vec.get_feature_names())for pipeline in pipelines: print('-' * 50) print('Estimator: %s' % (pipeline['name'])) if pipeline['name'] in ['Logistic Regression', 'Random Forest']: estimator = pipeline['pipeline'].steps[1][1] else: continue print(estimator) pyint_model = InMemoryModel(estimator.predict_proba, examples=transfromed_x_test) f, axes = plt.subplots(1, 1, figsize = (26, 18)) ax = axes interpreter.feature_importance.plot_feature_importance(pyint_model, ascending=False, ax=ax) plt.show() Skater provides the feature importance per word. Partial dependence [3]is a bunch of figures to represent the relationship (linear, monotonic or complex) between target and features one by one. Providing a visualization, we can visualize the impact between one feature and target. However, we may not use partial dependency if there is NLP. For local interpretation. Skater wraps LIME module to perform local Text Interpretation. So I will prefer to use native LIME rather than a pure wrapper. You can access code via my github repo When you read Christoph’s Blog, you can refer to above code for Local Surrogate Models (LIME) part. As a data scientist, we have to explain the model behavior so that product team and management trust the deliverable and debug your model. Otherwise you may not know what you build. For NLP problem, feature importance or permutation feature importance are demanding as too much features (word). Not quite useful/ recommend to use it in NLP aspect. LIME do not able to explain the model correctly on some scenario. For example, the score can be different every time as it generates samples randomly. Will have another article to introduce how to resolve it. For ELI5, sci-kit learn pipeline is supported in show_weight (Global Interpretation) but it is not supported in show_prediction (Local Interpretation) in ELI5. Reason is mentioned in here. To overcome it, you can simply use LIME directly. There is bug when using ELI5 (version: 0.8) if the classifier is XGBoost Classifier. If you use XGBoost classifier, have to perform some workaround due to ELI5 bug (xgb_classifier.get_booster()) For Keras model, implemented sci-kit learn API interface but still cannot use ELI5. ELI5 will check the object type to prevent unexpected library. Special thank to Dipanjan (DJ) Sarkar supplement on Skater part. I am Data Scientist in Bay Area. Focusing on state-of-the-art in Data Science, Artificial Intelligence , especially in NLP and platform related. Visit my blog from http://medium.com/@makcedward/ Get connection from https://www.linkedin.com/in/edwardma1026 Explore my code from https://github.com/makcedward Check my kernal from https://www.kaggle.com/makcedward [1] Marco Tulio Ribeiro, Sameer Singh, Carlos Guestrin. “Why Should I Trust You?” Explaining the Predictions of Any Classifier. Sep 2016. https://arxiv.org/pdf/1602.04938.pdf [2] Breiman Leo. “ Random Forests”.Jan 2001. https://www.stat.berkeley.edu/~breiman/randomforest2001.pdf [3] Friedman, Jerome H. 2001. “Greedy Function Approximation: A Gradient Boosting Machine.” Apr 2001. https://statweb.stanford.edu/~jhf/ftp/trebst.pdf
[ { "code": null, "e": 352, "s": 172, "text": "Machine Learning (ML) and Artificial Intelligence (AI) changed the landscape in doing business. Lots of company hire data scientist (I am one of them:)) to deliver a data product." }, { "code": null, "e": 801, "s": 352, "text": "It is absolute easy to deliver a engine with “high” accuracy (Here is the reason why I double quoted). If somebody ask about reason, we can say that the model is black box or it is a statistical calculation few year ago but we cannot say that anymore nowadays. We also need to convince product team and management to trust our model but we cannot simply say that the engine “learnt” from data or it is a black box which cannot be explained as well." }, { "code": null, "e": 1003, "s": 801, "text": "Of course, we may not need to explain model in some special scenario. For example, you do not want to explain the fraud detection model to public. Otherwise, public can find a way to “hack” the system." }, { "code": null, "e": 1052, "s": 1003, "text": "After reading this article, you will understand:" }, { "code": null, "e": 1082, "s": 1052, "text": "What is model interpretation?" }, { "code": null, "e": 1120, "s": 1082, "text": "Why do we need to interpretate model?" }, { "code": null, "e": 1143, "s": 1120, "text": "Interpreting NLP model" }, { "code": null, "e": 1153, "s": 1143, "text": "Take Away" }, { "code": null, "e": 1163, "s": 1153, "text": "Reference" }, { "code": null, "e": 1356, "s": 1163, "text": "Model interpretation means providing reason and the logic behind in order to enable the accountability and transparency on model. There are many types of model interpretations which including:" }, { "code": null, "e": 1531, "s": 1356, "text": "During exploratory data analysis (EDA), we may apply principal component analysis (PCA) or t-Distributed Stochastic Neighbor Embedding (t-SNE) to understand about the feature" }, { "code": null, "e": 1794, "s": 1531, "text": "After built model, we will use various metric to measure classification and regression model. Accuracy, precision and recall used in classification while mean squared error (MSE) used in regression. This kind of metric help us to understand the model performance" }, { "code": null, "e": 1990, "s": 1794, "text": "Besides performance, static feature summary such as feature importance can be retrieved from model. However, it only exist in those decision tree base algorithm such as Random Forest and XGBoost." }, { "code": null, "e": 2117, "s": 1990, "text": "When evaluating model, we want to know why we predict it wrongly. We can leverage library to explain it so that we can fix it." }, { "code": null, "e": 2208, "s": 2117, "text": "Before explaining the model, we can first understand the criteria of model interpretation:" }, { "code": null, "e": 2225, "s": 2208, "text": "Interpretability" }, { "code": null, "e": 2351, "s": 2225, "text": "Intrinsic: We do not need to train another model to explain the target. For example, it is using decision tree or liner model" }, { "code": null, "e": 2499, "s": 2351, "text": "Post hoc: The model belongs to black-box model which we need to use another model to interpret it. We will focus on this area in the following part" }, { "code": null, "e": 2508, "s": 2499, "text": "Approach" }, { "code": null, "e": 2611, "s": 2508, "text": "Model-specific: Some tools are limited to specific model such as liner model and neural network model." }, { "code": null, "e": 2712, "s": 2611, "text": "Model-agnostic: On the other hand, some tools able to explain any model by building write-box model." }, { "code": null, "e": 2718, "s": 2712, "text": "Level" }, { "code": null, "e": 2822, "s": 2718, "text": "Global: Explain the overall model such as feature weight. This one give you a in general model behavior" }, { "code": null, "e": 2869, "s": 2822, "text": "Local: Explain the specific prediction result." }, { "code": null, "e": 2941, "s": 2869, "text": "As mentioned before, we should explain in most of the scenario because:" }, { "code": null, "e": 3191, "s": 2941, "text": "Accountability. Model should has a accountability to provide a correct (relatively) answer to consumer. As a model author, we should validate model features to guarantee it help on make a correct decision but not including as much feature as we can." }, { "code": null, "e": 3455, "s": 3191, "text": "Transparency. Machine learning is not a black box and we should provide the model transparency to customer and management. So that they know why you are doing. Just like open source, people are willing to use open source much more as they know what you are doing." }, { "code": null, "e": 3705, "s": 3455, "text": "Trustability. It is the basic requirement if consumer want to use the classification or prediction result. Most of the time, use has some domain knowledge such as trader need to understand why you provide the decision for buy/ sell particular stock." }, { "code": null, "e": 3905, "s": 3705, "text": "As you know, I mainly focus on NLP. Therefore, I only demonstrate the capability of interpreting NLP model although the following library can also explain other problems such as regression and image." }, { "code": null, "e": 4127, "s": 3905, "text": "For the following demonstration, I did NOT do any preprocessing for the sake of keeping it easy to understand. In real life business problem, we should do the preprocessing all the time. Otherwise, garbage in garbage out." }, { "code": null, "e": 4286, "s": 4127, "text": "Several libraries helps to explain model which including Explain Like I am Five (ELI5), Local Interpretable Model-agnostic Explanations (LIME) [1] and Skater." }, { "code": null, "e": 4422, "s": 4286, "text": "Library: I will demonstrate how we can use ELI5 and LIME. How about Skater? Stay tuned, will explain reason why I do not use it in NLP." }, { "code": null, "e": 4717, "s": 4422, "text": "Algorithm: In the following demonstration, it will include linear model (Logistic Regression in scikit-learn), ensemble model (Random Forest in scikit-learn, XGBoost) and deep learning model(self build word embedding in keras). For word embedding, you can check out my previous post for detail." }, { "code": null, "e": 4722, "s": 4717, "text": "ELI5" }, { "code": null, "e": 5001, "s": 4722, "text": "ELI5 provides both global model interpretation and local model interpretation. You may simply consider the global model interpretation as a feature importance but it not only support decision tree algorithm such as Radom Forest and XGBoost but also all sci-kit learn estimators." }, { "code": null, "e": 5586, "s": 5001, "text": "ELI5 author introduces it as Permutation Importance for global interpretation. To calculate the score, feature (a word) will be replaced by other word (noise) and predicting it. The idea is that feature importance [2]can be deduced by getting how much score decrease when a particular word is not provided. For example, “I like apple”. It will may changed to “I like orange” and then it will classify the newly created record to understand how “apple” is important. Of course, we need to assume the replaced word (e.g. orange) is noise and it should not provide major change on score." }, { "code": null, "e": 6192, "s": 5586, "text": "for pipeline in pipelines: print('Estimator: %s' % (pipeline['name'])) labels = pipeline['pipeline'].classes_.tolist() if pipeline['name'] in ['Logistic Regression', 'Random Forest']: estimator = pipeline['pipeline'] elif pipeline['name'] == 'XGBoost Classifier': estimator = pipeline['pipeline'].steps[1][1].get_booster()# Not support Keras# elif pipeline['name'] == 'keras':# estimator = pipeline['pipeline'] else: continue IPython.display.display( eli5.show_weights(estimator=estimator, top=10, target_names=labels, vec=vec))" }, { "code": null, "e": 6375, "s": 6192, "text": "The above figure means that, if input includes “keith”, then score of y=0 increase 2.138. Another case is “the”, it will decrease score -0.731 and -1.387 in y=1 and y=2 respectively." }, { "code": null, "e": 6495, "s": 6375, "text": "For local model interpretation, ELI5 use LIME algorithm. The display format is different from LIME but using same idea." }, { "code": null, "e": 7271, "s": 6495, "text": "number_of_sample = 1sample_ids = [random.randint(0, len(x_test) -1 ) for p in range(0, number_of_sample)]for idx in sample_ids: print('Index: %d' % (idx))# print('Index: %d, Feature: %s' % (idx, x_test[idx])) for pipeline in pipelines: if pipeline['name'] in ['Logistic Regression', 'Random Forest']: estimator = pipeline['pipeline'].steps[1][1] elif pipeline['name'] == 'XGBoost Classifier': estimator = pipeline['pipeline'].steps[1][1].get_booster() # Not support Keras# elif pipeline['name'] == 'Keras':# estimator = pipeline['pipeline'].model else: continueIPython.display.display( eli5.show_prediction(estimator, x_test[idx], top=10, vec=vec, target_names=labels))" }, { "code": null, "e": 7429, "s": 7271, "text": "ELI5 explains the test data and deciding that it may be y=0 and the probabilty is 0.031. It also highlight some high positive score and negative score words." }, { "code": null, "e": 7434, "s": 7429, "text": "LIME" }, { "code": null, "e": 7527, "s": 7434, "text": "As the name mentioned, LIME focus on local model interpretable and model-agnostic part only." }, { "code": null, "e": 7939, "s": 7527, "text": "Passing trained model and target record to LIME library. A liner bag-of-words model will be created and providing lots of generated record for training a white box model. The while box model work as a binary classifier indicating the impact of word existence. For example, “I like apple”. It will may changed to “I like” and then it will classify the newly created record to understand how “apple” is important." }, { "code": null, "e": 8257, "s": 7939, "text": "So no matter what is the provided model is, it can also explain the model by generating records. No matter it is scikit-learn library, XGBoost or even Keras word embedding model. In my sample code, I implemented Keras in sci-kit learn API interface so that I can also use LIME to explain Keras’s word embedding model." }, { "code": null, "e": 9038, "s": 8257, "text": "number_of_sample = 1sample_ids = [random.randint(0, len(x_test) -1 ) for p in range(0, number_of_sample)]for idx in sample_ids: print('Index: %d' % (idx))# print('Index: %d, Feature: %s' % (idx, x_test[idx])) for pipeline in pipelines: print('-' * 50) print('Estimator: %s' % (pipeline['name'])) print('True Label: %s, Predicted Label: %s' % (y_test[idx], pipeline['pipeline'].predict([x_test[idx]])[0])) labels = pipeline['pipeline'].classes_.tolist() explainer = LimeTextExplainer(class_names=labels) exp = explainer.explain_instance(x_test[idx], pipeline['pipeline'].predict_proba, num_features=6, top_labels=5) IPython.display.display(exp.show_in_notebook(text=True)) # break# break" }, { "code": null, "e": 9201, "s": 9038, "text": "LIME builds binary classifiers so we can see that it represent whether it is 0, 9, 15 classes with weight and highlighting high positive and negative score words." }, { "code": null, "e": 9208, "s": 9201, "text": "Skater" }, { "code": null, "e": 9305, "s": 9208, "text": "For global interpretation, Skater provides feature importance and partial dependence approaches." }, { "code": null, "e": 9582, "s": 9305, "text": "Tried several time and cannot find a way to provide sci-kit learn pipeline package. Have to convert raw text to numpy format and passing the model separately. Second thing is that it takes about 2 minutes to prepare the feature importance when there is about 800 unique words." }, { "code": null, "e": 10452, "s": 9582, "text": "%matplotlib inlineimport warningswarnings.filterwarnings('ignore')import matplotlib.pyplot as pltfrom skater.model import InMemoryModelfrom skater.core.explanations import Interpretationtransfromed_x_test = vec.transform(x_test[:2]).toarray()interpreter = Interpretation(transfromed_x_test, feature_names=vec.get_feature_names())for pipeline in pipelines: print('-' * 50) print('Estimator: %s' % (pipeline['name'])) if pipeline['name'] in ['Logistic Regression', 'Random Forest']: estimator = pipeline['pipeline'].steps[1][1] else: continue print(estimator) pyint_model = InMemoryModel(estimator.predict_proba, examples=transfromed_x_test) f, axes = plt.subplots(1, 1, figsize = (26, 18)) ax = axes interpreter.feature_importance.plot_feature_importance(pyint_model, ascending=False, ax=ax) plt.show()" }, { "code": null, "e": 10501, "s": 10452, "text": "Skater provides the feature importance per word." }, { "code": null, "e": 10793, "s": 10501, "text": "Partial dependence [3]is a bunch of figures to represent the relationship (linear, monotonic or complex) between target and features one by one. Providing a visualization, we can visualize the impact between one feature and target. However, we may not use partial dependency if there is NLP." }, { "code": null, "e": 10946, "s": 10793, "text": "For local interpretation. Skater wraps LIME module to perform local Text Interpretation. So I will prefer to use native LIME rather than a pure wrapper." }, { "code": null, "e": 10985, "s": 10946, "text": "You can access code via my github repo" }, { "code": null, "e": 11085, "s": 10985, "text": "When you read Christoph’s Blog, you can refer to above code for Local Surrogate Models (LIME) part." }, { "code": null, "e": 11267, "s": 11085, "text": "As a data scientist, we have to explain the model behavior so that product team and management trust the deliverable and debug your model. Otherwise you may not know what you build." }, { "code": null, "e": 11433, "s": 11267, "text": "For NLP problem, feature importance or permutation feature importance are demanding as too much features (word). Not quite useful/ recommend to use it in NLP aspect." }, { "code": null, "e": 11642, "s": 11433, "text": "LIME do not able to explain the model correctly on some scenario. For example, the score can be different every time as it generates samples randomly. Will have another article to introduce how to resolve it." }, { "code": null, "e": 11881, "s": 11642, "text": "For ELI5, sci-kit learn pipeline is supported in show_weight (Global Interpretation) but it is not supported in show_prediction (Local Interpretation) in ELI5. Reason is mentioned in here. To overcome it, you can simply use LIME directly." }, { "code": null, "e": 12076, "s": 11881, "text": "There is bug when using ELI5 (version: 0.8) if the classifier is XGBoost Classifier. If you use XGBoost classifier, have to perform some workaround due to ELI5 bug (xgb_classifier.get_booster())" }, { "code": null, "e": 12223, "s": 12076, "text": "For Keras model, implemented sci-kit learn API interface but still cannot use ELI5. ELI5 will check the object type to prevent unexpected library." }, { "code": null, "e": 12288, "s": 12223, "text": "Special thank to Dipanjan (DJ) Sarkar supplement on Skater part." }, { "code": null, "e": 12433, "s": 12288, "text": "I am Data Scientist in Bay Area. Focusing on state-of-the-art in Data Science, Artificial Intelligence , especially in NLP and platform related." }, { "code": null, "e": 12483, "s": 12433, "text": "Visit my blog from http://medium.com/@makcedward/" }, { "code": null, "e": 12544, "s": 12483, "text": "Get connection from https://www.linkedin.com/in/edwardma1026" }, { "code": null, "e": 12595, "s": 12544, "text": "Explore my code from https://github.com/makcedward" }, { "code": null, "e": 12650, "s": 12595, "text": "Check my kernal from https://www.kaggle.com/makcedward" }, { "code": null, "e": 12825, "s": 12650, "text": "[1] Marco Tulio Ribeiro, Sameer Singh, Carlos Guestrin. “Why Should I Trust You?” Explaining the Predictions of Any Classifier. Sep 2016. https://arxiv.org/pdf/1602.04938.pdf" }, { "code": null, "e": 12930, "s": 12825, "text": "[2] Breiman Leo. “ Random Forests”.Jan 2001. https://www.stat.berkeley.edu/~breiman/randomforest2001.pdf" } ]
SAS - Basic Syntax
Like any other programming language, the SAS language has its own rules of syntax to create the SAS programs. The three components of any SAS program - Statements, Variables and Data sets follow the below rules on Syntax. Statements can start anywhere and end anywhere. A semicolon at the end of the last line marks the end of the statement. Statements can start anywhere and end anywhere. A semicolon at the end of the last line marks the end of the statement. Many SAS statements can be on the same line, with each statement ending with a semicolon. Many SAS statements can be on the same line, with each statement ending with a semicolon. Space can be used to separate the components in a SAS program statement. Space can be used to separate the components in a SAS program statement. SAS keywords are not case sensitive. SAS keywords are not case sensitive. Every SAS program must end with a RUN statement. Every SAS program must end with a RUN statement. Variables in SAS represent a column in the SAS data set. The variable names follow the below rules. It can be maximum 32 characters long. It can be maximum 32 characters long. It can not include blanks. It can not include blanks. It must start with the letters A through Z (not case sensitive) or an underscore (_). It must start with the letters A through Z (not case sensitive) or an underscore (_). Can include numbers but not as the first character. Can include numbers but not as the first character. Variable names are case insensitive. Variable names are case insensitive. # Valid Variable Names REVENUE_YEAR MaxVal _Length # Invalid variable Names Miles Per Liter #contains Space. RainfFall% # contains apecial character other than underscore. 90_high # Starts with a number. The DATA statement marks the creation of a new SAS data set. The rules for DATA set creation are as below. A single word after the DATA statement indicates a temporary data set name. Which means the data set gets erased at the end of the session. A single word after the DATA statement indicates a temporary data set name. Which means the data set gets erased at the end of the session. The data set name can be prefixed with a library name which makes it a permanent data set. Which means the data set persists after the session is over. The data set name can be prefixed with a library name which makes it a permanent data set. Which means the data set persists after the session is over. If the SAS data set name is omitted then SAS creates a temporary data set with a name generated by SAS like - DATA1, DATA2 etc. If the SAS data set name is omitted then SAS creates a temporary data set with a name generated by SAS like - DATA1, DATA2 etc. # Temporary data sets. DATA TempData; DATA abc; DATA newdat; # Permanent data sets. DATA LIBRARY1.DATA1 DATA MYLIB.newdat; The SAS programs, data files and the results of the programs are saved with various extensions in windows. *.sas − It represents the SAS code file which can be edited using the SAS Editor or any text editor. *.sas − It represents the SAS code file which can be edited using the SAS Editor or any text editor. *.log − It represents the SAS Log File it contains information such as errors, warnings, and data set details for a submitted SAS program. *.log − It represents the SAS Log File it contains information such as errors, warnings, and data set details for a submitted SAS program. *.mht / *.html −It represents the SAS Results file. *.mht / *.html −It represents the SAS Results file. *.sas7bdat −It represents SAS Data File which contains a SAS data set including variable names, labels, and the results of calculations. *.sas7bdat −It represents SAS Data File which contains a SAS data set including variable names, labels, and the results of calculations. Comments in SAS code are specified in two ways. Below are these two formats. A comment in the form of *message; can not contain semicolons or unmatched quotation mark inside it. Also there should not be any reference to any macro statements inside such comments. It can span multiple lines and can be of any length.. Following is a single line comment example − * This is comment ; Following is a multiline comment example − * This is first line of the comment * This is second line of the comment; A comment in the form of /*message*/ is used more frequently and it can not be nested. But it can span multiple lines and can be of any length. Following is a single line comment example − /* This is comment */ Following is a multiline comment example − /* This is first line of the comment * This is second line of the comment */ 50 Lectures 5.5 hours Code And Create 124 Lectures 30 hours Juan Galvan 162 Lectures 31.5 hours Yossef Ayman Zedan 35 Lectures 2.5 hours Ermin Dedic 167 Lectures 45.5 hours Muslim Helalee Print Add Notes Bookmark this page
[ { "code": null, "e": 2693, "s": 2583, "text": "Like any other programming language, the SAS language has its own rules of syntax to create the SAS programs." }, { "code": null, "e": 2807, "s": 2695, "text": "The three components of any SAS program - Statements, Variables and Data sets follow the below rules on Syntax." }, { "code": null, "e": 2927, "s": 2807, "text": "Statements can start anywhere and end anywhere. A semicolon at the end of the last line marks the end of the statement." }, { "code": null, "e": 3047, "s": 2927, "text": "Statements can start anywhere and end anywhere. A semicolon at the end of the last line marks the end of the statement." }, { "code": null, "e": 3137, "s": 3047, "text": "Many SAS statements can be on the same line, with each statement ending with a semicolon." }, { "code": null, "e": 3227, "s": 3137, "text": "Many SAS statements can be on the same line, with each statement ending with a semicolon." }, { "code": null, "e": 3300, "s": 3227, "text": "Space can be used to separate the components in a SAS program statement." }, { "code": null, "e": 3373, "s": 3300, "text": "Space can be used to separate the components in a SAS program statement." }, { "code": null, "e": 3411, "s": 3373, "text": "SAS keywords are not case sensitive." }, { "code": null, "e": 3449, "s": 3411, "text": "SAS keywords are not case sensitive." }, { "code": null, "e": 3498, "s": 3449, "text": "Every SAS program must end with a RUN statement." }, { "code": null, "e": 3547, "s": 3498, "text": "Every SAS program must end with a RUN statement." }, { "code": null, "e": 3647, "s": 3547, "text": "Variables in SAS represent a column in the SAS data set. The variable names follow the below rules." }, { "code": null, "e": 3685, "s": 3647, "text": "It can be maximum 32 characters long." }, { "code": null, "e": 3723, "s": 3685, "text": "It can be maximum 32 characters long." }, { "code": null, "e": 3750, "s": 3723, "text": "It can not include blanks." }, { "code": null, "e": 3777, "s": 3750, "text": "It can not include blanks." }, { "code": null, "e": 3863, "s": 3777, "text": "It must start with the letters A through Z (not case sensitive) or an underscore (_)." }, { "code": null, "e": 3949, "s": 3863, "text": "It must start with the letters A through Z (not case sensitive) or an underscore (_)." }, { "code": null, "e": 4001, "s": 3949, "text": "Can include numbers but not as the first character." }, { "code": null, "e": 4053, "s": 4001, "text": "Can include numbers but not as the first character." }, { "code": null, "e": 4090, "s": 4053, "text": "Variable names are case insensitive." }, { "code": null, "e": 4127, "s": 4090, "text": "Variable names are case insensitive." }, { "code": null, "e": 4338, "s": 4127, "text": "# Valid Variable Names\nREVENUE_YEAR\nMaxVal\n_Length\n\n# Invalid variable Names\nMiles Per Liter\t#contains Space.\nRainfFall% # contains apecial character other than underscore.\n90_high\t\t# Starts with a number." }, { "code": null, "e": 4445, "s": 4338, "text": "The DATA statement marks the creation of a new SAS data set. The rules for DATA set creation are as below." }, { "code": null, "e": 4585, "s": 4445, "text": "A single word after the DATA statement indicates a temporary data set name. Which means the data set gets erased at the end of the session." }, { "code": null, "e": 4725, "s": 4585, "text": "A single word after the DATA statement indicates a temporary data set name. Which means the data set gets erased at the end of the session." }, { "code": null, "e": 4877, "s": 4725, "text": "The data set name can be prefixed with a library name which makes it a permanent data set. Which means the data set persists after the session is over." }, { "code": null, "e": 5029, "s": 4877, "text": "The data set name can be prefixed with a library name which makes it a permanent data set. Which means the data set persists after the session is over." }, { "code": null, "e": 5157, "s": 5029, "text": "If the SAS data set name is omitted then SAS creates a temporary data set with a name generated by SAS like - DATA1, DATA2 etc." }, { "code": null, "e": 5285, "s": 5157, "text": "If the SAS data set name is omitted then SAS creates a temporary data set with a name generated by SAS like - DATA1, DATA2 etc." }, { "code": null, "e": 5409, "s": 5285, "text": "# Temporary data sets.\nDATA TempData;\nDATA abc;\nDATA newdat;\n\n# Permanent data sets.\nDATA LIBRARY1.DATA1\nDATA MYLIB.newdat;" }, { "code": null, "e": 5516, "s": 5409, "text": "The SAS programs, data files and the results of the programs are saved with various extensions in windows." }, { "code": null, "e": 5617, "s": 5516, "text": "*.sas − It represents the SAS code file which can be edited using the SAS Editor or any text editor." }, { "code": null, "e": 5718, "s": 5617, "text": "*.sas − It represents the SAS code file which can be edited using the SAS Editor or any text editor." }, { "code": null, "e": 5859, "s": 5718, "text": "*.log − It represents the SAS Log File it contains information such as errors, warnings, and data set details for a submitted SAS program." }, { "code": null, "e": 6000, "s": 5859, "text": "*.log − It represents the SAS Log File it contains information such as errors, warnings, and data set details for a submitted SAS program." }, { "code": null, "e": 6052, "s": 6000, "text": "*.mht / *.html −It represents the SAS Results file." }, { "code": null, "e": 6104, "s": 6052, "text": "*.mht / *.html −It represents the SAS Results file." }, { "code": null, "e": 6241, "s": 6104, "text": "*.sas7bdat −It represents SAS Data File which contains a SAS data set including variable names, labels, and the results of calculations." }, { "code": null, "e": 6378, "s": 6241, "text": "*.sas7bdat −It represents SAS Data File which contains a SAS data set including variable names, labels, and the results of calculations." }, { "code": null, "e": 6455, "s": 6378, "text": "Comments in SAS code are specified in two ways. Below are these two formats." }, { "code": null, "e": 6740, "s": 6455, "text": "A comment in the form of *message; can not contain semicolons or unmatched quotation mark inside it. Also there should not be any reference to any macro statements inside such comments. It can span multiple lines and can be of any length.. Following is a single line comment example −" }, { "code": null, "e": 6761, "s": 6740, "text": "* This is comment ;\n" }, { "code": null, "e": 6804, "s": 6761, "text": "Following is a multiline comment example −" }, { "code": null, "e": 6879, "s": 6804, "text": "* This is first line of the comment\n* This is second line of the comment;\n" }, { "code": null, "e": 7069, "s": 6879, "text": " A comment in the form of /*message*/ is used more frequently and it can not be nested. But it can span multiple lines and can be of any length. Following is a single line comment example −" }, { "code": null, "e": 7092, "s": 7069, "text": "/* This is comment */\n" }, { "code": null, "e": 7135, "s": 7092, "text": "Following is a multiline comment example −" }, { "code": null, "e": 7213, "s": 7135, "text": "/* This is first line of the comment\n* This is second line of the comment */\n" }, { "code": null, "e": 7248, "s": 7213, "text": "\n 50 Lectures \n 5.5 hours \n" }, { "code": null, "e": 7265, "s": 7248, "text": " Code And Create" }, { "code": null, "e": 7300, "s": 7265, "text": "\n 124 Lectures \n 30 hours \n" }, { "code": null, "e": 7313, "s": 7300, "text": " Juan Galvan" }, { "code": null, "e": 7350, "s": 7313, "text": "\n 162 Lectures \n 31.5 hours \n" }, { "code": null, "e": 7370, "s": 7350, "text": " Yossef Ayman Zedan" }, { "code": null, "e": 7405, "s": 7370, "text": "\n 35 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7418, "s": 7405, "text": " Ermin Dedic" }, { "code": null, "e": 7455, "s": 7418, "text": "\n 167 Lectures \n 45.5 hours \n" }, { "code": null, "e": 7471, "s": 7455, "text": " Muslim Helalee" }, { "code": null, "e": 7478, "s": 7471, "text": " Print" }, { "code": null, "e": 7489, "s": 7478, "text": " Add Notes" } ]
XAML - Triggers
Basically, a trigger enables you to change property values or take actions based on the value of a property. So, it basically allows you to dynamically change the appearance and/or behavior of your control without having to create a new one. Triggers are used to change the value of any given property, when certain conditions are satisfied. Triggers are usually defined in a style or in the root of a document which are applied to that specific control. There are three types of triggers − Property Triggers Data Triggers Event Triggers In property triggers, when a change occurs in one property, it will bring either an immediate or an animated change in another property. For example, you can use a property trigger if you want to change the button appearance when the mouse is over the button. The following example demonstrates how to change the foreground color of a button when the mouse enters its region. <Window x:Class = "XAMLPropertyTriggers.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "MainWindow" Height = "350" Width = "604"> <Window.Resources> <Style x:Key = "TriggerStyle" TargetType = "Button"> <Setter Property = "Foreground" Value = "Blue" /> <Style.Triggers> <Trigger Property = "IsMouseOver" Value = "True"> <Setter Property = "Foreground" Value = "Green" /> </Trigger> </Style.Triggers> </Style> </Window.Resources> <Grid> <Button Width = "100" Height = "70" Style = "{StaticResource TriggerStyle}" Content = "Trigger"/> </Grid> </Window> When you compile and execute the above code, it will produce the following output − When the mouse enters the region of button, the foreground color will change to green. A data trigger performs some action when the bound data satisfies some condition. Let’s have a look at the following XAML code in which a checkbox and a text block are created with some properties. When the checkbox is checked, it will change the foreground color to red. <Window x:Class = "XAMLDataTrigger.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "Data Trigger" Height = "350" Width = "604"> <StackPanel HorizontalAlignment = "Center"> <CheckBox x:Name = "redColorCheckBox" Content = "Set red as foreground color" Margin = "20"/> <TextBlock Name = "txtblock" VerticalAlignment = "Center" Text = "Event Trigger" FontSize = "24" Margin = "20"> <TextBlock.Style> <Style> <Style.Triggers> <DataTrigger Binding = "{Binding ElementName = redColorCheckBox, Path = IsChecked}" Value = "true"> <Setter Property = "TextBlock.Foreground" Value = "Red"/> <Setter Property = "TextBlock.Cursor" Value = "Hand" /> </DataTrigger> </Style.Triggers> </Style> </TextBlock.Style> </TextBlock> </StackPanel> </Window> When you compile and execute the above code, it will produce the following output − When the checkbox is checked, the foreground color of the text block will change to red. An event trigger performs some action when a specific event is fired. It is usually used to accomplish some animation such DoubleAnimation, ColorAnimation, etc. The following code block creates a simple button. When the click event is fired, it will expand the width and height of the button. <Window x:Class = "XAMLEventTrigger.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "MainWindow" Height = "350" Width = "604"> <Grid> <Button Content = "Click Me" Width = "60" Height = "30"> <Button.Triggers> <EventTrigger RoutedEvent = "Button.Click"> <EventTrigger.Actions> <BeginStoryboard> <Storyboard> <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty = "Width" Duration = "0:0:4"> <LinearDoubleKeyFrame Value = "60" KeyTime = "0:0:0"/> <LinearDoubleKeyFrame Value = "120" KeyTime = "0:0:1"/> <LinearDoubleKeyFrame Value = "200" KeyTime = "0:0:2"/> <LinearDoubleKeyFrame Value = "300" KeyTime = "0:0:3"/> </DoubleAnimationUsingKeyFrames> <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty = "Height" Duration = "0:0:4"> <LinearDoubleKeyFrame Value = "30" KeyTime = "0:0:0"/> <LinearDoubleKeyFrame Value = "40" KeyTime = "0:0:1"/> <LinearDoubleKeyFrame Value = "80" KeyTime = "0:0:2"/> <LinearDoubleKeyFrame Value = "150" KeyTime = "0:0:3"/> </DoubleAnimationUsingKeyFrames> </Storyboard> </BeginStoryboard> </EventTrigger.Actions> </EventTrigger> </Button.Triggers> </Button> </Grid> </Window> When you compile and execute the above code, it will produce the following output − Now, click on the button and you will observe that it will start expanding in both dimensions. Print Add Notes Bookmark this page
[ { "code": null, "e": 2165, "s": 1923, "text": "Basically, a trigger enables you to change property values or take actions based on the value of a property. So, it basically allows you to dynamically change the appearance and/or behavior of your control without having to create a new one." }, { "code": null, "e": 2414, "s": 2165, "text": "Triggers are used to change the value of any given property, when certain conditions are satisfied. Triggers are usually defined in a style or in the root of a document which are applied to that specific control. There are three types of triggers −" }, { "code": null, "e": 2432, "s": 2414, "text": "Property Triggers" }, { "code": null, "e": 2446, "s": 2432, "text": "Data Triggers" }, { "code": null, "e": 2461, "s": 2446, "text": "Event Triggers" }, { "code": null, "e": 2721, "s": 2461, "text": "In property triggers, when a change occurs in one property, it will bring either an immediate or an animated change in another property. For example, you can use a property trigger if you want to change the button appearance when the mouse is over the button." }, { "code": null, "e": 2837, "s": 2721, "text": "The following example demonstrates how to change the foreground color of a button when the mouse enters its region." }, { "code": null, "e": 3610, "s": 2837, "text": "<Window x:Class = \"XAMLPropertyTriggers.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n Title = \"MainWindow\" Height = \"350\" Width = \"604\">\n\t\n <Window.Resources>\n <Style x:Key = \"TriggerStyle\" TargetType = \"Button\">\n <Setter Property = \"Foreground\" Value = \"Blue\" />\n <Style.Triggers>\n <Trigger Property = \"IsMouseOver\" Value = \"True\">\n <Setter Property = \"Foreground\" Value = \"Green\" />\n </Trigger> \n </Style.Triggers>\n </Style>\n </Window.Resources>\n\t\n <Grid>\n <Button Width = \"100\" Height = \"70\" Style = \"{StaticResource TriggerStyle}\" \n Content = \"Trigger\"/>\n </Grid>\n\t\n</Window>" }, { "code": null, "e": 3694, "s": 3610, "text": "When you compile and execute the above code, it will produce the following output −" }, { "code": null, "e": 3781, "s": 3694, "text": "When the mouse enters the region of button, the foreground color will change to green." }, { "code": null, "e": 4053, "s": 3781, "text": "A data trigger performs some action when the bound data satisfies some condition. Let’s have a look at the following XAML code in which a checkbox and a text block are created with some properties. When the checkbox is checked, it will change the foreground color to red." }, { "code": null, "e": 5109, "s": 4053, "text": "<Window x:Class = \"XAMLDataTrigger.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n Title = \"Data Trigger\" Height = \"350\" Width = \"604\">\n\t\n <StackPanel HorizontalAlignment = \"Center\">\n <CheckBox x:Name = \"redColorCheckBox\" Content = \"Set red as foreground color\" Margin = \"20\"/>\n\t\t\n <TextBlock Name = \"txtblock\" VerticalAlignment = \"Center\" \n Text = \"Event Trigger\" FontSize = \"24\" Margin = \"20\">\n <TextBlock.Style>\n <Style>\n <Style.Triggers>\n <DataTrigger Binding = \"{Binding ElementName = redColorCheckBox, Path = IsChecked}\" \n Value = \"true\">\n <Setter Property = \"TextBlock.Foreground\" Value = \"Red\"/>\n <Setter Property = \"TextBlock.Cursor\" Value = \"Hand\" />\n </DataTrigger>\n </Style.Triggers>\n </Style>\n </TextBlock.Style>\n </TextBlock>\n </StackPanel>\n\t\n</Window>\t\t" }, { "code": null, "e": 5193, "s": 5109, "text": "When you compile and execute the above code, it will produce the following output −" }, { "code": null, "e": 5282, "s": 5193, "text": "When the checkbox is checked, the foreground color of the text block will change to red." }, { "code": null, "e": 5575, "s": 5282, "text": "An event trigger performs some action when a specific event is fired. It is usually used to accomplish some animation such DoubleAnimation, ColorAnimation, etc. The following code block creates a simple button. When the click event is fired, it will expand the width and height of the button." }, { "code": null, "e": 7314, "s": 5575, "text": "<Window x:Class = \"XAMLEventTrigger.MainWindow\"\n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n Title = \"MainWindow\" Height = \"350\" Width = \"604\">\n\t\n <Grid>\n <Button Content = \"Click Me\" Width = \"60\" Height = \"30\">\n <Button.Triggers>\n <EventTrigger RoutedEvent = \"Button.Click\">\n <EventTrigger.Actions>\n <BeginStoryboard>\n <Storyboard>\n \n <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty = \"Width\" Duration = \"0:0:4\">\n <LinearDoubleKeyFrame Value = \"60\" KeyTime = \"0:0:0\"/>\n <LinearDoubleKeyFrame Value = \"120\" KeyTime = \"0:0:1\"/>\n <LinearDoubleKeyFrame Value = \"200\" KeyTime = \"0:0:2\"/>\n <LinearDoubleKeyFrame Value = \"300\" KeyTime = \"0:0:3\"/>\n </DoubleAnimationUsingKeyFrames>\n\t\t\t\t\t\t\t\n <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty = \"Height\" Duration = \"0:0:4\">\n <LinearDoubleKeyFrame Value = \"30\" KeyTime = \"0:0:0\"/>\n <LinearDoubleKeyFrame Value = \"40\" KeyTime = \"0:0:1\"/>\n <LinearDoubleKeyFrame Value = \"80\" KeyTime = \"0:0:2\"/>\n <LinearDoubleKeyFrame Value = \"150\" KeyTime = \"0:0:3\"/>\n </DoubleAnimationUsingKeyFrames>\n\t\t\t\t\t\t\t\n </Storyboard>\n </BeginStoryboard>\n </EventTrigger.Actions>\n </EventTrigger>\n </Button.Triggers>\n </Button>\n </Grid>\n</Window>" }, { "code": null, "e": 7398, "s": 7314, "text": "When you compile and execute the above code, it will produce the following output −" }, { "code": null, "e": 7493, "s": 7398, "text": "Now, click on the button and you will observe that it will start expanding in both dimensions." }, { "code": null, "e": 7500, "s": 7493, "text": " Print" }, { "code": null, "e": 7511, "s": 7500, "text": " Add Notes" } ]
A Not so Short Introduction to the Rust Programming Language | by Kasper Müller | Towards Data Science
What is your favorite programming language? If your answer isn’t Rust then please read this post. At the end of it all, your answer might have changed! In this post, I will teach you the basics of Rust programming. Enough to get you started and create your own programs. At the end of the article, I will guide you in some very nice directions for further studies. You can return to this article during your Rust training as a small dictionary or lookup article. Learning a new programming language is like learning any other language. The fastest way is to try it and in this case, you don’t need a friend from a different country or an aircraft. You just need your new friend - the Rust compiler. And believe me, it will be a very good friend indeed. So feel free to code along and try out examples of your own or simply read this with a cop of strong coffee like you would any other article or book. Let’s begin... · Installation and First Project· Variables· Data Types ∘ Numbers ∘ Booleans ∘ Strings, &str and Characters· Collections ∘ Array ∘ Tuple ∘ Vector ∘ Hash Map· Functions· Control Flow and Loops ∘ Conditions ∘ Loops· Ownership and Borrowing· Structs, Enums and Methods· Error Handling· Tests· Advance Concepts: Generic Types, Traits, Lifetimes, Closures and Concurrency Rust is here to stay and if you want to learn a performant and modern language that is both safe and future-proof, Rust is a good choice. Rust is a systems programming language that runs blazingly fast, prevents almost all crashes, and eliminates data races. Even though Rust is classified as a systems programming language, you can really build anything in Rust. You just need to sacrifice some time. In return, you get safety and mind-blowing speed. Rust has gotten a reputation of being hard to learn, but I think that it really comes down to the initial approach and mindset. You just need to think a little differently when coding - like a Rustacean! The installation of Rust is painless thanks to a little nifty cli called rustup. You can install Rust by following the instructions here or by just Googling. When you have installed Rust and its fantastic package manager called Cargo, you are good to go. Say you want to create a project called “rusty_cli”. Find a location on your file system where you want to place your project. Then “cd” yourself to that location in the cmd/terminal. When you are inside the folder that you want to place the project, simply use cargo new rusty_cli. Cargo will work its magic and create a project structure that it understands, including a folder called src, and inside will be a file called main.rs. The file main.rs is the entry point of the program. In order to run the program, you have a few different options using Cargo. You can use cargo run to run the main file in debugging mode or cargo build to create an executable. This executable will be stored in target/debug . You don’t have to use cargo to compile and run Rust programs, but it is a very friendly tool and I highly recommend using it. When you are ready to build the final executable, you can use the command cargo build --release to compile it with optimizations. This command will create an executable inside target/release instead of target/debug. The optimizations make your Rust code run much much faster but with a small penalty in compilation time. Variables in Rust are defined using the let keyword and are immutable by default. Let’s have an example. The following code will not compile just yet. If you are following along, then you’ll see the compiler complaining about something like “cannot assign twice to immutable variable”. In order to fix this, we could do the following: Note that if we put the keyword mut in front of the variable name then the variable becomes mutable. Also, note how expressions work in Rust. An expression is something that returns a value. If you put a semicolon you are suppressing the result of this expression, which in most cases is what you want. This will be clearer when we get to functions in a little while. Data types usually go hand in hand with arithmetic operations, but I won’t dedicate much space for this since the usual operations on numbers apply in Rust as well. Many of the data types in Rust are shared with other languages. We have integer types such as i32 or i64 and floating-point numbers as for instance f64. We also have the data type boolwhich can contain the values true or false, we have string, &strand char for storing text data and tuple, array, vector and hash map as some of the common collections. On top of this, we have structs, methods and associated functionsas a replacement of classes and methods in OOP languages and an interesting type called trait which is kinda like an interface in e.g. Go. Besides structures and tuple structs for structuring related data, we also have the type enum which plays a central role in the Rust language. The usage of some of these types is best learned through examples and by experimenting on your own, however, I think some initial explanations and examples at this point are in order. Note that when you declare variables, you can choose to specify the data type by explicitly stating it in the declaration. If we want to store a variable containing an unsigned integer of size 8 bits, we have to do something like the following: If you had just written let age = 18; then Rust would have inferred the type of age to be of typei32. Booleans in Rust called “bools” are like the booleans in other languages. The syntax is true and false (note the lower case) and an example could be let b = true;. The character type is written with single quotes like ‘c’ and the keyword denoting the data type is char. Strings are a bit more complicated in Rust than they are in e.g. Python but that is because a lot of the details are kept hidden in Python. Well, not so much in Rust! The reason for this is to prevent future errors when dealing with strings. A common concept in Rust is that the language goes a long way to ensure safety by dealing with possible errors at compile time. This is, by all means, a good thing, but it puts some demands on the programmer. Strings are implemented as a collection of bytes, together with some methods to provide useful functionality when those bytes are interpreted as text. Strings are more complicated than many programmers give them credit for. That is because they look natural to the programmer - after all, we modern humans are used to dealing with text in everyday life. However, since there is a difference between what we would consider being a meaningful substring and how the machine would interpret substrings, things are not as easy as they seem. We need something called encodings as a bridge between the machine and our brain. We won’t go into details about the world of encodings but if you find yourself unable to sleep one night, then by all means take a research tour and dive deep into encodings, it is more fascinating than you might think! Rust encodes strings in UTF-8 and unlike in Python, we can make strings growable in Rust. As indicated above Rust has more than one kind of string. The type String and the type str, where the latter is usually seen in the form &str , and is called a string slice or string literal. A String is stored as a vector of bytes Vec<u8> and comes with convenient methods: We will deal with vectors shortly. For now, you can think of them as a typical array. Exactly what the difference is between the two types of strings will be skipped for now, but what I can say is that if you make a variable like the following: let s = "Towards Data Science"; then s will be of type &str. If you want to store "Towards Data Science" as a String type, you would either do let s = "Towards Data Science".to_string(); or equivalently: let s = String::from("Towards Data Science"); The main difference between the two types is that &str is immutable and stored on the stack and String types can be made mutable and are thus stored on the heap. If you don’t know about the stack and the heap, don’t sweat it. The most important thing to know about them is that accessing and writing to the stack is much faster than the heap. Data stored on the stack needs to be of a fixed size during the whole runtime. This means that if a variable is allowed to grow in size, then it needs to be stored on the heap. The two types are also related as indicated by the name string slice by &str being a substring of a String type, whatever that means (try to find out yourself). Since this is a short introduction, we will leave this topic and this data type for now but the data type of strings is a rich and exciting topic and I encourage you to take a deep dive into this subject after you are done reading this post. In Rust, we have many collections, but some of them are used more than others. An array in Rust is like an array in Go for example. It is of fixed size and thus can be stored on the stack which means quick access. In an array, you can only store one data type at a time. The syntax is like Python’s list: let rust_array = [1, 2, 3]; and you can access a specific element in the same way as in Python. rust_array[0] gives us the first element and in this case 1. The tuple type is commonly used in Rust for storing different data types in one collection. We can access the elements with a dot notation: Vectors are one of the most commonly used collections in Rust because like Python’s lists or Go’s slices, the vector in Rust can grow in size. It can only hold a single data type but as you will see later, there are ways around that. We will have to know about a type called enumto begin writing about that though. The fact that a vector can grow makes it a very important type as you would imagine. To create a new, empty vector, we can call the Vec::new function: let mut v: Vec<i32> = Vec::new(); Once created, we can now push elements into it. For instance, v.push(1) will append 1 to v and the size has now grown. If you want to instantiate the vector with elements in it, we have a convenient macro for that: let v = vec![1, 2, 3]; We will see more macros a little later. There are two ways of getting elements from a vector. We can do it like in Python with the v[i] notation getting the ith element in this case. But we need to be careful that the vector actually has enough elements. If it has fewer elements and we try to access an element that does not exist, then we’ll get an error at runtime! This is dangerous so Rust has another way of accessing elements in a vector. We access it like let second = v.get(1); Now second will be of type Option<T> which I haven’t covered yet, but soon you’ll know what that means and how to get the value out. We can also iterate over vectors in a for loop but since I haven’t covered loops yet, I’ll wait with showing you the syntax as well. Hash maps are like dictionaries in Python or maps in Go and The type is denoted HashMap<K, V>. It stores a mapping of keys of type K to values of type V. To initialize and populate a hash map, we could do the following: The insert method pushes data into the hash map by a tuple of key and value as an argument. If you want to access the data inside the hash map, then we have the get method for this as well. Specifically, let a = articles.get(&String::from("Python Graph")); will return an Option type we can then get the value from. The symbol & will be covered shortly as well. When we want to update the hash map by a key, and we are not sure whether it’s there already, we have several options. One of them is the convenient entry method: articles.entry(String::from("Rust")).or_insert("https://www.cantorsparadise.com/the-most-loved-programming-language-in-the-world-5220475fcc22"); If the key is already in the hash map, then we’ll get a mutable reference to it, if not, then we’ll insert the data specified in the argument to or_insert . References will be explained in a bit. Functions are one of the most important features of Rust. We have seen the main function which plays a special role, but we are of course able to create other functions as well. The syntax is simple. Here is an example of another function in Rust: Note that we need to tell Rust which data type the function accepts as input and which type it will output. This is a good thing since it prevents many errors. Another interesting thing about Rust is that you don’t have to explicitly tell Rust what you return by a return keyword. If the last statement in a function has no trailing semicolon, then that is what the function returns. This also applies to blocks of code wrapped in curly braces in general. A lot like Scala. In the above example. the function plus_one returns x+1 where x is the integer that the function takes in as an argument. In Rust, we have a return keyword, but it is usually only used if you want to return something early. The syntax of control flow operations is usually best learned by playing around with small exercises yourself. Take a look at the following program and try to modify it: We see that comments in Rust are done by a double slash or alternatively /* blah blah */ for multiline comments. Note also how we are able to return something early with the return keyword. The if, else if, else syntax is like Go’s. No parentheses are needed around the boolean expression which is great for readability. In Rust, we have several different kinds of loops. If you want an infinite loop, we have the loop which of course should be broken at some point. Therefore, Rust also has a convenient feature that enables you to break specific loops and not just the inner one. The following example is borrowed from The Rust Book which we should all have under our pillow (or saved as a bookmark in these times). Note how we can label the loop by the 'label: loop syntax and break a specific loop by calling that label based on some conditions later. We also have a while loop which is quite intuitive to use: Then of course comes the for loop which has the following syntax: We are able to loop over iterators and whether you have to make your data type an iterator is of course dependent on the type itself. Note that this syntax is a lot like in Python except you rarely have to change your types in Python. The one feature that really sets Rust apart from other languages is its clever Ownership system for handling memory. You see, different programming languages deal with memory in different ways. In some languages, you have to allocate and free up memory yourself which makes your code fast and gives you low-level control. You get “closer to the metal” so to speak. An example of this could be C. In other languages, you have what is known as a garbage collector which makes sure that you are safe and clears up memory automatically. This is convenient and safe, but it does not come for free. It slows down the program. Examples of this include Python, Java and Go along with many others. Rust has taken a completely different approach to memory management. Rust combines safety and speed in a system known as Ownership. As the Rust book puts it: Because ownership is a new concept for many programmers, it does take some time to get used to. The good news is that the more experienced you become with Rust and the rules of the ownership system, the more you’ll be able to naturally develop code that is safe and efficient. Keep at it! — The Rust Book. First, let’s state the rules of ownership: Each value in Rust has a variable that’s called its owner. There can only be one owner at a time. When the owner goes out of scope, the value will be dropped. Interesting... What does it mean? Consider the following code: This will actually not compile. To understand this, let’s see it from an ownership perspective. First, the variable s1comes into scope by taking ownership over the value String::from("Hi"). Then the variable s2 takes ownership over that value and we know from the ownership rules that there can only be one owner. This means that the variable s1 is no longer valid. In Rust we talk about “a value being moved”. So what is really happening is that the ownership or value is moved to s2 and therefore we can’t access s1 after that. If s1 and s2 had been e.g. i32, then this wouldn’t have happened because their values would have been copied instead. This has to do with how Rust stores different values. If a value is stored on the heap, then these rules apply but if it is stored on the stack and thus implements the Copy trait, then a simple copy of the value will happen. Let us take a look at another example where we’ll see that functions can take ownership as well. The following example is also from the Rust book. You can clearly see what happens by looking at the comments. When a variable is passed as a parameter to a function, ownership of that variable is moved to the function and the variable becomes inaccessible in the current scope. Also, note that if a variable stored on the heap like a string or a vector for example goes out of scope, then memory is freed only if ownership hasn’t moved before then. At this point, I am sure this seems a bit limiting and cumbersome that you can’t even print out the variable without transferring ownership and thus make the variable inaccessible. Of course, there is a system that addresses this issue. This system is called borrowing. Many other languages have pointers. Rust has references and these play well together with the borrowing rules. Consider the following code: This actually compiles and runs without any issues at all. The & prefix is called a reference and when a function is fed a reference or if a variable is assigned a reference, they don’t take ownership over it. In the above, we need to use the variable s1 in the println! macro and therefore we cannot let the function calculate_lenght take ownership. The function is only borrowing an immutable reference to the value that is assigned to s1 which is what we want. We can also have mutable references but there are some rules governing this feature to avoid nasty issues like race conditions etc. The rules of referencing are the following: At any given time, you can have either one mutable reference or any number of immutable references. References must always be valid. The way to remember this is that it is like any other file. It is fine to distribute read rights to several different people at a time because nothing bad can happen in that case. However, if you give several people write access to a file at the same time, a lot of issues might occur. This is what happens when you get a merge conflict in Git right? We shouldn’t have that issue in our code because Rust doesn’t know how to handle this. Therefore, there can be at most one mutable reference at any given time. Structs and enums are in many ways the core building blocks of Rust. If you come from an object-oriented language, you will feel right at home. When we introduced hash maps, we created an articles hash map to store articles. However, what if we wanted to save more information about them such as the publisher or the length in minutes? Could we make a custom data type that contained such structured information? Well, yes. Take a look at the following: At the bottom of the file, we have created a struct called Article. We are now able to store related data in one single container. The link, magazine and length data are called fields and we are able to access them with the dot notation which we will see in a bit. Let’s see how to implement methods on structs using the impl syntax. The output of this program is the following: The article "The Most Loved Programming Language in the World" is about 4 minutes long and is published in Cantors's Paradise.Please go to https://www.cantorsparadise.com/the-most-loved-programming-language-in-the-world-5220475fcc22 to read it.The article "How to Give Your Python Code a Magic Touch" is about 6 minutes long and is published in Towards Data Science.Please go to https://towardsdatascience.com/how-to-give-your-python-code-a-magic-touch-c778eeb9ac57 to read it. An enum is a lot like a struct but in an enum, one can have subtypes of a given data type which can be very useful. Consider the following changes to out code: The output from this program is: The article "How to Give Your Python Code a Magic Touch" is about 6 minutes long and is published in Towards Data Science.Please go to https://towardsdatascience.com/how-to-give-your-python-code-a-magic-touch-c778eeb9ac57 to read it.Programming article coming up!The article "The Most Loved Programming Language in the World" is about 4 minutes long and is published in Cantors's Paradise.Please go to https://www.cantorsparadise.com/the-most-loved-programming-language-in-the-world-5220475fcc22 to read it. A couple of new features are introduced here as well as collecting some old ones. First of all, notice how we have created a Story enum that contains two variants: Mathematics and DataScience. This is convenient because recall in the vector subsection above when we said that the vector can only hold one type? Well, we have created a vector that holds the type Story but there are variants to this and the variants don’t necessarily have to contain the same type. Both DataScience and Mathematics contain the type Article but we could have chosen say String and f64 if we wanted. Then we also introduced the match control flow operator which takes an enum in this case and checks its variant. If we get a match, we execute some code. Pretty simple, but extremely powerful. Recall that the get-method on both vectors and hash maps returned some type called Option. Option is an enum that has two variants: Some and None. Rust forces you to deal with None values in a controlled and safe way, unlike other languages. Notice that we can have nested match clauses. The output from this code will be the same as before but then also a line: We have less than three elements... In this way, we can deal with missing values in a safe way. Rust needs to deal with errors like any other programming language does. There is no such thing as error-free software. In Rust though, we have enums at our disposal and that means safe error handling! Sometimes we actually need to crash our program. That may sound weird, but if an error is unrecoverable and dangerous, then it is better to just shut down. This can be done with the panic! macro. The panic! macro wraps up by clearing the memory before shutting down. This takes a little time, and this behavior can be modified. Most times we are actually able to handle the error gracefully. This is done with the Result enum. We haven’t talked about generic types yet, so this shouldn’t really make sense to you. Just replace T with any data type and E with any Error type. You don’t need to get all of this as of now. But I think that you get the main point. File::open returns a Result enum that may or may not contain an error. You can use pattern matching to extract and handle it. Once you learn about closures, you’ll have more options at your disposal. Tests in Rust are built into the fabric of the language itself. Take a look at the following snippet: You should add a test module to every file you write. We haven’t talked about modules in Rust but you get the idea. If you run cargo test all your tests will automatically be run. The huge advantage of testing in Rust is the extremely useful compiler. In fact, the best practice in Rust for developing software is by the use of test-driven development (TDD). This is because the compiler comes with great suggestions for possible solutions to your problems. So much so it almost writes the code for you. Take a look at this small tutorial to see what I mean: doc.rust-lang.org There is much more to learn about Rust but if you followed along this far, you definitely are on the right track. The features in this headline are what you should focus on next but I will redirect you from here since this is only an introductory article and not a full-blown book. If you are not a member of Medium yet but would like unlimited access to stories like this one, all you need to do is click the below: kaspermuller.medium.com Resources for further reading: The rust book: doc.rust-lang.org Rust by Example: doc.rust-lang.org Documentation: web.mit.edu Let’s Get Rusty:
[ { "code": null, "e": 216, "s": 172, "text": "What is your favorite programming language?" }, { "code": null, "e": 324, "s": 216, "text": "If your answer isn’t Rust then please read this post. At the end of it all, your answer might have changed!" }, { "code": null, "e": 443, "s": 324, "text": "In this post, I will teach you the basics of Rust programming. Enough to get you started and create your own programs." }, { "code": null, "e": 537, "s": 443, "text": "At the end of the article, I will guide you in some very nice directions for further studies." }, { "code": null, "e": 635, "s": 537, "text": "You can return to this article during your Rust training as a small dictionary or lookup article." }, { "code": null, "e": 925, "s": 635, "text": "Learning a new programming language is like learning any other language. The fastest way is to try it and in this case, you don’t need a friend from a different country or an aircraft. You just need your new friend - the Rust compiler. And believe me, it will be a very good friend indeed." }, { "code": null, "e": 1075, "s": 925, "text": "So feel free to code along and try out examples of your own or simply read this with a cop of strong coffee like you would any other article or book." }, { "code": null, "e": 1090, "s": 1075, "text": "Let’s begin..." }, { "code": null, "e": 1457, "s": 1090, "text": "· Installation and First Project· Variables· Data Types ∘ Numbers ∘ Booleans ∘ Strings, &str and Characters· Collections ∘ Array ∘ Tuple ∘ Vector ∘ Hash Map· Functions· Control Flow and Loops ∘ Conditions ∘ Loops· Ownership and Borrowing· Structs, Enums and Methods· Error Handling· Tests· Advance Concepts: Generic Types, Traits, Lifetimes, Closures and Concurrency" }, { "code": null, "e": 1595, "s": 1457, "text": "Rust is here to stay and if you want to learn a performant and modern language that is both safe and future-proof, Rust is a good choice." }, { "code": null, "e": 1716, "s": 1595, "text": "Rust is a systems programming language that runs blazingly fast, prevents almost all crashes, and eliminates data races." }, { "code": null, "e": 1909, "s": 1716, "text": "Even though Rust is classified as a systems programming language, you can really build anything in Rust. You just need to sacrifice some time. In return, you get safety and mind-blowing speed." }, { "code": null, "e": 2037, "s": 1909, "text": "Rust has gotten a reputation of being hard to learn, but I think that it really comes down to the initial approach and mindset." }, { "code": null, "e": 2113, "s": 2037, "text": "You just need to think a little differently when coding - like a Rustacean!" }, { "code": null, "e": 2194, "s": 2113, "text": "The installation of Rust is painless thanks to a little nifty cli called rustup." }, { "code": null, "e": 2271, "s": 2194, "text": "You can install Rust by following the instructions here or by just Googling." }, { "code": null, "e": 2368, "s": 2271, "text": "When you have installed Rust and its fantastic package manager called Cargo, you are good to go." }, { "code": null, "e": 2421, "s": 2368, "text": "Say you want to create a project called “rusty_cli”." }, { "code": null, "e": 2552, "s": 2421, "text": "Find a location on your file system where you want to place your project. Then “cd” yourself to that location in the cmd/terminal." }, { "code": null, "e": 2651, "s": 2552, "text": "When you are inside the folder that you want to place the project, simply use cargo new rusty_cli." }, { "code": null, "e": 2802, "s": 2651, "text": "Cargo will work its magic and create a project structure that it understands, including a folder called src, and inside will be a file called main.rs." }, { "code": null, "e": 2929, "s": 2802, "text": "The file main.rs is the entry point of the program. In order to run the program, you have a few different options using Cargo." }, { "code": null, "e": 3079, "s": 2929, "text": "You can use cargo run to run the main file in debugging mode or cargo build to create an executable. This executable will be stored in target/debug ." }, { "code": null, "e": 3205, "s": 3079, "text": "You don’t have to use cargo to compile and run Rust programs, but it is a very friendly tool and I highly recommend using it." }, { "code": null, "e": 3421, "s": 3205, "text": "When you are ready to build the final executable, you can use the command cargo build --release to compile it with optimizations. This command will create an executable inside target/release instead of target/debug." }, { "code": null, "e": 3526, "s": 3421, "text": "The optimizations make your Rust code run much much faster but with a small penalty in compilation time." }, { "code": null, "e": 3677, "s": 3526, "text": "Variables in Rust are defined using the let keyword and are immutable by default. Let’s have an example. The following code will not compile just yet." }, { "code": null, "e": 3812, "s": 3677, "text": "If you are following along, then you’ll see the compiler complaining about something like “cannot assign twice to immutable variable”." }, { "code": null, "e": 3861, "s": 3812, "text": "In order to fix this, we could do the following:" }, { "code": null, "e": 3962, "s": 3861, "text": "Note that if we put the keyword mut in front of the variable name then the variable becomes mutable." }, { "code": null, "e": 4164, "s": 3962, "text": "Also, note how expressions work in Rust. An expression is something that returns a value. If you put a semicolon you are suppressing the result of this expression, which in most cases is what you want." }, { "code": null, "e": 4229, "s": 4164, "text": "This will be clearer when we get to functions in a little while." }, { "code": null, "e": 4394, "s": 4229, "text": "Data types usually go hand in hand with arithmetic operations, but I won’t dedicate much space for this since the usual operations on numbers apply in Rust as well." }, { "code": null, "e": 4547, "s": 4394, "text": "Many of the data types in Rust are shared with other languages. We have integer types such as i32 or i64 and floating-point numbers as for instance f64." }, { "code": null, "e": 4746, "s": 4547, "text": "We also have the data type boolwhich can contain the values true or false, we have string, &strand char for storing text data and tuple, array, vector and hash map as some of the common collections." }, { "code": null, "e": 4950, "s": 4746, "text": "On top of this, we have structs, methods and associated functionsas a replacement of classes and methods in OOP languages and an interesting type called trait which is kinda like an interface in e.g. Go." }, { "code": null, "e": 5093, "s": 4950, "text": "Besides structures and tuple structs for structuring related data, we also have the type enum which plays a central role in the Rust language." }, { "code": null, "e": 5277, "s": 5093, "text": "The usage of some of these types is best learned through examples and by experimenting on your own, however, I think some initial explanations and examples at this point are in order." }, { "code": null, "e": 5400, "s": 5277, "text": "Note that when you declare variables, you can choose to specify the data type by explicitly stating it in the declaration." }, { "code": null, "e": 5522, "s": 5400, "text": "If we want to store a variable containing an unsigned integer of size 8 bits, we have to do something like the following:" }, { "code": null, "e": 5624, "s": 5522, "text": "If you had just written let age = 18; then Rust would have inferred the type of age to be of typei32." }, { "code": null, "e": 5788, "s": 5624, "text": "Booleans in Rust called “bools” are like the booleans in other languages. The syntax is true and false (note the lower case) and an example could be let b = true;." }, { "code": null, "e": 5894, "s": 5788, "text": "The character type is written with single quotes like ‘c’ and the keyword denoting the data type is char." }, { "code": null, "e": 6061, "s": 5894, "text": "Strings are a bit more complicated in Rust than they are in e.g. Python but that is because a lot of the details are kept hidden in Python. Well, not so much in Rust!" }, { "code": null, "e": 6345, "s": 6061, "text": "The reason for this is to prevent future errors when dealing with strings. A common concept in Rust is that the language goes a long way to ensure safety by dealing with possible errors at compile time. This is, by all means, a good thing, but it puts some demands on the programmer." }, { "code": null, "e": 6496, "s": 6345, "text": "Strings are implemented as a collection of bytes, together with some methods to provide useful functionality when those bytes are interpreted as text." }, { "code": null, "e": 6699, "s": 6496, "text": "Strings are more complicated than many programmers give them credit for. That is because they look natural to the programmer - after all, we modern humans are used to dealing with text in everyday life." }, { "code": null, "e": 6963, "s": 6699, "text": "However, since there is a difference between what we would consider being a meaningful substring and how the machine would interpret substrings, things are not as easy as they seem. We need something called encodings as a bridge between the machine and our brain." }, { "code": null, "e": 7183, "s": 6963, "text": "We won’t go into details about the world of encodings but if you find yourself unable to sleep one night, then by all means take a research tour and dive deep into encodings, it is more fascinating than you might think!" }, { "code": null, "e": 7273, "s": 7183, "text": "Rust encodes strings in UTF-8 and unlike in Python, we can make strings growable in Rust." }, { "code": null, "e": 7465, "s": 7273, "text": "As indicated above Rust has more than one kind of string. The type String and the type str, where the latter is usually seen in the form &str , and is called a string slice or string literal." }, { "code": null, "e": 7548, "s": 7465, "text": "A String is stored as a vector of bytes Vec<u8> and comes with convenient methods:" }, { "code": null, "e": 7634, "s": 7548, "text": "We will deal with vectors shortly. For now, you can think of them as a typical array." }, { "code": null, "e": 7793, "s": 7634, "text": "Exactly what the difference is between the two types of strings will be skipped for now, but what I can say is that if you make a variable like the following:" }, { "code": null, "e": 7825, "s": 7793, "text": "let s = \"Towards Data Science\";" }, { "code": null, "e": 7936, "s": 7825, "text": "then s will be of type &str. If you want to store \"Towards Data Science\" as a String type, you would either do" }, { "code": null, "e": 7980, "s": 7936, "text": "let s = \"Towards Data Science\".to_string();" }, { "code": null, "e": 7997, "s": 7980, "text": "or equivalently:" }, { "code": null, "e": 8043, "s": 7997, "text": "let s = String::from(\"Towards Data Science\");" }, { "code": null, "e": 8205, "s": 8043, "text": "The main difference between the two types is that &str is immutable and stored on the stack and String types can be made mutable and are thus stored on the heap." }, { "code": null, "e": 8386, "s": 8205, "text": "If you don’t know about the stack and the heap, don’t sweat it. The most important thing to know about them is that accessing and writing to the stack is much faster than the heap." }, { "code": null, "e": 8563, "s": 8386, "text": "Data stored on the stack needs to be of a fixed size during the whole runtime. This means that if a variable is allowed to grow in size, then it needs to be stored on the heap." }, { "code": null, "e": 8724, "s": 8563, "text": "The two types are also related as indicated by the name string slice by &str being a substring of a String type, whatever that means (try to find out yourself)." }, { "code": null, "e": 8966, "s": 8724, "text": "Since this is a short introduction, we will leave this topic and this data type for now but the data type of strings is a rich and exciting topic and I encourage you to take a deep dive into this subject after you are done reading this post." }, { "code": null, "e": 9045, "s": 8966, "text": "In Rust, we have many collections, but some of them are used more than others." }, { "code": null, "e": 9180, "s": 9045, "text": "An array in Rust is like an array in Go for example. It is of fixed size and thus can be stored on the stack which means quick access." }, { "code": null, "e": 9237, "s": 9180, "text": "In an array, you can only store one data type at a time." }, { "code": null, "e": 9271, "s": 9237, "text": "The syntax is like Python’s list:" }, { "code": null, "e": 9299, "s": 9271, "text": "let rust_array = [1, 2, 3];" }, { "code": null, "e": 9428, "s": 9299, "text": "and you can access a specific element in the same way as in Python. rust_array[0] gives us the first element and in this case 1." }, { "code": null, "e": 9520, "s": 9428, "text": "The tuple type is commonly used in Rust for storing different data types in one collection." }, { "code": null, "e": 9568, "s": 9520, "text": "We can access the elements with a dot notation:" }, { "code": null, "e": 9711, "s": 9568, "text": "Vectors are one of the most commonly used collections in Rust because like Python’s lists or Go’s slices, the vector in Rust can grow in size." }, { "code": null, "e": 9883, "s": 9711, "text": "It can only hold a single data type but as you will see later, there are ways around that. We will have to know about a type called enumto begin writing about that though." }, { "code": null, "e": 9968, "s": 9883, "text": "The fact that a vector can grow makes it a very important type as you would imagine." }, { "code": null, "e": 10034, "s": 9968, "text": "To create a new, empty vector, we can call the Vec::new function:" }, { "code": null, "e": 10068, "s": 10034, "text": "let mut v: Vec<i32> = Vec::new();" }, { "code": null, "e": 10187, "s": 10068, "text": "Once created, we can now push elements into it. For instance, v.push(1) will append 1 to v and the size has now grown." }, { "code": null, "e": 10283, "s": 10187, "text": "If you want to instantiate the vector with elements in it, we have a convenient macro for that:" }, { "code": null, "e": 10306, "s": 10283, "text": "let v = vec![1, 2, 3];" }, { "code": null, "e": 10346, "s": 10306, "text": "We will see more macros a little later." }, { "code": null, "e": 10561, "s": 10346, "text": "There are two ways of getting elements from a vector. We can do it like in Python with the v[i] notation getting the ith element in this case. But we need to be careful that the vector actually has enough elements." }, { "code": null, "e": 10752, "s": 10561, "text": "If it has fewer elements and we try to access an element that does not exist, then we’ll get an error at runtime! This is dangerous so Rust has another way of accessing elements in a vector." }, { "code": null, "e": 10793, "s": 10752, "text": "We access it like let second = v.get(1);" }, { "code": null, "e": 10926, "s": 10793, "text": "Now second will be of type Option<T> which I haven’t covered yet, but soon you’ll know what that means and how to get the value out." }, { "code": null, "e": 11059, "s": 10926, "text": "We can also iterate over vectors in a for loop but since I haven’t covered loops yet, I’ll wait with showing you the syntax as well." }, { "code": null, "e": 11213, "s": 11059, "text": "Hash maps are like dictionaries in Python or maps in Go and The type is denoted HashMap<K, V>. It stores a mapping of keys of type K to values of type V." }, { "code": null, "e": 11279, "s": 11213, "text": "To initialize and populate a hash map, we could do the following:" }, { "code": null, "e": 11371, "s": 11279, "text": "The insert method pushes data into the hash map by a tuple of key and value as an argument." }, { "code": null, "e": 11483, "s": 11371, "text": "If you want to access the data inside the hash map, then we have the get method for this as well. Specifically," }, { "code": null, "e": 11536, "s": 11483, "text": "let a = articles.get(&String::from(\"Python Graph\"));" }, { "code": null, "e": 11641, "s": 11536, "text": "will return an Option type we can then get the value from. The symbol & will be covered shortly as well." }, { "code": null, "e": 11804, "s": 11641, "text": "When we want to update the hash map by a key, and we are not sure whether it’s there already, we have several options. One of them is the convenient entry method:" }, { "code": null, "e": 11949, "s": 11804, "text": "articles.entry(String::from(\"Rust\")).or_insert(\"https://www.cantorsparadise.com/the-most-loved-programming-language-in-the-world-5220475fcc22\");" }, { "code": null, "e": 12145, "s": 11949, "text": "If the key is already in the hash map, then we’ll get a mutable reference to it, if not, then we’ll insert the data specified in the argument to or_insert . References will be explained in a bit." }, { "code": null, "e": 12203, "s": 12145, "text": "Functions are one of the most important features of Rust." }, { "code": null, "e": 12323, "s": 12203, "text": "We have seen the main function which plays a special role, but we are of course able to create other functions as well." }, { "code": null, "e": 12393, "s": 12323, "text": "The syntax is simple. Here is an example of another function in Rust:" }, { "code": null, "e": 12553, "s": 12393, "text": "Note that we need to tell Rust which data type the function accepts as input and which type it will output. This is a good thing since it prevents many errors." }, { "code": null, "e": 12777, "s": 12553, "text": "Another interesting thing about Rust is that you don’t have to explicitly tell Rust what you return by a return keyword. If the last statement in a function has no trailing semicolon, then that is what the function returns." }, { "code": null, "e": 12867, "s": 12777, "text": "This also applies to blocks of code wrapped in curly braces in general. A lot like Scala." }, { "code": null, "e": 12989, "s": 12867, "text": "In the above example. the function plus_one returns x+1 where x is the integer that the function takes in as an argument." }, { "code": null, "e": 13091, "s": 12989, "text": "In Rust, we have a return keyword, but it is usually only used if you want to return something early." }, { "code": null, "e": 13202, "s": 13091, "text": "The syntax of control flow operations is usually best learned by playing around with small exercises yourself." }, { "code": null, "e": 13261, "s": 13202, "text": "Take a look at the following program and try to modify it:" }, { "code": null, "e": 13451, "s": 13261, "text": "We see that comments in Rust are done by a double slash or alternatively /* blah blah */ for multiline comments. Note also how we are able to return something early with the return keyword." }, { "code": null, "e": 13582, "s": 13451, "text": "The if, else if, else syntax is like Go’s. No parentheses are needed around the boolean expression which is great for readability." }, { "code": null, "e": 13633, "s": 13582, "text": "In Rust, we have several different kinds of loops." }, { "code": null, "e": 13843, "s": 13633, "text": "If you want an infinite loop, we have the loop which of course should be broken at some point. Therefore, Rust also has a convenient feature that enables you to break specific loops and not just the inner one." }, { "code": null, "e": 13979, "s": 13843, "text": "The following example is borrowed from The Rust Book which we should all have under our pillow (or saved as a bookmark in these times)." }, { "code": null, "e": 14117, "s": 13979, "text": "Note how we can label the loop by the 'label: loop syntax and break a specific loop by calling that label based on some conditions later." }, { "code": null, "e": 14176, "s": 14117, "text": "We also have a while loop which is quite intuitive to use:" }, { "code": null, "e": 14242, "s": 14176, "text": "Then of course comes the for loop which has the following syntax:" }, { "code": null, "e": 14477, "s": 14242, "text": "We are able to loop over iterators and whether you have to make your data type an iterator is of course dependent on the type itself. Note that this syntax is a lot like in Python except you rarely have to change your types in Python." }, { "code": null, "e": 14594, "s": 14477, "text": "The one feature that really sets Rust apart from other languages is its clever Ownership system for handling memory." }, { "code": null, "e": 14873, "s": 14594, "text": "You see, different programming languages deal with memory in different ways. In some languages, you have to allocate and free up memory yourself which makes your code fast and gives you low-level control. You get “closer to the metal” so to speak. An example of this could be C." }, { "code": null, "e": 15166, "s": 14873, "text": "In other languages, you have what is known as a garbage collector which makes sure that you are safe and clears up memory automatically. This is convenient and safe, but it does not come for free. It slows down the program. Examples of this include Python, Java and Go along with many others." }, { "code": null, "e": 15298, "s": 15166, "text": "Rust has taken a completely different approach to memory management. Rust combines safety and speed in a system known as Ownership." }, { "code": null, "e": 15324, "s": 15298, "text": "As the Rust book puts it:" }, { "code": null, "e": 15613, "s": 15324, "text": "Because ownership is a new concept for many programmers, it does take some time to get used to. The good news is that the more experienced you become with Rust and the rules of the ownership system, the more you’ll be able to naturally develop code that is safe and efficient. Keep at it!" }, { "code": null, "e": 15630, "s": 15613, "text": "— The Rust Book." }, { "code": null, "e": 15673, "s": 15630, "text": "First, let’s state the rules of ownership:" }, { "code": null, "e": 15732, "s": 15673, "text": "Each value in Rust has a variable that’s called its owner." }, { "code": null, "e": 15771, "s": 15732, "text": "There can only be one owner at a time." }, { "code": null, "e": 15832, "s": 15771, "text": "When the owner goes out of scope, the value will be dropped." }, { "code": null, "e": 15866, "s": 15832, "text": "Interesting... What does it mean?" }, { "code": null, "e": 15895, "s": 15866, "text": "Consider the following code:" }, { "code": null, "e": 15991, "s": 15895, "text": "This will actually not compile. To understand this, let’s see it from an ownership perspective." }, { "code": null, "e": 16209, "s": 15991, "text": "First, the variable s1comes into scope by taking ownership over the value String::from(\"Hi\"). Then the variable s2 takes ownership over that value and we know from the ownership rules that there can only be one owner." }, { "code": null, "e": 16425, "s": 16209, "text": "This means that the variable s1 is no longer valid. In Rust we talk about “a value being moved”. So what is really happening is that the ownership or value is moved to s2 and therefore we can’t access s1 after that." }, { "code": null, "e": 16768, "s": 16425, "text": "If s1 and s2 had been e.g. i32, then this wouldn’t have happened because their values would have been copied instead. This has to do with how Rust stores different values. If a value is stored on the heap, then these rules apply but if it is stored on the stack and thus implements the Copy trait, then a simple copy of the value will happen." }, { "code": null, "e": 16865, "s": 16768, "text": "Let us take a look at another example where we’ll see that functions can take ownership as well." }, { "code": null, "e": 16915, "s": 16865, "text": "The following example is also from the Rust book." }, { "code": null, "e": 17144, "s": 16915, "text": "You can clearly see what happens by looking at the comments. When a variable is passed as a parameter to a function, ownership of that variable is moved to the function and the variable becomes inaccessible in the current scope." }, { "code": null, "e": 17315, "s": 17144, "text": "Also, note that if a variable stored on the heap like a string or a vector for example goes out of scope, then memory is freed only if ownership hasn’t moved before then." }, { "code": null, "e": 17496, "s": 17315, "text": "At this point, I am sure this seems a bit limiting and cumbersome that you can’t even print out the variable without transferring ownership and thus make the variable inaccessible." }, { "code": null, "e": 17552, "s": 17496, "text": "Of course, there is a system that addresses this issue." }, { "code": null, "e": 17696, "s": 17552, "text": "This system is called borrowing. Many other languages have pointers. Rust has references and these play well together with the borrowing rules." }, { "code": null, "e": 17725, "s": 17696, "text": "Consider the following code:" }, { "code": null, "e": 17935, "s": 17725, "text": "This actually compiles and runs without any issues at all. The & prefix is called a reference and when a function is fed a reference or if a variable is assigned a reference, they don’t take ownership over it." }, { "code": null, "e": 18189, "s": 17935, "text": "In the above, we need to use the variable s1 in the println! macro and therefore we cannot let the function calculate_lenght take ownership. The function is only borrowing an immutable reference to the value that is assigned to s1 which is what we want." }, { "code": null, "e": 18321, "s": 18189, "text": "We can also have mutable references but there are some rules governing this feature to avoid nasty issues like race conditions etc." }, { "code": null, "e": 18365, "s": 18321, "text": "The rules of referencing are the following:" }, { "code": null, "e": 18465, "s": 18365, "text": "At any given time, you can have either one mutable reference or any number of immutable references." }, { "code": null, "e": 18498, "s": 18465, "text": "References must always be valid." }, { "code": null, "e": 18784, "s": 18498, "text": "The way to remember this is that it is like any other file. It is fine to distribute read rights to several different people at a time because nothing bad can happen in that case. However, if you give several people write access to a file at the same time, a lot of issues might occur." }, { "code": null, "e": 19009, "s": 18784, "text": "This is what happens when you get a merge conflict in Git right? We shouldn’t have that issue in our code because Rust doesn’t know how to handle this. Therefore, there can be at most one mutable reference at any given time." }, { "code": null, "e": 19153, "s": 19009, "text": "Structs and enums are in many ways the core building blocks of Rust. If you come from an object-oriented language, you will feel right at home." }, { "code": null, "e": 19345, "s": 19153, "text": "When we introduced hash maps, we created an articles hash map to store articles. However, what if we wanted to save more information about them such as the publisher or the length in minutes?" }, { "code": null, "e": 19433, "s": 19345, "text": "Could we make a custom data type that contained such structured information? Well, yes." }, { "code": null, "e": 19463, "s": 19433, "text": "Take a look at the following:" }, { "code": null, "e": 19728, "s": 19463, "text": "At the bottom of the file, we have created a struct called Article. We are now able to store related data in one single container. The link, magazine and length data are called fields and we are able to access them with the dot notation which we will see in a bit." }, { "code": null, "e": 19797, "s": 19728, "text": "Let’s see how to implement methods on structs using the impl syntax." }, { "code": null, "e": 19842, "s": 19797, "text": "The output of this program is the following:" }, { "code": null, "e": 20320, "s": 19842, "text": "The article \"The Most Loved Programming Language in the World\" is about 4 minutes long and is published in Cantors's Paradise.Please go to https://www.cantorsparadise.com/the-most-loved-programming-language-in-the-world-5220475fcc22 to read it.The article \"How to Give Your Python Code a Magic Touch\" is about 6 minutes long and is published in Towards Data Science.Please go to https://towardsdatascience.com/how-to-give-your-python-code-a-magic-touch-c778eeb9ac57 to read it." }, { "code": null, "e": 20436, "s": 20320, "text": "An enum is a lot like a struct but in an enum, one can have subtypes of a given data type which can be very useful." }, { "code": null, "e": 20480, "s": 20436, "text": "Consider the following changes to out code:" }, { "code": null, "e": 20513, "s": 20480, "text": "The output from this program is:" }, { "code": null, "e": 21021, "s": 20513, "text": "The article \"How to Give Your Python Code a Magic Touch\" is about 6 minutes long and is published in Towards Data Science.Please go to https://towardsdatascience.com/how-to-give-your-python-code-a-magic-touch-c778eeb9ac57 to read it.Programming article coming up!The article \"The Most Loved Programming Language in the World\" is about 4 minutes long and is published in Cantors's Paradise.Please go to https://www.cantorsparadise.com/the-most-loved-programming-language-in-the-world-5220475fcc22 to read it." }, { "code": null, "e": 21103, "s": 21021, "text": "A couple of new features are introduced here as well as collecting some old ones." }, { "code": null, "e": 21486, "s": 21103, "text": "First of all, notice how we have created a Story enum that contains two variants: Mathematics and DataScience. This is convenient because recall in the vector subsection above when we said that the vector can only hold one type? Well, we have created a vector that holds the type Story but there are variants to this and the variants don’t necessarily have to contain the same type." }, { "code": null, "e": 21602, "s": 21486, "text": "Both DataScience and Mathematics contain the type Article but we could have chosen say String and f64 if we wanted." }, { "code": null, "e": 21756, "s": 21602, "text": "Then we also introduced the match control flow operator which takes an enum in this case and checks its variant. If we get a match, we execute some code." }, { "code": null, "e": 21795, "s": 21756, "text": "Pretty simple, but extremely powerful." }, { "code": null, "e": 21886, "s": 21795, "text": "Recall that the get-method on both vectors and hash maps returned some type called Option." }, { "code": null, "e": 21942, "s": 21886, "text": "Option is an enum that has two variants: Some and None." }, { "code": null, "e": 22037, "s": 21942, "text": "Rust forces you to deal with None values in a controlled and safe way, unlike other languages." }, { "code": null, "e": 22158, "s": 22037, "text": "Notice that we can have nested match clauses. The output from this code will be the same as before but then also a line:" }, { "code": null, "e": 22194, "s": 22158, "text": "We have less than three elements..." }, { "code": null, "e": 22254, "s": 22194, "text": "In this way, we can deal with missing values in a safe way." }, { "code": null, "e": 22374, "s": 22254, "text": "Rust needs to deal with errors like any other programming language does. There is no such thing as error-free software." }, { "code": null, "e": 22456, "s": 22374, "text": "In Rust though, we have enums at our disposal and that means safe error handling!" }, { "code": null, "e": 22612, "s": 22456, "text": "Sometimes we actually need to crash our program. That may sound weird, but if an error is unrecoverable and dangerous, then it is better to just shut down." }, { "code": null, "e": 22652, "s": 22612, "text": "This can be done with the panic! macro." }, { "code": null, "e": 22784, "s": 22652, "text": "The panic! macro wraps up by clearing the memory before shutting down. This takes a little time, and this behavior can be modified." }, { "code": null, "e": 22883, "s": 22784, "text": "Most times we are actually able to handle the error gracefully. This is done with the Result enum." }, { "code": null, "e": 22970, "s": 22883, "text": "We haven’t talked about generic types yet, so this shouldn’t really make sense to you." }, { "code": null, "e": 23031, "s": 22970, "text": "Just replace T with any data type and E with any Error type." }, { "code": null, "e": 23188, "s": 23031, "text": "You don’t need to get all of this as of now. But I think that you get the main point. File::open returns a Result enum that may or may not contain an error." }, { "code": null, "e": 23317, "s": 23188, "text": "You can use pattern matching to extract and handle it. Once you learn about closures, you’ll have more options at your disposal." }, { "code": null, "e": 23419, "s": 23317, "text": "Tests in Rust are built into the fabric of the language itself. Take a look at the following snippet:" }, { "code": null, "e": 23535, "s": 23419, "text": "You should add a test module to every file you write. We haven’t talked about modules in Rust but you get the idea." }, { "code": null, "e": 23599, "s": 23535, "text": "If you run cargo test all your tests will automatically be run." }, { "code": null, "e": 23778, "s": 23599, "text": "The huge advantage of testing in Rust is the extremely useful compiler. In fact, the best practice in Rust for developing software is by the use of test-driven development (TDD)." }, { "code": null, "e": 23923, "s": 23778, "text": "This is because the compiler comes with great suggestions for possible solutions to your problems. So much so it almost writes the code for you." }, { "code": null, "e": 23978, "s": 23923, "text": "Take a look at this small tutorial to see what I mean:" }, { "code": null, "e": 23996, "s": 23978, "text": "doc.rust-lang.org" }, { "code": null, "e": 24110, "s": 23996, "text": "There is much more to learn about Rust but if you followed along this far, you definitely are on the right track." }, { "code": null, "e": 24278, "s": 24110, "text": "The features in this headline are what you should focus on next but I will redirect you from here since this is only an introductory article and not a full-blown book." }, { "code": null, "e": 24413, "s": 24278, "text": "If you are not a member of Medium yet but would like unlimited access to stories like this one, all you need to do is click the below:" }, { "code": null, "e": 24437, "s": 24413, "text": "kaspermuller.medium.com" }, { "code": null, "e": 24468, "s": 24437, "text": "Resources for further reading:" }, { "code": null, "e": 24483, "s": 24468, "text": "The rust book:" }, { "code": null, "e": 24501, "s": 24483, "text": "doc.rust-lang.org" }, { "code": null, "e": 24518, "s": 24501, "text": "Rust by Example:" }, { "code": null, "e": 24536, "s": 24518, "text": "doc.rust-lang.org" }, { "code": null, "e": 24551, "s": 24536, "text": "Documentation:" }, { "code": null, "e": 24563, "s": 24551, "text": "web.mit.edu" } ]
Subsets in Python
Suppose we have a set of numbers; we have to generate all possible subsets of that set. This is also known as power set. So if the set is like [1,2,3], then the power set will be [[], [1], [2], [3], [1,2], [1,3], [2,3], [1,2,3]] Let us see the steps − We will solve this using recursive approach. So if the recursive method name is called solve(), and this takes the set of numbers (nums), temporary set (temp), res and index The solve() function will work like below − if index = length of nums, then create a list same as temp, and insert into res and return temp[index] := 0 solve(nums, temp, res, index + 1) temp[index] := 1 solve(nums, temp, res, index + 1) The main function will be like below − res := an empty list create temp list of size same as the nums, and fill this with 0 call solve(nums, temp, res, 0) main_res := an empty list for all lists in temp_restemp := empty listfor i := 0 to length of listsif lists[i] = 1, then insert nums[i] into tempinsert temp into main_res temp := empty list for i := 0 to length of listsif lists[i] = 1, then insert nums[i] into temp if lists[i] = 1, then insert nums[i] into temp insert temp into main_res return main res Let us see the following implementation to get better understanding − Live Demo class Solution(object): def subsets(self, nums): temp_result = [] self.subsets_util(nums,[0 for i in range(len(nums))],temp_result,0) main_result = [] for lists in temp_result: temp = [] for i in range(len(lists)): if lists[i] == 1: temp.append(nums[i]) main_result.append(temp) return main_result def subsets_util(self,nums,temp,result,index): if index == len(nums): result.append([i for i in temp]) #print(temp) return temp[index] = 0 self.subsets_util(nums,temp,result,index+1) temp[index] = 1 self.subsets_util(nums, temp, result,index + 1) ob1 = Solution() print(ob1.subsets([1,2,3,4])) [1,2,3,4] [[], [4], [3], [3, 4], [2], [2, 4], [2, 3], [2, 3, 4], [1], [1, 4], [1, 3], [1, 3, 4], [1, 2], [1, 2, 4], [1, 2, 3], [1, 2, 3, 4]]
[ { "code": null, "e": 1291, "s": 1062, "text": "Suppose we have a set of numbers; we have to generate all possible subsets of that set. This is also known as power set. So if the set is like [1,2,3], then the power set will be [[], [1], [2], [3], [1,2], [1,3], [2,3], [1,2,3]]" }, { "code": null, "e": 1314, "s": 1291, "text": "Let us see the steps −" }, { "code": null, "e": 1488, "s": 1314, "text": "We will solve this using recursive approach. So if the recursive method name is called solve(), and this takes the set of numbers (nums), temporary set (temp), res and index" }, { "code": null, "e": 1532, "s": 1488, "text": "The solve() function will work like below −" }, { "code": null, "e": 1623, "s": 1532, "text": "if index = length of nums, then create a list same as temp, and insert into res and return" }, { "code": null, "e": 1640, "s": 1623, "text": "temp[index] := 0" }, { "code": null, "e": 1674, "s": 1640, "text": "solve(nums, temp, res, index + 1)" }, { "code": null, "e": 1691, "s": 1674, "text": "temp[index] := 1" }, { "code": null, "e": 1725, "s": 1691, "text": "solve(nums, temp, res, index + 1)" }, { "code": null, "e": 1764, "s": 1725, "text": "The main function will be like below −" }, { "code": null, "e": 1785, "s": 1764, "text": "res := an empty list" }, { "code": null, "e": 1849, "s": 1785, "text": "create temp list of size same as the nums, and fill this with 0" }, { "code": null, "e": 1880, "s": 1849, "text": "call solve(nums, temp, res, 0)" }, { "code": null, "e": 1906, "s": 1880, "text": "main_res := an empty list" }, { "code": null, "e": 2050, "s": 1906, "text": "for all lists in temp_restemp := empty listfor i := 0 to length of listsif lists[i] = 1, then insert nums[i] into tempinsert temp into main_res" }, { "code": null, "e": 2069, "s": 2050, "text": "temp := empty list" }, { "code": null, "e": 2145, "s": 2069, "text": "for i := 0 to length of listsif lists[i] = 1, then insert nums[i] into temp" }, { "code": null, "e": 2192, "s": 2145, "text": "if lists[i] = 1, then insert nums[i] into temp" }, { "code": null, "e": 2218, "s": 2192, "text": "insert temp into main_res" }, { "code": null, "e": 2234, "s": 2218, "text": "return main res" }, { "code": null, "e": 2304, "s": 2234, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2315, "s": 2304, "text": " Live Demo" }, { "code": null, "e": 3054, "s": 2315, "text": "class Solution(object):\n def subsets(self, nums):\n temp_result = []\n self.subsets_util(nums,[0 for i in range(len(nums))],temp_result,0)\n main_result = []\n for lists in temp_result:\n temp = []\n for i in range(len(lists)):\n if lists[i] == 1:\n temp.append(nums[i])\n main_result.append(temp)\n return main_result\n def subsets_util(self,nums,temp,result,index):\n if index == len(nums):\n result.append([i for i in temp])\n #print(temp)\n return\n temp[index] = 0\n self.subsets_util(nums,temp,result,index+1)\n temp[index] = 1\n self.subsets_util(nums, temp, result,index + 1)\nob1 = Solution()\nprint(ob1.subsets([1,2,3,4]))" }, { "code": null, "e": 3064, "s": 3054, "text": "[1,2,3,4]" }, { "code": null, "e": 3196, "s": 3064, "text": "[[], [4], [3], [3, 4], [2], [2, 4], [2, 3], [2, 3, 4], [1], [1, 4], \n[1, 3], [1, 3, 4], [1, 2], [1, 2, 4], [1, 2, 3], [1, 2, 3, 4]]" } ]
Swift - Characters
A character in Swift is a single character String literal, addressed by the data type Character. Take a look at the following example. It uses two Character constants − let char1: Character = "A" let char2: Character = "B" print("Value of char1 \(char1)") print("Value of char2 \(char2)") When the above code is compiled and executed, it produces the following result − Value of char1 A Value of char2 B If you try to store more than one character in a Character type variable or constant, then Swift 4 will not allow that. Try to type the following example in Swift 4 Playground and you will get an error even before compilation. // Following is wrong in Swift 4 let char: Character = "AB" print("Value of char \(char)") It is not possible to create an empty Character variable or constant which will have an empty value. The following syntax is not possible − // Following is wrong in Swift 4 let char1: Character = "" var char2: Character = "" print("Value of char1 \(char1)") print("Value of char2 \(char2)") As explained while discussing Swift 4's Strings, String represents a collection of Character values in a specified order. So we can access individual characters from the given String by iterating over that string with a for-in loop − for ch in "Hello" { print(ch) } When the above code is compiled and executed, it produces the following result − H e l l o The following example demonstrates how a Swift 4's Character can be concatenated with Swift 4's String. var varA:String = "Hello " let varB:Character = "G" varA.append( varB ) print("Value of varC = \(varA)") When the above code is compiled and executed, it produces the following result − Value of varC = Hello G 38 Lectures 1 hours Ashish Sharma 13 Lectures 2 hours Three Millennials 7 Lectures 1 hours Three Millennials 22 Lectures 1 hours Frahaan Hussain 12 Lectures 39 mins Devasena Rajendran 40 Lectures 2.5 hours Grant Klimaytys Print Add Notes Bookmark this page
[ { "code": null, "e": 2422, "s": 2253, "text": "A character in Swift is a single character String literal, addressed by the data type Character. Take a look at the following example. It uses two Character constants −" }, { "code": null, "e": 2543, "s": 2422, "text": "let char1: Character = \"A\"\nlet char2: Character = \"B\"\n\nprint(\"Value of char1 \\(char1)\")\nprint(\"Value of char2 \\(char2)\")" }, { "code": null, "e": 2624, "s": 2543, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 2659, "s": 2624, "text": "Value of char1 A\nValue of char2 B\n" }, { "code": null, "e": 2886, "s": 2659, "text": "If you try to store more than one character in a Character type variable or constant, then Swift 4 will not allow that. Try to type the following example in Swift 4 Playground and you will get an error even before compilation." }, { "code": null, "e": 2978, "s": 2886, "text": "// Following is wrong in Swift 4\nlet char: Character = \"AB\"\n\nprint(\"Value of char \\(char)\")" }, { "code": null, "e": 3118, "s": 2978, "text": "It is not possible to create an empty Character variable or constant which will have an empty value. The following syntax is not possible −" }, { "code": null, "e": 3270, "s": 3118, "text": "// Following is wrong in Swift 4\nlet char1: Character = \"\"\nvar char2: Character = \"\"\n\nprint(\"Value of char1 \\(char1)\")\nprint(\"Value of char2 \\(char2)\")" }, { "code": null, "e": 3504, "s": 3270, "text": "As explained while discussing Swift 4's Strings, String represents a collection of Character values in a specified order. So we can access individual characters from the given String by iterating over that string with a for-in loop −" }, { "code": null, "e": 3539, "s": 3504, "text": "for ch in \"Hello\" {\n print(ch)\n}" }, { "code": null, "e": 3620, "s": 3539, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 3631, "s": 3620, "text": "H\ne\nl\nl\no\n" }, { "code": null, "e": 3735, "s": 3631, "text": "The following example demonstrates how a Swift 4's Character can be concatenated with Swift 4's String." }, { "code": null, "e": 3842, "s": 3735, "text": "var varA:String = \"Hello \"\nlet varB:Character = \"G\"\n\nvarA.append( varB )\n\nprint(\"Value of varC = \\(varA)\")" }, { "code": null, "e": 3923, "s": 3842, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 3948, "s": 3923, "text": "Value of varC = Hello G\n" }, { "code": null, "e": 3981, "s": 3948, "text": "\n 38 Lectures \n 1 hours \n" }, { "code": null, "e": 3996, "s": 3981, "text": " Ashish Sharma" }, { "code": null, "e": 4029, "s": 3996, "text": "\n 13 Lectures \n 2 hours \n" }, { "code": null, "e": 4048, "s": 4029, "text": " Three Millennials" }, { "code": null, "e": 4080, "s": 4048, "text": "\n 7 Lectures \n 1 hours \n" }, { "code": null, "e": 4099, "s": 4080, "text": " Three Millennials" }, { "code": null, "e": 4132, "s": 4099, "text": "\n 22 Lectures \n 1 hours \n" }, { "code": null, "e": 4149, "s": 4132, "text": " Frahaan Hussain" }, { "code": null, "e": 4181, "s": 4149, "text": "\n 12 Lectures \n 39 mins\n" }, { "code": null, "e": 4201, "s": 4181, "text": " Devasena Rajendran" }, { "code": null, "e": 4236, "s": 4201, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4253, "s": 4236, "text": " Grant Klimaytys" }, { "code": null, "e": 4260, "s": 4253, "text": " Print" }, { "code": null, "e": 4271, "s": 4260, "text": " Add Notes" } ]
Mathematics | Introduction to Propositional Logic | Set 1 - GeeksforGeeks
11 Jan, 2022 Logic is the basis of all mathematical reasoning, and of all automated reasoning. The rules of logic specify the meaning of mathematical statements. These rules help us understand and reason with statements such as – such that where Which in Simple English means “There exists an integer that is not the sum of two squares”. Importance of Mathematical Logic The rules of logic give precise meaning to mathematical statements. These rules are used to distinguish between valid and invalid mathematical arguments.Apart from its importance in understanding mathematical reasoning, logic has numerous applications in Computer Science, varying from design of digital circuits, to the construction of computer programs and verification of correctness of programs. What is a proposition?A proposition is the basic building block of logic. It is defined as a declarative sentence that is either True or False, but not both.The Truth Value of a proposition is True(denoted as T) if it is a true statement, and False(denoted as F) if it is a false statement.For Example, 1. The sun rises in the East and sets in the West. 2. 1 + 1 = 2 3. 'b' is a vowel. All of the above sentences are propositions, where the first two are Valid(True) and the third one is Invalid(False).Some sentences that do not have a truth value or may have more than one truth value are not propositions.For Example, 1. What time is it? 2. Go out and play. 3. x + 1 = 2. The above sentences are not propositions as the first two do not have a truth value, and the third one may be true or false. To represent propositions, propositional variables are used. By Convention, these variables are represented by small alphabets such as .The area of logic which deals with propositions is called propositional calculus or propositional logic.It also includes producing new propositions using existing ones. Propositions constructed using one or more propositions are called compound propositions. The propositions are combined together using Logical Connectives or Logical Operators. Since we need to know the truth value of a proposition in all possible scenarios, we consider all the possible combinations of the propositions which are joined together by Logical Connectives to form the given compound proposition. This compilation of all possible scenarios in a tabular format is called a truth table. Most Common Logical Connectives- 1. Negation – If is a proposition, then the negation of is denoted by , which when translated to simple English means-“It is not the case that ” or simply “not “.The truth value of is the opposite of the truth value of .The truth table of is- Example,The negation of “It is raining today”, is “It is not the case that is raining today” or simply “It is not raining today”. 2. Conjunction – For any two propositions and , their conjunction is denoted by , which means “ and “. The conjuction is True when both and are True, otherwise False.The truth table of is- Example,The conjunction of the propositions – “Today is Friday” and – “It is raining today”, is “Today is Friday and it is raining today”. This proposition is true only on rainy Fridays and is false on any other rainy day or on Fridays when it does not rain. 3. Disjunction – For any two propositions and , their disjunction is denoted by , which means “ or “. The disjuction is True when either or is True, otherwise False.The truth table of is- Example,The disjunction of the propositions – “Today is Friday” and – “It is raining today”, is “Today is Friday or it is raining today”. This proposition is true on any day that is a Friday or a rainy day(including rainy Fridays) and is false on any day other than Friday when it also does not rain. 4. Exclusive Or – For any two propositions and , their exclusive or is denoted by , which means “either or but not both”. The exclusive or is True when either or is True, and False when both are true or both are false.The truth table of is- Example,The exclusive or of the propositions – “Today is Friday” and – “It is raining today”, is “Either today is Friday or it is raining today, but not both”. This proposition is true on any day that is a Friday or a rainy day(not including rainy Fridays) and is false on any day other than Friday when it does not rain or rainy Fridays. 5. Implication – For any two propositions and , the statement “if then ” is called an implication and it is denoted by .In the implication , is called the hypothesis or antecedent or premise and is called the conclusion or consequence.The implication is is also called a conditional statement.The implication is false when is true and is false otherwise it is true. The truth table of is- You might wonder that why is true when is false. This is because the implication guarantees that when and are true then the implication is true. But the implication does not guarantee anything when the premise is false. There is no way of knowing whether or not the implication is false since did not happen.This situation is similar to the “Innocent until proven Guilty” stance, which means that the implication is considered true until proven false. Since we cannot call the implication false when is false, our only alternative is to call it true.This follows from the Explosion Principle which says-“A False statement implies anything”Conditional statements play a very important role in mathematical reasoning, thus a variety of terminology is used to express , some of which are listed below. "if , then " " is sufficient for " " when " "a necessary condition for is " " only if " " unless " " follows from " Example,“If it is Friday then it is raining today” is a proposition which is of the form . The above proposition is true if it is not Friday(premise is false) or if it is Friday and it is raining, and it is false when it is Friday but it is not raining. 6. Biconditional or Double Implication – For any two propositions and , the statement “ if and only if(iff) ” is called a biconditional and it is denoted by .The statement is also called a bi-implication. has the same truth value as The implication is true when and have same truth values, and is false otherwise. The truth table of is- Some other common ways of expressing are- " is necessary and sufficient for " "if then , and conversely" " iff " Example,“It is raining today if and only if it is Friday today.” is a proposition which is of the form . The above proposition is true if it is not Friday and it is not raining or if it is Friday and it is raining, and it is false when it is not Friday or it is not raining. Exercise:1) Consider the following statements: P: Good mobile phones are not cheap. Q: Cheap mobile phones are not good. L: P implies Q M: Q implies P N: P is equivalent to Q Which one of the following about L, M, and N is CORRECT?(Gate 2014)(A) Only L is TRUE.(B) Only M is TRUE.(C) Only N is TRUE.(D) L, M and N are TRUE.For solution, see GATE | GATE-CS-2014-(Set-3) | Question 11 2) Which one of the following is not equivalent to p⇔q (Gate 2015) For solution, see GATE | GATE-CS-2015 (Set 1) | Question 65 References- Propositional Logic – WikipediaPrinciple of Explosion – WikipediaDiscrete Mathematics and its Applications, by Kenneth H Rosen Read next part : Introduction to Propositional Logic – Set 2 This article is contributed by Chirag Manwani. 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. surindertarika1234 Engineering Mathematics GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Inequalities in LaTeX Arrow Symbols in LaTeX Properties of Boolean Algebra Newton's Divided Difference Interpolation Formula Set Notations in LaTeX Layers of OSI Model ACID Properties in DBMS Types of Operating Systems TCP/IP Model Page Replacement Algorithms in Operating Systems
[ { "code": null, "e": 29641, "s": 29613, "text": "\n11 Jan, 2022" }, { "code": null, "e": 29858, "s": 29641, "text": "Logic is the basis of all mathematical reasoning, and of all automated reasoning. The rules of logic specify the meaning of mathematical statements. These rules help us understand and reason with statements such as –" }, { "code": null, "e": 29878, "s": 29858, "text": " such that where \n" }, { "code": null, "e": 29970, "s": 29878, "text": "Which in Simple English means “There exists an integer that is not the sum of two squares”." }, { "code": null, "e": 30003, "s": 29970, "text": "Importance of Mathematical Logic" }, { "code": null, "e": 30403, "s": 30003, "text": "The rules of logic give precise meaning to mathematical statements. These rules are used to distinguish between valid and invalid mathematical arguments.Apart from its importance in understanding mathematical reasoning, logic has numerous applications in Computer Science, varying from design of digital circuits, to the construction of computer programs and verification of correctness of programs." }, { "code": null, "e": 30706, "s": 30403, "text": "What is a proposition?A proposition is the basic building block of logic. It is defined as a declarative sentence that is either True or False, but not both.The Truth Value of a proposition is True(denoted as T) if it is a true statement, and False(denoted as F) if it is a false statement.For Example," }, { "code": null, "e": 30790, "s": 30706, "text": "1. The sun rises in the East and sets in the West.\n2. 1 + 1 = 2\n3. 'b' is a vowel.\n" }, { "code": null, "e": 31025, "s": 30790, "text": "All of the above sentences are propositions, where the first two are Valid(True) and the third one is Invalid(False).Some sentences that do not have a truth value or may have more than one truth value are not propositions.For Example," }, { "code": null, "e": 31080, "s": 31025, "text": "1. What time is it?\n2. Go out and play.\n3. x + 1 = 2.\n" }, { "code": null, "e": 31205, "s": 31080, "text": "The above sentences are not propositions as the first two do not have a truth value, and the third one may be true or false." }, { "code": null, "e": 31687, "s": 31205, "text": "To represent propositions, propositional variables are used. By Convention, these variables are represented by small alphabets such as .The area of logic which deals with propositions is called propositional calculus or propositional logic.It also includes producing new propositions using existing ones. Propositions constructed using one or more propositions are called compound propositions. The propositions are combined together using Logical Connectives or Logical Operators." }, { "code": null, "e": 32008, "s": 31687, "text": "Since we need to know the truth value of a proposition in all possible scenarios, we consider all the possible combinations of the propositions which are joined together by Logical Connectives to form the given compound proposition. This compilation of all possible scenarios in a tabular format is called a truth table." }, { "code": null, "e": 32041, "s": 32008, "text": "Most Common Logical Connectives-" }, { "code": null, "e": 32288, "s": 32041, "text": "1. Negation – If is a proposition, then the negation of is denoted by , which when translated to simple English means-“It is not the case that ” or simply “not “.The truth value of is the opposite of the truth value of .The truth table of is-" }, { "code": null, "e": 32420, "s": 32290, "text": "Example,The negation of “It is raining today”, is “It is not the case that is raining today” or simply “It is not raining today”." }, { "code": null, "e": 32614, "s": 32420, "text": "2. Conjunction – For any two propositions and , their conjunction is denoted by , which means “ and “. The conjuction is True when both and are True, otherwise False.The truth table of is-" }, { "code": null, "e": 32878, "s": 32616, "text": "Example,The conjunction of the propositions – “Today is Friday” and – “It is raining today”, is “Today is Friday and it is raining today”. This proposition is true only on rainy Fridays and is false on any other rainy day or on Fridays when it does not rain." }, { "code": null, "e": 33071, "s": 32878, "text": "3. Disjunction – For any two propositions and , their disjunction is denoted by , which means “ or “. The disjuction is True when either or is True, otherwise False.The truth table of is-" }, { "code": null, "e": 33377, "s": 33073, "text": "Example,The disjunction of the propositions – “Today is Friday” and – “It is raining today”, is “Today is Friday or it is raining today”. This proposition is true on any day that is a Friday or a rainy day(including rainy Fridays) and is false on any day other than Friday when it also does not rain." }, { "code": null, "e": 33625, "s": 33377, "text": "4. Exclusive Or – For any two propositions and , their exclusive or is denoted by , which means “either or but not both”. The exclusive or is True when either or is True, and False when both are true or both are false.The truth table of is-" }, { "code": null, "e": 33969, "s": 33627, "text": "Example,The exclusive or of the propositions – “Today is Friday” and – “It is raining today”, is “Either today is Friday or it is raining today, but not both”. This proposition is true on any day that is a Friday or a rainy day(not including rainy Fridays) and is false on any day other than Friday when it does not rain or rainy Fridays." }, { "code": null, "e": 34366, "s": 33969, "text": "5. Implication – For any two propositions and , the statement “if then ” is called an implication and it is denoted by .In the implication , is called the hypothesis or antecedent or premise and is called the conclusion or consequence.The implication is is also called a conditional statement.The implication is false when is true and is false otherwise it is true. The truth table of is-" }, { "code": null, "e": 35176, "s": 34368, "text": "You might wonder that why is true when is false. This is because the implication guarantees that when and are true then the implication is true. But the implication does not guarantee anything when the premise is false. There is no way of knowing whether or not the implication is false since did not happen.This situation is similar to the “Innocent until proven Guilty” stance, which means that the implication is considered true until proven false. Since we cannot call the implication false when is false, our only alternative is to call it true.This follows from the Explosion Principle which says-“A False statement implies anything”Conditional statements play a very important role in mathematical reasoning, thus a variety of terminology is used to express , some of which are listed below." }, { "code": null, "e": 35294, "s": 35176, "text": "\"if , then \"\n\" is sufficient for \"\n\" when \"\n\"a necessary condition for is \"\n\" only if \"\n\" unless \"\n\" follows from \"\n" }, { "code": null, "e": 35548, "s": 35294, "text": "Example,“If it is Friday then it is raining today” is a proposition which is of the form . The above proposition is true if it is not Friday(premise is false) or if it is Friday and it is raining, and it is false when it is Friday but it is not raining." }, { "code": null, "e": 35890, "s": 35548, "text": "6. Biconditional or Double Implication – For any two propositions and , the statement “ if and only if(iff) ” is called a biconditional and it is denoted by .The statement is also called a bi-implication. has the same truth value as The implication is true when and have same truth values, and is false otherwise. The truth table of is-" }, { "code": null, "e": 35935, "s": 35892, "text": "Some other common ways of expressing are-" }, { "code": null, "e": 36008, "s": 35935, "text": "\" is necessary and sufficient for \"\n\"if then , and conversely\"\n\" iff \"\n" }, { "code": null, "e": 36283, "s": 36008, "text": "Example,“It is raining today if and only if it is Friday today.” is a proposition which is of the form . The above proposition is true if it is not Friday and it is not raining or if it is Friday and it is raining, and it is false when it is not Friday or it is not raining." }, { "code": null, "e": 36330, "s": 36283, "text": "Exercise:1) Consider the following statements:" }, { "code": null, "e": 36468, "s": 36330, "text": " P: Good mobile phones are not cheap.\n Q: Cheap mobile phones are not good.\n L: P implies Q\n M: Q implies P\n N: P is equivalent to Q" }, { "code": null, "e": 36676, "s": 36468, "text": "Which one of the following about L, M, and N is CORRECT?(Gate 2014)(A) Only L is TRUE.(B) Only M is TRUE.(C) Only N is TRUE.(D) L, M and N are TRUE.For solution, see GATE | GATE-CS-2014-(Set-3) | Question 11" }, { "code": null, "e": 36744, "s": 36676, "text": " 2) Which one of the following is not equivalent to p⇔q (Gate 2015)" }, { "code": null, "e": 36804, "s": 36744, "text": "For solution, see GATE | GATE-CS-2015 (Set 1) | Question 65" }, { "code": null, "e": 36816, "s": 36804, "text": "References-" }, { "code": null, "e": 36943, "s": 36816, "text": "Propositional Logic – WikipediaPrinciple of Explosion – WikipediaDiscrete Mathematics and its Applications, by Kenneth H Rosen" }, { "code": null, "e": 37004, "s": 36943, "text": "Read next part : Introduction to Propositional Logic – Set 2" }, { "code": null, "e": 37302, "s": 37004, "text": "This article is contributed by Chirag Manwani. 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": 37427, "s": 37302, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 37446, "s": 37427, "text": "surindertarika1234" }, { "code": null, "e": 37470, "s": 37446, "text": "Engineering Mathematics" }, { "code": null, "e": 37478, "s": 37470, "text": "GATE CS" }, { "code": null, "e": 37576, "s": 37478, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37585, "s": 37576, "text": "Comments" }, { "code": null, "e": 37598, "s": 37585, "text": "Old Comments" }, { "code": null, "e": 37620, "s": 37598, "text": "Inequalities in LaTeX" }, { "code": null, "e": 37643, "s": 37620, "text": "Arrow Symbols in LaTeX" }, { "code": null, "e": 37673, "s": 37643, "text": "Properties of Boolean Algebra" }, { "code": null, "e": 37723, "s": 37673, "text": "Newton's Divided Difference Interpolation Formula" }, { "code": null, "e": 37746, "s": 37723, "text": "Set Notations in LaTeX" }, { "code": null, "e": 37766, "s": 37746, "text": "Layers of OSI Model" }, { "code": null, "e": 37790, "s": 37766, "text": "ACID Properties in DBMS" }, { "code": null, "e": 37817, "s": 37790, "text": "Types of Operating Systems" }, { "code": null, "e": 37830, "s": 37817, "text": "TCP/IP Model" } ]
How to send an attachment in email using Swift(ios)?
Knowing how to send attachments in the email is very important since most of the application has sharing features. Hence having hands-on experience is important. In this post, we will be seeing how to send an attachment in the mail using Swift. So, let’s get started. For this, we will be using MFMailComposeViewController, which is a standard view controller, whose interface lets the user manage, edit, and send email messages. You can read more about it here https://developer.apple.com/documentation/messageui/mfmailcomposeviewcontroller We will also be using MFMailComposeViewControllerDelegate to handle results from MFMailComposeResult. You can read about it here https://developer.apple.com/documentation/messageui/mfmailcomposeviewcontrollerdelegate We will be creating one sample application to understand, Step 1 − Open Xcode → Single View Application → Name it EmailAttachment Step 2 − Open Main.storyboard and add one button name it sends mail as shown below, Step 3 − Create @IBAction and name it btnSendMail as below @IBAction func btnSendMail(_ sender: Any) { } Step 4 − In ViewController.swift, Import MessageUI import MessageUI Step 5 − Confirm the class to MFMailComposeViewControllerDelegate class ViewController: UIViewController, MFMailComposeViewControllerDelegate Step 6 − Add attachment file to project, Step 7 − In btnSendMail write below function, @IBAction func btnSendMail(_ sender: Any) { if MFMailComposeViewController.canSendMail() { let mail = MFMailComposeViewController() mail.setToRecipients(["[email protected]"]) mail.setSubject("GREETING") mail.setMessageBody("Welcome to Tutorials Point!", isHTML: true) mail.mailComposeDelegate = self //add attachment if let filePath = Bundle.main.path(forResource: "sampleData", ofType: "json") { if let data = NSData(contentsOfFile: filePath) { mail.addAttachmentData(data as Data, mimeType: "application/json" , fileName: "sampleData.json") } } present(mail, animated: true) } else { print("Email cannot be sent") } } And you’re done!! But we need to handle other conditions also, such as a message sent, canceled or failed. For this only we’ve conformed to the above protocol, Let’s implement delegate methods, func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { if let _ = error { self.dismiss(animated: true, completion: nil) } switch result { case .cancelled: print("Cancelled") break case .sent: print("Mail sent successfully") break case .failed: print("Sending mail failed") break default: break } controller.dismiss(animated: true, completion: nil) } And you’re done!! Run the program in a real device, Complete code import UIKit import MessageUI class ViewController: UIViewController, MFMailComposeViewControllerDelegate { override func viewDidLoad() { } @IBAction func btnSendMail(_ sender: Any) { if MFMailComposeViewController.canSendMail() { let mail = MFMailComposeViewController() mail.setToRecipients(["[email protected]"]) mail.setSubject("GREETING") mail.setMessageBody("Welcome to Tutorials Point!", isHTML: true) mail.mailComposeDelegate = self if let filePath = Bundle.main.path(forResource: "sampleData", ofType: "json") { if let data = NSData(contentsOfFile: filePath) { mail.addAttachmentData(data as Data, mimeType: "application/json" , fileName: "sampleData.json") } } present(mail, animated: true) } else { print("Email cannot be sent") } } func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { if let _ = error { self.dismiss(animated: true, completion: nil) } switch result { case .cancelled: print("Cancelled") break case .sent: print("Mail sent successfully") break case .failed: print("Sending mail failed") break default: break } controller.dismiss(animated: true, completion: nil) } }
[ { "code": null, "e": 1224, "s": 1062, "text": "Knowing how to send attachments in the email is very important since most of the application has sharing features. Hence having hands-on experience is important." }, { "code": null, "e": 1307, "s": 1224, "text": "In this post, we will be seeing how to send an attachment in the mail using Swift." }, { "code": null, "e": 1330, "s": 1307, "text": "So, let’s get started." }, { "code": null, "e": 1492, "s": 1330, "text": "For this, we will be using MFMailComposeViewController, which is a standard view controller, whose interface lets the user manage, edit, and send email messages." }, { "code": null, "e": 1604, "s": 1492, "text": "You can read more about it here https://developer.apple.com/documentation/messageui/mfmailcomposeviewcontroller" }, { "code": null, "e": 1706, "s": 1604, "text": "We will also be using MFMailComposeViewControllerDelegate to handle results from MFMailComposeResult." }, { "code": null, "e": 1821, "s": 1706, "text": "You can read about it here https://developer.apple.com/documentation/messageui/mfmailcomposeviewcontrollerdelegate" }, { "code": null, "e": 1879, "s": 1821, "text": "We will be creating one sample application to understand," }, { "code": null, "e": 1951, "s": 1879, "text": "Step 1 − Open Xcode → Single View Application → Name it EmailAttachment" }, { "code": null, "e": 2035, "s": 1951, "text": "Step 2 − Open Main.storyboard and add one button name it sends mail as shown below," }, { "code": null, "e": 2094, "s": 2035, "text": "Step 3 − Create @IBAction and name it btnSendMail as below" }, { "code": null, "e": 2140, "s": 2094, "text": "@IBAction func btnSendMail(_ sender: Any) { }" }, { "code": null, "e": 2191, "s": 2140, "text": "Step 4 − In ViewController.swift, Import MessageUI" }, { "code": null, "e": 2208, "s": 2191, "text": "import MessageUI" }, { "code": null, "e": 2274, "s": 2208, "text": "Step 5 − Confirm the class to MFMailComposeViewControllerDelegate" }, { "code": null, "e": 2350, "s": 2274, "text": "class ViewController: UIViewController, MFMailComposeViewControllerDelegate" }, { "code": null, "e": 2391, "s": 2350, "text": "Step 6 − Add attachment file to project," }, { "code": null, "e": 2437, "s": 2391, "text": "Step 7 − In btnSendMail write below function," }, { "code": null, "e": 3160, "s": 2437, "text": "@IBAction func btnSendMail(_ sender: Any) {\n if MFMailComposeViewController.canSendMail() {\n let mail = MFMailComposeViewController()\n mail.setToRecipients([\"[email protected]\"])\n mail.setSubject(\"GREETING\")\n mail.setMessageBody(\"Welcome to Tutorials Point!\", isHTML: true)\n mail.mailComposeDelegate = self\n //add attachment\n if let filePath = Bundle.main.path(forResource: \"sampleData\", ofType: \"json\") {\n if let data = NSData(contentsOfFile: filePath) {\n mail.addAttachmentData(data as Data, mimeType: \"application/json\" , fileName: \"sampleData.json\")\n }\n }\n present(mail, animated: true)\n }\n else {\n print(\"Email cannot be sent\")\n }\n}" }, { "code": null, "e": 3178, "s": 3160, "text": "And you’re done!!" }, { "code": null, "e": 3320, "s": 3178, "text": "But we need to handle other conditions also, such as a message sent, canceled or failed. For this only we’ve conformed to the above protocol," }, { "code": null, "e": 3354, "s": 3320, "text": "Let’s implement delegate methods," }, { "code": null, "e": 3866, "s": 3354, "text": "func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {\n if let _ = error {\n self.dismiss(animated: true, completion: nil)\n }\n switch result {\n case .cancelled:\n print(\"Cancelled\")\n break\n case .sent:\n print(\"Mail sent successfully\")\n break\n case .failed:\n print(\"Sending mail failed\")\n break\n default:\n break\n }\n controller.dismiss(animated: true, completion: nil)\n}" }, { "code": null, "e": 3884, "s": 3866, "text": "And you’re done!!" }, { "code": null, "e": 3918, "s": 3884, "text": "Run the program in a real device," }, { "code": null, "e": 3932, "s": 3918, "text": "Complete code" }, { "code": null, "e": 5409, "s": 3932, "text": "import UIKit\nimport MessageUI\nclass ViewController: UIViewController, MFMailComposeViewControllerDelegate {\n override func viewDidLoad() {\n }\n @IBAction func btnSendMail(_ sender: Any) {\n if MFMailComposeViewController.canSendMail() {\n let mail = MFMailComposeViewController()\n mail.setToRecipients([\"[email protected]\"])\n mail.setSubject(\"GREETING\")\n mail.setMessageBody(\"Welcome to Tutorials Point!\", isHTML: true)\n mail.mailComposeDelegate = self\n if let filePath = Bundle.main.path(forResource: \"sampleData\", ofType: \"json\") {\n if let data = NSData(contentsOfFile: filePath) {\n mail.addAttachmentData(data as Data, mimeType: \"application/json\" , fileName: \"sampleData.json\")\n }\n }\n present(mail, animated: true)\n }\n else {\n print(\"Email cannot be sent\")\n }\n }\n func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {\n if let _ = error {\n self.dismiss(animated: true, completion: nil)\n }\n switch result {\n case .cancelled:\n print(\"Cancelled\")\n break\n case .sent:\n print(\"Mail sent successfully\")\n break\n case .failed:\n print(\"Sending mail failed\")\n break\n default:\n break\n }\n controller.dismiss(animated: true, completion: nil)\n }\n}" } ]
How to send data from one activity to another in Android using intent?
This example demonstrate about How to send data from one activity to another in Android using intent. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" android:layout_margin = "16dp" android:orientation = "vertical" tools:context = ".MainActivity"> <EditText android:id = "@+id/edit_text" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_gravity = "center" android:hint = "Enter something to pass" android:inputType = "text" /> <Button android:id = "@+id/button" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_gravity = "center" android:layout_marginTop = "16dp" android:text = "Next" /> </LinearLayout> Step 3 − Add the following code to src/MainActivity.java package com.example.myapplication; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final EditText editText = findViewById(R.id.edit_text); Button button = findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String value = editText.getText().toString().trim(); Intent intent = new Intent(MainActivity.this, SecondActivity.class); intent.putString(“value”,value); startActivity(intent); } }); } } Step 4 − Add the following code to res/layout/activity_second.xml. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" android:layout_margin = "16dp" android:orientation = "vertical" tools:context = ".SecondActivity"> <TextView android:id = "@+id/text_view" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_gravity = "center" /> </LinearLayout> Step 5 − Add the following code to src/SecondActivity.java package com.example.myapplication; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; public class SecondActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); Bundle bundle = getIntent().getExtras(); if (bundle ! = null) { String value = bundle.getString("value"); TextView textView = findViewById(R.id.text_view); textView.setText(value); } } } Step 6 − Add the following code to androidManifest.xml <?xml version = "1.0" encoding = "utf-8"?> <manifest xmlns:android = "http://schemas.android.com/apk/res/android" package = "com.example.myapplication"> <application android:allowBackup = "true" android:icon = "@mipmap/ic_launcher" android:label = "@string/app_name" android:roundIcon = "@mipmap/ic_launcher_round" android:supportsRtl = "true" android:theme = "@style/AppTheme"> <activity android:name = ".MainActivity"> <intent-filter> <action android:name = "android.intent.action.MAIN" /> <category android:name = "android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name = ".SecondActivity"></activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – Click here to download the project code
[ { "code": null, "e": 1164, "s": 1062, "text": "This example demonstrate about How to send data from one activity to another in Android using intent." }, { "code": null, "e": 1293, "s": 1164, "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": 1358, "s": 1293, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2238, "s": 1358, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n android:layout_margin = \"16dp\"\n android:orientation = \"vertical\"\n tools:context = \".MainActivity\">\n <EditText\n android:id = \"@+id/edit_text\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:layout_gravity = \"center\"\n android:hint = \"Enter something to pass\"\n android:inputType = \"text\" />\n <Button\n android:id = \"@+id/button\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\"\n android:layout_gravity = \"center\"\n android:layout_marginTop = \"16dp\"\n android:text = \"Next\" />\n</LinearLayout>" }, { "code": null, "e": 2295, "s": 2238, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3220, "s": 2295, "text": "package com.example.myapplication;\nimport android.content.Intent;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;\n\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n final EditText editText = findViewById(R.id.edit_text);\n Button button = findViewById(R.id.button);\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n String value = editText.getText().toString().trim();\n Intent intent = new Intent(MainActivity.this, SecondActivity.class);\n intent.putString(“value”,value);\n startActivity(intent);\n }\n });\n }\n}" }, { "code": null, "e": 3287, "s": 3220, "text": "Step 4 − Add the following code to res/layout/activity_second.xml." }, { "code": null, "e": 3845, "s": 3287, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n android:layout_margin = \"16dp\"\n android:orientation = \"vertical\"\n tools:context = \".SecondActivity\">\n <TextView\n android:id = \"@+id/text_view\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:layout_gravity = \"center\" />\n</LinearLayout>" }, { "code": null, "e": 3904, "s": 3845, "text": "Step 5 − Add the following code to src/SecondActivity.java" }, { "code": null, "e": 4497, "s": 3904, "text": "package com.example.myapplication;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.widget.TextView;\n\npublic class SecondActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_second);\n Bundle bundle = getIntent().getExtras();\n if (bundle ! = null) {\n String value = bundle.getString(\"value\");\n TextView textView = findViewById(R.id.text_view);\n textView.setText(value);\n }\n }\n}" }, { "code": null, "e": 4552, "s": 4497, "text": "Step 6 − Add the following code to androidManifest.xml" }, { "code": null, "e": 5323, "s": 4552, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.example.myapplication\">\n <application\n android:allowBackup = \"true\"\n android:icon = \"@mipmap/ic_launcher\"\n android:label = \"@string/app_name\"\n android:roundIcon = \"@mipmap/ic_launcher_round\"\n android:supportsRtl = \"true\"\n android:theme = \"@style/AppTheme\">\n <activity android:name = \".MainActivity\">\n <intent-filter>\n <action android:name = \"android.intent.action.MAIN\" />\n <category android:name = \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n <activity android:name = \".SecondActivity\"></activity>\n </application>\n</manifest>" }, { "code": null, "e": 5672, "s": 5323, "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": 5712, "s": 5672, "text": "Click here to download the project code" } ]
Custom Environments in OpenAI’s Gym | Towards Data Science
OpenAI’s Gym is (citing their website): “... a toolkit for developing and comparing reinforcement learning algorithms”. It includes simulated environments, ranging from very simple games to complex physics-based engines, that you can use to train reinforcement learning algorithms. OpenAI’s other package, Baselines, comes with a number of algorithms, so training a reinforcement learning agent is really straightforward with these two libraries, it only takes a couple of lines in Python. Of course, there is not much fun in only using the built-in elements, you either use the algorithms as benchmarks when you test your own algorithm, or you build a custom environment to solve your own problem with any of the available algorithms. Right now, we are interested in the latter: we are going to set up a custom environment in Gym with Python. You might assume you can just follow guidelines in the Gym Documentation, but that is not entirely correct. I had to hunt down and compile the information from multiple sources (documentation, GitHub, Stack Overflow, etc), so I figured I should write a clean and simple summary. Apart from the OpenAI Gym library, we are also going to use a package called Stable Baselines — a project that started as a fork of the OpenAI Baseline library’s reinforcement learning algorithms, with the intention to make it more documented and more user-friendly. One more source that I used is deeplizard’s step-by-step guide on implementing a simple Q-learning algorithm — we will use this code to test whether our environment can be trained on. All the code can be found on my GitHub, most importantly in gym_basic_env_test.ipynb. The rest of the repo is a Gym custom environment that you can register, but, as we will see later, you don’t necessarily need to do this step. After working through the guide, you’ll be able to: Set up a custom environment that is consistent with Gym.Develop and register different versions of your environment.Decide what exactly needs to go in the environment class — in my opinion, this is the trickiest part of the whole project!Train a simple Q-learning algorithm on your new environment.Utilise Stable Baselines in the environment, use the package to verify that your custom environment is Gym-consistent, and train a more sophisticated algorithm. Set up a custom environment that is consistent with Gym. Develop and register different versions of your environment. Decide what exactly needs to go in the environment class — in my opinion, this is the trickiest part of the whole project! Train a simple Q-learning algorithm on your new environment. Utilise Stable Baselines in the environment, use the package to verify that your custom environment is Gym-consistent, and train a more sophisticated algorithm. (Just to manage expectations, I’d like to mention that the environment we set up is going to be the simplest “game” I could come up with, with one singular choice — our aim is just to understand the structure.) I won’t go through the reinforcement learning basics, you will need to be familiar with at least the following terms: agent, environment, state, action. The following concepts will also indirectly come up when we do the Q-learning algorithm, but they are less important: Q-values, epsilon-greedy strategy, learning rate, exploration vs. exploitation. If you are not familiar with these terms, there are tons of good materials out there. The Stable Baselines Documentation has a list of useful links, and I personally used the code of the Q-learning section on deeplizard, they also have nice summaries of the basic stuff. We need to install Gym and Stable Baselines before we start working. Quite straightforward, you can follow the documentation. The most convenient method is to use pip: pip install gym That’s it. This one is trickier. For starters, you’ll need some prerequisites, have a look at the documentation. Once that’s done, you can pip install the package. If you are on a Mac, this is all you need to do: brew install cmake openmpipip install stable-baselines[mpi] Now, the issue comes when you are starting to use deep learning algorithms that are built on top of tensorflow — as of 2020 December, the Stable Baselines package only supports tensorflow up until version 1.15.0. There is a warning message on the Installation guide page, and if you are interested, you can read more about the cause of the problem on GitHub. Bottom line is, you need an older version of tensorflow. I did not use tensorflow for anything else, so I just installed an older version like so: pip install tensorflow==1.15.0 Now that we have the libraries, we can start working on the custom environment. If you try doing a custom environment from the official guide, chances are, you will start with building this file structure: gym-basic/ README.md setup.py gym_basic/ __init__.py envs/ __init__.py basic_env.py basic_env_2.py The thing is, it’s not... You don’t actually need to worry about this whole file structure thing, the only thing that really matters is basic_env.py. When I started working on this project, I assumed that when you later build your environment from a Gym command: env = gym.make(“gym_basic:basic-v0”) something magical happens in the background, but it seems to me you get the same result if you simply initiate an object from your environment class: env = BasicEnv() (You need to import it first of course.) My understanding is that the main advantage of registering your environment in your Gym package is that you can keep all your environments in one place, and you can also run Baseline RL algorithms (original OpenAI and Stable Baselines likewise) in one line: python -m baselines.run --alg=<name of the algorithm> --env=<environment_id> [additional arguments] So if you want to register your Gym environment, follow this section, otherwise, skip ahead to the next section, The Environment Class. You can use the documentation for this part, or my GitHub repository is basically also a Gym custom environment (if you ignore the two Jupyter Notebooks). You need to set up a setup.py, two __init__.py's, and most importantly, your environment file(s), which we will do in the next section. Pay attention to the difference between the two __init__.py’s, they handle the different versions of your environment. For your convenience, I’m copying the content of the three files here. In this example, we are setting up an environment called basic, and do two versions of it. Naturally, just change the string to whatever you want to call your environment. from setuptools import setup setup(name=’gym_basic’, version=’0.0.1', install_requires=[‘gym’] ) from gym.envs.registration import register register(id='basic-v0',entry_point='gym_basic.envs:BasicEnv',) register(id='basic-v2',entry_point='gym_basic.envs:BasicEnv2',) (We will have two environments, BasicEnv, with id = 'basic-v0', and BasicEnv2, with id = basic-v2. This way, you can keep different versions of the environment in the same registry.) from gym_basic.envs.basic_env import BasicEnvfrom gym_basic.envs.basic_env_2 import BasicEnv2 Hang on, there was another file in there, the README markdown, what do I put in there? Well, that is just your git repo readme file, it has nothing to do with your Gym environment. As long as you have the corresponding environment files in the envs folder (basic_env.py and basic_env_2.py in our case), you can register your environment. Just navigate up in your terminal to the folder that contains gym-basic, and use pip: pip install -e gym-basic If you update the environment .py files later, it should update your environment automatically. All right, we registered the Gym environment. We can finally concentrate on the important part: the environment class. Here, I think the Gym documentation is quite misleading. There are parts in the foo_env.py template they provide that you don’t need to include, and there are missing parts that you need. Stable Baselines has a better template, but it was still not entirely clear to me. Once again, my aim is to create the absolute minimum environment here. The environment needs to be a class inherited from gym.Env. In __init__, you need to create two variables with fixed names and types. You need a self.action_space, and a self.observation_space. These two need to be of Gym’s special class, space, which is not outright tricky, but not entirely straightforward either. Have a look at the documentation, there are basically two types: a one-dimensional called Discrete, and an n-dimensional called Box. In this example, we will keep things simple and only use Discrete. (One could argue that you can always re-code your spaces to one-dimensional id codes.) The reset function returns a value that is within self.observation_space. This is the function that will re-start the environment, for example, at the beginning of a game. In my environments, I call the variable that keeps track of the current state... well, state, but there is no restriction there, you can call it whatever. If we use a Discrete observation space, this state value needs to be an integer. With a Box, it can be a numpy.array. The step function has one input parameter, needs an action value, usually called action, that is within self.action_space. Similarly to state in the previous point, action can be an integer or a numpy.array. This is the response function, the agent provides the action they want to take, and the environment returns the state it brought them to. The return value is a 4-tuple, in the following order (the naming does not matter, but the variable type does):- state, same type of variable as the return of the reset function, of self.observation_space;- reward, a number that informs the agent about the immediate consequences of its action;- done, a boolean, value that is TRUE if the environment reached an endpoint, and should be reset, or FALSE otherwise;- info, a dictionary that can be used in bug fixing, and as far as I know, the baselines algorithms don’t use it.You need to provide these variables, but they don’t all have to have “proper“ values. For example, the info can be just an empty dictionary. It’s important to note that you can have as many helping functions within your class as you want, and it doesn’t matter what you call them, as long as they don’t use any of the reserved names. Now, I’m not saying that having these in an environment is a bad idea, but I think it’s important to distinguish between “absolute requirements” and “things that you will probably need later”. I’m a big fan of trying not to mindlessly copy code and clutter our projects with unnecessary stuff. So next is a list of things in the Gym documentation that you as a beginner probably won’t need right away when you start playing with custom environments: metadata = {‘render.modes’: [‘human’]}: This line simply defines possible types for your render function (see next point). You don’t actually need a render function. I mean, naturally, it comes handy when you try to do bug fixing, but in terms of training a reinforcement algorithm, as far as I noticed, the baseline algorithms don’t assume it to be there, and they are not using it. If you think about it, the purpose of render is simply to convert your state variable to something more readable. Similarly, you don’t actually need a close function either. The GitHub page of the core environment has some comments on this function, this would be called for additional cleanup when the environment is closed or picked up by the garbage collector. Same with the seed function. This will be useful when you want to have reproducibility in an environment that uses random number generators. Please note that the class from which you inherit (gym.env) will have these functions implemented, with a single pass line in each of them. So strictly speaking, you will always have these functions, but don’t need them to do anything. All right, and now, let’s see a custom environment! As I mentioned earlier, this is going to be very simple. We start at state = 0, and the agent can choose between 5 actions, numbered 0 to 4. If they pick action = 2, they get a reward of 1, otherwise, the reward is -1. (If you would like to see something that’s a tiny bit more complicated, have a look at basic_env_2.py in my GitHub repo.) The way you can code it as a Gym environment: import gymclass BasicEnv(gym.Env):def __init__(self): self.action_space = gym.spaces.Discrete(5) self.observation_space = gym.spaces.Discrete(2)def step(self, action): state = 1 if action == 2: reward = 1 else: reward = -1 done = True info = {} return state, reward, done, infodef reset(self): state = 0 return state That’s it, you have a Gym environment! Note that the state is always kept within the scope of the function that uses it, and it’s implied that if the environment takes a step (via the step function), it moves from state 0 to 1, and then the “game” immediately ends. So there is no need to keep track of the state within the object in this simple game, but generally, you would want to have a self.state variable. As mentioned above, you can create an object with either env = gym.make(“gym_basic:basic-v0”) if you registered the environment (see File Structure section above), or simply with env = BasicEnv() if you have not registered it. In the remainder of the post, I will assume that env is initiated and is a BasicEnv Gym environment. One cool thing about Stable Baselines is that it comes with a function that verifies if your environment is Gym-compatible. Running this checker is as simple as: from stable_baselines.common.env_checker import check_envcheck_env(env) If you followed the tutorial, the function will not return anything. Which is a bit weird, but it means that everything is OK. You can test what happens if you change any of the elements in your environment. For example, if you don’t have a reset function, you will get a NotImplementedError. If you don’t have a proper self.action_space and self.observation_space, for example if you defined them as a regular list instead of the special space class, you will get this error: AssertionError: The action space must inherit from gym.spaces. Notice how the checker function did not complain about not having any of the stuff we listed as unnecessary earlier! I am following the Q-learning algorithm implementation from deeplizard. In this section, we are repeating the tutorial, but we replace the environment with our own. Just like with the built-in environment, the following section works properly on the custom environment. The Gym space class has an n attribute that you can use to gather the dimensions: action_space_size = env.action_space.nstate_space_size = env.observation_space.nq_table = np.zeros((state_space_size, action_space_size))print(q_table) returns: [[0. 0. 0. 0. 0.] [0. 0. 0. 0. 0.]] These are the environment’s state-action Q-values. Please note that the first row, corresponding with state 0, is the only one we care about, the second row of state 1 is the end state, no action will be taken there. I’m not sure if this is usual practice or not, it seemed logical to me to keep the end state separate. I’m not going to copy the whole code here, please refer to my GitHub repo. After the model is trained, the updated Q-values look like this: [[-0.94185026 -0.89058101 1. -0.92023356 -0.91137062] [ 0. 0. 0. 0. 0. ]] Which indicates that the model indeed learned the environment, and identified action = 2 as the optimal action to take. If you think that this was a slight overkill, you are right, but I think it is interesting to see how the environment would work in practice. Plus, wait until what we do in the next section! In this section, we are going to dial up the overkill a bit, and train a Proximal Policy Optimizing Algorithm on our humble environment. (Full disclosure: I have no idea how this algorithm works, or what its advantages are, I simply picked it because it is in the tutorial.) Long story short, taking the code in the Getting Started Guide on Stable Baselines, and replacing the env with our own (once again, by running either env = gym.make(“gym_basic:basic-v0”), or env = BasicEnv(), this code works perfectly: from stable_baselines.common.policies import MlpPolicyfrom stable_baselines.common.vec_env import DummyVecEnvfrom stable_baselines import PPO2model = PPO2(MlpPolicy, env, verbose=1)model.learn(total_timesteps=10000)obs = env.reset()for i in range(10): action, _states = model.predict(obs) print(action) obs, rewards, dones, info = env.step(action) env.render() (Our render function does not do anything, so I added in a line to print out our action.) Quite reassuringly, the model was able to learn how to play our game correctly, and picks action = 2 in every case.
[ { "code": null, "e": 662, "s": 172, "text": "OpenAI’s Gym is (citing their website): “... a toolkit for developing and comparing reinforcement learning algorithms”. It includes simulated environments, ranging from very simple games to complex physics-based engines, that you can use to train reinforcement learning algorithms. OpenAI’s other package, Baselines, comes with a number of algorithms, so training a reinforcement learning agent is really straightforward with these two libraries, it only takes a couple of lines in Python." }, { "code": null, "e": 1016, "s": 662, "text": "Of course, there is not much fun in only using the built-in elements, you either use the algorithms as benchmarks when you test your own algorithm, or you build a custom environment to solve your own problem with any of the available algorithms. Right now, we are interested in the latter: we are going to set up a custom environment in Gym with Python." }, { "code": null, "e": 1295, "s": 1016, "text": "You might assume you can just follow guidelines in the Gym Documentation, but that is not entirely correct. I had to hunt down and compile the information from multiple sources (documentation, GitHub, Stack Overflow, etc), so I figured I should write a clean and simple summary." }, { "code": null, "e": 1562, "s": 1295, "text": "Apart from the OpenAI Gym library, we are also going to use a package called Stable Baselines — a project that started as a fork of the OpenAI Baseline library’s reinforcement learning algorithms, with the intention to make it more documented and more user-friendly." }, { "code": null, "e": 1746, "s": 1562, "text": "One more source that I used is deeplizard’s step-by-step guide on implementing a simple Q-learning algorithm — we will use this code to test whether our environment can be trained on." }, { "code": null, "e": 1975, "s": 1746, "text": "All the code can be found on my GitHub, most importantly in gym_basic_env_test.ipynb. The rest of the repo is a Gym custom environment that you can register, but, as we will see later, you don’t necessarily need to do this step." }, { "code": null, "e": 2027, "s": 1975, "text": "After working through the guide, you’ll be able to:" }, { "code": null, "e": 2486, "s": 2027, "text": "Set up a custom environment that is consistent with Gym.Develop and register different versions of your environment.Decide what exactly needs to go in the environment class — in my opinion, this is the trickiest part of the whole project!Train a simple Q-learning algorithm on your new environment.Utilise Stable Baselines in the environment, use the package to verify that your custom environment is Gym-consistent, and train a more sophisticated algorithm." }, { "code": null, "e": 2543, "s": 2486, "text": "Set up a custom environment that is consistent with Gym." }, { "code": null, "e": 2604, "s": 2543, "text": "Develop and register different versions of your environment." }, { "code": null, "e": 2727, "s": 2604, "text": "Decide what exactly needs to go in the environment class — in my opinion, this is the trickiest part of the whole project!" }, { "code": null, "e": 2788, "s": 2727, "text": "Train a simple Q-learning algorithm on your new environment." }, { "code": null, "e": 2949, "s": 2788, "text": "Utilise Stable Baselines in the environment, use the package to verify that your custom environment is Gym-consistent, and train a more sophisticated algorithm." }, { "code": null, "e": 3160, "s": 2949, "text": "(Just to manage expectations, I’d like to mention that the environment we set up is going to be the simplest “game” I could come up with, with one singular choice — our aim is just to understand the structure.)" }, { "code": null, "e": 3511, "s": 3160, "text": "I won’t go through the reinforcement learning basics, you will need to be familiar with at least the following terms: agent, environment, state, action. The following concepts will also indirectly come up when we do the Q-learning algorithm, but they are less important: Q-values, epsilon-greedy strategy, learning rate, exploration vs. exploitation." }, { "code": null, "e": 3782, "s": 3511, "text": "If you are not familiar with these terms, there are tons of good materials out there. The Stable Baselines Documentation has a list of useful links, and I personally used the code of the Q-learning section on deeplizard, they also have nice summaries of the basic stuff." }, { "code": null, "e": 3851, "s": 3782, "text": "We need to install Gym and Stable Baselines before we start working." }, { "code": null, "e": 3950, "s": 3851, "text": "Quite straightforward, you can follow the documentation. The most convenient method is to use pip:" }, { "code": null, "e": 3966, "s": 3950, "text": "pip install gym" }, { "code": null, "e": 3977, "s": 3966, "text": "That’s it." }, { "code": null, "e": 4179, "s": 3977, "text": "This one is trickier. For starters, you’ll need some prerequisites, have a look at the documentation. Once that’s done, you can pip install the package. If you are on a Mac, this is all you need to do:" }, { "code": null, "e": 4239, "s": 4179, "text": "brew install cmake openmpipip install stable-baselines[mpi]" }, { "code": null, "e": 4598, "s": 4239, "text": "Now, the issue comes when you are starting to use deep learning algorithms that are built on top of tensorflow — as of 2020 December, the Stable Baselines package only supports tensorflow up until version 1.15.0. There is a warning message on the Installation guide page, and if you are interested, you can read more about the cause of the problem on GitHub." }, { "code": null, "e": 4745, "s": 4598, "text": "Bottom line is, you need an older version of tensorflow. I did not use tensorflow for anything else, so I just installed an older version like so:" }, { "code": null, "e": 4776, "s": 4745, "text": "pip install tensorflow==1.15.0" }, { "code": null, "e": 4856, "s": 4776, "text": "Now that we have the libraries, we can start working on the custom environment." }, { "code": null, "e": 4982, "s": 4856, "text": "If you try doing a custom environment from the official guide, chances are, you will start with building this file structure:" }, { "code": null, "e": 5105, "s": 4982, "text": "gym-basic/ README.md setup.py gym_basic/ __init__.py envs/ __init__.py basic_env.py basic_env_2.py" }, { "code": null, "e": 5368, "s": 5105, "text": "The thing is, it’s not... You don’t actually need to worry about this whole file structure thing, the only thing that really matters is basic_env.py. When I started working on this project, I assumed that when you later build your environment from a Gym command:" }, { "code": null, "e": 5405, "s": 5368, "text": "env = gym.make(“gym_basic:basic-v0”)" }, { "code": null, "e": 5555, "s": 5405, "text": "something magical happens in the background, but it seems to me you get the same result if you simply initiate an object from your environment class:" }, { "code": null, "e": 5572, "s": 5555, "text": "env = BasicEnv()" }, { "code": null, "e": 5871, "s": 5572, "text": "(You need to import it first of course.) My understanding is that the main advantage of registering your environment in your Gym package is that you can keep all your environments in one place, and you can also run Baseline RL algorithms (original OpenAI and Stable Baselines likewise) in one line:" }, { "code": null, "e": 5971, "s": 5871, "text": "python -m baselines.run --alg=<name of the algorithm> --env=<environment_id> [additional arguments]" }, { "code": null, "e": 6107, "s": 5971, "text": "So if you want to register your Gym environment, follow this section, otherwise, skip ahead to the next section, The Environment Class." }, { "code": null, "e": 6517, "s": 6107, "text": "You can use the documentation for this part, or my GitHub repository is basically also a Gym custom environment (if you ignore the two Jupyter Notebooks). You need to set up a setup.py, two __init__.py's, and most importantly, your environment file(s), which we will do in the next section. Pay attention to the difference between the two __init__.py’s, they handle the different versions of your environment." }, { "code": null, "e": 6760, "s": 6517, "text": "For your convenience, I’m copying the content of the three files here. In this example, we are setting up an environment called basic, and do two versions of it. Naturally, just change the string to whatever you want to call your environment." }, { "code": null, "e": 6857, "s": 6760, "text": "from setuptools import setup setup(name=’gym_basic’, version=’0.0.1', install_requires=[‘gym’] )" }, { "code": null, "e": 7027, "s": 6857, "text": "from gym.envs.registration import register register(id='basic-v0',entry_point='gym_basic.envs:BasicEnv',) register(id='basic-v2',entry_point='gym_basic.envs:BasicEnv2',)" }, { "code": null, "e": 7210, "s": 7027, "text": "(We will have two environments, BasicEnv, with id = 'basic-v0', and BasicEnv2, with id = basic-v2. This way, you can keep different versions of the environment in the same registry.)" }, { "code": null, "e": 7304, "s": 7210, "text": "from gym_basic.envs.basic_env import BasicEnvfrom gym_basic.envs.basic_env_2 import BasicEnv2" }, { "code": null, "e": 7485, "s": 7304, "text": "Hang on, there was another file in there, the README markdown, what do I put in there? Well, that is just your git repo readme file, it has nothing to do with your Gym environment." }, { "code": null, "e": 7728, "s": 7485, "text": "As long as you have the corresponding environment files in the envs folder (basic_env.py and basic_env_2.py in our case), you can register your environment. Just navigate up in your terminal to the folder that contains gym-basic, and use pip:" }, { "code": null, "e": 7753, "s": 7728, "text": "pip install -e gym-basic" }, { "code": null, "e": 7849, "s": 7753, "text": "If you update the environment .py files later, it should update your environment automatically." }, { "code": null, "e": 7968, "s": 7849, "text": "All right, we registered the Gym environment. We can finally concentrate on the important part: the environment class." }, { "code": null, "e": 8239, "s": 7968, "text": "Here, I think the Gym documentation is quite misleading. There are parts in the foo_env.py template they provide that you don’t need to include, and there are missing parts that you need. Stable Baselines has a better template, but it was still not entirely clear to me." }, { "code": null, "e": 8310, "s": 8239, "text": "Once again, my aim is to create the absolute minimum environment here." }, { "code": null, "e": 8370, "s": 8310, "text": "The environment needs to be a class inherited from gym.Env." }, { "code": null, "e": 8914, "s": 8370, "text": "In __init__, you need to create two variables with fixed names and types. You need a self.action_space, and a self.observation_space. These two need to be of Gym’s special class, space, which is not outright tricky, but not entirely straightforward either. Have a look at the documentation, there are basically two types: a one-dimensional called Discrete, and an n-dimensional called Box. In this example, we will keep things simple and only use Discrete. (One could argue that you can always re-code your spaces to one-dimensional id codes.)" }, { "code": null, "e": 9359, "s": 8914, "text": "The reset function returns a value that is within self.observation_space. This is the function that will re-start the environment, for example, at the beginning of a game. In my environments, I call the variable that keeps track of the current state... well, state, but there is no restriction there, you can call it whatever. If we use a Discrete observation space, this state value needs to be an integer. With a Box, it can be a numpy.array." }, { "code": null, "e": 10371, "s": 9359, "text": "The step function has one input parameter, needs an action value, usually called action, that is within self.action_space. Similarly to state in the previous point, action can be an integer or a numpy.array. This is the response function, the agent provides the action they want to take, and the environment returns the state it brought them to. The return value is a 4-tuple, in the following order (the naming does not matter, but the variable type does):- state, same type of variable as the return of the reset function, of self.observation_space;- reward, a number that informs the agent about the immediate consequences of its action;- done, a boolean, value that is TRUE if the environment reached an endpoint, and should be reset, or FALSE otherwise;- info, a dictionary that can be used in bug fixing, and as far as I know, the baselines algorithms don’t use it.You need to provide these variables, but they don’t all have to have “proper“ values. For example, the info can be just an empty dictionary." }, { "code": null, "e": 10564, "s": 10371, "text": "It’s important to note that you can have as many helping functions within your class as you want, and it doesn’t matter what you call them, as long as they don’t use any of the reserved names." }, { "code": null, "e": 10858, "s": 10564, "text": "Now, I’m not saying that having these in an environment is a bad idea, but I think it’s important to distinguish between “absolute requirements” and “things that you will probably need later”. I’m a big fan of trying not to mindlessly copy code and clutter our projects with unnecessary stuff." }, { "code": null, "e": 11014, "s": 10858, "text": "So next is a list of things in the Gym documentation that you as a beginner probably won’t need right away when you start playing with custom environments:" }, { "code": null, "e": 11137, "s": 11014, "text": "metadata = {‘render.modes’: [‘human’]}: This line simply defines possible types for your render function (see next point)." }, { "code": null, "e": 11512, "s": 11137, "text": "You don’t actually need a render function. I mean, naturally, it comes handy when you try to do bug fixing, but in terms of training a reinforcement algorithm, as far as I noticed, the baseline algorithms don’t assume it to be there, and they are not using it. If you think about it, the purpose of render is simply to convert your state variable to something more readable." }, { "code": null, "e": 11762, "s": 11512, "text": "Similarly, you don’t actually need a close function either. The GitHub page of the core environment has some comments on this function, this would be called for additional cleanup when the environment is closed or picked up by the garbage collector." }, { "code": null, "e": 11903, "s": 11762, "text": "Same with the seed function. This will be useful when you want to have reproducibility in an environment that uses random number generators." }, { "code": null, "e": 12139, "s": 11903, "text": "Please note that the class from which you inherit (gym.env) will have these functions implemented, with a single pass line in each of them. So strictly speaking, you will always have these functions, but don’t need them to do anything." }, { "code": null, "e": 12532, "s": 12139, "text": "All right, and now, let’s see a custom environment! As I mentioned earlier, this is going to be very simple. We start at state = 0, and the agent can choose between 5 actions, numbered 0 to 4. If they pick action = 2, they get a reward of 1, otherwise, the reward is -1. (If you would like to see something that’s a tiny bit more complicated, have a look at basic_env_2.py in my GitHub repo.)" }, { "code": null, "e": 12578, "s": 12532, "text": "The way you can code it as a Gym environment:" }, { "code": null, "e": 13003, "s": 12578, "text": "import gymclass BasicEnv(gym.Env):def __init__(self): self.action_space = gym.spaces.Discrete(5) self.observation_space = gym.spaces.Discrete(2)def step(self, action): state = 1 if action == 2: reward = 1 else: reward = -1 done = True info = {} return state, reward, done, infodef reset(self): state = 0 return state" }, { "code": null, "e": 13042, "s": 13003, "text": "That’s it, you have a Gym environment!" }, { "code": null, "e": 13416, "s": 13042, "text": "Note that the state is always kept within the scope of the function that uses it, and it’s implied that if the environment takes a step (via the step function), it moves from state 0 to 1, and then the “game” immediately ends. So there is no need to keep track of the state within the object in this simple game, but generally, you would want to have a self.state variable." }, { "code": null, "e": 13473, "s": 13416, "text": "As mentioned above, you can create an object with either" }, { "code": null, "e": 13510, "s": 13473, "text": "env = gym.make(“gym_basic:basic-v0”)" }, { "code": null, "e": 13595, "s": 13510, "text": "if you registered the environment (see File Structure section above), or simply with" }, { "code": null, "e": 13612, "s": 13595, "text": "env = BasicEnv()" }, { "code": null, "e": 13643, "s": 13612, "text": "if you have not registered it." }, { "code": null, "e": 13744, "s": 13643, "text": "In the remainder of the post, I will assume that env is initiated and is a BasicEnv Gym environment." }, { "code": null, "e": 13868, "s": 13744, "text": "One cool thing about Stable Baselines is that it comes with a function that verifies if your environment is Gym-compatible." }, { "code": null, "e": 13906, "s": 13868, "text": "Running this checker is as simple as:" }, { "code": null, "e": 13978, "s": 13906, "text": "from stable_baselines.common.env_checker import check_envcheck_env(env)" }, { "code": null, "e": 14105, "s": 13978, "text": "If you followed the tutorial, the function will not return anything. Which is a bit weird, but it means that everything is OK." }, { "code": null, "e": 14518, "s": 14105, "text": "You can test what happens if you change any of the elements in your environment. For example, if you don’t have a reset function, you will get a NotImplementedError. If you don’t have a proper self.action_space and self.observation_space, for example if you defined them as a regular list instead of the special space class, you will get this error: AssertionError: The action space must inherit from gym.spaces." }, { "code": null, "e": 14635, "s": 14518, "text": "Notice how the checker function did not complain about not having any of the stuff we listed as unnecessary earlier!" }, { "code": null, "e": 14800, "s": 14635, "text": "I am following the Q-learning algorithm implementation from deeplizard. In this section, we are repeating the tutorial, but we replace the environment with our own." }, { "code": null, "e": 14987, "s": 14800, "text": "Just like with the built-in environment, the following section works properly on the custom environment. The Gym space class has an n attribute that you can use to gather the dimensions:" }, { "code": null, "e": 15139, "s": 14987, "text": "action_space_size = env.action_space.nstate_space_size = env.observation_space.nq_table = np.zeros((state_space_size, action_space_size))print(q_table)" }, { "code": null, "e": 15148, "s": 15139, "text": "returns:" }, { "code": null, "e": 15184, "s": 15148, "text": "[[0. 0. 0. 0. 0.] [0. 0. 0. 0. 0.]]" }, { "code": null, "e": 15504, "s": 15184, "text": "These are the environment’s state-action Q-values. Please note that the first row, corresponding with state 0, is the only one we care about, the second row of state 1 is the end state, no action will be taken there. I’m not sure if this is usual practice or not, it seemed logical to me to keep the end state separate." }, { "code": null, "e": 15579, "s": 15504, "text": "I’m not going to copy the whole code here, please refer to my GitHub repo." }, { "code": null, "e": 15644, "s": 15579, "text": "After the model is trained, the updated Q-values look like this:" }, { "code": null, "e": 15770, "s": 15644, "text": "[[-0.94185026 -0.89058101 1. -0.92023356 -0.91137062] [ 0. 0. 0. 0. 0. ]]" }, { "code": null, "e": 15890, "s": 15770, "text": "Which indicates that the model indeed learned the environment, and identified action = 2 as the optimal action to take." }, { "code": null, "e": 16081, "s": 15890, "text": "If you think that this was a slight overkill, you are right, but I think it is interesting to see how the environment would work in practice. Plus, wait until what we do in the next section!" }, { "code": null, "e": 16356, "s": 16081, "text": "In this section, we are going to dial up the overkill a bit, and train a Proximal Policy Optimizing Algorithm on our humble environment. (Full disclosure: I have no idea how this algorithm works, or what its advantages are, I simply picked it because it is in the tutorial.)" }, { "code": null, "e": 16592, "s": 16356, "text": "Long story short, taking the code in the Getting Started Guide on Stable Baselines, and replacing the env with our own (once again, by running either env = gym.make(“gym_basic:basic-v0”), or env = BasicEnv(), this code works perfectly:" }, { "code": null, "e": 16965, "s": 16592, "text": "from stable_baselines.common.policies import MlpPolicyfrom stable_baselines.common.vec_env import DummyVecEnvfrom stable_baselines import PPO2model = PPO2(MlpPolicy, env, verbose=1)model.learn(total_timesteps=10000)obs = env.reset()for i in range(10): action, _states = model.predict(obs) print(action) obs, rewards, dones, info = env.step(action) env.render()" }, { "code": null, "e": 17055, "s": 16965, "text": "(Our render function does not do anything, so I added in a line to print out our action.)" } ]
C++ program to implement ASCII lookup table
In this tutorial, we will be discussing a program to implement ASCII lookup table. ASCII lookup table is a tabular representation that provides with the octal, hexadecimal, decimal and HTML values of a given character. The character for the ASCII lookup table includes alphabets, digits, separators and special symbols. #include <iostream> #include <string> using namespace std; //converting decimal value to octal int Octal(int decimal){ int octal = 0; string temp = ""; while (decimal > 0) { int remainder = decimal % 8; temp = to_string(remainder) + temp; decimal /= 8; } for (int i = 0; i < temp.length(); i++) octal = (octal * 10) + (temp[i] - '0'); return octal; } //converting decimal value to hexadecimal string Hexadecimal(int decimal){ string hex = ""; while (decimal > 0) { int remainder = decimal % 16; if (remainder >= 0 && remainder <= 9) hex = to_string(remainder) + hex; else hex = (char)('A' + remainder % 10) + hex; decimal /= 16; } return hex; } //converting decimal value to HTML string HTML(int decimal){ string html = to_string(decimal); html = "&#" + html + ";"; return html; } //calculating the ASCII lookup table void ASCIIlookuptable(char ch){ int decimal = ch; cout << "Octal value: " << Octal(decimal) << endl; cout << "Decimal value: " << decimal << endl; cout << "Hexadecimal value: " << Hexadecimal(decimal) << endl; cout << "HTML value: " << HTML(decimal); } int main(){ char ch = 'a'; ASCIIlookuptable(ch); return 0; } Octal value: 141 Decimal value: 97 Hexadecimal value: 61 HTML value: a
[ { "code": null, "e": 1145, "s": 1062, "text": "In this tutorial, we will be discussing a program to implement ASCII lookup table." }, { "code": null, "e": 1281, "s": 1145, "text": "ASCII lookup table is a tabular representation that provides with the octal, hexadecimal, decimal and HTML values of a given character." }, { "code": null, "e": 1382, "s": 1281, "text": "The character for the ASCII lookup table includes alphabets, digits, separators and special symbols." }, { "code": null, "e": 2646, "s": 1382, "text": "#include <iostream>\n#include <string>\nusing namespace std;\n//converting decimal value to octal\nint Octal(int decimal){\n int octal = 0;\n string temp = \"\";\n while (decimal > 0) {\n int remainder = decimal % 8;\n temp = to_string(remainder) + temp;\n decimal /= 8;\n }\n for (int i = 0; i < temp.length(); i++)\n octal = (octal * 10) + (temp[i] - '0');\n return octal;\n}\n//converting decimal value to hexadecimal\nstring Hexadecimal(int decimal){\n string hex = \"\";\n while (decimal > 0) {\n int remainder = decimal % 16;\n if (remainder >= 0 && remainder <= 9)\n hex = to_string(remainder) + hex;\n else\n hex = (char)('A' + remainder % 10) + hex;\n decimal /= 16;\n }\n return hex;\n}\n//converting decimal value to HTML\nstring HTML(int decimal){\n string html = to_string(decimal);\n html = \"&#\" + html + \";\";\n return html;\n}\n//calculating the ASCII lookup table\nvoid ASCIIlookuptable(char ch){\n int decimal = ch;\n cout << \"Octal value: \" << Octal(decimal) << endl;\n cout << \"Decimal value: \" << decimal << endl;\n cout << \"Hexadecimal value: \" << Hexadecimal(decimal) <<\n endl;\n cout << \"HTML value: \" << HTML(decimal);\n}\nint main(){\n char ch = 'a';\n ASCIIlookuptable(ch);\n return 0;\n}" }, { "code": null, "e": 2717, "s": 2646, "text": "Octal value: 141\nDecimal value: 97\nHexadecimal value: 61\nHTML value: a" } ]
Creating Histograms of Well Log Data Using Matplotlib in Python | by Andy McDonald | Towards Data Science
Histograms are a commonly used tool within exploratory data analysis and data science. They are an excellent data visualisation tool and appear similar to bar charts. However, histograms allow us to gain insights about the distribution of the values within a set of data and allow us to display a large range of data in a concise plot. Within the petrophysics and geoscience domains, we can use histograms to identify outliers and also pick key interpretation parameters. For example, clay volume or shale volume end points from a gamma ray. To create a histogram: We first take a logging curve and determine the range of values that are contained within it. For example, me may have a gamma ray log, from one of our wells, that ranges from 5 to 145 API. We then divide the entire range into different bins or intervals. Using our example gamma ray log, we could have bins ranging from 0 to 10, 11 to 20, 21 to 30 all the way up to 141 to 150. Once the bins have been created, we then take the data and assign each value into the appropriate bin. And what we end up with is an interval vs frequency graph like the one below In this short tutorial we will see how we can quickly create a histogram in python using matplotlib. We will also see how we can customise the plot to include additional information, such as percentile values and the mean. The associated Python Notebook can be found here. The accompanying video for this tutorial can be found on my new YouTube channel at: The first stage of any python project or notebook is generally to import the required libraries. In this case, we are going to be using lasio to load our las file, pandas for storing our well log data, and matplotlib for visualising our data. import pandas as pdimport matplotlib.pyplot as pltimport lasio The data we are using for this short tutorial comes from the publicly released Equinor Volve dataset. Details of which can be found here. This dataset was released by Equinor, formerly Statoil, as a way to promote research, development and learning. In this exercise, we will be using one of the wells from this dataset. To read the data we will use the lasio library which we explored in the previous notebook and video. las = lasio.read("Data/15-9-19_SR_COMP.LAS") We then convert the las file to a pandas dataframe object. df = las.df() Using the .describe() method we can explore the summary statistics of the data. df.describe() We can see that we have seven logging curves within this file. AC for acoustic compressional slowness CALI for borehole caliper DEN for bulk density GR for gamma ray NEU for neutron porosity RDEP for deep resisitivity RMED for medium resistivity We can create a quick histogram using pandas without relying on importing other libraries. df['GR'].plot(kind='hist')plt.show() We can also create the same histogram using matplotlib like so. plt.hist(df['GR'])plt.show() This generates a very minimal plot. We can see that the values range from around 0 to 150, with a very small piece of data at 250 API. Each bin is around 25 API wide, which is quite a large range. We can control this by specifying a set number for the bins argument, in this example we will set it to 30. plt.hist(df['GR'], bins=30)plt.show() Let’s tidy the plot up a little by adding edge colours to the bins. plt.hist(df['GR'], bins=30, edgecolor='black')plt.show() When we do this, we can see that the bins just below 100 API, is in fact two separate bins. To tidy the plot up further, we can assign both an x and y label, and also set the x-axis limits. plt.hist(df['GR'], bins=30, color='red', alpha=0.5, edgecolor='black')plt.xlabel('Gamma Ray - API', fontsize=14)plt.ylabel('Frequency', fontsize=14)plt.xlim(0,200)plt.show() In addition to the bars, we can also add in a kernel density estimation, which provides us with a line illustrating the distribution of the data. df['GR'].plot(kind='hist', bins=30, color='red', alpha=0.5, density=True, edgecolor='black')df['GR'].plot(kind='kde', color='black')plt.xlabel('Gamma Ray - API', fontsize=14)plt.ylabel('Density', fontsize=14)plt.xlim(0,200)plt.show() When calculating clay and shale volumes as part of a petrophysical workflow, we often use the percentiles as our interpretation parameters. This reduces the influence of outliers or a small amount of data points that may represent a thin hot shale for example. We can calculated the key statsitics using built in pandas functions: mean() and quantile(). mean = df['GR'].mean()p5 = df['GR'].quantile(0.05)p95 = df['GR'].quantile(0.95)print(f'Mean: \t {mean}')print(f'P05: \t {p5}')print(f'P95: \t {p95}') This returns the following output. Mean: 71.98679770957146P05: 12.74656P95: 128.33267999999995 To get a better idea of where these points fall in relation to our data, we can add them onto the plot using axvline and passing in the calculated variables, a colour and a label. df['GR'].plot(kind='hist', bins=30, color='red', alpha=0.5, edgecolor='black')plt.xlabel('Gamma Ray', fontsize=14)plt.ylabel('Frequency', fontsize=14)plt.xlim(0,200)plt.axvline(mean, color='blue', label='mean')plt.axvline(p5, color='green', label='5th Percentile')plt.axvline(p95, color='purple', label='95th Percentile')plt.legend()plt.show() In this short tutorial, we have covered the basics of how to display a well log curve as a histogram and customise to provide a plot that is suitable for including in reports and publications. Thanks for reading! If you have found this article useful, please feel free to check out my other articles looking at various aspects of Python and well log data. You can also find my code used in this article and others at GitHub. If you want to get in touch you can find me on LinkedIn or at my website. Interested in learning more about python and well log data or petrophysics? Follow me on Medium.
[ { "code": null, "e": 714, "s": 172, "text": "Histograms are a commonly used tool within exploratory data analysis and data science. They are an excellent data visualisation tool and appear similar to bar charts. However, histograms allow us to gain insights about the distribution of the values within a set of data and allow us to display a large range of data in a concise plot. Within the petrophysics and geoscience domains, we can use histograms to identify outliers and also pick key interpretation parameters. For example, clay volume or shale volume end points from a gamma ray." }, { "code": null, "e": 737, "s": 714, "text": "To create a histogram:" }, { "code": null, "e": 927, "s": 737, "text": "We first take a logging curve and determine the range of values that are contained within it. For example, me may have a gamma ray log, from one of our wells, that ranges from 5 to 145 API." }, { "code": null, "e": 1116, "s": 927, "text": "We then divide the entire range into different bins or intervals. Using our example gamma ray log, we could have bins ranging from 0 to 10, 11 to 20, 21 to 30 all the way up to 141 to 150." }, { "code": null, "e": 1219, "s": 1116, "text": "Once the bins have been created, we then take the data and assign each value into the appropriate bin." }, { "code": null, "e": 1296, "s": 1219, "text": "And what we end up with is an interval vs frequency graph like the one below" }, { "code": null, "e": 1519, "s": 1296, "text": "In this short tutorial we will see how we can quickly create a histogram in python using matplotlib. We will also see how we can customise the plot to include additional information, such as percentile values and the mean." }, { "code": null, "e": 1569, "s": 1519, "text": "The associated Python Notebook can be found here." }, { "code": null, "e": 1653, "s": 1569, "text": "The accompanying video for this tutorial can be found on my new YouTube channel at:" }, { "code": null, "e": 1896, "s": 1653, "text": "The first stage of any python project or notebook is generally to import the required libraries. In this case, we are going to be using lasio to load our las file, pandas for storing our well log data, and matplotlib for visualising our data." }, { "code": null, "e": 1959, "s": 1896, "text": "import pandas as pdimport matplotlib.pyplot as pltimport lasio" }, { "code": null, "e": 2280, "s": 1959, "text": "The data we are using for this short tutorial comes from the publicly released Equinor Volve dataset. Details of which can be found here. This dataset was released by Equinor, formerly Statoil, as a way to promote research, development and learning. In this exercise, we will be using one of the wells from this dataset." }, { "code": null, "e": 2381, "s": 2280, "text": "To read the data we will use the lasio library which we explored in the previous notebook and video." }, { "code": null, "e": 2426, "s": 2381, "text": "las = lasio.read(\"Data/15-9-19_SR_COMP.LAS\")" }, { "code": null, "e": 2485, "s": 2426, "text": "We then convert the las file to a pandas dataframe object." }, { "code": null, "e": 2499, "s": 2485, "text": "df = las.df()" }, { "code": null, "e": 2579, "s": 2499, "text": "Using the .describe() method we can explore the summary statistics of the data." }, { "code": null, "e": 2593, "s": 2579, "text": "df.describe()" }, { "code": null, "e": 2656, "s": 2593, "text": "We can see that we have seven logging curves within this file." }, { "code": null, "e": 2695, "s": 2656, "text": "AC for acoustic compressional slowness" }, { "code": null, "e": 2721, "s": 2695, "text": "CALI for borehole caliper" }, { "code": null, "e": 2742, "s": 2721, "text": "DEN for bulk density" }, { "code": null, "e": 2759, "s": 2742, "text": "GR for gamma ray" }, { "code": null, "e": 2784, "s": 2759, "text": "NEU for neutron porosity" }, { "code": null, "e": 2811, "s": 2784, "text": "RDEP for deep resisitivity" }, { "code": null, "e": 2839, "s": 2811, "text": "RMED for medium resistivity" }, { "code": null, "e": 2930, "s": 2839, "text": "We can create a quick histogram using pandas without relying on importing other libraries." }, { "code": null, "e": 2967, "s": 2930, "text": "df['GR'].plot(kind='hist')plt.show()" }, { "code": null, "e": 3031, "s": 2967, "text": "We can also create the same histogram using matplotlib like so." }, { "code": null, "e": 3060, "s": 3031, "text": "plt.hist(df['GR'])plt.show()" }, { "code": null, "e": 3257, "s": 3060, "text": "This generates a very minimal plot. We can see that the values range from around 0 to 150, with a very small piece of data at 250 API. Each bin is around 25 API wide, which is quite a large range." }, { "code": null, "e": 3365, "s": 3257, "text": "We can control this by specifying a set number for the bins argument, in this example we will set it to 30." }, { "code": null, "e": 3403, "s": 3365, "text": "plt.hist(df['GR'], bins=30)plt.show()" }, { "code": null, "e": 3471, "s": 3403, "text": "Let’s tidy the plot up a little by adding edge colours to the bins." }, { "code": null, "e": 3528, "s": 3471, "text": "plt.hist(df['GR'], bins=30, edgecolor='black')plt.show()" }, { "code": null, "e": 3620, "s": 3528, "text": "When we do this, we can see that the bins just below 100 API, is in fact two separate bins." }, { "code": null, "e": 3718, "s": 3620, "text": "To tidy the plot up further, we can assign both an x and y label, and also set the x-axis limits." }, { "code": null, "e": 3892, "s": 3718, "text": "plt.hist(df['GR'], bins=30, color='red', alpha=0.5, edgecolor='black')plt.xlabel('Gamma Ray - API', fontsize=14)plt.ylabel('Frequency', fontsize=14)plt.xlim(0,200)plt.show()" }, { "code": null, "e": 4038, "s": 3892, "text": "In addition to the bars, we can also add in a kernel density estimation, which provides us with a line illustrating the distribution of the data." }, { "code": null, "e": 4272, "s": 4038, "text": "df['GR'].plot(kind='hist', bins=30, color='red', alpha=0.5, density=True, edgecolor='black')df['GR'].plot(kind='kde', color='black')plt.xlabel('Gamma Ray - API', fontsize=14)plt.ylabel('Density', fontsize=14)plt.xlim(0,200)plt.show()" }, { "code": null, "e": 4533, "s": 4272, "text": "When calculating clay and shale volumes as part of a petrophysical workflow, we often use the percentiles as our interpretation parameters. This reduces the influence of outliers or a small amount of data points that may represent a thin hot shale for example." }, { "code": null, "e": 4626, "s": 4533, "text": "We can calculated the key statsitics using built in pandas functions: mean() and quantile()." }, { "code": null, "e": 4776, "s": 4626, "text": "mean = df['GR'].mean()p5 = df['GR'].quantile(0.05)p95 = df['GR'].quantile(0.95)print(f'Mean: \\t {mean}')print(f'P05: \\t {p5}')print(f'P95: \\t {p95}')" }, { "code": null, "e": 4811, "s": 4776, "text": "This returns the following output." }, { "code": null, "e": 4877, "s": 4811, "text": "Mean: \t 71.98679770957146P05: \t 12.74656P95: \t 128.33267999999995" }, { "code": null, "e": 5057, "s": 4877, "text": "To get a better idea of where these points fall in relation to our data, we can add them onto the plot using axvline and passing in the calculated variables, a colour and a label." }, { "code": null, "e": 5401, "s": 5057, "text": "df['GR'].plot(kind='hist', bins=30, color='red', alpha=0.5, edgecolor='black')plt.xlabel('Gamma Ray', fontsize=14)plt.ylabel('Frequency', fontsize=14)plt.xlim(0,200)plt.axvline(mean, color='blue', label='mean')plt.axvline(p5, color='green', label='5th Percentile')plt.axvline(p95, color='purple', label='95th Percentile')plt.legend()plt.show()" }, { "code": null, "e": 5594, "s": 5401, "text": "In this short tutorial, we have covered the basics of how to display a well log curve as a histogram and customise to provide a plot that is suitable for including in reports and publications." }, { "code": null, "e": 5614, "s": 5594, "text": "Thanks for reading!" }, { "code": null, "e": 5826, "s": 5614, "text": "If you have found this article useful, please feel free to check out my other articles looking at various aspects of Python and well log data. You can also find my code used in this article and others at GitHub." }, { "code": null, "e": 5900, "s": 5826, "text": "If you want to get in touch you can find me on LinkedIn or at my website." } ]
JuMPing into Puzzle Solving with Linear Programming | by Sarah Eade | Towards Data Science
Linear programming (LP) is a powerful technique to solve optimization problems, and you will often see it applied to problems from airline scheduling, vehicle routing, to revenue management. In this post, I’d like to explore a more whimsical application — how can linear programming be used to solve a puzzle? The puzzle is similar to Sudoku, so I’m going to extend the well-known Sudoku LP formulation for this new brain teaser. I recommend that you understand that Sudoku solution first before proceeding since it will have some similar logic (here’s a medium post about it). This puzzle was introduced to me by a friend who speculated that it could be solved with LP. The problem was presented on Jane Street Puzzles, and you can read the description here. From just reading about the constraints, it seems pretty similar to Sudoku — there are constraints on number of occurrences, but also some other constraints regarding first/last appearance, the sum of values, etc. Can it be solved with LP? The answer is Yes, and let’s see how. After reading your problem and getting a strong grasp of the goal, you should start with defining the variables. What would the decision look like? Is it continuous, integer, binary? Does it have bounds? Technically this is a constraint but it may be helpful to think about this in the beginning so you don’t forget to add it later. For this puzzle, the decision is simply: what number should go into a given cell? My variable name is going to be x, it’s going to be binary, and it is going to be indexed by three values: v is the value of the number from 1 to 7 that we are considering r is the row index from 1 to 7 c is the column index from 1 to 7 In math notation, this is The resulting solution will then tell us which number should go into which cell. For instance, if the solution specifies x_{1, 1, 1}=1, then that means number 1 goes into cell at location (1, 1). If x_{3, 4, 7}=0, then that means number 3 does not go into cell at location (4, 7). We will have a solution when we know all of these 1s and 0s for each number and cell combination. This is going to create 7•7•7 = 343 binary variables. Binary variables will always be more difficult to solve than continuous-valued variables for LP problems. Fortunately this is a small number of variables nowadays, and much larger problems with hundreds of thousands of variables can be solved by solvers nowadays. You should have no problem solving this problem locally. This problem is unusual — there is no objective! Set it to a constant, such as 0. Our goal is just to find a solution that meets all constraints; there is no measure of one solution being better than another. As long as the result is feasible, we will have achieved the goal. Thus we don’t need an objective function. Here’s where the heavy-lifting comes in. Let’s tackle them one at a time. Each cell can only contain one number or it can be blank. For a given cell, if the sum of the binary variables for v=1,2,...7 equals zero, then I’ll interpret it as the cell is blank. We should use an inequality in the constraint to allow for these null cells, and set the upper threshold to 1 because we don’t want more than one number per cell. Number of occurrences of each value v (not including the null) must equal the value v. This ensures that the number of fives in the whole grid is five, the number of sixes is six, etc. We know the value of the number since it is equal to the index v, so that will be the right-hand-side of the constraint. Each row has 4 numbers. Also, each column has 4 numbers. So just sum over all the columns (rows) and all the possible values. This must be less 4 because there must be 4 numbers. The sum of numbers in each row should be 20. Also each column’s sum should be 20. This is similar to the constraint above except we need to multiply by the value of the number, v. Every 2x2 sub-square must contain at least one empty cell. Thus not every cell can be filled, so there should be 3 or less numbers in a sub-square. The result should have a connected region. This also means that a number should not be surrounded by nulls. This is achieved if we look at at the cells adjacent to a given location (think of drawing a box around a number). If the region is entirely full of nulls, then the sum of the binary variables for that border will be zero. In that case, we then want to force the center number to be null too in order to satisfy the rules. If the count of non-null values in the border is greater than zero, then a number in the center is allowed. The constraints need to be written depending on where they appear in the grid. For the points where we can draw a 3x3 box (see image below) around the cell, the following equation will apply This equation is modified to accommodate the remaining areas of the grid. For instance, for the cells in the top row, the equation will be modified for the rows to range from 1 to 2 (since there is no 0 row). The rest of the equations can be similarly modified for the first and last columns and the cells in the corner. The start of the row/column should start/end with a particular number. For the case of row 2 needs to start with 3, then it means that the first column in row 2 can be null or 3. After applying that, then if we move one-by-one across row 2, then a cell can only have a number if the cells to its left had a 3. The remaining start/end constraints follow a similar formulation. That’s it! Those are all the steps needed in order to define the problem. Great work and glad you’re still with me. Now, the next step is to code it up. I learned optimization in grad school where the Julia language was enthusiastically used. The packages you’ll need are GLPK and Julia for Mathematical Programming (JuMP) — hence the title of this article. It’s a terrific package; it’s very fast, intuitive to write LP problems, and trivial to switch between a variety of solvers. If you’re not familiar with Julia and JuMP, then I urge you to check it out. Even without understanding the language, the code should be understandable. I used Julia 1.1.1, JuMP 0.19.2, and GLPK 0.10.0 using GLPKusing JuMP# Set variable for number of rows/cols/numbersN = 7function solve_puzzle(start_grid::Array{Int64,2}, edge_constraints::Array{Int64,2}) model = Model(with_optimizer(GLPK.Optimizer, Presolve=0, OutputFlag=0)); # Since we don't care about the objective just set it to something arbitrary @objective(model, Min, 0);# Define variables which will be 7x7x7 matrix # Use integer instead of binary because I was having trouble fixing Binary values in step below @variable(model, 0 <= x[1:N, 1:N, 1:N] <= 1, integer=true);# Initialize values for idx in 1:size(start_grid)[1] v = start_grid[idx, 1] r = start_grid[idx, 2] c = start_grid[idx, 3] # Fix value to 1 fix(x[v, r, c], 1, force=true) end# Create the constraints # At most one value per cell for c in 1:N for r in 1:N @constraint(model, sum(x[v, r, c] for v in 1:N) <= 1) end end# The number of occurrences of a number should equal the value of that number for v in 1:N @constraint(model, sum(x[v, r, c] for r in 1:N for c in 1:N) == v) end# Each row has 4 non-null numbers for r in 1:N @constraint(model, sum(x[v, r, c] for c in 1:N for v in 1:N) == 4) end# Each column has 4 non-null numbers for c in 1:N @constraint(model, sum(x[v, r, c] for r in 1:N for v in 1:N) == 4) end# Each row numbers sums to 20 for r in 1:N @constraint(model, sum(v*x[v, r, c] for c in 1:N for v in 1:N) == 20) end # Each column numbers sums to 20 for c in 1:N @constraint(model, sum(v*x[v, r, c] for r in 1:N for v in 1:N) == 20) end# Every 2x2 subsquare must contain one or more empty square for p in 1:(N-1) for q in 1:(N-1) @constraint(model, sum(x[v, r, c] for r in p:(p+1) for c in q:(q+1) for v in 1:N) <= 3) end end# Connected region = no islands for c in 1:N for r in 1:N @constraint(model, 2*sum(x[v, r, c] for v in 1:N) <= sum(x[v, i, j] for v in 1:N for i in (r-1):(r+1) if i in 1:7 for j in (c-1):(c+1) if j in 1:7 )) end end# Edge constraints val_set = Set(1:N) # define all possible values for idx in 1:size(edge_constraints)[1] v = edge_constraints[idx, 1] # value k = edge_constraints[idx, 2] # affected row/col is_col = Bool(edge_constraints[idx, 3]) # row/col is_last = Bool(edge_constraints[idx, 4])v_prime = setdiff(Set(1:7), v)for j in 1:(N-1) for not_v in v_prime if is_col if is_last # last in column k must be v or null fix(x[not_v, 7, k], 0; force=true) # cell is non-null if the values after cell in column have number @constraint(model, x[not_v, j, k] <= sum(x[v, r, k] for r in (j+1):N )) else # first in column k must be v or null fix(x[not_v, 1, k], 0; force=true) # cell is non-null if values before cell in column have number @constraint(model, x[not_v, j+1, k] <= sum(x[v, r, k] for r in 1:j) ) end else if is_last # last in row k must be v or null fix(x[not_v, k, 7], 0; force=true) # cell is non-null if values after cell in row have number @constraint(model, x[not_v, k, j] <= sum(x[v, k, c] for c in (j+1):N )) else # first col in row k must be v or null fix(x[not_v, k, 1], 0; force=true) # cell is non-null if values before cell in row have number @constraint(model, x[not_v, k, j+1] <= sum(x[v, k, c] for c in 1:j) ) end end end end endoptimize!(model) # want to see the code 1 println(termination_status(model)) primal_status(model)# Create results results = zeros(N,N) for i in 1:N vals = reshape(value.(x[i,:,:]), N, N) multiplier = ones(N,N)*i results += multiplier.*vals end return results end To run it, just specify the edge constraints and starting grid values, and call the function. # Initialize starting values# column 1 specifies number, column 2 is the row number, column 3 is the column numbervalues = [7 1 2; 6 1 3; 6 2 4; 6 2 5; 5 3 1; 6 4 2; 4 4 6; 6 5 7; 4 6 3; 7 6 4; 7 7 5; 7 7 6]# Encode the first/end row/col constraints (counter-clockwise)# column 1 specifies the number# column 2 specifies the affected row/col# column 3 has values 0 for row and 1 for col# column 4 has values 0 for start and 1 for endstart_end_constraints = [3 2 0 0; 5 5 0 0; 1 7 0 0; 7 1 1 1; 2 2 1 1; 2 6 0 1; 4 3 0 1; 4 1 0 1; 7 7 1 0; 5 6 1 0];results = solve_puzzle(values, start_end_constraints) For those wanting the solution: Thanks for reading! I’ll try to monitor the comments for questions.
[ { "code": null, "e": 482, "s": 172, "text": "Linear programming (LP) is a powerful technique to solve optimization problems, and you will often see it applied to problems from airline scheduling, vehicle routing, to revenue management. In this post, I’d like to explore a more whimsical application — how can linear programming be used to solve a puzzle?" }, { "code": null, "e": 750, "s": 482, "text": "The puzzle is similar to Sudoku, so I’m going to extend the well-known Sudoku LP formulation for this new brain teaser. I recommend that you understand that Sudoku solution first before proceeding since it will have some similar logic (here’s a medium post about it)." }, { "code": null, "e": 1210, "s": 750, "text": "This puzzle was introduced to me by a friend who speculated that it could be solved with LP. The problem was presented on Jane Street Puzzles, and you can read the description here. From just reading about the constraints, it seems pretty similar to Sudoku — there are constraints on number of occurrences, but also some other constraints regarding first/last appearance, the sum of values, etc. Can it be solved with LP? The answer is Yes, and let’s see how." }, { "code": null, "e": 1543, "s": 1210, "text": "After reading your problem and getting a strong grasp of the goal, you should start with defining the variables. What would the decision look like? Is it continuous, integer, binary? Does it have bounds? Technically this is a constraint but it may be helpful to think about this in the beginning so you don’t forget to add it later." }, { "code": null, "e": 1625, "s": 1543, "text": "For this puzzle, the decision is simply: what number should go into a given cell?" }, { "code": null, "e": 1732, "s": 1625, "text": "My variable name is going to be x, it’s going to be binary, and it is going to be indexed by three values:" }, { "code": null, "e": 1797, "s": 1732, "text": "v is the value of the number from 1 to 7 that we are considering" }, { "code": null, "e": 1828, "s": 1797, "text": "r is the row index from 1 to 7" }, { "code": null, "e": 1862, "s": 1828, "text": "c is the column index from 1 to 7" }, { "code": null, "e": 1888, "s": 1862, "text": "In math notation, this is" }, { "code": null, "e": 2267, "s": 1888, "text": "The resulting solution will then tell us which number should go into which cell. For instance, if the solution specifies x_{1, 1, 1}=1, then that means number 1 goes into cell at location (1, 1). If x_{3, 4, 7}=0, then that means number 3 does not go into cell at location (4, 7). We will have a solution when we know all of these 1s and 0s for each number and cell combination." }, { "code": null, "e": 2642, "s": 2267, "text": "This is going to create 7•7•7 = 343 binary variables. Binary variables will always be more difficult to solve than continuous-valued variables for LP problems. Fortunately this is a small number of variables nowadays, and much larger problems with hundreds of thousands of variables can be solved by solvers nowadays. You should have no problem solving this problem locally." }, { "code": null, "e": 2960, "s": 2642, "text": "This problem is unusual — there is no objective! Set it to a constant, such as 0. Our goal is just to find a solution that meets all constraints; there is no measure of one solution being better than another. As long as the result is feasible, we will have achieved the goal. Thus we don’t need an objective function." }, { "code": null, "e": 3034, "s": 2960, "text": "Here’s where the heavy-lifting comes in. Let’s tackle them one at a time." }, { "code": null, "e": 3092, "s": 3034, "text": "Each cell can only contain one number or it can be blank." }, { "code": null, "e": 3381, "s": 3092, "text": "For a given cell, if the sum of the binary variables for v=1,2,...7 equals zero, then I’ll interpret it as the cell is blank. We should use an inequality in the constraint to allow for these null cells, and set the upper threshold to 1 because we don’t want more than one number per cell." }, { "code": null, "e": 3687, "s": 3381, "text": "Number of occurrences of each value v (not including the null) must equal the value v. This ensures that the number of fives in the whole grid is five, the number of sixes is six, etc. We know the value of the number since it is equal to the index v, so that will be the right-hand-side of the constraint." }, { "code": null, "e": 3866, "s": 3687, "text": "Each row has 4 numbers. Also, each column has 4 numbers. So just sum over all the columns (rows) and all the possible values. This must be less 4 because there must be 4 numbers." }, { "code": null, "e": 4046, "s": 3866, "text": "The sum of numbers in each row should be 20. Also each column’s sum should be 20. This is similar to the constraint above except we need to multiply by the value of the number, v." }, { "code": null, "e": 4194, "s": 4046, "text": "Every 2x2 sub-square must contain at least one empty cell. Thus not every cell can be filled, so there should be 3 or less numbers in a sub-square." }, { "code": null, "e": 4302, "s": 4194, "text": "The result should have a connected region. This also means that a number should not be surrounded by nulls." }, { "code": null, "e": 4733, "s": 4302, "text": "This is achieved if we look at at the cells adjacent to a given location (think of drawing a box around a number). If the region is entirely full of nulls, then the sum of the binary variables for that border will be zero. In that case, we then want to force the center number to be null too in order to satisfy the rules. If the count of non-null values in the border is greater than zero, then a number in the center is allowed." }, { "code": null, "e": 4924, "s": 4733, "text": "The constraints need to be written depending on where they appear in the grid. For the points where we can draw a 3x3 box (see image below) around the cell, the following equation will apply" }, { "code": null, "e": 5133, "s": 4924, "text": "This equation is modified to accommodate the remaining areas of the grid. For instance, for the cells in the top row, the equation will be modified for the rows to range from 1 to 2 (since there is no 0 row)." }, { "code": null, "e": 5245, "s": 5133, "text": "The rest of the equations can be similarly modified for the first and last columns and the cells in the corner." }, { "code": null, "e": 5555, "s": 5245, "text": "The start of the row/column should start/end with a particular number. For the case of row 2 needs to start with 3, then it means that the first column in row 2 can be null or 3. After applying that, then if we move one-by-one across row 2, then a cell can only have a number if the cells to its left had a 3." }, { "code": null, "e": 5621, "s": 5555, "text": "The remaining start/end constraints follow a similar formulation." }, { "code": null, "e": 5774, "s": 5621, "text": "That’s it! Those are all the steps needed in order to define the problem. Great work and glad you’re still with me. Now, the next step is to code it up." }, { "code": null, "e": 6306, "s": 5774, "text": "I learned optimization in grad school where the Julia language was enthusiastically used. The packages you’ll need are GLPK and Julia for Mathematical Programming (JuMP) — hence the title of this article. It’s a terrific package; it’s very fast, intuitive to write LP problems, and trivial to switch between a variety of solvers. If you’re not familiar with Julia and JuMP, then I urge you to check it out. Even without understanding the language, the code should be understandable. I used Julia 1.1.1, JuMP 0.19.2, and GLPK 0.10.0" }, { "code": null, "e": 10900, "s": 6306, "text": "using GLPKusing JuMP# Set variable for number of rows/cols/numbersN = 7function solve_puzzle(start_grid::Array{Int64,2}, edge_constraints::Array{Int64,2}) model = Model(with_optimizer(GLPK.Optimizer, Presolve=0, OutputFlag=0)); # Since we don't care about the objective just set it to something arbitrary @objective(model, Min, 0);# Define variables which will be 7x7x7 matrix # Use integer instead of binary because I was having trouble fixing Binary values in step below @variable(model, 0 <= x[1:N, 1:N, 1:N] <= 1, integer=true);# Initialize values for idx in 1:size(start_grid)[1] v = start_grid[idx, 1] r = start_grid[idx, 2] c = start_grid[idx, 3] # Fix value to 1 fix(x[v, r, c], 1, force=true) end# Create the constraints # At most one value per cell for c in 1:N for r in 1:N @constraint(model, sum(x[v, r, c] for v in 1:N) <= 1) end end# The number of occurrences of a number should equal the value of that number for v in 1:N @constraint(model, sum(x[v, r, c] for r in 1:N for c in 1:N) == v) end# Each row has 4 non-null numbers for r in 1:N @constraint(model, sum(x[v, r, c] for c in 1:N for v in 1:N) == 4) end# Each column has 4 non-null numbers for c in 1:N @constraint(model, sum(x[v, r, c] for r in 1:N for v in 1:N) == 4) end# Each row numbers sums to 20 for r in 1:N @constraint(model, sum(v*x[v, r, c] for c in 1:N for v in 1:N) == 20) end # Each column numbers sums to 20 for c in 1:N @constraint(model, sum(v*x[v, r, c] for r in 1:N for v in 1:N) == 20) end# Every 2x2 subsquare must contain one or more empty square for p in 1:(N-1) for q in 1:(N-1) @constraint(model, sum(x[v, r, c] for r in p:(p+1) for c in q:(q+1) for v in 1:N) <= 3) end end# Connected region = no islands for c in 1:N for r in 1:N @constraint(model, 2*sum(x[v, r, c] for v in 1:N) <= sum(x[v, i, j] for v in 1:N for i in (r-1):(r+1) if i in 1:7 for j in (c-1):(c+1) if j in 1:7 )) end end# Edge constraints val_set = Set(1:N) # define all possible values for idx in 1:size(edge_constraints)[1] v = edge_constraints[idx, 1] # value k = edge_constraints[idx, 2] # affected row/col is_col = Bool(edge_constraints[idx, 3]) # row/col is_last = Bool(edge_constraints[idx, 4])v_prime = setdiff(Set(1:7), v)for j in 1:(N-1) for not_v in v_prime if is_col if is_last # last in column k must be v or null fix(x[not_v, 7, k], 0; force=true) # cell is non-null if the values after cell in column have number @constraint(model, x[not_v, j, k] <= sum(x[v, r, k] for r in (j+1):N )) else # first in column k must be v or null fix(x[not_v, 1, k], 0; force=true) # cell is non-null if values before cell in column have number @constraint(model, x[not_v, j+1, k] <= sum(x[v, r, k] for r in 1:j) ) end else if is_last # last in row k must be v or null fix(x[not_v, k, 7], 0; force=true) # cell is non-null if values after cell in row have number @constraint(model, x[not_v, k, j] <= sum(x[v, k, c] for c in (j+1):N )) else # first col in row k must be v or null fix(x[not_v, k, 1], 0; force=true) # cell is non-null if values before cell in row have number @constraint(model, x[not_v, k, j+1] <= sum(x[v, k, c] for c in 1:j) ) end end end end endoptimize!(model) # want to see the code 1 println(termination_status(model)) primal_status(model)# Create results results = zeros(N,N) for i in 1:N vals = reshape(value.(x[i,:,:]), N, N) multiplier = ones(N,N)*i results += multiplier.*vals end return results end" }, { "code": null, "e": 10994, "s": 10900, "text": "To run it, just specify the edge constraints and starting grid values, and call the function." }, { "code": null, "e": 11911, "s": 10994, "text": "# Initialize starting values# column 1 specifies number, column 2 is the row number, column 3 is the column numbervalues = [7 1 2; 6 1 3; 6 2 4; 6 2 5; 5 3 1; 6 4 2; 4 4 6; 6 5 7; 4 6 3; 7 6 4; 7 7 5; 7 7 6]# Encode the first/end row/col constraints (counter-clockwise)# column 1 specifies the number# column 2 specifies the affected row/col# column 3 has values 0 for row and 1 for col# column 4 has values 0 for start and 1 for endstart_end_constraints = [3 2 0 0; 5 5 0 0; 1 7 0 0; 7 1 1 1; 2 2 1 1; 2 6 0 1; 4 3 0 1; 4 1 0 1; 7 7 1 0; 5 6 1 0];results = solve_puzzle(values, start_end_constraints)" }, { "code": null, "e": 11943, "s": 11911, "text": "For those wanting the solution:" } ]
JavaScript Array keys() Method - GeeksforGeeks
23 Jun, 2020 Below is the example of the Array keys() method. Example:<script> // Taking input as an array A // containing some elements. var A = [ 5, 6, 10 ]; // array.keys() method is called var iterator = A.keys(); // printing index array using the iterator for (let key of iterator) { document.write(key + ' '); }</script> <script> // Taking input as an array A // containing some elements. var A = [ 5, 6, 10 ]; // array.keys() method is called var iterator = A.keys(); // printing index array using the iterator for (let key of iterator) { document.write(key + ' '); }</script> Output:0 1 2 0 1 2 The array.keys() method is used to return a new array iterator which contains the keys for each index in the given input array. Syntax: array.keys() Parameters: This method does not accept any parameters. Return Values: It returns a new array iterator. Below example illustrate the Array keys() method in JavaScript: Example:var A = [ 'gfg', 'geeks', 'cse', 'geekpro' ]; var iterator = A.keys(document.write(key + ' '));Output:0 1 2 3 var A = [ 'gfg', 'geeks', 'cse', 'geekpro' ]; var iterator = A.keys(document.write(key + ' ')); Output: 0 1 2 3 Code for the above method is provided below:Program 1: <script> // Taking input as an array A // containing some elements. var A = [ 'gfg', 'geeks', 'cse', 'geekpro' ]; // array.keys() method is called var iterator = A.keys(); // printing index array using the iterator for (let key of iterator) { document.write(key + ' '); }</script> Output: 0 1 2 3 Program 2: <script> // Taking input as an array A // containing some elements var A = [ 'gfg', 'geeks', 'cse', 'geekpro', '', 1, 2 ]; // array.keys() method is called var iterator = A.keys(); // Printing index array using the iterator for (let key of iterator) { document.write(key + ' '); }</script> Output: 0 1 2 3 4 5 6 Supported Browsers: The browsers supported by JavaScript Array keys() method are listed below: Google Chrome 38.0 Microsoft Edge 12.0 Mozilla Firefox 28.0 Safari 8.0 Opera 25.0 javascript-array JavaScript-Methods JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request How to get character array from string in JavaScript? How to remove duplicate elements from JavaScript Array ? How to get selected value in dropdown list using JavaScript ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25246, "s": 25218, "text": "\n23 Jun, 2020" }, { "code": null, "e": 25295, "s": 25246, "text": "Below is the example of the Array keys() method." }, { "code": null, "e": 25586, "s": 25295, "text": "Example:<script> // Taking input as an array A // containing some elements. var A = [ 5, 6, 10 ]; // array.keys() method is called var iterator = A.keys(); // printing index array using the iterator for (let key of iterator) { document.write(key + ' '); }</script>" }, { "code": "<script> // Taking input as an array A // containing some elements. var A = [ 5, 6, 10 ]; // array.keys() method is called var iterator = A.keys(); // printing index array using the iterator for (let key of iterator) { document.write(key + ' '); }</script>", "e": 25869, "s": 25586, "text": null }, { "code": null, "e": 25882, "s": 25869, "text": "Output:0 1 2" }, { "code": null, "e": 25888, "s": 25882, "text": "0 1 2" }, { "code": null, "e": 26016, "s": 25888, "text": "The array.keys() method is used to return a new array iterator which contains the keys for each index in the given input array." }, { "code": null, "e": 26024, "s": 26016, "text": "Syntax:" }, { "code": null, "e": 26037, "s": 26024, "text": "array.keys()" }, { "code": null, "e": 26093, "s": 26037, "text": "Parameters: This method does not accept any parameters." }, { "code": null, "e": 26141, "s": 26093, "text": "Return Values: It returns a new array iterator." }, { "code": null, "e": 26205, "s": 26141, "text": "Below example illustrate the Array keys() method in JavaScript:" }, { "code": null, "e": 26323, "s": 26205, "text": "Example:var A = [ 'gfg', 'geeks', 'cse', 'geekpro' ];\nvar iterator = A.keys(document.write(key + ' '));Output:0 1 2 3" }, { "code": null, "e": 26419, "s": 26323, "text": "var A = [ 'gfg', 'geeks', 'cse', 'geekpro' ];\nvar iterator = A.keys(document.write(key + ' '));" }, { "code": null, "e": 26427, "s": 26419, "text": "Output:" }, { "code": null, "e": 26435, "s": 26427, "text": "0 1 2 3" }, { "code": null, "e": 26490, "s": 26435, "text": "Code for the above method is provided below:Program 1:" }, { "code": "<script> // Taking input as an array A // containing some elements. var A = [ 'gfg', 'geeks', 'cse', 'geekpro' ]; // array.keys() method is called var iterator = A.keys(); // printing index array using the iterator for (let key of iterator) { document.write(key + ' '); }</script>", "e": 26797, "s": 26490, "text": null }, { "code": null, "e": 26805, "s": 26797, "text": "Output:" }, { "code": null, "e": 26814, "s": 26805, "text": "0 1 2 3 " }, { "code": null, "e": 26825, "s": 26814, "text": "Program 2:" }, { "code": "<script> // Taking input as an array A // containing some elements var A = [ 'gfg', 'geeks', 'cse', 'geekpro', '', 1, 2 ]; // array.keys() method is called var iterator = A.keys(); // Printing index array using the iterator for (let key of iterator) { document.write(key + ' '); }</script>", "e": 27132, "s": 26825, "text": null }, { "code": null, "e": 27140, "s": 27132, "text": "Output:" }, { "code": null, "e": 27155, "s": 27140, "text": "0 1 2 3 4 5 6 " }, { "code": null, "e": 27250, "s": 27155, "text": "Supported Browsers: The browsers supported by JavaScript Array keys() method are listed below:" }, { "code": null, "e": 27269, "s": 27250, "text": "Google Chrome 38.0" }, { "code": null, "e": 27289, "s": 27269, "text": "Microsoft Edge 12.0" }, { "code": null, "e": 27310, "s": 27289, "text": "Mozilla Firefox 28.0" }, { "code": null, "e": 27321, "s": 27310, "text": "Safari 8.0" }, { "code": null, "e": 27332, "s": 27321, "text": "Opera 25.0" }, { "code": null, "e": 27349, "s": 27332, "text": "javascript-array" }, { "code": null, "e": 27368, "s": 27349, "text": "JavaScript-Methods" }, { "code": null, "e": 27379, "s": 27368, "text": "JavaScript" }, { "code": null, "e": 27396, "s": 27379, "text": "Web Technologies" }, { "code": null, "e": 27494, "s": 27396, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27503, "s": 27494, "text": "Comments" }, { "code": null, "e": 27516, "s": 27503, "text": "Old Comments" }, { "code": null, "e": 27577, "s": 27516, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27618, "s": 27577, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 27672, "s": 27618, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 27729, "s": 27672, "text": "How to remove duplicate elements from JavaScript Array ?" }, { "code": null, "e": 27791, "s": 27729, "text": "How to get selected value in dropdown list using JavaScript ?" }, { "code": null, "e": 27833, "s": 27791, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27866, "s": 27833, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27928, "s": 27866, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27971, "s": 27928, "text": "How to fetch data from an API in ReactJS ?" } ]
SASS | @forward rule - GeeksforGeeks
21 Jun, 2020 The @forward rule processes the Sass stylesheets and makes their functions, mixins, and variables available in the cases when the stylesheet is loaded using @use rule. Organizing Sass libraries across many files are made possible, along with providing users to process a single entry point file. Syntax: @forward "<url>" The above code loads the module available at the given URL. It makes the public members of the loaded module available to users of the module as though they were defined directly in the module. Those members aren’t available in the module if needed, @use rule is also likely to be used. It only processes the module once. If both @forward and @use are written for the same module in the same file, always write @forward first. Through this, if the users want to configure the forwarded module, that configuration will be applied to @forward before @use processes it without any configuration.Example: // gfg/_list.css@mixin geeks font-family: times new roman font-size: 4px padding: 2px // geeksforgeeks.scss@forward "gfg/list" // style.scss@use "geeksforgeeks"gfg1 @include geeksforgeeks.geeks This would result in the following CSS output: gfg1 { font-family: times new roman font-size: 4px padding: 2px } Adding Prefix:Sometimes the names may not be correct outside of the module that they’re defined in, for this reason, @forward has the option of adding an extra prefix to all the members that it points to.Syntax: @forward "<url>" as <prefix>-* This adds the given prefix to the beginning of each mixin, function, and variable name pointed by the module.Example: // gfg/_list.css@mixin forgeeks font-family: times new roman font-size: 4px padding: 2px // geeks.scss@forward "gfg/list" as geeks* // style.scss@use "geeksforgeeks"gfg1 @include geeks.geeksforgeeks This would result in the following CSS output: gfg1 { font-family: times new roman font-size: 4px padding: 2px } Configuring Modules:Processing a module with configuration is also possible using @forward rule. @forward rule’s configuration can also use !default flag in its configuration. This allows the module to change the defaults of the upstream stylesheet while also allowing downstream stylesheets to override them.Example: // _gfg.sass$green: #000 !default$border-radius: 2px !default$box-shadow: 0 2px 1px rgba($green, 1) !default geeks border-radius: $border-radius box-shadow: $box-shadow // _geeksforgeeks.sass@forward 'gfg' with ($green: #222 !default, $border-radius: 4px !default) // style.sass@use 'geeksforgeeks' with ($green: #333) This would result in the following CSS output: geeks { border-radius: 4px; box-shadow: 0 2px 1px rgba(51, 51, 51, 1); } SASS CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to create footer to stay at the bottom of a Web page? Types of CSS (Cascading Style Sheet) Create a Responsive Navbar using ReactJS Design a web page using HTML and CSS How to position a div at the bottom of its container using CSS? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript
[ { "code": null, "e": 23899, "s": 23871, "text": "\n21 Jun, 2020" }, { "code": null, "e": 24195, "s": 23899, "text": "The @forward rule processes the Sass stylesheets and makes their functions, mixins, and variables available in the cases when the stylesheet is loaded using @use rule. Organizing Sass libraries across many files are made possible, along with providing users to process a single entry point file." }, { "code": null, "e": 24203, "s": 24195, "text": "Syntax:" }, { "code": "@forward \"<url>\"", "e": 24220, "s": 24203, "text": null }, { "code": null, "e": 24821, "s": 24220, "text": "The above code loads the module available at the given URL. It makes the public members of the loaded module available to users of the module as though they were defined directly in the module. Those members aren’t available in the module if needed, @use rule is also likely to be used. It only processes the module once. If both @forward and @use are written for the same module in the same file, always write @forward first. Through this, if the users want to configure the forwarded module, that configuration will be applied to @forward before @use processes it without any configuration.Example:" }, { "code": "// gfg/_list.css@mixin geeks font-family: times new roman font-size: 4px padding: 2px // geeksforgeeks.scss@forward \"gfg/list\" // style.scss@use \"geeksforgeeks\"gfg1 @include geeksforgeeks.geeks", "e": 25027, "s": 24821, "text": null }, { "code": null, "e": 25074, "s": 25027, "text": "This would result in the following CSS output:" }, { "code": null, "e": 25147, "s": 25074, "text": "gfg1 {\n font-family: times new roman\n font-size: 4px\n padding: 2px\n}\n" }, { "code": null, "e": 25359, "s": 25147, "text": "Adding Prefix:Sometimes the names may not be correct outside of the module that they’re defined in, for this reason, @forward has the option of adding an extra prefix to all the members that it points to.Syntax:" }, { "code": "@forward \"<url>\" as <prefix>-*", "e": 25390, "s": 25359, "text": null }, { "code": null, "e": 25508, "s": 25390, "text": "This adds the given prefix to the beginning of each mixin, function, and variable name pointed by the module.Example:" }, { "code": "// gfg/_list.css@mixin forgeeks font-family: times new roman font-size: 4px padding: 2px // geeks.scss@forward \"gfg/list\" as geeks* // style.scss@use \"geeksforgeeks\"gfg1 @include geeks.geeksforgeeks", "e": 25718, "s": 25508, "text": null }, { "code": null, "e": 25765, "s": 25718, "text": "This would result in the following CSS output:" }, { "code": null, "e": 25838, "s": 25765, "text": "gfg1 {\n font-family: times new roman\n font-size: 4px\n padding: 2px\n}\n" }, { "code": null, "e": 26156, "s": 25838, "text": "Configuring Modules:Processing a module with configuration is also possible using @forward rule. @forward rule’s configuration can also use !default flag in its configuration. This allows the module to change the defaults of the upstream stylesheet while also allowing downstream stylesheets to override them.Example:" }, { "code": "// _gfg.sass$green: #000 !default$border-radius: 2px !default$box-shadow: 0 2px 1px rgba($green, 1) !default geeks border-radius: $border-radius box-shadow: $box-shadow // _geeksforgeeks.sass@forward 'gfg' with ($green: #222 !default, $border-radius: 4px !default) // style.sass@use 'geeksforgeeks' with ($green: #333)", "e": 26498, "s": 26156, "text": null }, { "code": null, "e": 26545, "s": 26498, "text": "This would result in the following CSS output:" }, { "code": null, "e": 26623, "s": 26545, "text": "geeks {\n border-radius: 4px;\n box-shadow: 0 2px 1px rgba(51, 51, 51, 1);\n}\n" }, { "code": null, "e": 26628, "s": 26623, "text": "SASS" }, { "code": null, "e": 26632, "s": 26628, "text": "CSS" }, { "code": null, "e": 26649, "s": 26632, "text": "Web Technologies" }, { "code": null, "e": 26747, "s": 26649, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26756, "s": 26747, "text": "Comments" }, { "code": null, "e": 26769, "s": 26756, "text": "Old Comments" }, { "code": null, "e": 26827, "s": 26769, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 26864, "s": 26827, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 26905, "s": 26864, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 26942, "s": 26905, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 27006, "s": 26942, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 27062, "s": 27006, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 27095, "s": 27062, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27138, "s": 27095, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27199, "s": 27138, "text": "Difference between var, let and const keywords in JavaScript" } ]
How to increment a field in MongoDB?
To increment a field in MongoDB, you can use $inc operator. Let us first create a collection with documents − > db.incrementDemo.insertOne({"PlayerScore":100}); { "acknowledged" : true, "insertedId" : ObjectId("5cc81cdd8f9e6ff3eb0ce44e") } > db.incrementDemo.insertOne({"PlayerScore":290}); { "acknowledged" : true, "insertedId" : ObjectId("5cc81ce28f9e6ff3eb0ce44f") } > db.incrementDemo.insertOne({"PlayerScore":560}); { "acknowledged" : true, "insertedId" : ObjectId("5cc81ce68f9e6ff3eb0ce450") } Following is the query to display all documents from a collection with the help of find() method − > db.incrementDemo.find().pretty(); This will produce the following output − { "_id" : ObjectId("5cc81cdd8f9e6ff3eb0ce44e"), "PlayerScore" : 100 } { "_id" : ObjectId("5cc81ce28f9e6ff3eb0ce44f"), "PlayerScore" : 290 } { "_id" : ObjectId("5cc81ce68f9e6ff3eb0ce450"), "PlayerScore" : 560 } Following is the query to increment a field in MongoDB − > db.incrementDemo.update({ _id:ObjectId("5cc81ce28f9e6ff3eb0ce44f") },{ $inc: {"PlayerScore":10 }}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) In the above query, I have incremented the value 290 with value 10 − > db.incrementDemo.find().pretty(); This will produce the following output − { "_id" : ObjectId("5cc81cdd8f9e6ff3eb0ce44e"), "PlayerScore" : 100 } { "_id" : ObjectId("5cc81ce28f9e6ff3eb0ce44f"), "PlayerScore" : 300 } { "_id" : ObjectId("5cc81ce68f9e6ff3eb0ce450"), "PlayerScore" : 560 }
[ { "code": null, "e": 1172, "s": 1062, "text": "To increment a field in MongoDB, you can use $inc operator. Let us first create a collection with documents −" }, { "code": null, "e": 1580, "s": 1172, "text": "> db.incrementDemo.insertOne({\"PlayerScore\":100});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cc81cdd8f9e6ff3eb0ce44e\")\n}\n> db.incrementDemo.insertOne({\"PlayerScore\":290});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cc81ce28f9e6ff3eb0ce44f\")\n}\n> db.incrementDemo.insertOne({\"PlayerScore\":560});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cc81ce68f9e6ff3eb0ce450\")\n}" }, { "code": null, "e": 1679, "s": 1580, "text": "Following is the query to display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1715, "s": 1679, "text": "> db.incrementDemo.find().pretty();" }, { "code": null, "e": 1756, "s": 1715, "text": "This will produce the following output −" }, { "code": null, "e": 1966, "s": 1756, "text": "{ \"_id\" : ObjectId(\"5cc81cdd8f9e6ff3eb0ce44e\"), \"PlayerScore\" : 100 }\n{ \"_id\" : ObjectId(\"5cc81ce28f9e6ff3eb0ce44f\"), \"PlayerScore\" : 290 }\n{ \"_id\" : ObjectId(\"5cc81ce68f9e6ff3eb0ce450\"), \"PlayerScore\" : 560 }" }, { "code": null, "e": 2023, "s": 1966, "text": "Following is the query to increment a field in MongoDB −" }, { "code": null, "e": 2191, "s": 2023, "text": "> db.incrementDemo.update({ _id:ObjectId(\"5cc81ce28f9e6ff3eb0ce44f\") },{ $inc: {\"PlayerScore\":10 }});\nWriteResult({ \"nMatched\" : 1, \"nUpserted\" : 0, \"nModified\" : 1 })" }, { "code": null, "e": 2260, "s": 2191, "text": "In the above query, I have incremented the value 290 with value 10 −" }, { "code": null, "e": 2296, "s": 2260, "text": "> db.incrementDemo.find().pretty();" }, { "code": null, "e": 2337, "s": 2296, "text": "This will produce the following output −" }, { "code": null, "e": 2547, "s": 2337, "text": "{ \"_id\" : ObjectId(\"5cc81cdd8f9e6ff3eb0ce44e\"), \"PlayerScore\" : 100 }\n{ \"_id\" : ObjectId(\"5cc81ce28f9e6ff3eb0ce44f\"), \"PlayerScore\" : 300 }\n{ \"_id\" : ObjectId(\"5cc81ce68f9e6ff3eb0ce450\"), \"PlayerScore\" : 560 }" } ]
AWX - Automate AWS services - GeeksforGeeks
15 Sep, 2021 In this article, we will look into the process of Automating AWS services using the AWX, a VM provided by Ansible Tower. Ansible Tower is a simple IT automation engine that automates cloud provisioning, configuration, deployment, and orchestration. AWX provides a web-based user interface, REST API, and task engine built on top of Ansible. It is the upstream project for Ansible Tower. Install AWX. You must have an AWS free tier account, a user in IAM services having enough permissions to create a VPC, Subnet, IGW, RouteTables, EC2 Instance, and also have an Access Key ID and Secret Access Key. Also, create a key-pair (key) in the region where we want to launch these services. Since we are not using Elastic IP services so doing this job costs nothing. Now follow the below steps to automate AWS services using AWX: Step 1: Add a credential in the AWX dashboard. Step 2:Create a new project directory (e.g. AWS) inside /var/lib/awx/projects/ on the host where AWX is running. In this example, AWX is running on Docker containers, managed using docker-compose. Therefore, create this directory on the same host where the AWX is running [root@localhost ~]# mkdir /var/lib/awx/projects/AWS Step 3: Create a new playbook inside the project we had created earlier. (e.g. AWS) [root@localhost ~]# cat << EOF >> /var/lib/awx/projects/AWS/playbook.yml --- - name: "Run the playbook for AWS resources provisioning." hosts: localhost vars: aws_region: us-east-1 tasks: - name: "Create VPC with cidr block" ec2_vpc_net: name: "awx_vpc" cidr_block: 10.10.0.0/16 region: "{{ aws_region }}" tags: module: ec2_vpc_net this: works tenancy: default register: awx_vpc - name: "Create Internet Gateway and Associate it with above VPC" ec2_vpc_igw: vpc_id: "{{ awx_vpc.vpc.id }}" region: "{{ aws_region }}" state: present register: awx_igw - name: "Create a subnet in the above VPC" ec2_vpc_subnet: state: present vpc_id: "{{ awx_vpc.vpc.id }}" cidr: 10.10.0.0/20 region: "{{ aws_region }}" tags: Name: "EC2 Instance Subnet" register: awx_subnet - name: "Create Route Table for the public Subnet" ec2_vpc_route_table: vpc_id: "{{ awx_vpc.vpc.id }}" region: "{{ aws_region }}" tags: Name: Public subnets: - "{{ awx_subnet.subnet.id }}" routes: - dest: 0.0.0.0/0 gateway_id: "{{ awx_igw.gateway_id }}" register: awx_public_route_table - name: "Create Security Group rules for EC2 Instance" ec2_group: name: awx_sg description: "sg for allowing ssh connections" vpc_id: "{{ awx_vpc.vpc.id }}" region: "{{ aws_region }}" rules: - proto: tcp ports: - 22 cidr_ip: 0.0.0.0/0 rule_desc: allow all connections on port 22 - name: "Provisioning of a RHEL8 EC2 Instance" ec2: region: "{{ aws_region }}" key_name: aws-awk-key-us-east-1 instance_type: t2.micro image: ami-098f16afa9edf40be wait: yes group: awx_sg count: 1 vpc_subnet_id: "{{ awx_subnet.subnet.id }}" assign_public_ip: yes register: awx_instance - name: "Debug task to show the public IP of RHEL8 EC2 Instance" debug: msg: "Public IP of the RHEL8 Instance is {{ awx_instance.instances[0].public_ip }}" All the modules that are used in the above playbook have documentation available. Modules used in the above playbook: ec2_vpc_net ec2_vpc_igw ec2_vpc_subnet ec2_vpc_route_table ec2_vpc_route_table ec2_group, ec2 Step 4: Create a new project “AWS” from the AWX dashboard. Step 5: Create a new template. Step 6: Start a job using this template. On running this job in the Debug ( verbosity ), so check the output whether it is failed or succeeded. If failed then run the failed job again. The last debug message we have used to display the public IP that is assigned to the EC2 instance. Final verification, go to AWS Console, and the region where you had launched the ec2 instance and check if the instance is running or not. Step 7: We can also take the help of AWS Dynamic Inventories to see the IP of newly created hosts in the AWS region we had chosen earlier. First, we have to add an inventory in the AWX. After creating the inventory, go to the SOURCES option and Create a new SOURCE. Here we require our AWS region and the credentials that we had used to launch the ec2 instances. Now sync from the SOURCE that we had created in the above step. As the sync process gets completed, we can discover the new hosts in the host’s section of the inventory. sweetyty Advanced Computer Subject Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Copying Files to and from Docker Containers Principal Component Analysis with Python ML | Stochastic Gradient Descent (SGD) Different Types of Clustering Algorithm Fuzzy Logic | Introduction Sed Command in Linux/Unix with examples AWK command in Unix/Linux with examples grep command in Unix/Linux cut command in Linux with examples TCP Server-Client implementation in C
[ { "code": null, "e": 24228, "s": 24200, "text": "\n15 Sep, 2021" }, { "code": null, "e": 24616, "s": 24228, "text": "In this article, we will look into the process of Automating AWS services using the AWX, a VM provided by Ansible Tower. Ansible Tower is a simple IT automation engine that automates cloud provisioning, configuration, deployment, and orchestration. AWX provides a web-based user interface, REST API, and task engine built on top of Ansible. It is the upstream project for Ansible Tower." }, { "code": null, "e": 24629, "s": 24616, "text": "Install AWX." }, { "code": null, "e": 24829, "s": 24629, "text": "You must have an AWS free tier account, a user in IAM services having enough permissions to create a VPC, Subnet, IGW, RouteTables, EC2 Instance, and also have an Access Key ID and Secret Access Key." }, { "code": null, "e": 24989, "s": 24829, "text": "Also, create a key-pair (key) in the region where we want to launch these services. Since we are not using Elastic IP services so doing this job costs nothing." }, { "code": null, "e": 25052, "s": 24989, "text": "Now follow the below steps to automate AWS services using AWX:" }, { "code": null, "e": 25099, "s": 25052, "text": "Step 1: Add a credential in the AWX dashboard." }, { "code": null, "e": 25371, "s": 25099, "text": "Step 2:Create a new project directory (e.g. AWS) inside /var/lib/awx/projects/ on the host where AWX is running. In this example, AWX is running on Docker containers, managed using docker-compose. Therefore, create this directory on the same host where the AWX is running" }, { "code": null, "e": 25423, "s": 25371, "text": "[root@localhost ~]# mkdir /var/lib/awx/projects/AWS" }, { "code": null, "e": 25507, "s": 25423, "text": "Step 3: Create a new playbook inside the project we had created earlier. (e.g. AWS)" }, { "code": null, "e": 27792, "s": 25507, "text": "[root@localhost ~]# cat << EOF >> /var/lib/awx/projects/AWS/playbook.yml\n\n---\n- name: \"Run the playbook for AWS resources provisioning.\"\n hosts: localhost\n vars:\n aws_region: us-east-1\n tasks:\n - name: \"Create VPC with cidr block\"\n ec2_vpc_net:\n name: \"awx_vpc\"\n cidr_block: 10.10.0.0/16\n region: \"{{ aws_region }}\"\n tags:\n module: ec2_vpc_net\n this: works\n tenancy: default\n register: awx_vpc\n \n - name: \"Create Internet Gateway and Associate it with above VPC\"\n ec2_vpc_igw:\n vpc_id: \"{{ awx_vpc.vpc.id }}\"\n region: \"{{ aws_region }}\"\n state: present\n register: awx_igw\n\n\n - name: \"Create a subnet in the above VPC\"\n ec2_vpc_subnet:\n state: present\n vpc_id: \"{{ awx_vpc.vpc.id }}\"\n cidr: 10.10.0.0/20\n region: \"{{ aws_region }}\"\n tags:\n Name: \"EC2 Instance Subnet\"\n register: awx_subnet\n\n\n - name: \"Create Route Table for the public Subnet\"\n ec2_vpc_route_table:\n vpc_id: \"{{ awx_vpc.vpc.id }}\"\n region: \"{{ aws_region }}\"\n tags:\n Name: Public\n subnets:\n - \"{{ awx_subnet.subnet.id }}\"\n routes:\n - dest: 0.0.0.0/0\n gateway_id: \"{{ awx_igw.gateway_id }}\"\n register: awx_public_route_table\n\n\n - name: \"Create Security Group rules for EC2 Instance\"\n ec2_group:\n name: awx_sg\n description: \"sg for allowing ssh connections\"\n vpc_id: \"{{ awx_vpc.vpc.id }}\"\n region: \"{{ aws_region }}\"\n rules:\n - proto: tcp\n ports:\n - 22\n cidr_ip: 0.0.0.0/0\n rule_desc: allow all connections on port 22\n\n\n - name: \"Provisioning of a RHEL8 EC2 Instance\"\n ec2:\n region: \"{{ aws_region }}\"\n key_name: aws-awk-key-us-east-1\n instance_type: t2.micro\n image: ami-098f16afa9edf40be\n wait: yes\n group: awx_sg\n count: 1\n vpc_subnet_id: \"{{ awx_subnet.subnet.id }}\"\n assign_public_ip: yes\n register: awx_instance\n\n\n - name: \"Debug task to show the public IP of RHEL8 EC2 Instance\"\n debug:\n msg: \"Public IP of the RHEL8 Instance is {{ awx_instance.instances[0].public_ip }}\"" }, { "code": null, "e": 27910, "s": 27792, "text": "All the modules that are used in the above playbook have documentation available. Modules used in the above playbook:" }, { "code": null, "e": 27922, "s": 27910, "text": "ec2_vpc_net" }, { "code": null, "e": 27934, "s": 27922, "text": "ec2_vpc_igw" }, { "code": null, "e": 27949, "s": 27934, "text": "ec2_vpc_subnet" }, { "code": null, "e": 27969, "s": 27949, "text": "ec2_vpc_route_table" }, { "code": null, "e": 27989, "s": 27969, "text": "ec2_vpc_route_table" }, { "code": null, "e": 28004, "s": 27989, "text": "ec2_group, ec2" }, { "code": null, "e": 28063, "s": 28004, "text": "Step 4: Create a new project “AWS” from the AWX dashboard." }, { "code": null, "e": 28094, "s": 28063, "text": "Step 5: Create a new template." }, { "code": null, "e": 28135, "s": 28094, "text": "Step 6: Start a job using this template." }, { "code": null, "e": 28378, "s": 28135, "text": "On running this job in the Debug ( verbosity ), so check the output whether it is failed or succeeded. If failed then run the failed job again. The last debug message we have used to display the public IP that is assigned to the EC2 instance." }, { "code": null, "e": 28517, "s": 28378, "text": "Final verification, go to AWS Console, and the region where you had launched the ec2 instance and check if the instance is running or not." }, { "code": null, "e": 28703, "s": 28517, "text": "Step 7: We can also take the help of AWS Dynamic Inventories to see the IP of newly created hosts in the AWS region we had chosen earlier. First, we have to add an inventory in the AWX." }, { "code": null, "e": 28880, "s": 28703, "text": "After creating the inventory, go to the SOURCES option and Create a new SOURCE. Here we require our AWS region and the credentials that we had used to launch the ec2 instances." }, { "code": null, "e": 28944, "s": 28880, "text": "Now sync from the SOURCE that we had created in the above step." }, { "code": null, "e": 29050, "s": 28944, "text": "As the sync process gets completed, we can discover the new hosts in the host’s section of the inventory." }, { "code": null, "e": 29059, "s": 29050, "text": "sweetyty" }, { "code": null, "e": 29085, "s": 29059, "text": "Advanced Computer Subject" }, { "code": null, "e": 29096, "s": 29085, "text": "Linux-Unix" }, { "code": null, "e": 29194, "s": 29096, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29203, "s": 29194, "text": "Comments" }, { "code": null, "e": 29216, "s": 29203, "text": "Old Comments" }, { "code": null, "e": 29260, "s": 29216, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 29301, "s": 29260, "text": "Principal Component Analysis with Python" }, { "code": null, "e": 29340, "s": 29301, "text": "ML | Stochastic Gradient Descent (SGD)" }, { "code": null, "e": 29380, "s": 29340, "text": "Different Types of Clustering Algorithm" }, { "code": null, "e": 29407, "s": 29380, "text": "Fuzzy Logic | Introduction" }, { "code": null, "e": 29447, "s": 29407, "text": "Sed Command in Linux/Unix with examples" }, { "code": null, "e": 29487, "s": 29447, "text": "AWK command in Unix/Linux with examples" }, { "code": null, "e": 29514, "s": 29487, "text": "grep command in Unix/Linux" }, { "code": null, "e": 29549, "s": 29514, "text": "cut command in Linux with examples" } ]
How MySQL WHILE loop statement can be used in stored procedure?
As we know that MySQL provides us loop statements that allow us to execute a block of SQL code repeatedly based on a condition. WHILE loop statement is one of such kind of loop statements. Its syntax is as follows − WHILE expression DO statements END WHILE Actually, the WHILE loop checks the expression at the starting of every iteration. If the expression evaluates to true, MySQL will execute statements between WHILE and END WHILE until the expression evaluates to false. The WHILE loop checks the expression before the statements execute, that is why it is also called the pretest loop. To demonstrate the use of WHILE loop with stored procedures, the following is an example − mysql> Delimiter // mysql> CREATE PROCEDURE While_Loop() -> BEGIN -> DECLARE A INT; -> DECLARE XYZ Varchar(50); -> SET A = 1; -> SET XYZ = ''; -> WHILE A <=10 DO -> SET XYZ = CONCAT(XYZ,A,','); -> SET A = A + 1; -> END WHILE; -> SELECT XYZ; -> END // Query OK, 0 rows affected (0.31 sec) Now, we can see the result below when we invoke this procedure − mysql> DELIMITER ; mysql> call While_Loop(); +-----------------------+ | XYZ | +-----------------------+ | 1,2,3,4,5,6,7,8,9,10, | +-----------------------+ 1 row in set (0.03 sec)
[ { "code": null, "e": 1278, "s": 1062, "text": "As we know that MySQL provides us loop statements that allow us to execute a block of SQL code repeatedly based on a condition. WHILE loop statement is one of such kind of loop statements. Its syntax is as follows −" }, { "code": null, "e": 1319, "s": 1278, "text": "WHILE expression DO\nstatements\nEND WHILE" }, { "code": null, "e": 1654, "s": 1319, "text": "Actually, the WHILE loop checks the expression at the starting of every iteration. If the expression evaluates to true, MySQL will execute statements between WHILE and END WHILE until the expression evaluates to false. The WHILE loop checks the expression before the statements execute, that is why it is also called the pretest loop." }, { "code": null, "e": 1745, "s": 1654, "text": "To demonstrate the use of WHILE loop with stored procedures, the following is an example −" }, { "code": null, "e": 2035, "s": 1745, "text": "mysql> Delimiter //\nmysql> CREATE PROCEDURE While_Loop()\n -> BEGIN\n-> DECLARE A INT;\n-> DECLARE XYZ Varchar(50);\n-> SET A = 1;\n-> SET XYZ = '';\n-> WHILE A <=10 DO\n-> SET XYZ = CONCAT(XYZ,A,',');\n-> SET A = A + 1;\n-> END WHILE;\n-> SELECT XYZ;\n-> END //\nQuery OK, 0 rows affected (0.31 sec)" }, { "code": null, "e": 2100, "s": 2035, "text": "Now, we can see the result below when we invoke this procedure −" }, { "code": null, "e": 2281, "s": 2100, "text": "mysql> DELIMITER ;\nmysql> call While_Loop();\n+-----------------------+\n| XYZ |\n+-----------------------+\n| 1,2,3,4,5,6,7,8,9,10, |\n+-----------------------+\n1 row in set (0.03 sec)" } ]
Spring Boot CLI - Using Shell
Spring Boot CLI provides a Shell interface to run the commands in which we can directly run the commands as shown below. Go to E:\Test folder and type the following command. E:/Test> spring shell You will see the following output. ←[1mSpring Boot←[m←[2m (v2.6.3)←[m Hit TAB to complete. Type 'help' and hit RETURN for help, and 'exit' to quit. $ Type the following and see the output. version Spring CLI v2.6.3 You can press tab to auto complete the commands and type exit to finish the shell console. Type the following and see the output. $ exit E:\Test\FirstApplication> Print Add Notes Bookmark this page
[ { "code": null, "e": 2183, "s": 2009, "text": "Spring Boot CLI provides a Shell interface to run the commands in which we can directly run the commands as shown below. Go to E:\\Test folder and type the following command." }, { "code": null, "e": 2206, "s": 2183, "text": "E:/Test> spring shell\n" }, { "code": null, "e": 2241, "s": 2206, "text": "You will see the following output." }, { "code": null, "e": 2357, "s": 2241, "text": "←[1mSpring Boot←[m←[2m (v2.6.3)←[m\nHit TAB to complete. Type 'help' and hit RETURN for help, and 'exit' to quit.\n$\n" }, { "code": null, "e": 2396, "s": 2357, "text": "Type the following and see the output." }, { "code": null, "e": 2423, "s": 2396, "text": "version\nSpring CLI v2.6.3\n" }, { "code": null, "e": 2514, "s": 2423, "text": "You can press tab to auto complete the commands and type exit to finish the shell console." }, { "code": null, "e": 2553, "s": 2514, "text": "Type the following and see the output." }, { "code": null, "e": 2587, "s": 2553, "text": "$ exit\nE:\\Test\\FirstApplication>\n" }, { "code": null, "e": 2594, "s": 2587, "text": " Print" }, { "code": null, "e": 2605, "s": 2594, "text": " Add Notes" } ]
C# program to check if a value is in an array
Use the Array.Exists method to check if a value is in an array or not. Set a string array − string[] strArray = new string[] {"keyboard", "screen", "mouse", "charger" }; Let’s say you need to find the value “keyboard” in the array. For that, use Array.Exists() − Array.Exists(strArray, ele => ele == "keyboard"); It returns a true value if element exists as shown below − Live Demo using System; using System.Text; public class Demo { public static void Main() { string[] strArray = new string[] {"keyboard", "screen", "mouse", "charger" }; bool res1 = Array.Exists(strArray, ele => ele == "harddisk"); Console.WriteLine(res1); bool res2 = Array.Exists(strArray, ele => ele == "keyboard"); Console.WriteLine(res2); } } False True
[ { "code": null, "e": 1133, "s": 1062, "text": "Use the Array.Exists method to check if a value is in an array or not." }, { "code": null, "e": 1154, "s": 1133, "text": "Set a string array −" }, { "code": null, "e": 1232, "s": 1154, "text": "string[] strArray = new string[] {\"keyboard\", \"screen\", \"mouse\", \"charger\" };" }, { "code": null, "e": 1325, "s": 1232, "text": "Let’s say you need to find the value “keyboard” in the array. For that, use Array.Exists() −" }, { "code": null, "e": 1375, "s": 1325, "text": "Array.Exists(strArray, ele => ele == \"keyboard\");" }, { "code": null, "e": 1434, "s": 1375, "text": "It returns a true value if element exists as shown below −" }, { "code": null, "e": 1445, "s": 1434, "text": " Live Demo" }, { "code": null, "e": 1818, "s": 1445, "text": "using System;\nusing System.Text;\npublic class Demo {\n public static void Main() {\n string[] strArray = new string[] {\"keyboard\", \"screen\", \"mouse\", \"charger\" };\n bool res1 = Array.Exists(strArray, ele => ele == \"harddisk\");\n Console.WriteLine(res1);\n bool res2 = Array.Exists(strArray, ele => ele == \"keyboard\");\n Console.WriteLine(res2);\n }\n}" }, { "code": null, "e": 1829, "s": 1818, "text": "False\nTrue" } ]
How to calculate monthly average for time series object in R?
To calculate monthly average for time series object, we can use tapply function with mean. For example, if we have a time series object called TimeData then the monthly average for this series can be found by using the command tapply(TimeData,cycle(TimeData),mean). Consider the below time series object − Live Demo > Data1<-ts(sample(101:999,240),frequency=12) > Data1 Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec 1 988 695 867 211 915 348 729 518 592 447 448 880 2 551 410 427 134 133 572 637 800 630 878 642 940 3 603 335 638 639 595 512 671 863 752 568 608 669 4 719 899 297 399 252 890 474 723 326 896 618 712 5 146 505 983 614 117 190 274 769 237 667 803 673 6 428 611 873 303 656 585 917 886 855 385 949 131 7 905 977 110 264 941 699 242 559 251 676 895 194 8 520 528 966 435 891 213 508 288 381 137 197 200 9 141 678 477 219 795 900 339 869 538 820 174 986 10 979 406 583 527 590 945 626 791 191 842 423 963 11 982 997 650 396 445 401 881 647 575 491 989 525 12 353 467 951 546 654 919 609 797 314 798 269 497 13 541 236 556 488 459 696 934 415 883 124 943 522 14 904 108 565 858 285 347 526 833 815 312 567 187 15 952 180 153 720 203 838 244 250 871 930 810 761 16 248 223 432 737 834 875 971 454 444 563 493 739 17 909 249 144 648 400 404 768 120 975 216 132 489 18 179 968 193 471 284 974 931 617 463 543 103 596 19 470 756 516 422 787 356 674 519 469 547 765 996 20 165 924 751 515 426 874 722 682 393 479 732 634 Finding monthly average for data in Data1 − > tapply(Data1,cycle(Data1),mean) 1 2 3 4 5 6 7 8 9 10 11 12 584.15 557.60 556.60 477.30 533.10 626.90 633.85 620.00 547.75 565.95 578.00 614.70 Live Demo > Data2<-ts(sample(101:999,360),frequency=12) > Data2 Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec 1 122 308 708 632 489 331 160 537 245 856 375 560 2 511 862 765 969 118 401 735 226 305 540 812 435 3 135 461 488 567 283 991 260 996 753 803 858 696 4 384 197 171 175 515 697 600 821 884 928 570 939 5 599 929 288 227 749 962 155 723 569 377 572 888 6 948 810 163 186 213 950 634 304 785 278 897 418 7 711 687 952 174 123 348 467 114 624 825 802 642 8 399 786 719 516 701 681 121 417 868 584 436 787 9 561 647 194 554 199 146 956 731 879 477 520 474 10 404 367 425 127 911 823 974 918 462 466 926 212 11 668 797 747 125 608 876 877 814 763 585 851 360 12 350 140 596 450 597 981 578 690 338 496 666 519 13 660 933 538 827 397 800 583 551 699 684 321 185 14 475 618 387 130 513 107 703 207 781 857 221 915 15 494 984 349 225 558 993 336 541 364 620 649 352 16 581 170 303 361 383 104 145 138 654 240 975 222 17 913 864 693 658 622 846 661 872 686 188 318 779 18 297 886 253 890 209 688 745 980 281 522 645 428 19 799 921 129 631 629 476 755 630 454 590 192 945 20 355 242 822 777 853 685 270 173 670 369 586 971 21 807 836 555 767 106 593 351 961 783 485 626 263 22 871 131 344 158 674 433 751 582 426 893 137 953 23 577 259 365 998 376 573 481 677 307 989 248 395 24 714 835 415 232 150 441 285 667 480 438 579 157 25 294 588 664 315 710 659 530 970 831 301 169 182 26 116 113 458 695 899 916 445 758 552 808 683 354 27 329 923 176 165 437 464 493 409 431 938 752 707 28 506 689 517 951 847 587 495 429 775 447 840 833 29 705 162 883 472 220 985 901 869 637 478 992 359 30 602 324 191 440 491 411 729 598 358 370 393 609 Finding monthly average for data in Data2 − > tapply(Data2,cycle(Data2),mean) 1 2 3 4 5 6 7 8 529.5667 582.3000 475.2667 479.8000 486.0000 631.6000 539.2000 610.1000 9 10 11 12 588.1333 581.0667 587.0333 551.3000
[ { "code": null, "e": 1328, "s": 1062, "text": "To calculate monthly average for time series object, we can use tapply function with mean. For example, if we have a time series object called TimeData then the monthly average for this series can be found by using the command tapply(TimeData,cycle(TimeData),mean)." }, { "code": null, "e": 1368, "s": 1328, "text": "Consider the below time series object −" }, { "code": null, "e": 1378, "s": 1368, "text": "Live Demo" }, { "code": null, "e": 1432, "s": 1378, "text": "> Data1<-ts(sample(101:999,240),frequency=12)\n> Data1" }, { "code": null, "e": 2503, "s": 1432, "text": " Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec\n1 988 695 867 211 915 348 729 518 592 447 448 880\n2 551 410 427 134 133 572 637 800 630 878 642 940\n3 603 335 638 639 595 512 671 863 752 568 608 669\n4 719 899 297 399 252 890 474 723 326 896 618 712\n5 146 505 983 614 117 190 274 769 237 667 803 673\n6 428 611 873 303 656 585 917 886 855 385 949 131\n7 905 977 110 264 941 699 242 559 251 676 895 194\n8 520 528 966 435 891 213 508 288 381 137 197 200\n9 141 678 477 219 795 900 339 869 538 820 174 986\n10 979 406 583 527 590 945 626 791 191 842 423 963\n11 982 997 650 396 445 401 881 647 575 491 989 525\n12 353 467 951 546 654 919 609 797 314 798 269 497\n13 541 236 556 488 459 696 934 415 883 124 943 522\n14 904 108 565 858 285 347 526 833 815 312 567 187\n15 952 180 153 720 203 838 244 250 871 930 810 761\n16 248 223 432 737 834 875 971 454 444 563 493 739\n17 909 249 144 648 400 404 768 120 975 216 132 489\n18 179 968 193 471 284 974 931 617 463 543 103 596\n19 470 756 516 422 787 356 674 519 469 547 765 996\n20 165 924 751 515 426 874 722 682 393 479 732 634" }, { "code": null, "e": 2547, "s": 2503, "text": "Finding monthly average for data in Data1 −" }, { "code": null, "e": 2581, "s": 2547, "text": "> tapply(Data1,cycle(Data1),mean)" }, { "code": null, "e": 2752, "s": 2581, "text": " 1 2 3 4 5 6 7 8 9 10 11 12\n584.15 557.60 556.60 477.30 533.10 626.90 633.85 620.00 547.75 565.95 578.00 614.70" }, { "code": null, "e": 2762, "s": 2752, "text": "Live Demo" }, { "code": null, "e": 2816, "s": 2762, "text": "> Data2<-ts(sample(101:999,360),frequency=12)\n> Data2" }, { "code": null, "e": 4397, "s": 2816, "text": " Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec\n1 122 308 708 632 489 331 160 537 245 856 375 560\n2 511 862 765 969 118 401 735 226 305 540 812 435\n3 135 461 488 567 283 991 260 996 753 803 858 696\n4 384 197 171 175 515 697 600 821 884 928 570 939\n5 599 929 288 227 749 962 155 723 569 377 572 888\n6 948 810 163 186 213 950 634 304 785 278 897 418\n7 711 687 952 174 123 348 467 114 624 825 802 642\n8 399 786 719 516 701 681 121 417 868 584 436 787\n9 561 647 194 554 199 146 956 731 879 477 520 474\n10 404 367 425 127 911 823 974 918 462 466 926 212\n11 668 797 747 125 608 876 877 814 763 585 851 360\n12 350 140 596 450 597 981 578 690 338 496 666 519\n13 660 933 538 827 397 800 583 551 699 684 321 185\n14 475 618 387 130 513 107 703 207 781 857 221 915\n15 494 984 349 225 558 993 336 541 364 620 649 352\n16 581 170 303 361 383 104 145 138 654 240 975 222\n17 913 864 693 658 622 846 661 872 686 188 318 779\n18 297 886 253 890 209 688 745 980 281 522 645 428\n19 799 921 129 631 629 476 755 630 454 590 192 945\n20 355 242 822 777 853 685 270 173 670 369 586 971\n21 807 836 555 767 106 593 351 961 783 485 626 263\n22 871 131 344 158 674 433 751 582 426 893 137 953\n23 577 259 365 998 376 573 481 677 307 989 248 395\n24 714 835 415 232 150 441 285 667 480 438 579 157\n25 294 588 664 315 710 659 530 970 831 301 169 182\n26 116 113 458 695 899 916 445 758 552 808 683 354\n27 329 923 176 165 437 464 493 409 431 938 752 707\n28 506 689 517 951 847 587 495 429 775 447 840 833\n29 705 162 883 472 220 985 901 869 637 478 992 359\n30 602 324 191 440 491 411 729 598 358 370 393 609" }, { "code": null, "e": 4441, "s": 4397, "text": "Finding monthly average for data in Data2 −" }, { "code": null, "e": 4475, "s": 4441, "text": "> tapply(Data2,cycle(Data2),mean)" }, { "code": null, "e": 4691, "s": 4475, "text": " 1 2 3 4 5 6 7 8\n529.5667 582.3000 475.2667 479.8000 486.0000 631.6000 539.2000 610.1000\n 9 10 11 12\n588.1333 581.0667 587.0333 551.3000" } ]
Pytorch [Tabular] — Regression. This blog post takes you through an... | by Akshaj Verma | Towards Data Science
We will use the red wine quality dataset available on Kaggle. This dataset has 12 columns where the first 11 are the features and the last column is the target column. The data set has 1599 rows. We’re using tqdm to enable progress bars for training and testing loops. import numpy as npimport pandas as pdimport seaborn as snsfrom tqdm.notebook import tqdmimport matplotlib.pyplot as pltimport torchimport torch.nn as nnimport torch.optim as optimfrom torch.utils.data import Dataset, DataLoaderfrom sklearn.preprocessing import MinMaxScaler from sklearn.model_selection import train_test_splitfrom sklearn.metrics import mean_squared_error, r2_score df = pd.read_csv("data/tabular/classification/winequality-red.csv")df.head() First off, we plot the output rows to observe the class distribution. There’s a lot of imbalance here. Classes 3, 4, and 8 have a very few number of samples. We will not treat the output variables as classes here because we’re performing regression. We will convert output column, which is all integers, to float values. sns.countplot(x = 'quality', data=df) In order to split our data into train, validation, and test sets, we need to separate out our inputs and outputs. Input X is all but the last column. Output y is the last column. X = df.iloc[:, 0:-1]y = df.iloc[:, -1] To create the train-val-test split, we’ll use train_test_split() from Sklearn. First, we’ll split our data into train+val and test sets. Then, we'll further split our train+val set to create our train and val sets. Because there’s a “class” imbalance, we want to have equal distribution of all output classes in our train, validation, and test sets. To do that, we use the stratify option in function train_test_split(). Remember that stratification only works with classes, not numbers. So, in general, we can bin our numbers into classes using quartiles, deciles, histogram(np.histogram()) and so on. So, you would have to create a new dataframe which contains the output and it's "class". This "class" was obtained using the above mentioned methods. In our case, let’s use the numbers as is because they are already like classes. After we split our data, we can convert the output to float (because regression). # Train - TestX_trainval, X_test, y_trainval, y_test = train_test_split(X, y, test_size=0.2, stratify=y, random_state=69)# Split train into train-valX_train, X_val, y_train, y_val = train_test_split(X_trainval, y_trainval, test_size=0.1, stratify=y_trainval, random_state=21) Neural networks need data that lies between the range of (0,1). There’s a ton of material available online on why we need to do it. To scale our values, we’ll use the MinMaxScaler() from Sklearn. The MinMaxScaler transforms features by scaling each feature to a given range which is (0,1) in our case. x_scaled = (x-min(x)) / (max(x)–min(x)) Notice that we use .fit_transform() on X_train while we use .transform() on X_val and X_test. We do this because we want to scale the validation and test set with the same parameters as that of the train set to avoid data leakage. fit_transform() calculates scaling values and applies them while .transform() only applies the calculated values. scaler = MinMaxScaler()X_train = scaler.fit_transform(X_train)X_val = scaler.transform(X_val)X_test = scaler.transform(X_test)X_train, y_train = np.array(X_train), np.array(y_train)X_val, y_val = np.array(X_val), np.array(y_val)X_test, y_test = np.array(X_test), np.array(y_test) Once we’ve split our data into train, validation, and test sets, let’s make sure the distribution of classes is equal in all three sets. To do that, let’s create a function called get_class_distribution(). This function takes as input the obj y , ie. y_train, y_val, or y_test. Inside the function, we initialize a dictionary which contains the output classes as keys and their count as values. The counts are all initialized to 0. We then loop through our y object and update our dictionary. def get_class_distribution(obj): count_dict = { "rating_3": 0, "rating_4": 0, "rating_5": 0, "rating_6": 0, "rating_7": 0, "rating_8": 0, } for i in obj: if i == 3: count_dict['rating_3'] += 1 elif i == 4: count_dict['rating_4'] += 1 elif i == 5: count_dict['rating_5'] += 1 elif i == 6: count_dict['rating_6'] += 1 elif i == 7: count_dict['rating_7'] += 1 elif i == 8: count_dict['rating_8'] += 1 else: print("Check classes.") return count_dict Once we have the dictionary count, we use Seaborn library to plot the bar charts. To make the plot, we first convert our dictionary to a dataframe using pd.DataFrame.from_dict([get_class_distribution(y_train)]). Subsequently, we .melt() our convert our dataframe into the long format and finally use sns.barplot() to build the plots. fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(25,7))# Trainsns.barplot(data = pd.DataFrame.from_dict([get_class_distribution(y_train)]).melt(), x = "variable", y="value", hue="variable", ax=axes[0]).set_title('Class Distribution in Train Set')# Valsns.barplot(data = pd.DataFrame.from_dict([get_class_distribution(y_val)]).melt(), x = "variable", y="value", hue="variable", ax=axes[1]).set_title('Class Distribution in Val Set')# Testsns.barplot(data = pd.DataFrame.from_dict([get_class_distribution(y_test)]).melt(), x = "variable", y="value", hue="variable", ax=axes[2]).set_title('Class Distribution in Test Set') y_train, y_test, y_val = y_train.astype(float), y_test.astype(float), y_val.astype(float) class RegressionDataset(Dataset): def __init__(self, X_data, y_data): self.X_data = X_data self.y_data = y_data def __getitem__(self, index): return self.X_data[index], self.y_data[index] def __len__ (self): return len(self.X_data)train_dataset = RegressionDataset(torch.from_numpy(X_train).float(), torch.from_numpy(y_train).float())val_dataset = RegressionDataset(torch.from_numpy(X_val).float(), torch.from_numpy(y_val).float())test_dataset = RegressionDataset(torch.from_numpy(X_test).float(), torch.from_numpy(y_test).float()) EPOCHS = 150BATCH_SIZE = 64LEARNING_RATE = 0.001NUM_FEATURES = len(X.columns) train_loader = DataLoader(dataset=train_dataset, batch_size=BATCH_SIZE, shuffle=True)val_loader = DataLoader(dataset=val_dataset, batch_size=1)test_loader = DataLoader(dataset=test_dataset, batch_size=1) We have a simple 3 layer feedforward neural net here. We use ReLU as the activation at all layers. class MultipleRegression(nn.Module): def __init__(self, num_features): super(MultipleRegression, self).__init__() self.layer_1 = nn.Linear(num_features, 16) self.layer_2 = nn.Linear(16, 32) self.layer_3 = nn.Linear(32, 16) self.layer_out = nn.Linear(16, 1) self.relu = nn.ReLU()def forward(self, inputs): x = self.relu(self.layer_1(inputs)) x = self.relu(self.layer_2(x)) x = self.relu(self.layer_3(x)) x = self.layer_out(x)return (x)def predict(self, test_inputs): x = self.relu(self.layer_1(test_inputs)) x = self.relu(self.layer_2(x)) x = self.relu(self.layer_3(x)) x = self.layer_out(x)return (x) device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")print(device)###################### OUTPUT ######################cuda:0 Initialize the model, optimizer, and loss function. Transfer the model to GPU. We are using the Mean Squared Error loss. model = MultipleRegression(NUM_FEATURES)model.to(device)print(model)criterion = nn.MSELoss()optimizer = optim.Adam(model.parameters(), lr=LEARNING_RATE)###################### OUTPUT ######################MultipleRegression( (layer_1): Linear(in_features=11, out_features=16, bias=True) (layer_2): Linear(in_features=16, out_features=32, bias=True) (layer_3): Linear(in_features=32, out_features=16, bias=True) (layer_out): Linear(in_features=16, out_features=1, bias=True) (relu): ReLU()) Before we start our training, let’s define a dictionary which will store the loss/epoch for both train and validation sets. loss_stats = { 'train': [], "val": []} Let the training begin. print("Begin training.")for e in tqdm(range(1, EPOCHS+1)): # TRAINING train_epoch_loss = 0model.train() for X_train_batch, y_train_batch in train_loader: X_train_batch, y_train_batch = X_train_batch.to(device), y_train_batch.to(device) optimizer.zero_grad() y_train_pred = model(X_train_batch) train_loss = criterion(y_train_pred, y_train_batch.unsqueeze(1)) train_loss.backward() optimizer.step() train_epoch_loss += train_loss.item() # VALIDATION with torch.no_grad(): val_epoch_loss = 0 model.eval() for X_val_batch, y_val_batch in val_loader: X_val_batch, y_val_batch = X_val_batch.to(device), y_val_batch.to(device) y_val_pred = model(X_val_batch) val_loss = criterion(y_val_pred, y_val_batch.unsqueeze(1)) val_epoch_loss += val_loss.item()loss_stats['train'].append(train_epoch_loss/len(train_loader)) loss_stats['val'].append(val_epoch_loss/len(val_loader)) print(f'Epoch {e+0:03}: | Train Loss: {train_epoch_loss/len(train_loader):.5f} | Val Loss: {val_epoch_loss/len(val_loader):.5f}')###################### OUTPUT ######################Epoch 001: | Train Loss: 31.22514 | Val Loss: 30.50931Epoch 002: | Train Loss: 30.02529 | Val Loss: 28.97327...Epoch 149: | Train Loss: 0.42277 | Val Loss: 0.37748Epoch 150: | Train Loss: 0.42012 | Val Loss: 0.37028 You can see we’ve put a model.train() at the before the loop. model.train() tells PyTorch that you’re in training mode. Well, why do we need to do that? If you’re using layers such as Dropout or BatchNorm which behave differently during training and evaluation (for example; not use dropout during evaluation), you need to tell PyTorch to act accordingly. Similarly, we’ll call model.eval() when we test our model. We’ll see that below. Back to training; we start a for-loop. At the top of this for-loop, we initialize our loss per epoch to 0. After every epoch, we’ll print out the loss and reset it back to 0. Then we have another for-loop. This for-loop is used to get our data in batches from the train_loader. We do optimizer.zero_grad() before we make any predictions. Since the backward() function accumulates gradients, we need to set it to 0 manually per mini-batch. From our defined model, we then obtain a prediction, get the loss(and accuracy) for that mini-batch, perform back-propagation using loss.backward() and optimizer.step() . Finally, we add all the mini-batch losses to obtain the average loss for that epoch. We add up all the losses for each mini-batch and finally divide it by the number of mini-batches ie. length of train_loader to obtain the average loss per epoch. The procedure we follow for training is the exact same for validation except for the fact that we wrap it up in torch.no_grad and not perform any back-propagation. torch.no_grad() tells PyTorch that we do not want to perform back-propagation, which reduces memory usage and speeds up computation. To plot the loss line plots, we again create a dataframe from the `loss_stats` dictionary. train_val_loss_df = pd.DataFrame.from_dict(loss_stats).reset_index().melt(id_vars=['index']).rename(columns={"index":"epochs"})plt.figure(figsize=(15,8))sns.lineplot(data=train_val_loss_df, x = "epochs", y="value", hue="variable").set_title('Train-Val Loss/Epoch') After training is done, we need to test how our model fared. Note that we’ve used model.eval() before we run our testing code. To tell PyTorch that we do not want to perform back-propagation during inference, we use torch.no_grad(), just like we did it for the validation loop above. y_pred_list = []with torch.no_grad(): model.eval() for X_batch, _ in test_loader: X_batch = X_batch.to(device) y_test_pred = model(X_batch) y_pred_list.append(y_test_pred.cpu().numpy())y_pred_list = [a.squeeze().tolist() for a in y_pred_list] Let’s check the MSE and R-squared metrics. mse = mean_squared_error(y_test, y_pred_list)r_square = r2_score(y_test, y_pred_list)print("Mean Squared Error :",mse)print("R^2 :",r_square)###################### OUTPUT ######################Mean Squared Error : 0.40861496703609534R^2 : 0.36675687655886924 Thank you for reading. Suggestions and constructive criticism are welcome. :) This blogpost is a part of the column — ” How to train you Neural Net”. You can find the column here. You can find me on LinkedIn and Twitter. If you liked this, check out my other blogposts.
[ { "code": null, "e": 368, "s": 172, "text": "We will use the red wine quality dataset available on Kaggle. This dataset has 12 columns where the first 11 are the features and the last column is the target column. The data set has 1599 rows." }, { "code": null, "e": 441, "s": 368, "text": "We’re using tqdm to enable progress bars for training and testing loops." }, { "code": null, "e": 827, "s": 441, "text": "import numpy as npimport pandas as pdimport seaborn as snsfrom tqdm.notebook import tqdmimport matplotlib.pyplot as pltimport torchimport torch.nn as nnimport torch.optim as optimfrom torch.utils.data import Dataset, DataLoaderfrom sklearn.preprocessing import MinMaxScaler from sklearn.model_selection import train_test_splitfrom sklearn.metrics import mean_squared_error, r2_score" }, { "code": null, "e": 904, "s": 827, "text": "df = pd.read_csv(\"data/tabular/classification/winequality-red.csv\")df.head()" }, { "code": null, "e": 1062, "s": 904, "text": "First off, we plot the output rows to observe the class distribution. There’s a lot of imbalance here. Classes 3, 4, and 8 have a very few number of samples." }, { "code": null, "e": 1225, "s": 1062, "text": "We will not treat the output variables as classes here because we’re performing regression. We will convert output column, which is all integers, to float values." }, { "code": null, "e": 1263, "s": 1225, "text": "sns.countplot(x = 'quality', data=df)" }, { "code": null, "e": 1377, "s": 1263, "text": "In order to split our data into train, validation, and test sets, we need to separate out our inputs and outputs." }, { "code": null, "e": 1442, "s": 1377, "text": "Input X is all but the last column. Output y is the last column." }, { "code": null, "e": 1481, "s": 1442, "text": "X = df.iloc[:, 0:-1]y = df.iloc[:, -1]" }, { "code": null, "e": 1560, "s": 1481, "text": "To create the train-val-test split, we’ll use train_test_split() from Sklearn." }, { "code": null, "e": 1696, "s": 1560, "text": "First, we’ll split our data into train+val and test sets. Then, we'll further split our train+val set to create our train and val sets." }, { "code": null, "e": 1831, "s": 1696, "text": "Because there’s a “class” imbalance, we want to have equal distribution of all output classes in our train, validation, and test sets." }, { "code": null, "e": 1902, "s": 1831, "text": "To do that, we use the stratify option in function train_test_split()." }, { "code": null, "e": 2234, "s": 1902, "text": "Remember that stratification only works with classes, not numbers. So, in general, we can bin our numbers into classes using quartiles, deciles, histogram(np.histogram()) and so on. So, you would have to create a new dataframe which contains the output and it's \"class\". This \"class\" was obtained using the above mentioned methods." }, { "code": null, "e": 2396, "s": 2234, "text": "In our case, let’s use the numbers as is because they are already like classes. After we split our data, we can convert the output to float (because regression)." }, { "code": null, "e": 2672, "s": 2396, "text": "# Train - TestX_trainval, X_test, y_trainval, y_test = train_test_split(X, y, test_size=0.2, stratify=y, random_state=69)# Split train into train-valX_train, X_val, y_train, y_val = train_test_split(X_trainval, y_trainval, test_size=0.1, stratify=y_trainval, random_state=21)" }, { "code": null, "e": 2804, "s": 2672, "text": "Neural networks need data that lies between the range of (0,1). There’s a ton of material available online on why we need to do it." }, { "code": null, "e": 2974, "s": 2804, "text": "To scale our values, we’ll use the MinMaxScaler() from Sklearn. The MinMaxScaler transforms features by scaling each feature to a given range which is (0,1) in our case." }, { "code": null, "e": 3014, "s": 2974, "text": "x_scaled = (x-min(x)) / (max(x)–min(x))" }, { "code": null, "e": 3108, "s": 3014, "text": "Notice that we use .fit_transform() on X_train while we use .transform() on X_val and X_test." }, { "code": null, "e": 3359, "s": 3108, "text": "We do this because we want to scale the validation and test set with the same parameters as that of the train set to avoid data leakage. fit_transform() calculates scaling values and applies them while .transform() only applies the calculated values." }, { "code": null, "e": 3639, "s": 3359, "text": "scaler = MinMaxScaler()X_train = scaler.fit_transform(X_train)X_val = scaler.transform(X_val)X_test = scaler.transform(X_test)X_train, y_train = np.array(X_train), np.array(y_train)X_val, y_val = np.array(X_val), np.array(y_val)X_test, y_test = np.array(X_test), np.array(y_test)" }, { "code": null, "e": 3776, "s": 3639, "text": "Once we’ve split our data into train, validation, and test sets, let’s make sure the distribution of classes is equal in all three sets." }, { "code": null, "e": 4071, "s": 3776, "text": "To do that, let’s create a function called get_class_distribution(). This function takes as input the obj y , ie. y_train, y_val, or y_test. Inside the function, we initialize a dictionary which contains the output classes as keys and their count as values. The counts are all initialized to 0." }, { "code": null, "e": 4132, "s": 4071, "text": "We then loop through our y object and update our dictionary." }, { "code": null, "e": 4796, "s": 4132, "text": "def get_class_distribution(obj): count_dict = { \"rating_3\": 0, \"rating_4\": 0, \"rating_5\": 0, \"rating_6\": 0, \"rating_7\": 0, \"rating_8\": 0, } for i in obj: if i == 3: count_dict['rating_3'] += 1 elif i == 4: count_dict['rating_4'] += 1 elif i == 5: count_dict['rating_5'] += 1 elif i == 6: count_dict['rating_6'] += 1 elif i == 7: count_dict['rating_7'] += 1 elif i == 8: count_dict['rating_8'] += 1 else: print(\"Check classes.\") return count_dict" }, { "code": null, "e": 4878, "s": 4796, "text": "Once we have the dictionary count, we use Seaborn library to plot the bar charts." }, { "code": null, "e": 5008, "s": 4878, "text": "To make the plot, we first convert our dictionary to a dataframe using pd.DataFrame.from_dict([get_class_distribution(y_train)])." }, { "code": null, "e": 5130, "s": 5008, "text": "Subsequently, we .melt() our convert our dataframe into the long format and finally use sns.barplot() to build the plots." }, { "code": null, "e": 5756, "s": 5130, "text": "fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(25,7))# Trainsns.barplot(data = pd.DataFrame.from_dict([get_class_distribution(y_train)]).melt(), x = \"variable\", y=\"value\", hue=\"variable\", ax=axes[0]).set_title('Class Distribution in Train Set')# Valsns.barplot(data = pd.DataFrame.from_dict([get_class_distribution(y_val)]).melt(), x = \"variable\", y=\"value\", hue=\"variable\", ax=axes[1]).set_title('Class Distribution in Val Set')# Testsns.barplot(data = pd.DataFrame.from_dict([get_class_distribution(y_test)]).melt(), x = \"variable\", y=\"value\", hue=\"variable\", ax=axes[2]).set_title('Class Distribution in Test Set')" }, { "code": null, "e": 5846, "s": 5756, "text": "y_train, y_test, y_val = y_train.astype(float), y_test.astype(float), y_val.astype(float)" }, { "code": null, "e": 6435, "s": 5846, "text": "class RegressionDataset(Dataset): def __init__(self, X_data, y_data): self.X_data = X_data self.y_data = y_data def __getitem__(self, index): return self.X_data[index], self.y_data[index] def __len__ (self): return len(self.X_data)train_dataset = RegressionDataset(torch.from_numpy(X_train).float(), torch.from_numpy(y_train).float())val_dataset = RegressionDataset(torch.from_numpy(X_val).float(), torch.from_numpy(y_val).float())test_dataset = RegressionDataset(torch.from_numpy(X_test).float(), torch.from_numpy(y_test).float())" }, { "code": null, "e": 6513, "s": 6435, "text": "EPOCHS = 150BATCH_SIZE = 64LEARNING_RATE = 0.001NUM_FEATURES = len(X.columns)" }, { "code": null, "e": 6717, "s": 6513, "text": "train_loader = DataLoader(dataset=train_dataset, batch_size=BATCH_SIZE, shuffle=True)val_loader = DataLoader(dataset=val_dataset, batch_size=1)test_loader = DataLoader(dataset=test_dataset, batch_size=1)" }, { "code": null, "e": 6816, "s": 6717, "text": "We have a simple 3 layer feedforward neural net here. We use ReLU as the activation at all layers." }, { "code": null, "e": 7534, "s": 6816, "text": "class MultipleRegression(nn.Module): def __init__(self, num_features): super(MultipleRegression, self).__init__() self.layer_1 = nn.Linear(num_features, 16) self.layer_2 = nn.Linear(16, 32) self.layer_3 = nn.Linear(32, 16) self.layer_out = nn.Linear(16, 1) self.relu = nn.ReLU()def forward(self, inputs): x = self.relu(self.layer_1(inputs)) x = self.relu(self.layer_2(x)) x = self.relu(self.layer_3(x)) x = self.layer_out(x)return (x)def predict(self, test_inputs): x = self.relu(self.layer_1(test_inputs)) x = self.relu(self.layer_2(x)) x = self.relu(self.layer_3(x)) x = self.layer_out(x)return (x)" }, { "code": null, "e": 7677, "s": 7534, "text": "device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")print(device)###################### OUTPUT ######################cuda:0" }, { "code": null, "e": 7756, "s": 7677, "text": "Initialize the model, optimizer, and loss function. Transfer the model to GPU." }, { "code": null, "e": 7798, "s": 7756, "text": "We are using the Mean Squared Error loss." }, { "code": null, "e": 8292, "s": 7798, "text": "model = MultipleRegression(NUM_FEATURES)model.to(device)print(model)criterion = nn.MSELoss()optimizer = optim.Adam(model.parameters(), lr=LEARNING_RATE)###################### OUTPUT ######################MultipleRegression( (layer_1): Linear(in_features=11, out_features=16, bias=True) (layer_2): Linear(in_features=16, out_features=32, bias=True) (layer_3): Linear(in_features=32, out_features=16, bias=True) (layer_out): Linear(in_features=16, out_features=1, bias=True) (relu): ReLU())" }, { "code": null, "e": 8416, "s": 8292, "text": "Before we start our training, let’s define a dictionary which will store the loss/epoch for both train and validation sets." }, { "code": null, "e": 8461, "s": 8416, "text": "loss_stats = { 'train': [], \"val\": []}" }, { "code": null, "e": 8485, "s": 8461, "text": "Let the training begin." }, { "code": null, "e": 10036, "s": 8485, "text": "print(\"Begin training.\")for e in tqdm(range(1, EPOCHS+1)): # TRAINING train_epoch_loss = 0model.train() for X_train_batch, y_train_batch in train_loader: X_train_batch, y_train_batch = X_train_batch.to(device), y_train_batch.to(device) optimizer.zero_grad() y_train_pred = model(X_train_batch) train_loss = criterion(y_train_pred, y_train_batch.unsqueeze(1)) train_loss.backward() optimizer.step() train_epoch_loss += train_loss.item() # VALIDATION with torch.no_grad(): val_epoch_loss = 0 model.eval() for X_val_batch, y_val_batch in val_loader: X_val_batch, y_val_batch = X_val_batch.to(device), y_val_batch.to(device) y_val_pred = model(X_val_batch) val_loss = criterion(y_val_pred, y_val_batch.unsqueeze(1)) val_epoch_loss += val_loss.item()loss_stats['train'].append(train_epoch_loss/len(train_loader)) loss_stats['val'].append(val_epoch_loss/len(val_loader)) print(f'Epoch {e+0:03}: | Train Loss: {train_epoch_loss/len(train_loader):.5f} | Val Loss: {val_epoch_loss/len(val_loader):.5f}')###################### OUTPUT ######################Epoch 001: | Train Loss: 31.22514 | Val Loss: 30.50931Epoch 002: | Train Loss: 30.02529 | Val Loss: 28.97327...Epoch 149: | Train Loss: 0.42277 | Val Loss: 0.37748Epoch 150: | Train Loss: 0.42012 | Val Loss: 0.37028" }, { "code": null, "e": 10156, "s": 10036, "text": "You can see we’ve put a model.train() at the before the loop. model.train() tells PyTorch that you’re in training mode." }, { "code": null, "e": 10392, "s": 10156, "text": "Well, why do we need to do that? If you’re using layers such as Dropout or BatchNorm which behave differently during training and evaluation (for example; not use dropout during evaluation), you need to tell PyTorch to act accordingly." }, { "code": null, "e": 10473, "s": 10392, "text": "Similarly, we’ll call model.eval() when we test our model. We’ll see that below." }, { "code": null, "e": 10648, "s": 10473, "text": "Back to training; we start a for-loop. At the top of this for-loop, we initialize our loss per epoch to 0. After every epoch, we’ll print out the loss and reset it back to 0." }, { "code": null, "e": 10751, "s": 10648, "text": "Then we have another for-loop. This for-loop is used to get our data in batches from the train_loader." }, { "code": null, "e": 10912, "s": 10751, "text": "We do optimizer.zero_grad() before we make any predictions. Since the backward() function accumulates gradients, we need to set it to 0 manually per mini-batch." }, { "code": null, "e": 11083, "s": 10912, "text": "From our defined model, we then obtain a prediction, get the loss(and accuracy) for that mini-batch, perform back-propagation using loss.backward() and optimizer.step() ." }, { "code": null, "e": 11330, "s": 11083, "text": "Finally, we add all the mini-batch losses to obtain the average loss for that epoch. We add up all the losses for each mini-batch and finally divide it by the number of mini-batches ie. length of train_loader to obtain the average loss per epoch." }, { "code": null, "e": 11627, "s": 11330, "text": "The procedure we follow for training is the exact same for validation except for the fact that we wrap it up in torch.no_grad and not perform any back-propagation. torch.no_grad() tells PyTorch that we do not want to perform back-propagation, which reduces memory usage and speeds up computation." }, { "code": null, "e": 11718, "s": 11627, "text": "To plot the loss line plots, we again create a dataframe from the `loss_stats` dictionary." }, { "code": null, "e": 11983, "s": 11718, "text": "train_val_loss_df = pd.DataFrame.from_dict(loss_stats).reset_index().melt(id_vars=['index']).rename(columns={\"index\":\"epochs\"})plt.figure(figsize=(15,8))sns.lineplot(data=train_val_loss_df, x = \"epochs\", y=\"value\", hue=\"variable\").set_title('Train-Val Loss/Epoch')" }, { "code": null, "e": 12267, "s": 11983, "text": "After training is done, we need to test how our model fared. Note that we’ve used model.eval() before we run our testing code. To tell PyTorch that we do not want to perform back-propagation during inference, we use torch.no_grad(), just like we did it for the validation loop above." }, { "code": null, "e": 12537, "s": 12267, "text": "y_pred_list = []with torch.no_grad(): model.eval() for X_batch, _ in test_loader: X_batch = X_batch.to(device) y_test_pred = model(X_batch) y_pred_list.append(y_test_pred.cpu().numpy())y_pred_list = [a.squeeze().tolist() for a in y_pred_list]" }, { "code": null, "e": 12580, "s": 12537, "text": "Let’s check the MSE and R-squared metrics." }, { "code": null, "e": 12839, "s": 12580, "text": "mse = mean_squared_error(y_test, y_pred_list)r_square = r2_score(y_test, y_pred_list)print(\"Mean Squared Error :\",mse)print(\"R^2 :\",r_square)###################### OUTPUT ######################Mean Squared Error : 0.40861496703609534R^2 : 0.36675687655886924" }, { "code": null, "e": 12917, "s": 12839, "text": "Thank you for reading. Suggestions and constructive criticism are welcome. :)" }, { "code": null, "e": 13019, "s": 12917, "text": "This blogpost is a part of the column — ” How to train you Neural Net”. You can find the column here." } ]
Design an efficient data structure for given operations - GeeksforGeeks
11 Jul, 2017 Design a Data Structure for the following operations. The data structure should be efficient enough to accommodate the operations according to their frequency. 1) findMin() : Returns the minimum item. Frequency: Most frequent 2) findMax() : Returns the maximum item. Frequency: Most frequent 3) deleteMin() : Delete the minimum item. Frequency: Moderate frequent 4) deleteMax() : Delete the maximum item. Frequency: Moderate frequent 5) Insert() : Inserts an item. Frequency: Least frequent 6) Delete() : Deletes an item. Frequency: Least frequent. A simple solution is to maintain a sorted array where smallest element is at first position and largest element is at last. The time complexity of findMin(), findMAx() and deleteMax() is O(1). But time complexities of deleteMin(), insert() and delete() will be O(n). Can we do the most frequent two operations in O(1) and other operations in O(Logn) time?.The idea is to use two binary heaps (one max and one min heap). The main challenge is, while deleting an item, we need to delete from both min-heap and max-heap. So, we need some kind of mutual data structure. In the following design, we have used doubly linked list as a mutual data structure. The doubly linked list contains all input items and indexes of corresponding min and max heap nodes. The nodes of min and max heaps store addresses of nodes of doubly linked list. The root node of min heap stores the address of minimum item in doubly linked list. Similarly, root of max heap stores address of maximum item in doubly linked list. Following are the details of operations. 1) findMax(): We get the address of maximum value node from root of Max Heap. So this is a O(1) operation. 1) findMin(): We get the address of minimum value node from root of Min Heap. So this is a O(1) operation. 3) deleteMin(): We get the address of minimum value node from root of Min Heap. We use this address to find the node in doubly linked list. From the doubly linked list, we get node of Max Heap. We delete node from all three. We can delete a node from doubly linked list in O(1) time. delete() operations for max and min heaps take O(Logn) time. 4) deleteMax(): is similar to deleteMin() 5) Insert() We always insert at the beginning of linked list in O(1) time. Inserting the address in Max and Min Heaps take O(Logn) time. So overall complexity is O(Logn) 6) Delete() We first search the item in Linked List. Once the item is found in O(n) time, we delete it from linked list. Then using the indexes stored in linked list, we delete it from Min Heap and Max Heaps in O(Logn) time. So overall complexity of this operation is O(n). The Delete operation can be optimized to O(Logn) by using a balanced binary search tree instead of doubly linked list as a mutual data structure. Use of balanced binary search will not effect time complexity of other operations as it will act as a mutual data structure like doubly Linked List. Following is C implementation of the above data structure. // C program for efficient data structure#include <stdio.h>#include <stdlib.h>#include <limits.h> // A node of doubly linked liststruct LNode{ int data; int minHeapIndex; int maxHeapIndex; struct LNode *next, *prev;}; // Structure for a doubly linked liststruct List{ struct LNode *head;}; // Structure for min heapstruct MinHeap{ int size; int capacity; struct LNode* *array;}; // Structure for max heapstruct MaxHeap{ int size; int capacity; struct LNode* *array;}; // The required data structurestruct MyDS{ struct MinHeap* minHeap; struct MaxHeap* maxHeap; struct List* list;}; // Function to swap two integersvoid swapData(int* a, int* b){ int t = *a; *a = *b; *b = t; } // Function to swap two List nodesvoid swapLNode(struct LNode** a, struct LNode** b){ struct LNode* t = *a; *a = *b; *b = t; } // A utility function to create a new List nodestruct LNode* newLNode(int data){ struct LNode* node = (struct LNode*) malloc(sizeof(struct LNode)); node->minHeapIndex = node->maxHeapIndex = -1; node->data = data; node->prev = node->next = NULL; return node;} // Utility function to create a max heap of given capacitystruct MaxHeap* createMaxHeap(int capacity){ struct MaxHeap* maxHeap = (struct MaxHeap*) malloc(sizeof(struct MaxHeap)); maxHeap->size = 0; maxHeap->capacity = capacity; maxHeap->array = (struct LNode**) malloc(maxHeap->capacity * sizeof(struct LNode*)); return maxHeap;} // Utility function to create a min heap of given capacitystruct MinHeap* createMinHeap(int capacity){ struct MinHeap* minHeap = (struct MinHeap*) malloc(sizeof(struct MinHeap)); minHeap->size = 0; minHeap->capacity = capacity; minHeap->array = (struct LNode**) malloc(minHeap->capacity * sizeof(struct LNode*)); return minHeap;} // Utility function to create a Liststruct List* createList(){ struct List* list = (struct List*) malloc(sizeof(struct List)); list->head = NULL; return list;} // Utility function to create the main data structure// with given capacitystruct MyDS* createMyDS(int capacity){ struct MyDS* myDS = (struct MyDS*) malloc(sizeof(struct MyDS)); myDS->minHeap = createMinHeap(capacity); myDS->maxHeap = createMaxHeap(capacity); myDS->list = createList(); return myDS;} // Some basic operations for heaps and Listint isMaxHeapEmpty(struct MaxHeap* heap){ return (heap->size == 0); } int isMinHeapEmpty(struct MinHeap* heap){ return heap->size == 0; } int isMaxHeapFull(struct MaxHeap* heap){ return heap->size == heap->capacity; } int isMinHeapFull(struct MinHeap* heap){ return heap->size == heap->capacity; } int isListEmpty(struct List* list){ return !list->head; } int hasOnlyOneLNode(struct List* list){ return !list->head->next && !list->head->prev; } // The standard minheapify function. The only thing it does extra// is swapping indexes of heaps inside the Listvoid minHeapify(struct MinHeap* minHeap, int index){ int smallest, left, right; smallest = index; left = 2 * index + 1; right = 2 * index + 2; if ( minHeap->array[left] && left < minHeap->size && minHeap->array[left]->data < minHeap->array[smallest]->data ) smallest = left; if ( minHeap->array[right] && right < minHeap->size && minHeap->array[right]->data < minHeap->array[smallest]->data ) smallest = right; if (smallest != index) { // First swap indexes inside the List using address // of List nodes swapData(&(minHeap->array[smallest]->minHeapIndex), &(minHeap->array[index]->minHeapIndex)); // Now swap pointers to List nodes swapLNode(&minHeap->array[smallest], &minHeap->array[index]); // Fix the heap downward minHeapify(minHeap, smallest); }} // The standard maxHeapify function. The only thing it does extra// is swapping indexes of heaps inside the Listvoid maxHeapify(struct MaxHeap* maxHeap, int index){ int largest, left, right; largest = index; left = 2 * index + 1; right = 2 * index + 2; if ( maxHeap->array[left] && left < maxHeap->size && maxHeap->array[left]->data > maxHeap->array[largest]->data ) largest = left; if ( maxHeap->array[right] && right < maxHeap->size && maxHeap->array[right]->data > maxHeap->array[largest]->data ) largest = right; if (largest != index) { // First swap indexes inside the List using address // of List nodes swapData(&maxHeap->array[largest]->maxHeapIndex, &maxHeap->array[index]->maxHeapIndex); // Now swap pointers to List nodes swapLNode(&maxHeap->array[largest], &maxHeap->array[index]); // Fix the heap downward maxHeapify(maxHeap, largest); }} // Standard function to insert an item in Min Heapvoid insertMinHeap(struct MinHeap* minHeap, struct LNode* temp){ if (isMinHeapFull(minHeap)) return; ++minHeap->size; int i = minHeap->size - 1; while (i && temp->data < minHeap->array[(i - 1) / 2]->data ) { minHeap->array[i] = minHeap->array[(i - 1) / 2]; minHeap->array[i]->minHeapIndex = i; i = (i - 1) / 2; } minHeap->array[i] = temp; minHeap->array[i]->minHeapIndex = i;} // Standard function to insert an item in Max Heapvoid insertMaxHeap(struct MaxHeap* maxHeap, struct LNode* temp){ if (isMaxHeapFull(maxHeap)) return; ++maxHeap->size; int i = maxHeap->size - 1; while (i && temp->data > maxHeap->array[(i - 1) / 2]->data ) { maxHeap->array[i] = maxHeap->array[(i - 1) / 2]; maxHeap->array[i]->maxHeapIndex = i; i = (i - 1) / 2; } maxHeap->array[i] = temp; maxHeap->array[i]->maxHeapIndex = i;} // Function to find minimum value stored in the main data structureint findMin(struct MyDS* myDS){ if (isMinHeapEmpty(myDS->minHeap)) return INT_MAX; return myDS->minHeap->array[0]->data;} // Function to find maximum value stored in the main data structureint findMax(struct MyDS* myDS){ if (isMaxHeapEmpty(myDS->maxHeap)) return INT_MIN; return myDS->maxHeap->array[0]->data;} // A utility function to remove an item from linked listvoid removeLNode(struct List* list, struct LNode** temp){ if (hasOnlyOneLNode(list)) list->head = NULL; else if (!(*temp)->prev) // first node { list->head = (*temp)->next; (*temp)->next->prev = NULL; } // any other node including last else { (*temp)->prev->next = (*temp)->next; // last node if ((*temp)->next) (*temp)->next->prev = (*temp)->prev; } free(*temp); *temp = NULL;} // Function to delete maximum value stored in the main data structurevoid deleteMax(struct MyDS* myDS){ MinHeap *minHeap = myDS->minHeap; MaxHeap *maxHeap = myDS->maxHeap; if (isMaxHeapEmpty(maxHeap)) return; struct LNode* temp = maxHeap->array[0]; // delete the maximum item from maxHeap maxHeap->array[0] = maxHeap->array[maxHeap->size - 1]; --maxHeap->size; maxHeap->array[0]->maxHeapIndex = 0; maxHeapify(maxHeap, 0); // remove the item from minHeap minHeap->array[temp->minHeapIndex] = minHeap->array[minHeap->size - 1]; --minHeap->size; minHeap->array[temp->minHeapIndex]->minHeapIndex = temp->minHeapIndex; minHeapify(minHeap, temp->minHeapIndex); // remove the node from List removeLNode(myDS->list, &temp);} // Function to delete minimum value stored in the main data structurevoid deleteMin(struct MyDS* myDS){ MinHeap *minHeap = myDS->minHeap; MaxHeap *maxHeap = myDS->maxHeap; if (isMinHeapEmpty(minHeap)) return; struct LNode* temp = minHeap->array[0]; // delete the minimum item from minHeap minHeap->array[0] = minHeap->array[minHeap->size - 1]; --minHeap->size; minHeap->array[0]->minHeapIndex = 0; minHeapify(minHeap, 0); // remove the item from maxHeap maxHeap->array[temp->maxHeapIndex] = maxHeap->array[maxHeap->size - 1]; --maxHeap->size; maxHeap->array[temp->maxHeapIndex]->maxHeapIndex = temp->maxHeapIndex; maxHeapify(maxHeap, temp->maxHeapIndex); // remove the node from List removeLNode(myDS->list, &temp);} // Function to enList an item to Listvoid insertAtHead(struct List* list, struct LNode* temp){ if (isListEmpty(list)) list->head = temp; else { temp->next = list->head; list->head->prev = temp; list->head = temp; }} // Function to delete an item from List. The function also// removes item from min and max heapsvoid Delete(struct MyDS* myDS, int item){ MinHeap *minHeap = myDS->minHeap; MaxHeap *maxHeap = myDS->maxHeap; if (isListEmpty(myDS->list)) return; // search the node in List struct LNode* temp = myDS->list->head; while (temp && temp->data != item) temp = temp->next; // if item not found if (!temp || temp && temp->data != item) return; // remove item from min heap minHeap->array[temp->minHeapIndex] = minHeap->array[minHeap->size - 1]; --minHeap->size; minHeap->array[temp->minHeapIndex]->minHeapIndex = temp->minHeapIndex; minHeapify(minHeap, temp->minHeapIndex); // remove item from max heap maxHeap->array[temp->maxHeapIndex] = maxHeap->array[maxHeap->size - 1]; --maxHeap->size; maxHeap->array[temp->maxHeapIndex]->maxHeapIndex = temp->maxHeapIndex; maxHeapify(maxHeap, temp->maxHeapIndex); // remove node from List removeLNode(myDS->list, &temp);} // insert operation for main data structurevoid Insert(struct MyDS* myDS, int data){ struct LNode* temp = newLNode(data); // insert the item in List insertAtHead(myDS->list, temp); // insert the item in min heap insertMinHeap(myDS->minHeap, temp); // insert the item in max heap insertMaxHeap(myDS->maxHeap, temp);} // Driver program to test above functionsint main(){ struct MyDS *myDS = createMyDS(10); // Test Case #1 /*Insert(myDS, 10); Insert(myDS, 2); Insert(myDS, 32); Insert(myDS, 40); Insert(myDS, 5);*/ // Test Case #2 Insert(myDS, 10); Insert(myDS, 20); Insert(myDS, 30); Insert(myDS, 40); Insert(myDS, 50); printf("Maximum = %d \n", findMax(myDS)); printf("Minimum = %d \n\n", findMin(myDS)); deleteMax(myDS); // 50 is deleted printf("After deleteMax()\n"); printf("Maximum = %d \n", findMax(myDS)); printf("Minimum = %d \n\n", findMin(myDS)); deleteMin(myDS); // 10 is deleted printf("After deleteMin()\n"); printf("Maximum = %d \n", findMax(myDS)); printf("Minimum = %d \n\n", findMin(myDS)); Delete(myDS, 40); // 40 is deleted printf("After Delete()\n"); printf("Maximum = %d \n", findMax(myDS)); printf("Minimum = %d \n", findMin(myDS)); return 0;} Output: Maximum = 50 Minimum = 10 After deleteMax() Maximum = 40 Minimum = 10 After deleteMin() Maximum = 40 Minimum = 20 After Delete() Maximum = 30 Minimum = 20 This article is compiled by Aashish Barnwal and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above doubly linked list Ola Cabs Advanced Data Structure Heap Ola Cabs Heap Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Agents in Artificial Intelligence Decision Tree Introduction with example AVL Tree | Set 2 (Deletion) Red-Black Tree | Set 2 (Insert) Disjoint Set Data Structures HeapSort Binary Heap Huffman Coding | Greedy Algo-3 Building Heap from Array Sliding Window Maximum (Maximum of all subarrays of size k)
[ { "code": null, "e": 24413, "s": 24385, "text": "\n11 Jul, 2017" }, { "code": null, "e": 24573, "s": 24413, "text": "Design a Data Structure for the following operations. The data structure should be efficient enough to accommodate the operations according to their frequency." }, { "code": null, "e": 24993, "s": 24573, "text": "1) findMin() : Returns the minimum item.\n Frequency: Most frequent\n\n2) findMax() : Returns the maximum item.\n Frequency: Most frequent\n\n3) deleteMin() : Delete the minimum item.\n Frequency: Moderate frequent \n\n4) deleteMax() : Delete the maximum item.\n Frequency: Moderate frequent \n\n5) Insert() : Inserts an item.\n Frequency: Least frequent\n\n6) Delete() : Deletes an item.\n Frequency: Least frequent. " }, { "code": null, "e": 25260, "s": 24993, "text": "A simple solution is to maintain a sorted array where smallest element is at first position and largest element is at last. The time complexity of findMin(), findMAx() and deleteMax() is O(1). But time complexities of deleteMin(), insert() and delete() will be O(n)." }, { "code": null, "e": 26031, "s": 25260, "text": "Can we do the most frequent two operations in O(1) and other operations in O(Logn) time?.The idea is to use two binary heaps (one max and one min heap). The main challenge is, while deleting an item, we need to delete from both min-heap and max-heap. So, we need some kind of mutual data structure. In the following design, we have used doubly linked list as a mutual data structure. The doubly linked list contains all input items and indexes of corresponding min and max heap nodes. The nodes of min and max heaps store addresses of nodes of doubly linked list. The root node of min heap stores the address of minimum item in doubly linked list. Similarly, root of max heap stores address of maximum item in doubly linked list. Following are the details of operations." }, { "code": null, "e": 26138, "s": 26031, "text": "1) findMax(): We get the address of maximum value node from root of Max Heap. So this is a O(1) operation." }, { "code": null, "e": 26245, "s": 26138, "text": "1) findMin(): We get the address of minimum value node from root of Min Heap. So this is a O(1) operation." }, { "code": null, "e": 26590, "s": 26245, "text": "3) deleteMin(): We get the address of minimum value node from root of Min Heap. We use this address to find the node in doubly linked list. From the doubly linked list, we get node of Max Heap. We delete node from all three. We can delete a node from doubly linked list in O(1) time. delete() operations for max and min heaps take O(Logn) time." }, { "code": null, "e": 26632, "s": 26590, "text": "4) deleteMax(): is similar to deleteMin()" }, { "code": null, "e": 26802, "s": 26632, "text": "5) Insert() We always insert at the beginning of linked list in O(1) time. Inserting the address in Max and Min Heaps take O(Logn) time. So overall complexity is O(Logn)" }, { "code": null, "e": 27371, "s": 26802, "text": "6) Delete() We first search the item in Linked List. Once the item is found in O(n) time, we delete it from linked list. Then using the indexes stored in linked list, we delete it from Min Heap and Max Heaps in O(Logn) time. So overall complexity of this operation is O(n). The Delete operation can be optimized to O(Logn) by using a balanced binary search tree instead of doubly linked list as a mutual data structure. Use of balanced binary search will not effect time complexity of other operations as it will act as a mutual data structure like doubly Linked List." }, { "code": null, "e": 27430, "s": 27371, "text": "Following is C implementation of the above data structure." }, { "code": "// C program for efficient data structure#include <stdio.h>#include <stdlib.h>#include <limits.h> // A node of doubly linked liststruct LNode{ int data; int minHeapIndex; int maxHeapIndex; struct LNode *next, *prev;}; // Structure for a doubly linked liststruct List{ struct LNode *head;}; // Structure for min heapstruct MinHeap{ int size; int capacity; struct LNode* *array;}; // Structure for max heapstruct MaxHeap{ int size; int capacity; struct LNode* *array;}; // The required data structurestruct MyDS{ struct MinHeap* minHeap; struct MaxHeap* maxHeap; struct List* list;}; // Function to swap two integersvoid swapData(int* a, int* b){ int t = *a; *a = *b; *b = t; } // Function to swap two List nodesvoid swapLNode(struct LNode** a, struct LNode** b){ struct LNode* t = *a; *a = *b; *b = t; } // A utility function to create a new List nodestruct LNode* newLNode(int data){ struct LNode* node = (struct LNode*) malloc(sizeof(struct LNode)); node->minHeapIndex = node->maxHeapIndex = -1; node->data = data; node->prev = node->next = NULL; return node;} // Utility function to create a max heap of given capacitystruct MaxHeap* createMaxHeap(int capacity){ struct MaxHeap* maxHeap = (struct MaxHeap*) malloc(sizeof(struct MaxHeap)); maxHeap->size = 0; maxHeap->capacity = capacity; maxHeap->array = (struct LNode**) malloc(maxHeap->capacity * sizeof(struct LNode*)); return maxHeap;} // Utility function to create a min heap of given capacitystruct MinHeap* createMinHeap(int capacity){ struct MinHeap* minHeap = (struct MinHeap*) malloc(sizeof(struct MinHeap)); minHeap->size = 0; minHeap->capacity = capacity; minHeap->array = (struct LNode**) malloc(minHeap->capacity * sizeof(struct LNode*)); return minHeap;} // Utility function to create a Liststruct List* createList(){ struct List* list = (struct List*) malloc(sizeof(struct List)); list->head = NULL; return list;} // Utility function to create the main data structure// with given capacitystruct MyDS* createMyDS(int capacity){ struct MyDS* myDS = (struct MyDS*) malloc(sizeof(struct MyDS)); myDS->minHeap = createMinHeap(capacity); myDS->maxHeap = createMaxHeap(capacity); myDS->list = createList(); return myDS;} // Some basic operations for heaps and Listint isMaxHeapEmpty(struct MaxHeap* heap){ return (heap->size == 0); } int isMinHeapEmpty(struct MinHeap* heap){ return heap->size == 0; } int isMaxHeapFull(struct MaxHeap* heap){ return heap->size == heap->capacity; } int isMinHeapFull(struct MinHeap* heap){ return heap->size == heap->capacity; } int isListEmpty(struct List* list){ return !list->head; } int hasOnlyOneLNode(struct List* list){ return !list->head->next && !list->head->prev; } // The standard minheapify function. The only thing it does extra// is swapping indexes of heaps inside the Listvoid minHeapify(struct MinHeap* minHeap, int index){ int smallest, left, right; smallest = index; left = 2 * index + 1; right = 2 * index + 2; if ( minHeap->array[left] && left < minHeap->size && minHeap->array[left]->data < minHeap->array[smallest]->data ) smallest = left; if ( minHeap->array[right] && right < minHeap->size && minHeap->array[right]->data < minHeap->array[smallest]->data ) smallest = right; if (smallest != index) { // First swap indexes inside the List using address // of List nodes swapData(&(minHeap->array[smallest]->minHeapIndex), &(minHeap->array[index]->minHeapIndex)); // Now swap pointers to List nodes swapLNode(&minHeap->array[smallest], &minHeap->array[index]); // Fix the heap downward minHeapify(minHeap, smallest); }} // The standard maxHeapify function. The only thing it does extra// is swapping indexes of heaps inside the Listvoid maxHeapify(struct MaxHeap* maxHeap, int index){ int largest, left, right; largest = index; left = 2 * index + 1; right = 2 * index + 2; if ( maxHeap->array[left] && left < maxHeap->size && maxHeap->array[left]->data > maxHeap->array[largest]->data ) largest = left; if ( maxHeap->array[right] && right < maxHeap->size && maxHeap->array[right]->data > maxHeap->array[largest]->data ) largest = right; if (largest != index) { // First swap indexes inside the List using address // of List nodes swapData(&maxHeap->array[largest]->maxHeapIndex, &maxHeap->array[index]->maxHeapIndex); // Now swap pointers to List nodes swapLNode(&maxHeap->array[largest], &maxHeap->array[index]); // Fix the heap downward maxHeapify(maxHeap, largest); }} // Standard function to insert an item in Min Heapvoid insertMinHeap(struct MinHeap* minHeap, struct LNode* temp){ if (isMinHeapFull(minHeap)) return; ++minHeap->size; int i = minHeap->size - 1; while (i && temp->data < minHeap->array[(i - 1) / 2]->data ) { minHeap->array[i] = minHeap->array[(i - 1) / 2]; minHeap->array[i]->minHeapIndex = i; i = (i - 1) / 2; } minHeap->array[i] = temp; minHeap->array[i]->minHeapIndex = i;} // Standard function to insert an item in Max Heapvoid insertMaxHeap(struct MaxHeap* maxHeap, struct LNode* temp){ if (isMaxHeapFull(maxHeap)) return; ++maxHeap->size; int i = maxHeap->size - 1; while (i && temp->data > maxHeap->array[(i - 1) / 2]->data ) { maxHeap->array[i] = maxHeap->array[(i - 1) / 2]; maxHeap->array[i]->maxHeapIndex = i; i = (i - 1) / 2; } maxHeap->array[i] = temp; maxHeap->array[i]->maxHeapIndex = i;} // Function to find minimum value stored in the main data structureint findMin(struct MyDS* myDS){ if (isMinHeapEmpty(myDS->minHeap)) return INT_MAX; return myDS->minHeap->array[0]->data;} // Function to find maximum value stored in the main data structureint findMax(struct MyDS* myDS){ if (isMaxHeapEmpty(myDS->maxHeap)) return INT_MIN; return myDS->maxHeap->array[0]->data;} // A utility function to remove an item from linked listvoid removeLNode(struct List* list, struct LNode** temp){ if (hasOnlyOneLNode(list)) list->head = NULL; else if (!(*temp)->prev) // first node { list->head = (*temp)->next; (*temp)->next->prev = NULL; } // any other node including last else { (*temp)->prev->next = (*temp)->next; // last node if ((*temp)->next) (*temp)->next->prev = (*temp)->prev; } free(*temp); *temp = NULL;} // Function to delete maximum value stored in the main data structurevoid deleteMax(struct MyDS* myDS){ MinHeap *minHeap = myDS->minHeap; MaxHeap *maxHeap = myDS->maxHeap; if (isMaxHeapEmpty(maxHeap)) return; struct LNode* temp = maxHeap->array[0]; // delete the maximum item from maxHeap maxHeap->array[0] = maxHeap->array[maxHeap->size - 1]; --maxHeap->size; maxHeap->array[0]->maxHeapIndex = 0; maxHeapify(maxHeap, 0); // remove the item from minHeap minHeap->array[temp->minHeapIndex] = minHeap->array[minHeap->size - 1]; --minHeap->size; minHeap->array[temp->minHeapIndex]->minHeapIndex = temp->minHeapIndex; minHeapify(minHeap, temp->minHeapIndex); // remove the node from List removeLNode(myDS->list, &temp);} // Function to delete minimum value stored in the main data structurevoid deleteMin(struct MyDS* myDS){ MinHeap *minHeap = myDS->minHeap; MaxHeap *maxHeap = myDS->maxHeap; if (isMinHeapEmpty(minHeap)) return; struct LNode* temp = minHeap->array[0]; // delete the minimum item from minHeap minHeap->array[0] = minHeap->array[minHeap->size - 1]; --minHeap->size; minHeap->array[0]->minHeapIndex = 0; minHeapify(minHeap, 0); // remove the item from maxHeap maxHeap->array[temp->maxHeapIndex] = maxHeap->array[maxHeap->size - 1]; --maxHeap->size; maxHeap->array[temp->maxHeapIndex]->maxHeapIndex = temp->maxHeapIndex; maxHeapify(maxHeap, temp->maxHeapIndex); // remove the node from List removeLNode(myDS->list, &temp);} // Function to enList an item to Listvoid insertAtHead(struct List* list, struct LNode* temp){ if (isListEmpty(list)) list->head = temp; else { temp->next = list->head; list->head->prev = temp; list->head = temp; }} // Function to delete an item from List. The function also// removes item from min and max heapsvoid Delete(struct MyDS* myDS, int item){ MinHeap *minHeap = myDS->minHeap; MaxHeap *maxHeap = myDS->maxHeap; if (isListEmpty(myDS->list)) return; // search the node in List struct LNode* temp = myDS->list->head; while (temp && temp->data != item) temp = temp->next; // if item not found if (!temp || temp && temp->data != item) return; // remove item from min heap minHeap->array[temp->minHeapIndex] = minHeap->array[minHeap->size - 1]; --minHeap->size; minHeap->array[temp->minHeapIndex]->minHeapIndex = temp->minHeapIndex; minHeapify(minHeap, temp->minHeapIndex); // remove item from max heap maxHeap->array[temp->maxHeapIndex] = maxHeap->array[maxHeap->size - 1]; --maxHeap->size; maxHeap->array[temp->maxHeapIndex]->maxHeapIndex = temp->maxHeapIndex; maxHeapify(maxHeap, temp->maxHeapIndex); // remove node from List removeLNode(myDS->list, &temp);} // insert operation for main data structurevoid Insert(struct MyDS* myDS, int data){ struct LNode* temp = newLNode(data); // insert the item in List insertAtHead(myDS->list, temp); // insert the item in min heap insertMinHeap(myDS->minHeap, temp); // insert the item in max heap insertMaxHeap(myDS->maxHeap, temp);} // Driver program to test above functionsint main(){ struct MyDS *myDS = createMyDS(10); // Test Case #1 /*Insert(myDS, 10); Insert(myDS, 2); Insert(myDS, 32); Insert(myDS, 40); Insert(myDS, 5);*/ // Test Case #2 Insert(myDS, 10); Insert(myDS, 20); Insert(myDS, 30); Insert(myDS, 40); Insert(myDS, 50); printf(\"Maximum = %d \\n\", findMax(myDS)); printf(\"Minimum = %d \\n\\n\", findMin(myDS)); deleteMax(myDS); // 50 is deleted printf(\"After deleteMax()\\n\"); printf(\"Maximum = %d \\n\", findMax(myDS)); printf(\"Minimum = %d \\n\\n\", findMin(myDS)); deleteMin(myDS); // 10 is deleted printf(\"After deleteMin()\\n\"); printf(\"Maximum = %d \\n\", findMax(myDS)); printf(\"Minimum = %d \\n\\n\", findMin(myDS)); Delete(myDS, 40); // 40 is deleted printf(\"After Delete()\\n\"); printf(\"Maximum = %d \\n\", findMax(myDS)); printf(\"Minimum = %d \\n\", findMin(myDS)); return 0;}", "e": 38426, "s": 27430, "text": null }, { "code": null, "e": 38434, "s": 38426, "text": "Output:" }, { "code": null, "e": 38592, "s": 38434, "text": "Maximum = 50\nMinimum = 10\n\nAfter deleteMax()\nMaximum = 40\nMinimum = 10\n\nAfter deleteMin()\nMaximum = 40\nMinimum = 20\n\nAfter Delete()\nMaximum = 30\nMinimum = 20" }, { "code": null, "e": 38796, "s": 38592, "text": "This article is compiled by Aashish Barnwal and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 38815, "s": 38796, "text": "doubly linked list" }, { "code": null, "e": 38824, "s": 38815, "text": "Ola Cabs" }, { "code": null, "e": 38848, "s": 38824, "text": "Advanced Data Structure" }, { "code": null, "e": 38853, "s": 38848, "text": "Heap" }, { "code": null, "e": 38862, "s": 38853, "text": "Ola Cabs" }, { "code": null, "e": 38867, "s": 38862, "text": "Heap" }, { "code": null, "e": 38965, "s": 38867, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38974, "s": 38965, "text": "Comments" }, { "code": null, "e": 38987, "s": 38974, "text": "Old Comments" }, { "code": null, "e": 39021, "s": 38987, "text": "Agents in Artificial Intelligence" }, { "code": null, "e": 39061, "s": 39021, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 39089, "s": 39061, "text": "AVL Tree | Set 2 (Deletion)" }, { "code": null, "e": 39121, "s": 39089, "text": "Red-Black Tree | Set 2 (Insert)" }, { "code": null, "e": 39150, "s": 39121, "text": "Disjoint Set Data Structures" }, { "code": null, "e": 39159, "s": 39150, "text": "HeapSort" }, { "code": null, "e": 39171, "s": 39159, "text": "Binary Heap" }, { "code": null, "e": 39202, "s": 39171, "text": "Huffman Coding | Greedy Algo-3" }, { "code": null, "e": 39227, "s": 39202, "text": "Building Heap from Array" } ]