title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Data Structure - Binary Search Tree
A Binary Search Tree (BST) is a tree in which all the nodes follow the below-mentioned properties − The value of the key of the left sub-tree is less than the value of its parent (root) node's key. The value of the key of the left sub-tree is less than the value of its parent (root) node's key. The value of the key of the right sub-tree is greater than or equal to the value of its parent (root) node's key. The value of the key of the right sub-tree is greater than or equal to the value of its parent (root) node's key. Thus, BST divides all its sub-trees into two segments; the left sub-tree and the right sub-tree and can be defined as − left_subtree (keys) < node (key) ≤ right_subtree (keys) BST is a collection of nodes arranged in a way where they maintain BST properties. Each node has a key and an associated value. While searching, the desired key is compared to the keys in BST and if found, the associated value is retrieved. Following is a pictorial representation of BST − We observe that the root node key (27) has all less-valued keys on the left sub-tree and the higher valued keys on the right sub-tree. Following are the basic operations of a tree − Search − Searches an element in a tree. Search − Searches an element in a tree. Insert − Inserts an element in a tree. Insert − Inserts an element in a tree. Pre-order Traversal − Traverses a tree in a pre-order manner. Pre-order Traversal − Traverses a tree in a pre-order manner. In-order Traversal − Traverses a tree in an in-order manner. In-order Traversal − Traverses a tree in an in-order manner. Post-order Traversal − Traverses a tree in a post-order manner. Post-order Traversal − Traverses a tree in a post-order manner. Define a node having some data, references to its left and right child nodes. struct node { int data; struct node *leftChild; struct node *rightChild; }; Whenever an element is to be searched, start searching from the root node. Then if the data is less than the key value, search for the element in the left subtree. Otherwise, search for the element in the right subtree. Follow the same algorithm for each node. struct node* search(int data){ struct node *current = root; printf("Visiting elements: "); while(current->data != data){ if(current != NULL) { printf("%d ",current->data); //go to left tree if(current->data > data){ current = current->leftChild; } //else go to right tree else { current = current->rightChild; } //not found if(current == NULL){ return NULL; } } } return current; } Whenever an element is to be inserted, first locate its proper location. Start searching from the root node, then if the data is less than the key value, search for the empty location in the left subtree and insert the data. Otherwise, search for the empty location in the right subtree and insert the data. void insert(int data) { struct node *tempNode = (struct node*) malloc(sizeof(struct node)); struct node *current; struct node *parent; tempNode->data = data; tempNode->leftChild = NULL; tempNode->rightChild = NULL; //if tree is empty if(root == NULL) { root = tempNode; } else { current = root; parent = NULL; while(1) { parent = current; //go to left of the tree if(data < parent->data) { current = current->leftChild; //insert to the left if(current == NULL) { parent->leftChild = tempNode; return; } } //go to right of the tree else { current = current->rightChild; //insert to the right if(current == NULL) { parent->rightChild = tempNode; return; } } } } } 42 Lectures 1.5 hours Ravi Kiran 141 Lectures 13 hours Arnab Chakraborty 26 Lectures 8.5 hours Parth Panjabi 65 Lectures 6 hours Arnab Chakraborty 75 Lectures 13 hours Eduonix Learning Solutions 64 Lectures 10.5 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2680, "s": 2580, "text": "A Binary Search Tree (BST) is a tree in which all the nodes follow the below-mentioned properties −" }, { "code": null, "e": 2778, "s": 2680, "text": "The value of the key of the left sub-tree is less than the value of its parent (root) node's key." }, { "code": null, "e": 2876, "s": 2778, "text": "The value of the key of the left sub-tree is less than the value of its parent (root) node's key." }, { "code": null, "e": 2990, "s": 2876, "text": "The value of the key of the right sub-tree is greater than or equal to the value of its parent (root) node's key." }, { "code": null, "e": 3104, "s": 2990, "text": "The value of the key of the right sub-tree is greater than or equal to the value of its parent (root) node's key." }, { "code": null, "e": 3224, "s": 3104, "text": "Thus, BST divides all its sub-trees into two segments; the left sub-tree and the right sub-tree and can be defined as −" }, { "code": null, "e": 3281, "s": 3224, "text": "left_subtree (keys) < node (key) ≤ right_subtree (keys)\n" }, { "code": null, "e": 3522, "s": 3281, "text": "BST is a collection of nodes arranged in a way where they maintain BST properties. Each node has a key and an associated value. While searching, the desired key is compared to the keys in BST and if found, the associated value is retrieved." }, { "code": null, "e": 3571, "s": 3522, "text": "Following is a pictorial representation of BST −" }, { "code": null, "e": 3706, "s": 3571, "text": "We observe that the root node key (27) has all less-valued keys on the left sub-tree and the higher valued keys on the right sub-tree." }, { "code": null, "e": 3753, "s": 3706, "text": "Following are the basic operations of a tree −" }, { "code": null, "e": 3793, "s": 3753, "text": "Search − Searches an element in a tree." }, { "code": null, "e": 3833, "s": 3793, "text": "Search − Searches an element in a tree." }, { "code": null, "e": 3872, "s": 3833, "text": "Insert − Inserts an element in a tree." }, { "code": null, "e": 3911, "s": 3872, "text": "Insert − Inserts an element in a tree." }, { "code": null, "e": 3973, "s": 3911, "text": "Pre-order Traversal − Traverses a tree in a pre-order manner." }, { "code": null, "e": 4035, "s": 3973, "text": "Pre-order Traversal − Traverses a tree in a pre-order manner." }, { "code": null, "e": 4096, "s": 4035, "text": "In-order Traversal − Traverses a tree in an in-order manner." }, { "code": null, "e": 4157, "s": 4096, "text": "In-order Traversal − Traverses a tree in an in-order manner." }, { "code": null, "e": 4221, "s": 4157, "text": "Post-order Traversal − Traverses a tree in a post-order manner." }, { "code": null, "e": 4285, "s": 4221, "text": "Post-order Traversal − Traverses a tree in a post-order manner." }, { "code": null, "e": 4363, "s": 4285, "text": "Define a node having some data, references to its left and right child nodes." }, { "code": null, "e": 4451, "s": 4363, "text": "struct node {\n int data; \n struct node *leftChild;\n struct node *rightChild;\n};" }, { "code": null, "e": 4712, "s": 4451, "text": "Whenever an element is to be searched, start searching from the root node. Then if the data is less than the key value, search for the element in the left subtree. Otherwise, search for the element in the right subtree. Follow the same algorithm for each node." }, { "code": null, "e": 5274, "s": 4712, "text": "struct node* search(int data){\n struct node *current = root;\n printf(\"Visiting elements: \");\n\t\n while(current->data != data){\n\t\n if(current != NULL) {\n printf(\"%d \",current->data);\n\t\t\t\n //go to left tree\n if(current->data > data){\n current = current->leftChild;\n } //else go to right tree\n else { \n current = current->rightChild;\n }\n\t\t\t\n //not found\n if(current == NULL){\n return NULL;\n }\n }\t\t\t\n }\n \n return current;\n}" }, { "code": null, "e": 5582, "s": 5274, "text": "Whenever an element is to be inserted, first locate its proper location. Start searching from the root node, then if the data is less than the key value, search for the empty location in the left subtree and insert the data. Otherwise, search for the empty location in the right subtree and insert the data." }, { "code": null, "e": 6592, "s": 5582, "text": "void insert(int data) {\n struct node *tempNode = (struct node*) malloc(sizeof(struct node));\n struct node *current;\n struct node *parent;\n\n tempNode->data = data;\n tempNode->leftChild = NULL;\n tempNode->rightChild = NULL;\n\n //if tree is empty\n if(root == NULL) {\n root = tempNode;\n } else {\n current = root;\n parent = NULL;\n\n while(1) { \n parent = current;\n\t\t\t\n //go to left of the tree\n if(data < parent->data) {\n current = current->leftChild; \n //insert to the left\n\t\t\t\t\n if(current == NULL) {\n parent->leftChild = tempNode;\n return;\n }\n } //go to right of the tree\n else {\n current = current->rightChild;\n \n //insert to the right\n if(current == NULL) {\n parent->rightChild = tempNode;\n return;\n }\n }\n } \n }\n} " }, { "code": null, "e": 6627, "s": 6592, "text": "\n 42 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6639, "s": 6627, "text": " Ravi Kiran" }, { "code": null, "e": 6674, "s": 6639, "text": "\n 141 Lectures \n 13 hours \n" }, { "code": null, "e": 6693, "s": 6674, "text": " Arnab Chakraborty" }, { "code": null, "e": 6728, "s": 6693, "text": "\n 26 Lectures \n 8.5 hours \n" }, { "code": null, "e": 6743, "s": 6728, "text": " Parth Panjabi" }, { "code": null, "e": 6776, "s": 6743, "text": "\n 65 Lectures \n 6 hours \n" }, { "code": null, "e": 6795, "s": 6776, "text": " Arnab Chakraborty" }, { "code": null, "e": 6829, "s": 6795, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 6857, "s": 6829, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 6893, "s": 6857, "text": "\n 64 Lectures \n 10.5 hours \n" }, { "code": null, "e": 6921, "s": 6893, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 6928, "s": 6921, "text": " Print" }, { "code": null, "e": 6939, "s": 6928, "text": " Add Notes" } ]
Convert a given Binary Tree to Doubly Linked List | Set 1 - GeeksforGeeks
28 Jan, 2022 Given a Binary Tree (Bt), convert it to a Doubly Linked List(DLL). The left and right pointers in nodes are to be used as previous and next pointers respectively in converted DLL. The order of nodes in DLL must be the same as in Inorder for the given Binary Tree. The first node of Inorder traversal (leftmost node in BT) must be the head node of the DLL. I came across this question during one of my interviews. A similar problem has been discussed in this post. The problem here is simpler as we don’t need to create a circular DLL, but a simple DLL. The idea behind its solution is quite simple and straight. If the left subtree exists, process the left subtreeRecursively convert the left subtree to DLL.Then find the inorder predecessor of the root in the left subtree (the inorder predecessor is the rightmost node in the left subtree).Make the inorder predecessor as the previous root and the root as the next in order predecessor. If the right subtree exists, process the right subtree (Below 3 steps are similar to the left subtree).Recursively convert the right subtree to DLL.Then find the inorder successor of the root in the right subtree (in order the successor is the leftmost node in the right subtree).Make the inorder successor as the next root and the root as the previous inorder successor.Find the leftmost node and return it (the leftmost node is always the head of a converted DLL). If the left subtree exists, process the left subtreeRecursively convert the left subtree to DLL.Then find the inorder predecessor of the root in the left subtree (the inorder predecessor is the rightmost node in the left subtree).Make the inorder predecessor as the previous root and the root as the next in order predecessor. Recursively convert the left subtree to DLL.Then find the inorder predecessor of the root in the left subtree (the inorder predecessor is the rightmost node in the left subtree).Make the inorder predecessor as the previous root and the root as the next in order predecessor. Recursively convert the left subtree to DLL. Then find the inorder predecessor of the root in the left subtree (the inorder predecessor is the rightmost node in the left subtree). Make the inorder predecessor as the previous root and the root as the next in order predecessor. If the right subtree exists, process the right subtree (Below 3 steps are similar to the left subtree).Recursively convert the right subtree to DLL.Then find the inorder successor of the root in the right subtree (in order the successor is the leftmost node in the right subtree).Make the inorder successor as the next root and the root as the previous inorder successor. Recursively convert the right subtree to DLL.Then find the inorder successor of the root in the right subtree (in order the successor is the leftmost node in the right subtree).Make the inorder successor as the next root and the root as the previous inorder successor. Recursively convert the right subtree to DLL. Then find the inorder successor of the root in the right subtree (in order the successor is the leftmost node in the right subtree). Make the inorder successor as the next root and the root as the previous inorder successor. Find the leftmost node and return it (the leftmost node is always the head of a converted DLL). Below is the source code for the above algorithm. C++ C Java Python3 C# Javascript // A C++ program for in-place// conversion of Binary Tree to DLL#include <bits/stdc++.h>using namespace std; /* A binary tree node has data,and left and right pointers */class node {public: int data; node* left; node* right;}; /* This is the core function to convertTree to list. This function followssteps 1 and 2 of the above algorithm */node* bintree2listUtil(node* root){ // Base case if (root == NULL) return root; // Convert the left subtree and link to root if (root->left != NULL) { // Convert the left subtree node* left = bintree2listUtil(root->left); // Find inorder predecessor. After this loop, left // will point to the inorder predecessor for (; left->right != NULL; left = left->right) ; // Make root as next of the predecessor left->right = root; // Make predecessor as previous of root root->left = left; } // Convert the right subtree and link to root if (root->right != NULL) { // Convert the right subtree node* right = bintree2listUtil(root->right); // Find inorder successor. After this loop, right // will point to the inorder successor for (; right->left != NULL; right = right->left) ; // Make root as previous of successor right->left = root; // Make successor as next of root root->right = right; } return root;} // The main function that first calls// bintree2listUtil(), then follows step 3// of the above algorithmnode* bintree2list(node* root){ // Base case if (root == NULL) return root; // Convert to DLL using bintree2listUtil() root = bintree2listUtil(root); // bintree2listUtil() returns root node of the converted // DLL. We need pointer to the leftmost node which is // head of the constructed DLL, so move to the leftmost // node while (root->left != NULL) root = root->left; return (root);} /* Helper function that allocates a new node with thegiven data and NULL left and right pointers. */node* newNode(int data){ node* new_node = new node(); new_node->data = data; new_node->left = new_node->right = NULL; return (new_node);} /* Function to print nodes in a given doubly linked list */void printList(node* node){ while (node != NULL) { cout << node->data << " "; node = node->right; }} /* Driver code*/int main(){ // Let us create the tree shown in above diagram node* root = newNode(10); root->left = newNode(12); root->right = newNode(15); root->left->left = newNode(25); root->left->right = newNode(30); root->right->left = newNode(36); // Convert to DLL node* head = bintree2list(root); // Print the converted list printList(head); return 0;} // This code is contributed by rathbhupendra // A C program for in-place conversion of Binary Tree to DLL#include <stdio.h> /* A binary tree node has data, and left and right pointers */struct node{ int data; node* left; node* right;}; /* This is the core function to convert Tree to list. This function follows steps 1 and 2 of the above algorithm */node* bintree2listUtil(node* root){ // Base case if (root == NULL) return root; // Convert the left subtree and link to root if (root->left != NULL) { // Convert the left subtree node* left = bintree2listUtil(root->left); // Find inorder predecessor. After this loop, left // will point to the inorder predecessor for (; left->right!=NULL; left=left->right); // Make root as next of the predecessor left->right = root; // Make predecessor as previous of root root->left = left; } // Convert the right subtree and link to root if (root->right!=NULL) { // Convert the right subtree node* right = bintree2listUtil(root->right); // Find inorder successor. After this loop, right // will point to the inorder successor for (; right->left!=NULL; right = right->left); // Make root as previous of successor right->left = root; // Make successor as next of root root->right = right; } return root;} // The main function that first calls bintree2listUtil(), then follows step 3// of the above algorithmnode* bintree2list(node *root){ // Base case if (root == NULL) return root; // Convert to DLL using bintree2listUtil() root = bintree2listUtil(root); // bintree2listUtil() returns root node of the converted // DLL. We need pointer to the leftmost node which is // head of the constructed DLL, so move to the leftmost node while (root->left != NULL) root = root->left; return (root);} /* Helper function that allocates a new node with the given data and NULL left and right pointers. */node* newNode(int data){ node* new_node = new node; new_node->data = data; new_node->left = new_node->right = NULL; return (new_node);} /* Function to print nodes in a given doubly linked list */void printList(node *node){ while (node!=NULL) { printf("%d ", node->data); node = node->right; }} /* Driver program to test above functions*/int main(){ // Let us create the tree shown in above diagram node *root = newNode(10); root->left = newNode(12); root->right = newNode(15); root->left->left = newNode(25); root->left->right = newNode(30); root->right->left = newNode(36); // Convert to DLL node *head = bintree2list(root); // Print the converted list printList(head); return 0;} // Java program to convert binary tree to double linked list /* A binary tree node has data, and left and right pointers */class Node{ int data; Node left, right; Node(int item) { data = item; left = right = null; }} class BinaryTree{ Node root; /* This is the core function to convert Tree to list. This function follows steps 1 and 2 of the above algorithm */ Node bintree2listUtil(Node node) { // Base case if (node == null) return node; // Convert the left subtree and link to root if (node.left != null) { // Convert the left subtree Node left = bintree2listUtil(node.left); // Find inorder predecessor. After this loop, left // will point to the inorder predecessor for (; left.right != null; left = left.right); // Make root as next of the predecessor left.right = node; // Make predecessor as previous of root node.left = left; } // Convert the right subtree and link to root if (node.right != null) { // Convert the right subtree Node right = bintree2listUtil(node.right); // Find inorder successor. After this loop, right // will point to the inorder successor for (; right.left != null; right = right.left); // Make root as previous of successor right.left = node; // Make successor as next of root node.right = right; } return node; } // The main function that first calls bintree2listUtil(), then follows // step 3 of the above algorithm Node bintree2list(Node node) { // Base case if (node == null) return node; // Convert to DLL using bintree2listUtil() node = bintree2listUtil(node); // bintree2listUtil() returns root node of the converted // DLL. We need pointer to the leftmost node which is // head of the constructed DLL, so move to the leftmost node while (node.left != null) node = node.left; return node; } /* Function to print nodes in a given doubly linked list */ void printList(Node node) { while (node != null) { System.out.print(node.data + " "); node = node.right; } } /* Driver program to test above functions*/ public static void main(String[] args) { BinaryTree tree = new BinaryTree(); // Let us create the tree shown in above diagram tree.root = new Node(10); tree.root.left = new Node(12); tree.root.right = new Node(15); tree.root.left.left = new Node(25); tree.root.left.right = new Node(30); tree.root.right.left = new Node(36); // Convert to DLL Node head = tree.bintree2list(tree.root); // Print the converted list tree.printList(head); }} # Python program to convert# binary tree to doubly linked list class Node(object): """Binary tree Node class has data, left and right child""" def __init__(self, item): self.data = item self.left = None self.right = None def BTToDLLUtil(root): """This is a utility function to convert the binary tree to doubly linked list. Most of the core task is done by this function.""" if root is None: return root # Convert left subtree # and link to root if root.left: # Convert the left subtree left = BTToDLLUtil(root.left) # Find inorder predecessor, After # this loop, left will point to the # inorder predecessor of root while left.right: left = left.right # Make root as next of predecessor left.right = root # Make predecessor as # previous of root root.left = left # Convert the right subtree # and link to root if root.right: # Convert the right subtree right = BTToDLLUtil(root.right) # Find inorder successor, After # this loop, right will point to # the inorder successor of root while right.left: right = right.left # Make root as previous # of successor right.left = root # Make successor as # next of root root.right = right return root def BTToDLL(root): if root is None: return root # Convert to doubly linked # list using BLLToDLLUtil root = BTToDLLUtil(root) # We need pointer to left most # node which is head of the # constructed Doubly Linked list while root.left: root = root.left return root def print_list(head): """Function to print the given doubly linked list""" if head is None: return while head: print(head.data, end = " ") head = head.right # Driver Codeif __name__ == '__main__': root = Node(10) root.left = Node(12) root.right = Node(15) root.left.left = Node(25) root.left.right = Node(30) root.right.left = Node(36) head = BTToDLL(root) print_list(head) # This code is contributed# by viveksyngh using System; // C# program to convert binary tree to double linked list /* A binary tree node has data, and left and right pointers */public class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} public class BinaryTree{ public Node root; /* This is the core function to convert Tree to list. This function follows steps 1 and 2 of the above algorithm */ public virtual Node bintree2listUtil(Node node) { // Base case if (node == null) { return node; } // Convert the left subtree and link to root if (node.left != null) { // Convert the left subtree Node left = bintree2listUtil(node.left); // Find inorder predecessor. After this loop, left // will point to the inorder predecessor for (; left.right != null; left = left.right) { ; } // Make root as next of the predecessor left.right = node; // Make predecessor as previous of root node.left = left; } // Convert the right subtree and link to root if (node.right != null) { // Convert the right subtree Node right = bintree2listUtil(node.right); // Find inorder successor. After this loop, right // will point to the inorder successor for (; right.left != null; right = right.left) { ; } // Make root as previous of successor right.left = node; // Make successor as next of root node.right = right; } return node; } // The main function that first calls bintree2listUtil(), then follows // step 3 of the above algorithm public virtual Node bintree2list(Node node) { // Base case if (node == null) { return node; } // Convert to DLL using bintree2listUtil() node = bintree2listUtil(node); // bintree2listUtil() returns root node of the converted // DLL. We need pointer to the leftmost node which is // head of the constructed DLL, so move to the leftmost node while (node.left != null) { node = node.left; } return node; } /* Function to print nodes in a given doubly linked list */ public virtual void printList(Node node) { while (node != null) { Console.Write(node.data + " "); node = node.right; } } /* Driver program to test above functions*/ public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); // Let us create the tree shown in above diagram tree.root = new Node(10); tree.root.left = new Node(12); tree.root.right = new Node(15); tree.root.left.left = new Node(25); tree.root.left.right = new Node(30); tree.root.right.left = new Node(36); // Convert to DLL Node head = tree.bintree2list(tree.root); // Print the converted list tree.printList(head); }} // This code is contributed by Shrikant13 <script> // javascript program to convert binary tree to double linked list /* A binary tree node has data, and left and right pointers */ class Node { constructor(val) { this.data = val; this.left = null; this.right = null; } } var root; /* * This is the core function to convert Tree to list. This function follows * steps 1 and 2 of the above algorithm */ function bintree2listUtil(node) { // Base case if (node == null) return node; // Convert the left subtree and link to root if (node.left != null) { // Convert the left subtree var left = bintree2listUtil(node.left); // Find inorder predecessor. After this loop, left // will point to the inorder predecessor for (; left.right != null; left = left.right) // Make root as next of the predecessor left.right = node; // Make predecessor as previous of root node.left = left; } // Convert the right subtree and link to root if (node.right != null) { // Convert the right subtree var right = bintree2listUtil(node.right); // Find inorder successor. After this loop, right // will point to the inorder successor for (; right.left != null; right = right.left) // Make root as previous of successor right.left = node; // Make successor as next of root node.right = right; } return node; } // The main function that first calls bintree2listUtil(), then follows // step 3 of the above algorithm function bintree2list(node) { // Base case if (node == null) return node; // Convert to DLL using bintree2listUtil() node = bintree2listUtil(node); // bintree2listUtil() returns root node of the converted // DLL. We need pointer to the leftmost node which is // head of the constructed DLL, so move to the leftmost node while (node.left != null) node = node.left; return node; } /* Function to print nodes in a given doubly linked list */ function printList(node) { while (node != null) { document.write(node.data + " "); node = node.right; } } /* Driver program to test above functions */ // Let us create the tree shown in above diagram root = new Node(10); root.left = new Node(12); root.right = new Node(15); root.left.left = new Node(25); root.left.right = new Node(30); root.right.left = new Node(36); // Convert to DLL var head = bintree2list(root); // Print the converted list printList(head); // This code contributed by umadevi9616</script> 25 12 30 10 36 15 Another Approach:Algorithm: Traverse the tree in inorder fashion.While visiting each node, keep track of DLL’s head and tail pointers, insert each visited node to the end of DLL using tail pointer.Return head of the list. Traverse the tree in inorder fashion. While visiting each node, keep track of DLL’s head and tail pointers, insert each visited node to the end of DLL using tail pointer. Return head of the list. Below is the implementation of the above approach: C++ Java C# Javascript // A C++ program for in-place// conversion of Binary Tree to DLL#include <bits/stdc++.h>using namespace std; /* A binary tree node has data,and left and right pointers */class node {public: int data; node* left; node* right;}; /* This is the core function to convertTree to list.*/void bintree2listUtil(node* root, node** head, node** tail){ if (root == NULL) return; bintree2listUtil(root->left, head, tail); if (*head == NULL) { *head = root; } root->left = *tail; if (*tail != NULL) { (*tail)->right = root; } *tail = root; bintree2listUtil(root->right, head, tail);} // The main function that first calls// bintree2listUtil()node* bintree2list(node* root){ // Base case if (root == NULL) return root; node* head = NULL; node* tail = NULL; bintree2listUtil(root, &head, &tail); return head;} /* Helper function that allocates a new node with thegiven data and NULL left and right pointers. */node* newNode(int data){ node* new_node = new node(); new_node->data = data; new_node->left = new_node->right = NULL; return (new_node);} /* Function to print nodes in a given doubly linked list */void printList(node* node){ while (node != NULL) { cout << node->data << " "; node = node->right; }} /* Driver code*/int main(){ // Let us create the tree shown in above diagram node* root = newNode(10); root->left = newNode(12); root->right = newNode(15); root->left->left = newNode(25); root->left->right = newNode(30); root->right->left = newNode(36); // Convert to DLL node* head = bintree2list(root); // Print the converted list printList(head); return 0;} // This code is contributed by rathbhupendra // A Java program for in-place// conversion of Binary Tree to DLLimport java.util.*; class GFG{ /* A binary tree node has data,and left and right pointers */static class node { int data; node left; node right;}; /* * This is the core function to convert Tree to list. */static node head, tail;static void bintree2listUtil(node root){ if (root == null) return ; node left = root.left; node right = root.right; bintree2listUtil(root.left); if (head == null) { head = root; } root.left = tail; if (tail != null) { (tail).right = root; } tail = root; bintree2listUtil(root.right);} // The main function that first calls// bintree2listUtil()static void bintree2list(node root){ // Base case if (root == null) head= root; bintree2listUtil(root); } /* Helper function that allocates a new node with thegiven data and null left and right pointers. */static node newNode(int data){ node new_node = new node(); new_node.data = data; new_node.left = new_node.right = null; return (new_node);} /* Function to print nodes in a given doubly linked list */static void printList(){ while (head != null) { System.out.print(head.data+ " "); head = head.right; }} /* Driver code */public static void main(String[] args){ // Let us create the tree shown in above diagram node root = newNode(10); root.left = newNode(12); root.right = newNode(15); root.left.left = newNode(25); root.left.right = newNode(30); root.right.left = newNode(36); head = null; tail = null; // Convert to DLL bintree2list(root); // Print the converted list printList(); }} // This code is contributed by umadevi9616 // A C# program for in-place// conversion of Binary Tree to DLLusing System; public class GFG { /* * A binary tree node has data, and left and right pointers */public class node { public int data; public node left; public node right; }; /* * This is the core function to convert Tree to list. */ static node head, tail; static void bintree2listUtil(node root) { if (root == null) return; node left = root.left; node right = root.right; bintree2listUtil(root.left); if (head == null) { head = root; } root.left = tail; if (tail != null) { (tail).right = root; } tail = root; bintree2listUtil(root.right); } // The main function that first calls // bintree2listUtil() static void bintree2list(node root) { // Base case if (root == null) head = root; bintree2listUtil(root); } /* * Helper function that allocates a new node with the given data and null left * and right pointers. */ static node newNode(int data) { node new_node = new node(); new_node.data = data; new_node.left = new_node.right = null; return (new_node); } /* Function to print nodes in a given doubly linked list */ static void printList() { while (head != null) { Console.Write(head.data + " "); head = head.right; } } /* Driver code */ public static void Main(String[] args) { // Let us create the tree shown in above diagram node root = newNode(10); root.left = newNode(12); root.right = newNode(15); root.left.left = newNode(25); root.left.right = newNode(30); root.right.left = newNode(36); head = null; tail = null; // Convert to DLL bintree2list(root); // Print the converted list printList(); }} // This code is contributed by gauravrajput1 <script>// A javascript program for in-place// conversion of Binary Tree to DLL /* * A binary tree node has data, and left and right pointers */ class Node { constructor() { this.data = 0; this.left = null; this.right = null; } } /* * This is the core function to convert Tree to list. */ var head, tail; function bintree2listUtil(root) { if (root == null) return; var left = root.left; var right = root.right; bintree2listUtil(root.left); if (head == null) { head = root; } root.left = tail; if (tail != null) { (tail).right = root; } tail = root; bintree2listUtil(root.right); } // The main function that first calls // bintree2listUtil() function bintree2list( root) { // Base case if (root == null) head = root; bintree2listUtil(root); } /* * Helper function that allocates a new node with the given data and null left * and right pointers. */ function newNode(data) { var new_node = new Node(); new_node.data = data; new_node.left = new_node.right = null; return (new_node); } /* Function to print nodes in a given doubly linked list */ function printList() { while (head != null) { document.write(head.data + " "); head = head.right; } } /* Driver code */ // Let us create the tree shown in above diagram var root = newNode(10); root.left = newNode(12); root.right = newNode(15); root.left.left = newNode(25); root.left.right = newNode(30); root.right.left = newNode(36); head = null; tail = null; // Convert to DLL bintree2list(root); // Print the converted list printList(); // This code is contributed by gauravrajput1</script> 25 12 30 10 36 15 This article is compiled by Ashish Mangla 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.You may also like to see Convert a given Binary Tree to Doubly Linked List | Set 2 for another simple and efficient solution. viveksyngh shrikanth13 rathbhupendra prakhar jauhari ankitshuklatiwari1 umadevi9616 bittu06 arorakashish0911 GauravRajput1 simmytarika5 amartyaghoshgfg gauravgupta092002 Amazon doubly linked list Goldman Sachs Microsoft Linked List Tree Amazon Microsoft Goldman Sachs Linked List Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Given a linked list which is sorted, how will you insert in sorted way Implementing a Linked List in Java using Class Insertion Sort for Singly Linked List Circular Linked List | Set 2 (Traversal) Split a Circular Linked List into two halves Tree Traversals (Inorder, Preorder and Postorder) Binary Tree | Set 1 (Introduction) Level Order Binary Tree Traversal AVL Tree | Set 1 (Insertion) Inorder Tree Traversal without Recursion
[ { "code": null, "e": 24585, "s": 24557, "text": "\n28 Jan, 2022" }, { "code": null, "e": 24942, "s": 24585, "text": "Given a Binary Tree (Bt), convert it to a Doubly Linked List(DLL). The left and right pointers in nodes are to be used as previous and next pointers respectively in converted DLL. The order of nodes in DLL must be the same as in Inorder for the given Binary Tree. The first node of Inorder traversal (leftmost node in BT) must be the head node of the DLL. " }, { "code": null, "e": 25051, "s": 24942, "text": "I came across this question during one of my interviews. A similar problem has been discussed in this post. " }, { "code": null, "e": 25199, "s": 25051, "text": "The problem here is simpler as we don’t need to create a circular DLL, but a simple DLL. The idea behind its solution is quite simple and straight." }, { "code": null, "e": 25993, "s": 25199, "text": "If the left subtree exists, process the left subtreeRecursively convert the left subtree to DLL.Then find the inorder predecessor of the root in the left subtree (the inorder predecessor is the rightmost node in the left subtree).Make the inorder predecessor as the previous root and the root as the next in order predecessor. If the right subtree exists, process the right subtree (Below 3 steps are similar to the left subtree).Recursively convert the right subtree to DLL.Then find the inorder successor of the root in the right subtree (in order the successor is the leftmost node in the right subtree).Make the inorder successor as the next root and the root as the previous inorder successor.Find the leftmost node and return it (the leftmost node is always the head of a converted DLL)." }, { "code": null, "e": 26320, "s": 25993, "text": "If the left subtree exists, process the left subtreeRecursively convert the left subtree to DLL.Then find the inorder predecessor of the root in the left subtree (the inorder predecessor is the rightmost node in the left subtree).Make the inorder predecessor as the previous root and the root as the next in order predecessor." }, { "code": null, "e": 26595, "s": 26320, "text": "Recursively convert the left subtree to DLL.Then find the inorder predecessor of the root in the left subtree (the inorder predecessor is the rightmost node in the left subtree).Make the inorder predecessor as the previous root and the root as the next in order predecessor." }, { "code": null, "e": 26640, "s": 26595, "text": "Recursively convert the left subtree to DLL." }, { "code": null, "e": 26775, "s": 26640, "text": "Then find the inorder predecessor of the root in the left subtree (the inorder predecessor is the rightmost node in the left subtree)." }, { "code": null, "e": 26872, "s": 26775, "text": "Make the inorder predecessor as the previous root and the root as the next in order predecessor." }, { "code": null, "e": 27245, "s": 26872, "text": " If the right subtree exists, process the right subtree (Below 3 steps are similar to the left subtree).Recursively convert the right subtree to DLL.Then find the inorder successor of the root in the right subtree (in order the successor is the leftmost node in the right subtree).Make the inorder successor as the next root and the root as the previous inorder successor." }, { "code": null, "e": 27514, "s": 27245, "text": "Recursively convert the right subtree to DLL.Then find the inorder successor of the root in the right subtree (in order the successor is the leftmost node in the right subtree).Make the inorder successor as the next root and the root as the previous inorder successor." }, { "code": null, "e": 27560, "s": 27514, "text": "Recursively convert the right subtree to DLL." }, { "code": null, "e": 27693, "s": 27560, "text": "Then find the inorder successor of the root in the right subtree (in order the successor is the leftmost node in the right subtree)." }, { "code": null, "e": 27785, "s": 27693, "text": "Make the inorder successor as the next root and the root as the previous inorder successor." }, { "code": null, "e": 27881, "s": 27785, "text": "Find the leftmost node and return it (the leftmost node is always the head of a converted DLL)." }, { "code": null, "e": 27931, "s": 27881, "text": "Below is the source code for the above algorithm." }, { "code": null, "e": 27935, "s": 27931, "text": "C++" }, { "code": null, "e": 27937, "s": 27935, "text": "C" }, { "code": null, "e": 27942, "s": 27937, "text": "Java" }, { "code": null, "e": 27950, "s": 27942, "text": "Python3" }, { "code": null, "e": 27953, "s": 27950, "text": "C#" }, { "code": null, "e": 27964, "s": 27953, "text": "Javascript" }, { "code": "// A C++ program for in-place// conversion of Binary Tree to DLL#include <bits/stdc++.h>using namespace std; /* A binary tree node has data,and left and right pointers */class node {public: int data; node* left; node* right;}; /* This is the core function to convertTree to list. This function followssteps 1 and 2 of the above algorithm */node* bintree2listUtil(node* root){ // Base case if (root == NULL) return root; // Convert the left subtree and link to root if (root->left != NULL) { // Convert the left subtree node* left = bintree2listUtil(root->left); // Find inorder predecessor. After this loop, left // will point to the inorder predecessor for (; left->right != NULL; left = left->right) ; // Make root as next of the predecessor left->right = root; // Make predecessor as previous of root root->left = left; } // Convert the right subtree and link to root if (root->right != NULL) { // Convert the right subtree node* right = bintree2listUtil(root->right); // Find inorder successor. After this loop, right // will point to the inorder successor for (; right->left != NULL; right = right->left) ; // Make root as previous of successor right->left = root; // Make successor as next of root root->right = right; } return root;} // The main function that first calls// bintree2listUtil(), then follows step 3// of the above algorithmnode* bintree2list(node* root){ // Base case if (root == NULL) return root; // Convert to DLL using bintree2listUtil() root = bintree2listUtil(root); // bintree2listUtil() returns root node of the converted // DLL. We need pointer to the leftmost node which is // head of the constructed DLL, so move to the leftmost // node while (root->left != NULL) root = root->left; return (root);} /* Helper function that allocates a new node with thegiven data and NULL left and right pointers. */node* newNode(int data){ node* new_node = new node(); new_node->data = data; new_node->left = new_node->right = NULL; return (new_node);} /* Function to print nodes in a given doubly linked list */void printList(node* node){ while (node != NULL) { cout << node->data << \" \"; node = node->right; }} /* Driver code*/int main(){ // Let us create the tree shown in above diagram node* root = newNode(10); root->left = newNode(12); root->right = newNode(15); root->left->left = newNode(25); root->left->right = newNode(30); root->right->left = newNode(36); // Convert to DLL node* head = bintree2list(root); // Print the converted list printList(head); return 0;} // This code is contributed by rathbhupendra", "e": 30818, "s": 27964, "text": null }, { "code": "// A C program for in-place conversion of Binary Tree to DLL#include <stdio.h> /* A binary tree node has data, and left and right pointers */struct node{ int data; node* left; node* right;}; /* This is the core function to convert Tree to list. This function follows steps 1 and 2 of the above algorithm */node* bintree2listUtil(node* root){ // Base case if (root == NULL) return root; // Convert the left subtree and link to root if (root->left != NULL) { // Convert the left subtree node* left = bintree2listUtil(root->left); // Find inorder predecessor. After this loop, left // will point to the inorder predecessor for (; left->right!=NULL; left=left->right); // Make root as next of the predecessor left->right = root; // Make predecessor as previous of root root->left = left; } // Convert the right subtree and link to root if (root->right!=NULL) { // Convert the right subtree node* right = bintree2listUtil(root->right); // Find inorder successor. After this loop, right // will point to the inorder successor for (; right->left!=NULL; right = right->left); // Make root as previous of successor right->left = root; // Make successor as next of root root->right = right; } return root;} // The main function that first calls bintree2listUtil(), then follows step 3// of the above algorithmnode* bintree2list(node *root){ // Base case if (root == NULL) return root; // Convert to DLL using bintree2listUtil() root = bintree2listUtil(root); // bintree2listUtil() returns root node of the converted // DLL. We need pointer to the leftmost node which is // head of the constructed DLL, so move to the leftmost node while (root->left != NULL) root = root->left; return (root);} /* Helper function that allocates a new node with the given data and NULL left and right pointers. */node* newNode(int data){ node* new_node = new node; new_node->data = data; new_node->left = new_node->right = NULL; return (new_node);} /* Function to print nodes in a given doubly linked list */void printList(node *node){ while (node!=NULL) { printf(\"%d \", node->data); node = node->right; }} /* Driver program to test above functions*/int main(){ // Let us create the tree shown in above diagram node *root = newNode(10); root->left = newNode(12); root->right = newNode(15); root->left->left = newNode(25); root->left->right = newNode(30); root->right->left = newNode(36); // Convert to DLL node *head = bintree2list(root); // Print the converted list printList(head); return 0;}", "e": 33612, "s": 30818, "text": null }, { "code": "// Java program to convert binary tree to double linked list /* A binary tree node has data, and left and right pointers */class Node{ int data; Node left, right; Node(int item) { data = item; left = right = null; }} class BinaryTree{ Node root; /* This is the core function to convert Tree to list. This function follows steps 1 and 2 of the above algorithm */ Node bintree2listUtil(Node node) { // Base case if (node == null) return node; // Convert the left subtree and link to root if (node.left != null) { // Convert the left subtree Node left = bintree2listUtil(node.left); // Find inorder predecessor. After this loop, left // will point to the inorder predecessor for (; left.right != null; left = left.right); // Make root as next of the predecessor left.right = node; // Make predecessor as previous of root node.left = left; } // Convert the right subtree and link to root if (node.right != null) { // Convert the right subtree Node right = bintree2listUtil(node.right); // Find inorder successor. After this loop, right // will point to the inorder successor for (; right.left != null; right = right.left); // Make root as previous of successor right.left = node; // Make successor as next of root node.right = right; } return node; } // The main function that first calls bintree2listUtil(), then follows // step 3 of the above algorithm Node bintree2list(Node node) { // Base case if (node == null) return node; // Convert to DLL using bintree2listUtil() node = bintree2listUtil(node); // bintree2listUtil() returns root node of the converted // DLL. We need pointer to the leftmost node which is // head of the constructed DLL, so move to the leftmost node while (node.left != null) node = node.left; return node; } /* Function to print nodes in a given doubly linked list */ void printList(Node node) { while (node != null) { System.out.print(node.data + \" \"); node = node.right; } } /* Driver program to test above functions*/ public static void main(String[] args) { BinaryTree tree = new BinaryTree(); // Let us create the tree shown in above diagram tree.root = new Node(10); tree.root.left = new Node(12); tree.root.right = new Node(15); tree.root.left.left = new Node(25); tree.root.left.right = new Node(30); tree.root.right.left = new Node(36); // Convert to DLL Node head = tree.bintree2list(tree.root); // Print the converted list tree.printList(head); }}", "e": 36630, "s": 33612, "text": null }, { "code": "# Python program to convert# binary tree to doubly linked list class Node(object): \"\"\"Binary tree Node class has data, left and right child\"\"\" def __init__(self, item): self.data = item self.left = None self.right = None def BTToDLLUtil(root): \"\"\"This is a utility function to convert the binary tree to doubly linked list. Most of the core task is done by this function.\"\"\" if root is None: return root # Convert left subtree # and link to root if root.left: # Convert the left subtree left = BTToDLLUtil(root.left) # Find inorder predecessor, After # this loop, left will point to the # inorder predecessor of root while left.right: left = left.right # Make root as next of predecessor left.right = root # Make predecessor as # previous of root root.left = left # Convert the right subtree # and link to root if root.right: # Convert the right subtree right = BTToDLLUtil(root.right) # Find inorder successor, After # this loop, right will point to # the inorder successor of root while right.left: right = right.left # Make root as previous # of successor right.left = root # Make successor as # next of root root.right = right return root def BTToDLL(root): if root is None: return root # Convert to doubly linked # list using BLLToDLLUtil root = BTToDLLUtil(root) # We need pointer to left most # node which is head of the # constructed Doubly Linked list while root.left: root = root.left return root def print_list(head): \"\"\"Function to print the given doubly linked list\"\"\" if head is None: return while head: print(head.data, end = \" \") head = head.right # Driver Codeif __name__ == '__main__': root = Node(10) root.left = Node(12) root.right = Node(15) root.left.left = Node(25) root.left.right = Node(30) root.right.left = Node(36) head = BTToDLL(root) print_list(head) # This code is contributed# by viveksyngh", "e": 38876, "s": 36630, "text": null }, { "code": "using System; // C# program to convert binary tree to double linked list /* A binary tree node has data, and left and right pointers */public class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} public class BinaryTree{ public Node root; /* This is the core function to convert Tree to list. This function follows steps 1 and 2 of the above algorithm */ public virtual Node bintree2listUtil(Node node) { // Base case if (node == null) { return node; } // Convert the left subtree and link to root if (node.left != null) { // Convert the left subtree Node left = bintree2listUtil(node.left); // Find inorder predecessor. After this loop, left // will point to the inorder predecessor for (; left.right != null; left = left.right) { ; } // Make root as next of the predecessor left.right = node; // Make predecessor as previous of root node.left = left; } // Convert the right subtree and link to root if (node.right != null) { // Convert the right subtree Node right = bintree2listUtil(node.right); // Find inorder successor. After this loop, right // will point to the inorder successor for (; right.left != null; right = right.left) { ; } // Make root as previous of successor right.left = node; // Make successor as next of root node.right = right; } return node; } // The main function that first calls bintree2listUtil(), then follows // step 3 of the above algorithm public virtual Node bintree2list(Node node) { // Base case if (node == null) { return node; } // Convert to DLL using bintree2listUtil() node = bintree2listUtil(node); // bintree2listUtil() returns root node of the converted // DLL. We need pointer to the leftmost node which is // head of the constructed DLL, so move to the leftmost node while (node.left != null) { node = node.left; } return node; } /* Function to print nodes in a given doubly linked list */ public virtual void printList(Node node) { while (node != null) { Console.Write(node.data + \" \"); node = node.right; } } /* Driver program to test above functions*/ public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); // Let us create the tree shown in above diagram tree.root = new Node(10); tree.root.left = new Node(12); tree.root.right = new Node(15); tree.root.left.left = new Node(25); tree.root.left.right = new Node(30); tree.root.right.left = new Node(36); // Convert to DLL Node head = tree.bintree2list(tree.root); // Print the converted list tree.printList(head); }} // This code is contributed by Shrikant13", "e": 42143, "s": 38876, "text": null }, { "code": "<script> // javascript program to convert binary tree to double linked list /* A binary tree node has data, and left and right pointers */ class Node { constructor(val) { this.data = val; this.left = null; this.right = null; } } var root; /* * This is the core function to convert Tree to list. This function follows * steps 1 and 2 of the above algorithm */ function bintree2listUtil(node) { // Base case if (node == null) return node; // Convert the left subtree and link to root if (node.left != null) { // Convert the left subtree var left = bintree2listUtil(node.left); // Find inorder predecessor. After this loop, left // will point to the inorder predecessor for (; left.right != null; left = left.right) // Make root as next of the predecessor left.right = node; // Make predecessor as previous of root node.left = left; } // Convert the right subtree and link to root if (node.right != null) { // Convert the right subtree var right = bintree2listUtil(node.right); // Find inorder successor. After this loop, right // will point to the inorder successor for (; right.left != null; right = right.left) // Make root as previous of successor right.left = node; // Make successor as next of root node.right = right; } return node; } // The main function that first calls bintree2listUtil(), then follows // step 3 of the above algorithm function bintree2list(node) { // Base case if (node == null) return node; // Convert to DLL using bintree2listUtil() node = bintree2listUtil(node); // bintree2listUtil() returns root node of the converted // DLL. We need pointer to the leftmost node which is // head of the constructed DLL, so move to the leftmost node while (node.left != null) node = node.left; return node; } /* Function to print nodes in a given doubly linked list */ function printList(node) { while (node != null) { document.write(node.data + \" \"); node = node.right; } } /* Driver program to test above functions */ // Let us create the tree shown in above diagram root = new Node(10); root.left = new Node(12); root.right = new Node(15); root.left.left = new Node(25); root.left.right = new Node(30); root.right.left = new Node(36); // Convert to DLL var head = bintree2list(root); // Print the converted list printList(head); // This code contributed by umadevi9616</script>", "e": 45030, "s": 42143, "text": null }, { "code": null, "e": 45049, "s": 45030, "text": "25 12 30 10 36 15 " }, { "code": null, "e": 45077, "s": 45049, "text": "Another Approach:Algorithm:" }, { "code": null, "e": 45271, "s": 45077, "text": "Traverse the tree in inorder fashion.While visiting each node, keep track of DLL’s head and tail pointers, insert each visited node to the end of DLL using tail pointer.Return head of the list." }, { "code": null, "e": 45309, "s": 45271, "text": "Traverse the tree in inorder fashion." }, { "code": null, "e": 45442, "s": 45309, "text": "While visiting each node, keep track of DLL’s head and tail pointers, insert each visited node to the end of DLL using tail pointer." }, { "code": null, "e": 45467, "s": 45442, "text": "Return head of the list." }, { "code": null, "e": 45518, "s": 45467, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 45522, "s": 45518, "text": "C++" }, { "code": null, "e": 45527, "s": 45522, "text": "Java" }, { "code": null, "e": 45530, "s": 45527, "text": "C#" }, { "code": null, "e": 45541, "s": 45530, "text": "Javascript" }, { "code": "// A C++ program for in-place// conversion of Binary Tree to DLL#include <bits/stdc++.h>using namespace std; /* A binary tree node has data,and left and right pointers */class node {public: int data; node* left; node* right;}; /* This is the core function to convertTree to list.*/void bintree2listUtil(node* root, node** head, node** tail){ if (root == NULL) return; bintree2listUtil(root->left, head, tail); if (*head == NULL) { *head = root; } root->left = *tail; if (*tail != NULL) { (*tail)->right = root; } *tail = root; bintree2listUtil(root->right, head, tail);} // The main function that first calls// bintree2listUtil()node* bintree2list(node* root){ // Base case if (root == NULL) return root; node* head = NULL; node* tail = NULL; bintree2listUtil(root, &head, &tail); return head;} /* Helper function that allocates a new node with thegiven data and NULL left and right pointers. */node* newNode(int data){ node* new_node = new node(); new_node->data = data; new_node->left = new_node->right = NULL; return (new_node);} /* Function to print nodes in a given doubly linked list */void printList(node* node){ while (node != NULL) { cout << node->data << \" \"; node = node->right; }} /* Driver code*/int main(){ // Let us create the tree shown in above diagram node* root = newNode(10); root->left = newNode(12); root->right = newNode(15); root->left->left = newNode(25); root->left->right = newNode(30); root->right->left = newNode(36); // Convert to DLL node* head = bintree2list(root); // Print the converted list printList(head); return 0;} // This code is contributed by rathbhupendra", "e": 47302, "s": 45541, "text": null }, { "code": "// A Java program for in-place// conversion of Binary Tree to DLLimport java.util.*; class GFG{ /* A binary tree node has data,and left and right pointers */static class node { int data; node left; node right;}; /* * This is the core function to convert Tree to list. */static node head, tail;static void bintree2listUtil(node root){ if (root == null) return ; node left = root.left; node right = root.right; bintree2listUtil(root.left); if (head == null) { head = root; } root.left = tail; if (tail != null) { (tail).right = root; } tail = root; bintree2listUtil(root.right);} // The main function that first calls// bintree2listUtil()static void bintree2list(node root){ // Base case if (root == null) head= root; bintree2listUtil(root); } /* Helper function that allocates a new node with thegiven data and null left and right pointers. */static node newNode(int data){ node new_node = new node(); new_node.data = data; new_node.left = new_node.right = null; return (new_node);} /* Function to print nodes in a given doubly linked list */static void printList(){ while (head != null) { System.out.print(head.data+ \" \"); head = head.right; }} /* Driver code */public static void main(String[] args){ // Let us create the tree shown in above diagram node root = newNode(10); root.left = newNode(12); root.right = newNode(15); root.left.left = newNode(25); root.left.right = newNode(30); root.right.left = newNode(36); head = null; tail = null; // Convert to DLL bintree2list(root); // Print the converted list printList(); }} // This code is contributed by umadevi9616", "e": 49069, "s": 47302, "text": null }, { "code": "// A C# program for in-place// conversion of Binary Tree to DLLusing System; public class GFG { /* * A binary tree node has data, and left and right pointers */public class node { public int data; public node left; public node right; }; /* * This is the core function to convert Tree to list. */ static node head, tail; static void bintree2listUtil(node root) { if (root == null) return; node left = root.left; node right = root.right; bintree2listUtil(root.left); if (head == null) { head = root; } root.left = tail; if (tail != null) { (tail).right = root; } tail = root; bintree2listUtil(root.right); } // The main function that first calls // bintree2listUtil() static void bintree2list(node root) { // Base case if (root == null) head = root; bintree2listUtil(root); } /* * Helper function that allocates a new node with the given data and null left * and right pointers. */ static node newNode(int data) { node new_node = new node(); new_node.data = data; new_node.left = new_node.right = null; return (new_node); } /* Function to print nodes in a given doubly linked list */ static void printList() { while (head != null) { Console.Write(head.data + \" \"); head = head.right; } } /* Driver code */ public static void Main(String[] args) { // Let us create the tree shown in above diagram node root = newNode(10); root.left = newNode(12); root.right = newNode(15); root.left.left = newNode(25); root.left.right = newNode(30); root.right.left = newNode(36); head = null; tail = null; // Convert to DLL bintree2list(root); // Print the converted list printList(); }} // This code is contributed by gauravrajput1", "e": 51109, "s": 49069, "text": null }, { "code": "<script>// A javascript program for in-place// conversion of Binary Tree to DLL /* * A binary tree node has data, and left and right pointers */ class Node { constructor() { this.data = 0; this.left = null; this.right = null; } } /* * This is the core function to convert Tree to list. */ var head, tail; function bintree2listUtil(root) { if (root == null) return; var left = root.left; var right = root.right; bintree2listUtil(root.left); if (head == null) { head = root; } root.left = tail; if (tail != null) { (tail).right = root; } tail = root; bintree2listUtil(root.right); } // The main function that first calls // bintree2listUtil() function bintree2list( root) { // Base case if (root == null) head = root; bintree2listUtil(root); } /* * Helper function that allocates a new node with the given data and null left * and right pointers. */ function newNode(data) { var new_node = new Node(); new_node.data = data; new_node.left = new_node.right = null; return (new_node); } /* Function to print nodes in a given doubly linked list */ function printList() { while (head != null) { document.write(head.data + \" \"); head = head.right; } } /* Driver code */ // Let us create the tree shown in above diagram var root = newNode(10); root.left = newNode(12); root.right = newNode(15); root.left.left = newNode(25); root.left.right = newNode(30); root.right.left = newNode(36); head = null; tail = null; // Convert to DLL bintree2list(root); // Print the converted list printList(); // This code is contributed by gauravrajput1</script>", "e": 53098, "s": 51109, "text": null }, { "code": null, "e": 53117, "s": 53098, "text": "25 12 30 10 36 15 " }, { "code": null, "e": 53446, "s": 53117, "text": "This article is compiled by Ashish Mangla 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.You may also like to see Convert a given Binary Tree to Doubly Linked List | Set 2 for another simple and efficient solution. " }, { "code": null, "e": 53457, "s": 53446, "text": "viveksyngh" }, { "code": null, "e": 53469, "s": 53457, "text": "shrikanth13" }, { "code": null, "e": 53483, "s": 53469, "text": "rathbhupendra" }, { "code": null, "e": 53499, "s": 53483, "text": "prakhar jauhari" }, { "code": null, "e": 53518, "s": 53499, "text": "ankitshuklatiwari1" }, { "code": null, "e": 53530, "s": 53518, "text": "umadevi9616" }, { "code": null, "e": 53538, "s": 53530, "text": "bittu06" }, { "code": null, "e": 53555, "s": 53538, "text": "arorakashish0911" }, { "code": null, "e": 53569, "s": 53555, "text": "GauravRajput1" }, { "code": null, "e": 53582, "s": 53569, "text": "simmytarika5" }, { "code": null, "e": 53598, "s": 53582, "text": "amartyaghoshgfg" }, { "code": null, "e": 53616, "s": 53598, "text": "gauravgupta092002" }, { "code": null, "e": 53623, "s": 53616, "text": "Amazon" }, { "code": null, "e": 53642, "s": 53623, "text": "doubly linked list" }, { "code": null, "e": 53656, "s": 53642, "text": "Goldman Sachs" }, { "code": null, "e": 53666, "s": 53656, "text": "Microsoft" }, { "code": null, "e": 53678, "s": 53666, "text": "Linked List" }, { "code": null, "e": 53683, "s": 53678, "text": "Tree" }, { "code": null, "e": 53690, "s": 53683, "text": "Amazon" }, { "code": null, "e": 53700, "s": 53690, "text": "Microsoft" }, { "code": null, "e": 53714, "s": 53700, "text": "Goldman Sachs" }, { "code": null, "e": 53726, "s": 53714, "text": "Linked List" }, { "code": null, "e": 53731, "s": 53726, "text": "Tree" }, { "code": null, "e": 53829, "s": 53731, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 53838, "s": 53829, "text": "Comments" }, { "code": null, "e": 53851, "s": 53838, "text": "Old Comments" }, { "code": null, "e": 53922, "s": 53851, "text": "Given a linked list which is sorted, how will you insert in sorted way" }, { "code": null, "e": 53969, "s": 53922, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 54007, "s": 53969, "text": "Insertion Sort for Singly Linked List" }, { "code": null, "e": 54048, "s": 54007, "text": "Circular Linked List | Set 2 (Traversal)" }, { "code": null, "e": 54093, "s": 54048, "text": "Split a Circular Linked List into two halves" }, { "code": null, "e": 54143, "s": 54093, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 54178, "s": 54143, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 54212, "s": 54178, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 54241, "s": 54212, "text": "AVL Tree | Set 1 (Insertion)" } ]
How to check internet connection availability and the network type on Android using Kotlin?
This example demonstrates how to check internet connection availability and the network type on Android using Kotlin. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="70dp" android:background="#008080" android:padding="5dp" android:text="TutorialsPoint" android:textColor="#fff" android:textSize="24sp" android:textStyle="bold" /> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:textColor="@android:color/holo_purple" android:textSize="24sp" android:textStyle="bold" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.kt import android.content.Context import android.net.ConnectivityManager import android.os.Bundle import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { lateinit var textView: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" textView = findViewById(R.id.textView) if (checkNetwork()) { Toast.makeText(this, "Network connection is available", Toast.LENGTH_SHORT).show() } else if (!checkNetwork()) { Toast.makeText(this, "Network connection is not available", Toast.LENGTH_SHORT).show() } } private fun checkNetwork(): Boolean { val connManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI) textView.text = "Network type is " + networkInfo!!.typeName return true } } 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="com.example.q11"> <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 the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen. Click here to download the project code.
[ { "code": null, "e": 1180, "s": 1062, "text": "This example demonstrates how to check internet connection availability and the network type on Android using Kotlin." }, { "code": null, "e": 1309, "s": 1180, "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": 1374, "s": 1309, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2252, "s": 1374, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\">\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"70dp\"\n android:background=\"#008080\"\n android:padding=\"5dp\"\n android:text=\"TutorialsPoint\"\n android:textColor=\"#fff\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:textColor=\"@android:color/holo_purple\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n</RelativeLayout>" }, { "code": null, "e": 2307, "s": 2252, "text": "Step 3 − Add the following code to src/MainActivity.kt" }, { "code": null, "e": 3379, "s": 2307, "text": "import android.content.Context\nimport android.net.ConnectivityManager\nimport android.os.Bundle\nimport android.widget.TextView\nimport android.widget.Toast\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n lateinit var textView: TextView\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n textView = findViewById(R.id.textView)\n if (checkNetwork()) {\n Toast.makeText(this, \"Network connection is available\", Toast.LENGTH_SHORT).show()\n }\n else if (!checkNetwork()) {\n Toast.makeText(this, \"Network connection is not available\", Toast.LENGTH_SHORT).show()\n }\n }\n private fun checkNetwork(): Boolean {\n val connManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager\n val networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)\n textView.text = \"Network type is \" + networkInfo!!.typeName\n return true\n }\n}" }, { "code": null, "e": 3434, "s": 3379, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 4105, "s": 3434, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example.q11\">\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": 4454, "s": 4105, "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 the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen." }, { "code": null, "e": 4495, "s": 4454, "text": "Click here to download the project code." } ]
Math class methods in C#
The System.Math class in C# provides methods are properties to perform mathematical operations, trigonometric, logarithmic calculations, etc. Some of its methods include − For all the methods, refer MSDN Let us see an example to get the absolute value − using System; class Program { static void Main() { int val1 = 50; int val2 = -150; Console.WriteLine("Before..."); Console.WriteLine(val1); Console.WriteLine(val2); int abs1 = Math.Abs(val1); int abs2 = Math.Abs(val2); Console.WriteLine("After..."); Console.WriteLine(abs1); Console.WriteLine(abs2); } }
[ { "code": null, "e": 1204, "s": 1062, "text": "The System.Math class in C# provides methods are properties to perform mathematical operations, trigonometric, logarithmic calculations, etc." }, { "code": null, "e": 1234, "s": 1204, "text": "Some of its methods include −" }, { "code": null, "e": 1266, "s": 1234, "text": "For all the methods, refer MSDN" }, { "code": null, "e": 1316, "s": 1266, "text": "Let us see an example to get the absolute value −" }, { "code": null, "e": 1690, "s": 1316, "text": "using System;\n\nclass Program {\n static void Main() {\n int val1 = 50;\n int val2 = -150;\n\n Console.WriteLine(\"Before...\");\n Console.WriteLine(val1);\n Console.WriteLine(val2);\n\n int abs1 = Math.Abs(val1);\n int abs2 = Math.Abs(val2);\n\n Console.WriteLine(\"After...\");\n Console.WriteLine(abs1);\n Console.WriteLine(abs2);\n }\n}" } ]
Type.GetProperties() Method in C#
The Type.GetProperties() method in C# is used to get the properties of the current Type. Following is the syntax − public System.Reflection.PropertyInfo[] GetProperties (); public abstract System.Reflection.PropertyInfo[] GetProperties (System.Reflection.BindingFlags bindingAttr); Above, bindingAttr is a bitwise combination of the enumeration values that specify how the search is performed. using System; using System.Reflection; public class Demo { public static void Main(){ Type type = typeof(System.Type); PropertyInfo[] info = type.GetProperties(); Console.WriteLine("Properties... "); for (int i = 0; i < info.Length; i++) Console.WriteLine(" {0}", info[i].ToString()); } } This will produce the following output − Properties... System.Reflection.MemberTypes MemberType System.Type DeclaringType System.Reflection.MethodBase DeclaringMethod System.Type ReflectedType System.Runtime.InteropServices.StructLayoutAttribute StructLayoutAttribute System.Guid GUID System.Reflection.Binder DefaultBinder System.Reflection.Module Module System.Reflection.Assembly Assembly System.RuntimeTypeHandle TypeHandle System.String FullName System.String Namespace System.String AssemblyQualifiedName System.Type BaseType System.Reflection.ConstructorInfo TypeInitializer Boolean IsNested System.Reflection.TypeAttributes Attributes System.Reflection.GenericParameterAttributes GenericParameterAttributes Boolean IsVisible Boolean IsNotPublic Boolean IsPublic Boolean IsNestedPublic Boolean IsNestedPrivate Boolean IsNestedFamily Boolean IsNestedAssembly Boolean IsNestedFamANDAssem Boolean IsNestedFamORAssem Boolean IsAutoLayout Boolean IsLayoutSequential Boolean IsExplicitLayout Boolean IsClass Boolean IsInterface Boolean IsValueType Boolean IsAbstract Boolean IsSealed Boolean IsEnum Boolean IsSpecialName Boolean IsImport Boolean IsSerializable Boolean IsAnsiClass Boolean IsUnicodeClass Boolean IsAutoClass Boolean IsArray Boolean IsGenericType Boolean IsGenericTypeDefinition Boolean IsConstructedGenericType Boolean IsGenericParameter Int32 GenericParameterPosition Boolean ContainsGenericParameters Boolean IsByRef Boolean IsPointer Boolean IsPrimitive Boolean IsCOMObject Boolean HasElementType Boolean IsContextful Boolean IsMarshalByRef System.Type[] GenericTypeArguments Boolean IsSecurityCritical Boolean IsSecuritySafeCritical Boolean IsSecurityTransparent System.Type UnderlyingSystemType System.String Name System.Collections.Generic.IEnumerable`1[System.Reflection.CustomAttributeData] CustomAttributes Int32 MetadataToken Let us now see another example to implement the Type.GetProperties() method − using System; using System.Reflection; public class Demo { public static void Main(){ Type type = typeof(string); PropertyInfo[] info = type.GetProperties(); Console.WriteLine("Count of Properties = "+info.Length); Console.WriteLine("Properties... "); for (int i = 0; i < info.Length; i++) Console.WriteLine(" {0}", info[i].ToString()); } } This will produce the following output − Count of Properties = 2 Properties... Char Chars [Int32] Int32 Length
[ { "code": null, "e": 1151, "s": 1062, "text": "The Type.GetProperties() method in C# is used to get the properties of the current Type." }, { "code": null, "e": 1177, "s": 1151, "text": "Following is the syntax −" }, { "code": null, "e": 1344, "s": 1177, "text": "public System.Reflection.PropertyInfo[] GetProperties ();\npublic abstract System.Reflection.PropertyInfo[] GetProperties (System.Reflection.BindingFlags bindingAttr);" }, { "code": null, "e": 1456, "s": 1344, "text": "Above, bindingAttr is a bitwise combination of the enumeration values that specify how the search is performed." }, { "code": null, "e": 1784, "s": 1456, "text": "using System;\nusing System.Reflection;\npublic class Demo {\n public static void Main(){\n Type type = typeof(System.Type);\n PropertyInfo[] info = type.GetProperties();\n Console.WriteLine(\"Properties... \");\n for (int i = 0; i < info.Length; i++)\n Console.WriteLine(\" {0}\", info[i].ToString());\n }\n}" }, { "code": null, "e": 1825, "s": 1784, "text": "This will produce the following output −" }, { "code": null, "e": 3637, "s": 1825, "text": "Properties...\nSystem.Reflection.MemberTypes MemberType\nSystem.Type DeclaringType\nSystem.Reflection.MethodBase DeclaringMethod\nSystem.Type ReflectedType\nSystem.Runtime.InteropServices.StructLayoutAttribute StructLayoutAttribute\nSystem.Guid GUID\nSystem.Reflection.Binder DefaultBinder\nSystem.Reflection.Module Module\nSystem.Reflection.Assembly Assembly\nSystem.RuntimeTypeHandle TypeHandle\nSystem.String FullName\nSystem.String Namespace\nSystem.String AssemblyQualifiedName\nSystem.Type BaseType\nSystem.Reflection.ConstructorInfo TypeInitializer\nBoolean IsNested\nSystem.Reflection.TypeAttributes Attributes\nSystem.Reflection.GenericParameterAttributes GenericParameterAttributes\nBoolean IsVisible\nBoolean IsNotPublic\nBoolean IsPublic\nBoolean IsNestedPublic\nBoolean IsNestedPrivate\nBoolean IsNestedFamily\nBoolean IsNestedAssembly\nBoolean IsNestedFamANDAssem\nBoolean IsNestedFamORAssem\nBoolean IsAutoLayout\nBoolean IsLayoutSequential\nBoolean IsExplicitLayout\nBoolean IsClass\nBoolean IsInterface\nBoolean IsValueType\nBoolean IsAbstract\nBoolean IsSealed\nBoolean IsEnum\nBoolean IsSpecialName\nBoolean IsImport\nBoolean IsSerializable\nBoolean IsAnsiClass\nBoolean IsUnicodeClass\nBoolean IsAutoClass\nBoolean IsArray\nBoolean IsGenericType\nBoolean IsGenericTypeDefinition\nBoolean IsConstructedGenericType\nBoolean IsGenericParameter\nInt32 GenericParameterPosition\nBoolean ContainsGenericParameters\nBoolean IsByRef\nBoolean IsPointer\nBoolean IsPrimitive\nBoolean IsCOMObject\nBoolean HasElementType\nBoolean IsContextful\nBoolean IsMarshalByRef\nSystem.Type[] GenericTypeArguments\nBoolean IsSecurityCritical\nBoolean IsSecuritySafeCritical\nBoolean IsSecurityTransparent\nSystem.Type UnderlyingSystemType\nSystem.String Name\nSystem.Collections.Generic.IEnumerable`1[System.Reflection.CustomAttributeData] CustomAttributes\nInt32 MetadataToken" }, { "code": null, "e": 3715, "s": 3637, "text": "Let us now see another example to implement the Type.GetProperties() method −" }, { "code": null, "e": 4101, "s": 3715, "text": "using System;\nusing System.Reflection;\npublic class Demo {\n public static void Main(){\n Type type = typeof(string);\n PropertyInfo[] info = type.GetProperties();\n Console.WriteLine(\"Count of Properties = \"+info.Length);\n Console.WriteLine(\"Properties... \");\n for (int i = 0; i < info.Length; i++)\n Console.WriteLine(\" {0}\", info[i].ToString());\n }\n}" }, { "code": null, "e": 4142, "s": 4101, "text": "This will produce the following output −" }, { "code": null, "e": 4212, "s": 4142, "text": "Count of Properties = 2\nProperties...\nChar Chars [Int32]\nInt32 Length" } ]
SQL Tryit Editor v1.6
SELECT * FROM Products WHERE ProductName BETWEEN "Carnarvon Tigers" AND "Chef Anton's Cajun Seasoning" ORDER BY ProductName; ​ Edit the SQL Statement, and click "Run SQL" to see the result. This SQL-Statement is not supported in the WebSQL Database. The example still works, because it uses a modified version of SQL. Your browser does not support WebSQL. Your are now using a light-version of the Try-SQL Editor, with a read-only Database. If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time. Our Try-SQL Editor uses WebSQL to demonstrate SQL. A Database-object is created in your browser, for testing purposes. You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button. WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object. WebSQL is supported in Chrome, Safari, Opera, and Edge(79). If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
[ { "code": null, "e": 23, "s": 0, "text": "SELECT * FROM Products" }, { "code": null, "e": 103, "s": 23, "text": "WHERE ProductName BETWEEN \"Carnarvon Tigers\" AND \"Chef Anton's Cajun Seasoning\"" }, { "code": null, "e": 125, "s": 103, "text": "ORDER BY ProductName;" }, { "code": null, "e": 127, "s": 125, "text": "​" }, { "code": null, "e": 190, "s": 127, "text": "Edit the SQL Statement, and click \"Run SQL\" to see the result." }, { "code": null, "e": 250, "s": 190, "text": "This SQL-Statement is not supported in the WebSQL Database." }, { "code": null, "e": 318, "s": 250, "text": "The example still works, because it uses a modified version of SQL." }, { "code": null, "e": 356, "s": 318, "text": "Your browser does not support WebSQL." }, { "code": null, "e": 441, "s": 356, "text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database." }, { "code": null, "e": 615, "s": 441, "text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time." }, { "code": null, "e": 666, "s": 615, "text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL." }, { "code": null, "e": 734, "s": 666, "text": "A Database-object is created in your browser, for testing purposes." }, { "code": null, "e": 905, "s": 734, "text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button." }, { "code": null, "e": 1005, "s": 905, "text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object." }, { "code": null, "e": 1065, "s": 1005, "text": "WebSQL is supported in Chrome, Safari, Opera, and Edge(79)." } ]
Create Stunning Visualizations with Altair | by Aigerim Shopenova | Towards Data Science
“Beauty will save the world.” - F. Dostoevsky Have you ever gotten frustrated after looking at your visualization in Python? Have you ever thought that it can be done better with less effort and time? If so, this post is perfect for you because I would like to share about the Altair library, which will boost your productivity and make your visualisations more appealing. I suppose you already know how visualization is vital for any analysis and how it helps convey and translate an idea to a wider audience. Also, visualizing data is one of the first steps to explore it and understand where to dig deeper. Therefore, I would like to focus on the basic grammar of Altair using a scatter plot and then share with you some examples of various graphs. Before that, let us talk about Altair and get to know why it is so powerful. Altair is a declarative statistical visualization library, which uses Vega and Vega-Lite grammars that help to describe the visual appearance and interactive behaviour of a visualization in a JSON format. The key idea behind Altair that you are declaring links between data columns and visual encoding channels (e.g., x and y axes, colour, size, etc.) and the rest of the visualization process is handled by the library. Thus, it gives you more time to focus on data and analysis rather than explaining how to visualize data [1]. Data: DataFrame used for visualization Data: DataFrame used for visualization 2. Mark: How would you like the data to be visualized (line, bar, tick, point)? 3. Encoding: How the data will be represented (positions for x and y, colour, size)? 4. Transform: How would you like to transform the data before applying visualization (aggregate, fold, filter, etc.)? 5. Scale: Function for inputting and rendering data on the screen 6. Guide: Visual aids such as legend, ticks on the x and y axes. As for the mark component, you can use the following basic mark properties: Let us get our hands dirty and learn Altair's grammar using a scatter plot. $ pip install altair vega_datasets The equivalent for conda is $ conda install -c conda-forge altair vega_datasets I will be using the following Vega datasets: data.gapminder()data.stocks()data.movies() data.gapminder() data.stocks() data.movies() Let's import packages and look at the data import pandas as pdimport altair as altfrom vega_datasets import data Chart() is a fundamental object in Altair, which accepts a single argument — a DataFrame. Let us look at a simple scatter plot using Chart(), mark_point() and encode() objects. alt.Chart(df_gm_2005).mark_point().encode( alt.X(‘life_expect’), alt.Y(‘fertility’)) By adding interactive() object to a scatter plot we can make it interactive. Also, let us define the size of the bubbles with alt.Size() to add more information to the plot. alt.Chart(df_gm_2005).mark_point(filled=True).encode( alt.X(‘life_expect’), alt.Y(‘fertility’), alt.Size(‘pop’)).interactive() We can change the colour of the bubbles by adding alt.Color() in encode() object. It is great that we do not need to worry about each colour for each country because Altair does it for you. alt.Chart(df_gm_2005).mark_point(filled=True).encode( alt.X(‘life_expect’), alt.Y(‘fertility’), alt.Size(‘pop’), alt.Color(‘country’), alt.OpacityValue(0.7)).interactive() We can add information to each dot by specifying Tooltip() in encode(). alt.Chart(df_gm_2005).mark_point(filled=True).encode( alt.X(‘life_expect’), alt.Y(‘fertility’), alt.Size(‘pop’), alt.Color(‘country’), alt.OpacityValue(0.7), tooltip = [alt.Tooltip(‘country’), alt.Tooltip(‘fertility’), alt.Tooltip(‘life_expect’), alt.Tooltip(‘pop’), alt.Tooltip(‘year’)]).interactive() Already looks amazing for the 2005 year’s data. Let’s add a bar to change the data and make the plot dynamic. select_year = alt.selection_single( name=’Select’, fields=[‘year’], init={‘year’: 1955}, bind=alt.binding_range(min=1955, max=2005, step=5))alt.Chart(df_gm).mark_point(filled=True).encode( alt.X(‘life_expect’), alt.Y(‘fertility’), alt.Size(‘pop’), alt.Color(‘country’), alt.OpacityValue(0.7), tooltip = [alt.Tooltip(‘country’), alt.Tooltip(‘fertility’), alt.Tooltip(‘life_expect’), alt.Tooltip(‘pop’), alt.Tooltip(‘year’)]).add_selection(select_year).transform_filter(select_year).interactive() Lastly, let us change the size of the plot and add a title select_year = alt.selection_single( name=’Select’, fields=[‘year’], init={‘year’: 1955}, bind=alt.binding_range(min=1955, max=2005, step=5))scatter_plot = alt.Chart(df_gm).mark_point(filled=True).encode( alt.X(‘life_expect’), alt.Y(‘fertility’), alt.Size(‘pop’), alt.Color(‘country’), alt.OpacityValue(0.7), tooltip = [alt.Tooltip(‘country’), alt.Tooltip(‘fertility’), alt.Tooltip(‘life_expect’), alt.Tooltip(‘pop’), alt.Tooltip(‘year’)]).properties( width=500, height=500, title=”Relationship between fertility and life expectancy for various countries by year”).add_selection(select_year).transform_filter(select_year).interactive()scatter_plot.configure_title( fontSize=16, font=”Arial”, anchor=”middle”, color=”gray”) The final output looks great and we can derive various insights from such a sophisticated visualization. Now, knowing the basics of Altair's grammar, let us look at some other plots. box_plot = alt.Chart(df_gm_2005).mark_boxplot(size=100, extent=0.5).encode( y=alt.Y(‘life_expect’, scale=alt.Scale(zero=False))).properties( width=400, height=400, title=”Distribution of life expectancy for various countries in 2005 year”).configure_axis( labelFontSize=14, titleFontSize=14).configure_mark( opacity=0.6, color=’darkmagenta’)box_plot.configure_title( fontSize=16, font=”Arial”, anchor=”middle”, color=”gray”) histogram = alt.Chart(df_gm_2005).mark_bar().encode( alt.X(“life_expect”, bin=alt.Bin(extent=[0, 100], step=10)), y=”count()”).properties( width=400, height=300, title=”Distribution of population for various countries in 2005 year”).configure_axis( labelFontSize=14, titleFontSize=14).configure_mark( opacity=0.5, color=’royalblue’)histogram.configure_title( fontSize=16, font=”Arial”, anchor=”middle”, color=”gray”) bar_chart = alt.Chart(df_gm_ir).mark_bar(color=’seagreen’, opacity=0.6).encode( x=’pop:Q’, y=”year:O”).properties( width=400, height=400, title=”Population of Ireland”)text = bar_chart.mark_text( align=’left’, baseline=’middle’, dx=3).encode( text=’pop:Q’)bar_chart + text line_chart = alt.Chart(df_stocks).mark_line().encode( x=’date’, y=’price’, color=’symbol’).properties( width=400, height=300, title=”Daily closing stock prices”)line_chart.configure_title( fontSize=16, font=”Arial”, anchor=”middle”, color=”gray”) mult_scatter_plots = alt.Chart(df_movies).mark_circle().encode( alt.X(alt.repeat(“column”), type=’quantitative’), alt.Y(alt.repeat(“row”), type=’quantitative’), color=’Major_Genre:N’).properties( width=150, height=150).repeat( row=[‘US_Gross’, ‘Worldwide_Gross’, ‘IMDB_Rating’], column=[‘US_Gross’, ‘Worldwide_Gross’, ‘IMDB_Rating’]).interactive()mult_scatter_plots Altair is a great tool to boost your productivity in visualizing data, where you only need to specify links between data and visual encoding channels. This allows you to put your thoughts directly to a plot without worrying about the time consuming "how" part. For more details please find My Jupyter notebook used for the blog post Official documentation with an example gallery of various plots. Thanks for reading and please do comment below about your ideas on visualizing data with Altair. To see more posts from me, please subscribe to Medium and LinkedIn. Overview page¶. Overview — Altair 4.1.0 documentation. (n.d.). https://altair-viz.github.io/getting_started/overview.html. Overview page¶. Overview — Altair 4.1.0 documentation. (n.d.). https://altair-viz.github.io/getting_started/overview.html.
[ { "code": null, "e": 202, "s": 172, "text": "“Beauty will save the world.”" }, { "code": null, "e": 218, "s": 202, "text": "- F. Dostoevsky" }, { "code": null, "e": 545, "s": 218, "text": "Have you ever gotten frustrated after looking at your visualization in Python? Have you ever thought that it can be done better with less effort and time? If so, this post is perfect for you because I would like to share about the Altair library, which will boost your productivity and make your visualisations more appealing." }, { "code": null, "e": 1001, "s": 545, "text": "I suppose you already know how visualization is vital for any analysis and how it helps convey and translate an idea to a wider audience. Also, visualizing data is one of the first steps to explore it and understand where to dig deeper. Therefore, I would like to focus on the basic grammar of Altair using a scatter plot and then share with you some examples of various graphs. Before that, let us talk about Altair and get to know why it is so powerful." }, { "code": null, "e": 1206, "s": 1001, "text": "Altair is a declarative statistical visualization library, which uses Vega and Vega-Lite grammars that help to describe the visual appearance and interactive behaviour of a visualization in a JSON format." }, { "code": null, "e": 1531, "s": 1206, "text": "The key idea behind Altair that you are declaring links between data columns and visual encoding channels (e.g., x and y axes, colour, size, etc.) and the rest of the visualization process is handled by the library. Thus, it gives you more time to focus on data and analysis rather than explaining how to visualize data [1]." }, { "code": null, "e": 1570, "s": 1531, "text": "Data: DataFrame used for visualization" }, { "code": null, "e": 1609, "s": 1570, "text": "Data: DataFrame used for visualization" }, { "code": null, "e": 1689, "s": 1609, "text": "2. Mark: How would you like the data to be visualized (line, bar, tick, point)?" }, { "code": null, "e": 1774, "s": 1689, "text": "3. Encoding: How the data will be represented (positions for x and y, colour, size)?" }, { "code": null, "e": 1892, "s": 1774, "text": "4. Transform: How would you like to transform the data before applying visualization (aggregate, fold, filter, etc.)?" }, { "code": null, "e": 1958, "s": 1892, "text": "5. Scale: Function for inputting and rendering data on the screen" }, { "code": null, "e": 2023, "s": 1958, "text": "6. Guide: Visual aids such as legend, ticks on the x and y axes." }, { "code": null, "e": 2099, "s": 2023, "text": "As for the mark component, you can use the following basic mark properties:" }, { "code": null, "e": 2175, "s": 2099, "text": "Let us get our hands dirty and learn Altair's grammar using a scatter plot." }, { "code": null, "e": 2210, "s": 2175, "text": "$ pip install altair vega_datasets" }, { "code": null, "e": 2238, "s": 2210, "text": "The equivalent for conda is" }, { "code": null, "e": 2290, "s": 2238, "text": "$ conda install -c conda-forge altair vega_datasets" }, { "code": null, "e": 2335, "s": 2290, "text": "I will be using the following Vega datasets:" }, { "code": null, "e": 2378, "s": 2335, "text": "data.gapminder()data.stocks()data.movies()" }, { "code": null, "e": 2395, "s": 2378, "text": "data.gapminder()" }, { "code": null, "e": 2409, "s": 2395, "text": "data.stocks()" }, { "code": null, "e": 2423, "s": 2409, "text": "data.movies()" }, { "code": null, "e": 2466, "s": 2423, "text": "Let's import packages and look at the data" }, { "code": null, "e": 2536, "s": 2466, "text": "import pandas as pdimport altair as altfrom vega_datasets import data" }, { "code": null, "e": 2713, "s": 2536, "text": "Chart() is a fundamental object in Altair, which accepts a single argument — a DataFrame. Let us look at a simple scatter plot using Chart(), mark_point() and encode() objects." }, { "code": null, "e": 2798, "s": 2713, "text": "alt.Chart(df_gm_2005).mark_point().encode( alt.X(‘life_expect’), alt.Y(‘fertility’))" }, { "code": null, "e": 2972, "s": 2798, "text": "By adding interactive() object to a scatter plot we can make it interactive. Also, let us define the size of the bubbles with alt.Size() to add more information to the plot." }, { "code": null, "e": 3099, "s": 2972, "text": "alt.Chart(df_gm_2005).mark_point(filled=True).encode( alt.X(‘life_expect’), alt.Y(‘fertility’), alt.Size(‘pop’)).interactive()" }, { "code": null, "e": 3289, "s": 3099, "text": "We can change the colour of the bubbles by adding alt.Color() in encode() object. It is great that we do not need to worry about each colour for each country because Altair does it for you." }, { "code": null, "e": 3461, "s": 3289, "text": "alt.Chart(df_gm_2005).mark_point(filled=True).encode( alt.X(‘life_expect’), alt.Y(‘fertility’), alt.Size(‘pop’), alt.Color(‘country’), alt.OpacityValue(0.7)).interactive()" }, { "code": null, "e": 3533, "s": 3461, "text": "We can add information to each dot by specifying Tooltip() in encode()." }, { "code": null, "e": 3836, "s": 3533, "text": "alt.Chart(df_gm_2005).mark_point(filled=True).encode( alt.X(‘life_expect’), alt.Y(‘fertility’), alt.Size(‘pop’), alt.Color(‘country’), alt.OpacityValue(0.7), tooltip = [alt.Tooltip(‘country’), alt.Tooltip(‘fertility’), alt.Tooltip(‘life_expect’), alt.Tooltip(‘pop’), alt.Tooltip(‘year’)]).interactive()" }, { "code": null, "e": 3946, "s": 3836, "text": "Already looks amazing for the 2005 year’s data. Let’s add a bar to change the data and make the plot dynamic." }, { "code": null, "e": 4441, "s": 3946, "text": "select_year = alt.selection_single( name=’Select’, fields=[‘year’], init={‘year’: 1955}, bind=alt.binding_range(min=1955, max=2005, step=5))alt.Chart(df_gm).mark_point(filled=True).encode( alt.X(‘life_expect’), alt.Y(‘fertility’), alt.Size(‘pop’), alt.Color(‘country’), alt.OpacityValue(0.7), tooltip = [alt.Tooltip(‘country’), alt.Tooltip(‘fertility’), alt.Tooltip(‘life_expect’), alt.Tooltip(‘pop’), alt.Tooltip(‘year’)]).add_selection(select_year).transform_filter(select_year).interactive()" }, { "code": null, "e": 4500, "s": 4441, "text": "Lastly, let us change the size of the plot and add a title" }, { "code": null, "e": 5222, "s": 4500, "text": "select_year = alt.selection_single( name=’Select’, fields=[‘year’], init={‘year’: 1955}, bind=alt.binding_range(min=1955, max=2005, step=5))scatter_plot = alt.Chart(df_gm).mark_point(filled=True).encode( alt.X(‘life_expect’), alt.Y(‘fertility’), alt.Size(‘pop’), alt.Color(‘country’), alt.OpacityValue(0.7), tooltip = [alt.Tooltip(‘country’), alt.Tooltip(‘fertility’), alt.Tooltip(‘life_expect’), alt.Tooltip(‘pop’), alt.Tooltip(‘year’)]).properties( width=500, height=500, title=”Relationship between fertility and life expectancy for various countries by year”).add_selection(select_year).transform_filter(select_year).interactive()scatter_plot.configure_title( fontSize=16, font=”Arial”, anchor=”middle”, color=”gray”)" }, { "code": null, "e": 5327, "s": 5222, "text": "The final output looks great and we can derive various insights from such a sophisticated visualization." }, { "code": null, "e": 5405, "s": 5327, "text": "Now, knowing the basics of Altair's grammar, let us look at some other plots." }, { "code": null, "e": 5830, "s": 5405, "text": "box_plot = alt.Chart(df_gm_2005).mark_boxplot(size=100, extent=0.5).encode( y=alt.Y(‘life_expect’, scale=alt.Scale(zero=False))).properties( width=400, height=400, title=”Distribution of life expectancy for various countries in 2005 year”).configure_axis( labelFontSize=14, titleFontSize=14).configure_mark( opacity=0.6, color=’darkmagenta’)box_plot.configure_title( fontSize=16, font=”Arial”, anchor=”middle”, color=”gray”)" }, { "code": null, "e": 6247, "s": 5830, "text": "histogram = alt.Chart(df_gm_2005).mark_bar().encode( alt.X(“life_expect”, bin=alt.Bin(extent=[0, 100], step=10)), y=”count()”).properties( width=400, height=300, title=”Distribution of population for various countries in 2005 year”).configure_axis( labelFontSize=14, titleFontSize=14).configure_mark( opacity=0.5, color=’royalblue’)histogram.configure_title( fontSize=16, font=”Arial”, anchor=”middle”, color=”gray”)" }, { "code": null, "e": 6520, "s": 6247, "text": "bar_chart = alt.Chart(df_gm_ir).mark_bar(color=’seagreen’, opacity=0.6).encode( x=’pop:Q’, y=”year:O”).properties( width=400, height=400, title=”Population of Ireland”)text = bar_chart.mark_text( align=’left’, baseline=’middle’, dx=3).encode( text=’pop:Q’)bar_chart + text" }, { "code": null, "e": 6767, "s": 6520, "text": "line_chart = alt.Chart(df_stocks).mark_line().encode( x=’date’, y=’price’, color=’symbol’).properties( width=400, height=300, title=”Daily closing stock prices”)line_chart.configure_title( fontSize=16, font=”Arial”, anchor=”middle”, color=”gray”)" }, { "code": null, "e": 7133, "s": 6767, "text": "mult_scatter_plots = alt.Chart(df_movies).mark_circle().encode( alt.X(alt.repeat(“column”), type=’quantitative’), alt.Y(alt.repeat(“row”), type=’quantitative’), color=’Major_Genre:N’).properties( width=150, height=150).repeat( row=[‘US_Gross’, ‘Worldwide_Gross’, ‘IMDB_Rating’], column=[‘US_Gross’, ‘Worldwide_Gross’, ‘IMDB_Rating’]).interactive()mult_scatter_plots" }, { "code": null, "e": 7394, "s": 7133, "text": "Altair is a great tool to boost your productivity in visualizing data, where you only need to specify links between data and visual encoding channels. This allows you to put your thoughts directly to a plot without worrying about the time consuming \"how\" part." }, { "code": null, "e": 7423, "s": 7394, "text": "For more details please find" }, { "code": null, "e": 7466, "s": 7423, "text": "My Jupyter notebook used for the blog post" }, { "code": null, "e": 7531, "s": 7466, "text": "Official documentation with an example gallery of various plots." }, { "code": null, "e": 7696, "s": 7531, "text": "Thanks for reading and please do comment below about your ideas on visualizing data with Altair. To see more posts from me, please subscribe to Medium and LinkedIn." }, { "code": null, "e": 7819, "s": 7696, "text": "Overview page¶. Overview — Altair 4.1.0 documentation. (n.d.). https://altair-viz.github.io/getting_started/overview.html." } ]
Node.js console.table() Method - GeeksforGeeks
09 Jul, 2020 The console.table() method is an inbuilt application programming interface of the console module which is used to print the table constructed from it’s parameters into the console. Syntax: console.table(data, properties); Parameters: This method accept two parameters as mentioned above and described below: data: Tabular data. An array of each row data that contains values for each column of that specific row.properties: It specifies the properties for constructing the table. data: Tabular data. An array of each row data that contains values for each column of that specific row. properties: It specifies the properties for constructing the table. Return Value: This method doesn’t return anything but print the constructed table and log it. If it fails to parse the arguments into the table then it simply logs the arguments. Below examples illustrate the use of console.table() method in Node.js. Example 1: Filename: app.js // Node.js program to demonstrate the // console.table() method // Accessing console moduleconst console = require('console'); // Calling console.table() // without construction ruleconsole.table([ { a: 1, b: 2 }, { a: 3, b: 7, c: 'y' }]); // With construction ruleconsole.table([ { a: 1, b: 2 }, { a: 3, b: 7, c: 'y' }], ["a", "b"]); Run the app.js file using the following command: node app.js Output: ┌─────────┬───┬───┬─────┐ │ (index) │ a │ b │ c │ ├─────────┼───┼───┼─────┤ │ 0 │ 1 │ 2 │ │ │ 1 │ 3 │ 7 │ 'y' │ └─────────┴───┴───┴─────┘ ┌─────────┬───┬───┐ │ (index) │ a │ b │ ├─────────┼───┼───┤ │ 0 │ 1 │ 2 │ │ 1 │ 3 │ 7 │ └─────────┴───┴───┘ Example 2: Filename: app.js // Node.js program to demonstrate the // console.table() method // Accessing console moduleconst console = require('console'); // Calling console.table() // fails to parse, so simply // print the argumentconsole.table("arg"); // Blank tableconsole.table([]); Run the app.js file using the following command: node app.js Output: arg ┌─────────┐ │ (index) │ ├─────────┤ └─────────┘ Note: The above program will compile and run by using the node filename.js command. Reference: https://nodejs.org/api/console.html#console_console_table_tabulardata_properties Node.js-console-module Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Node.js crypto.createCipheriv() Method Node.js CRUD Operations Using Mongoose and MongoDB Atlas Explain the working of Node.js How to make Mongoose multiple collections using Node.js ? Disabling Sessions in Passport.js Top 10 Front End Developer Skills That You Need in 2022 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? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 24169, "s": 24141, "text": "\n09 Jul, 2020" }, { "code": null, "e": 24350, "s": 24169, "text": "The console.table() method is an inbuilt application programming interface of the console module which is used to print the table constructed from it’s parameters into the console." }, { "code": null, "e": 24358, "s": 24350, "text": "Syntax:" }, { "code": null, "e": 24391, "s": 24358, "text": "console.table(data, properties);" }, { "code": null, "e": 24477, "s": 24391, "text": "Parameters: This method accept two parameters as mentioned above and described below:" }, { "code": null, "e": 24649, "s": 24477, "text": "data: Tabular data. An array of each row data that contains values for each column of that specific row.properties: It specifies the properties for constructing the table." }, { "code": null, "e": 24754, "s": 24649, "text": "data: Tabular data. An array of each row data that contains values for each column of that specific row." }, { "code": null, "e": 24822, "s": 24754, "text": "properties: It specifies the properties for constructing the table." }, { "code": null, "e": 25001, "s": 24822, "text": "Return Value: This method doesn’t return anything but print the constructed table and log it. If it fails to parse the arguments into the table then it simply logs the arguments." }, { "code": null, "e": 25073, "s": 25001, "text": "Below examples illustrate the use of console.table() method in Node.js." }, { "code": null, "e": 25101, "s": 25073, "text": "Example 1: Filename: app.js" }, { "code": "// Node.js program to demonstrate the // console.table() method // Accessing console moduleconst console = require('console'); // Calling console.table() // without construction ruleconsole.table([ { a: 1, b: 2 }, { a: 3, b: 7, c: 'y' }]); // With construction ruleconsole.table([ { a: 1, b: 2 }, { a: 3, b: 7, c: 'y' }], [\"a\", \"b\"]);", "e": 25458, "s": 25101, "text": null }, { "code": null, "e": 25507, "s": 25458, "text": "Run the app.js file using the following command:" }, { "code": null, "e": 25519, "s": 25507, "text": "node app.js" }, { "code": null, "e": 25527, "s": 25519, "text": "Output:" }, { "code": null, "e": 25805, "s": 25527, "text": "┌─────────┬───┬───┬─────┐\n│ (index) │ a │ b │ c │\n├─────────┼───┼───┼─────┤\n│ 0 │ 1 │ 2 │ │\n│ 1 │ 3 │ 7 │ 'y' │\n└─────────┴───┴───┴─────┘\n\n┌─────────┬───┬───┐\n│ (index) │ a │ b │\n├─────────┼───┼───┤\n│ 0 │ 1 │ 2 │\n│ 1 │ 3 │ 7 │\n└─────────┴───┴───┘\n" }, { "code": null, "e": 25833, "s": 25805, "text": "Example 2: Filename: app.js" }, { "code": "// Node.js program to demonstrate the // console.table() method // Accessing console moduleconst console = require('console'); // Calling console.table() // fails to parse, so simply // print the argumentconsole.table(\"arg\"); // Blank tableconsole.table([]);", "e": 26097, "s": 25833, "text": null }, { "code": null, "e": 26146, "s": 26097, "text": "Run the app.js file using the following command:" }, { "code": null, "e": 26158, "s": 26146, "text": "node app.js" }, { "code": null, "e": 26166, "s": 26158, "text": "Output:" }, { "code": null, "e": 26219, "s": 26166, "text": "arg\n┌─────────┐\n│ (index) │\n├─────────┤\n└─────────┘\n" }, { "code": null, "e": 26303, "s": 26219, "text": "Note: The above program will compile and run by using the node filename.js command." }, { "code": null, "e": 26395, "s": 26303, "text": "Reference: https://nodejs.org/api/console.html#console_console_table_tabulardata_properties" }, { "code": null, "e": 26418, "s": 26395, "text": "Node.js-console-module" }, { "code": null, "e": 26426, "s": 26418, "text": "Node.js" }, { "code": null, "e": 26443, "s": 26426, "text": "Web Technologies" }, { "code": null, "e": 26541, "s": 26443, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26550, "s": 26541, "text": "Comments" }, { "code": null, "e": 26563, "s": 26550, "text": "Old Comments" }, { "code": null, "e": 26602, "s": 26563, "text": "Node.js crypto.createCipheriv() Method" }, { "code": null, "e": 26659, "s": 26602, "text": "Node.js CRUD Operations Using Mongoose and MongoDB Atlas" }, { "code": null, "e": 26690, "s": 26659, "text": "Explain the working of Node.js" }, { "code": null, "e": 26748, "s": 26690, "text": "How to make Mongoose multiple collections using Node.js ?" }, { "code": null, "e": 26782, "s": 26748, "text": "Disabling Sessions in Passport.js" }, { "code": null, "e": 26838, "s": 26782, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 26900, "s": 26838, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 26943, "s": 26900, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 26993, "s": 26943, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
HTML | <frame> src Attribute
28 May, 2019 The HTML <frame> src Attribute is used to specifies the document URL which is used to display in the frame. Syntax: <frame src="URL"> Attribute Values: It contains single value URL which specifies the source of the document. The possible value of the URL is: absolute URL: It points to another website. relative URL: It points to a file within a website. Note: The <frame> src Attribute is not supported by HTML 5. Example: <!DOCTYPE html><html> <head> <title>HTML frame src Attribute</title></head> <frameset cols="30%, 40%, 30%"> <frame name="top" src="attr1.png" /> <frame name="main" src="gradient3.png" /> <frame name="bottom" src="col_last.png" /></frameset> </html> Output: Supported Browsers: The browser supported by HTML <frame> src Attribute are listed below: Google Chrome Internet Explorer Firefox Safari Opera HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? REST API (Introduction) Types of CSS (Cascading Style Sheet) How to Insert Form Data into Database using PHP ? Design a Tribute Page using HTML & CSS Installation of Node.js on Linux Node.js fs.readFileSync() Method How do you run JavaScript script through the Terminal? Node.js | fs.writeFileSync() Method Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 28, "s": 0, "text": "\n28 May, 2019" }, { "code": null, "e": 136, "s": 28, "text": "The HTML <frame> src Attribute is used to specifies the document URL which is used to display in the frame." }, { "code": null, "e": 144, "s": 136, "text": "Syntax:" }, { "code": null, "e": 162, "s": 144, "text": "<frame src=\"URL\">" }, { "code": null, "e": 287, "s": 162, "text": "Attribute Values: It contains single value URL which specifies the source of the document. The possible value of the URL is:" }, { "code": null, "e": 331, "s": 287, "text": "absolute URL: It points to another website." }, { "code": null, "e": 383, "s": 331, "text": "relative URL: It points to a file within a website." }, { "code": null, "e": 443, "s": 383, "text": "Note: The <frame> src Attribute is not supported by HTML 5." }, { "code": null, "e": 452, "s": 443, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title>HTML frame src Attribute</title></head> <frameset cols=\"30%, 40%, 30%\"> <frame name=\"top\" src=\"attr1.png\" /> <frame name=\"main\" src=\"gradient3.png\" /> <frame name=\"bottom\" src=\"col_last.png\" /></frameset> </html>", "e": 748, "s": 452, "text": null }, { "code": null, "e": 756, "s": 748, "text": "Output:" }, { "code": null, "e": 846, "s": 756, "text": "Supported Browsers: The browser supported by HTML <frame> src Attribute are listed below:" }, { "code": null, "e": 860, "s": 846, "text": "Google Chrome" }, { "code": null, "e": 878, "s": 860, "text": "Internet Explorer" }, { "code": null, "e": 886, "s": 878, "text": "Firefox" }, { "code": null, "e": 893, "s": 886, "text": "Safari" }, { "code": null, "e": 899, "s": 893, "text": "Opera" }, { "code": null, "e": 915, "s": 899, "text": "HTML-Attributes" }, { "code": null, "e": 920, "s": 915, "text": "HTML" }, { "code": null, "e": 937, "s": 920, "text": "Web Technologies" }, { "code": null, "e": 942, "s": 937, "text": "HTML" }, { "code": null, "e": 1040, "s": 942, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1088, "s": 1040, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 1112, "s": 1088, "text": "REST API (Introduction)" }, { "code": null, "e": 1149, "s": 1112, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 1199, "s": 1149, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 1238, "s": 1199, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 1271, "s": 1238, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1304, "s": 1271, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 1359, "s": 1304, "text": "How do you run JavaScript script through the Terminal?" }, { "code": null, "e": 1395, "s": 1359, "text": "Node.js | fs.writeFileSync() Method" } ]
Reset keys of array elements using PHP ?
12 Feb, 2019 In PHP, two types of arrays are possible indexed and associative array. In case of Indexed array, the elements are strictly integer indexed and in case of associative array every element has corresponding keys associated with them and the elements can only be accessed using these keys. To access the keys and values of an associative array using integer index the array_keys() and array_values() inbuilt functions can be used. The array_keys() function takes input an array and returns the indexed array of only keys from the input array. The array_values() function takes input an array and return the indexed array of only values from the input array. Now, to reset the keys of array elements two operations can be performed, key_swap() and key_change(). As these are not inbuilt function these has to implemented in the code. Using key_swap() function: This function will take input an array and two keys and then swap the values corresponding to these two keys with the help of another variable ($val) and returns the resulting array. Note: This function will throw an error if both the keys are not present in the array. Using key_change() function: This function will take input an array and two keys, one old key (already present in the array) and a new key. The function will first store the value corresponding to the old key in to a third variable ($val) and then delete (unset()) the old key and its corresponding value from the array. Then the new key will be added to the array the value stored in the third variable ($val) will be assigned to it and the resulting array will be returned. Note: This function will return desired output if the new key is not present in the array otherwise if the new key in present in the input array then value of the new key will be lost as the value of the old key will overwrite it. Also, the function will throw an error if the old key is not present in the input array. Program: PHP program to reset keys of array element in an array. <?php// PHP program to reset the keys of array elements // Function to swap the values of any// two keys in an array function key_swap($arr, $key1, $key2) { $val = $arr[$key1]; $arr[$key1] = $arr[$key2]; $arr[$key2] = $val; return $arr;} // Function to change the key corresponding// to the value in an arrayfunction key_change($arr, $oldkey, $newkey){ $val = $arr[$oldkey]; unset($arr[$oldkey]); $arr[$newkey] = $val; return $arr;} // Sample associative array$arr = array( 'zero' => 1, 'one' => 2, 'two' => 0, 'test' => 3 ); // Print the sample arrayecho "The Sample array: ";print_r($arr); // Swap the keys 'zero' and 'one'$arr = key_swap($arr, 'zero', 'one'); // Swap the keys 'zero' and 'two'$arr = key_swap($arr, 'zero', 'two'); // Change the key 'test' to 'three'$arr = key_change($arr, 'test', 'three'); // Print the modified arrayecho "The Modified array: ";print_r($arr); ?> The Sample array: Array ( [zero] => 1 [one] => 2 [two] => 0 [test] => 3 ) The Modified array: Array ( [zero] => 0 [one] => 1 [two] => 2 [three] => 3 ) Picked PHP PHP Programs Web Technologies PHP 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": 315, "s": 28, "text": "In PHP, two types of arrays are possible indexed and associative array. In case of Indexed array, the elements are strictly integer indexed and in case of associative array every element has corresponding keys associated with them and the elements can only be accessed using these keys." }, { "code": null, "e": 456, "s": 315, "text": "To access the keys and values of an associative array using integer index the array_keys() and array_values() inbuilt functions can be used." }, { "code": null, "e": 568, "s": 456, "text": "The array_keys() function takes input an array and returns the indexed array of only keys from the input array." }, { "code": null, "e": 683, "s": 568, "text": "The array_values() function takes input an array and return the indexed array of only values from the input array." }, { "code": null, "e": 858, "s": 683, "text": "Now, to reset the keys of array elements two operations can be performed, key_swap() and key_change(). As these are not inbuilt function these has to implemented in the code." }, { "code": null, "e": 1068, "s": 858, "text": "Using key_swap() function: This function will take input an array and two keys and then swap the values corresponding to these two keys with the help of another variable ($val) and returns the resulting array." }, { "code": null, "e": 1155, "s": 1068, "text": "Note: This function will throw an error if both the keys are not present in the array." }, { "code": null, "e": 1631, "s": 1155, "text": "Using key_change() function: This function will take input an array and two keys, one old key (already present in the array) and a new key. The function will first store the value corresponding to the old key in to a third variable ($val) and then delete (unset()) the old key and its corresponding value from the array. Then the new key will be added to the array the value stored in the third variable ($val) will be assigned to it and the resulting array will be returned." }, { "code": null, "e": 1951, "s": 1631, "text": "Note: This function will return desired output if the new key is not present in the array otherwise if the new key in present in the input array then value of the new key will be lost as the value of the old key will overwrite it. Also, the function will throw an error if the old key is not present in the input array." }, { "code": null, "e": 2016, "s": 1951, "text": "Program: PHP program to reset keys of array element in an array." }, { "code": "<?php// PHP program to reset the keys of array elements // Function to swap the values of any// two keys in an array function key_swap($arr, $key1, $key2) { $val = $arr[$key1]; $arr[$key1] = $arr[$key2]; $arr[$key2] = $val; return $arr;} // Function to change the key corresponding// to the value in an arrayfunction key_change($arr, $oldkey, $newkey){ $val = $arr[$oldkey]; unset($arr[$oldkey]); $arr[$newkey] = $val; return $arr;} // Sample associative array$arr = array( 'zero' => 1, 'one' => 2, 'two' => 0, 'test' => 3 ); // Print the sample arrayecho \"The Sample array: \";print_r($arr); // Swap the keys 'zero' and 'one'$arr = key_swap($arr, 'zero', 'one'); // Swap the keys 'zero' and 'two'$arr = key_swap($arr, 'zero', 'two'); // Change the key 'test' to 'three'$arr = key_change($arr, 'test', 'three'); // Print the modified arrayecho \"The Modified array: \";print_r($arr); ?>", "e": 3015, "s": 2016, "text": null }, { "code": null, "e": 3199, "s": 3015, "text": "The Sample array: Array\n(\n [zero] => 1\n [one] => 2\n [two] => 0\n [test] => 3\n)\nThe Modified array: Array\n(\n [zero] => 0\n [one] => 1\n [two] => 2\n [three] => 3\n)\n" }, { "code": null, "e": 3206, "s": 3199, "text": "Picked" }, { "code": null, "e": 3210, "s": 3206, "text": "PHP" }, { "code": null, "e": 3223, "s": 3210, "text": "PHP Programs" }, { "code": null, "e": 3240, "s": 3223, "text": "Web Technologies" }, { "code": null, "e": 3244, "s": 3240, "text": "PHP" } ]
Software Testing Life Cycle (STLC)
10 May, 2019 Software Testing Life Cycle (STLC) is a sequence of different activities performed during the software testing process. Characteristics of STLC: STLC is a fundamental part of Software Development Life Cycle (SDLC) but STLC consists of only the testing phases. STLC starts as soon as requirements are defined or software requirement document is shared by stakeholders. STLC yields a step-by-step process to ensure quality software. In the initial stages of STLC, while the software product or the application is being developed, the testing team analyzes and defines the scope of testing, entry and exit criteria and also the test cases. It helps to reduce the test cycle time and also enhance the product quality.As soon as the development phase is over, testing team is ready with test cases and start the execution. This helps in finding bugs in the early phase. Phases of STLC: Requirement Analysis:Requirement Analysis is the first step of Software Testing Life Cycle (STLC). In this phase quality assurance team understands the requirements like what is to be tested. If anything is missing or not understandable then quality assurance team meets with the stakeholders to better understand the detail knowledge of requirement.Test Planning:Test Planning is most efficient phase of software testing life cycle where all testing plans are defined. In this phase manager of the testing team calculates estimated effort and cost for the testing work. This phase gets started once the requirement gathering phase is completed.Test Case Development:The test case development phase gets started once the test planning phase is completed. In this phase testing team note down the detailed test cases. Testing team also prepare the required test data for the testing. When the test cases are prepared then they are reviewed by quality assurance team.Test Environment Setup:Test environment setup is the vital part of the STLC. Basically test environment decides the conditions on which software is tested. This is independent activity and can be started along with test case development. In this process the testing team is not involved. either the developer or the customer creates the testing environment.Test Execution:After the test case development and test environment setup test execution phase gets started. In this phase testing team start executing test cases based on prepared test cases in the earlier step.Test Closure:This is the last stage of STLC in which the process of testing is analyzed. Requirement Analysis:Requirement Analysis is the first step of Software Testing Life Cycle (STLC). In this phase quality assurance team understands the requirements like what is to be tested. If anything is missing or not understandable then quality assurance team meets with the stakeholders to better understand the detail knowledge of requirement. Test Planning:Test Planning is most efficient phase of software testing life cycle where all testing plans are defined. In this phase manager of the testing team calculates estimated effort and cost for the testing work. This phase gets started once the requirement gathering phase is completed. Test Case Development:The test case development phase gets started once the test planning phase is completed. In this phase testing team note down the detailed test cases. Testing team also prepare the required test data for the testing. When the test cases are prepared then they are reviewed by quality assurance team. Test Environment Setup:Test environment setup is the vital part of the STLC. Basically test environment decides the conditions on which software is tested. This is independent activity and can be started along with test case development. In this process the testing team is not involved. either the developer or the customer creates the testing environment. Test Execution:After the test case development and test environment setup test execution phase gets started. In this phase testing team start executing test cases based on prepared test cases in the earlier step. Test Closure:This is the last stage of STLC in which the process of testing is analyzed. Software Engineering Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n10 May, 2019" }, { "code": null, "e": 173, "s": 53, "text": "Software Testing Life Cycle (STLC) is a sequence of different activities performed during the software testing process." }, { "code": null, "e": 198, "s": 173, "text": "Characteristics of STLC:" }, { "code": null, "e": 313, "s": 198, "text": "STLC is a fundamental part of Software Development Life Cycle (SDLC) but STLC consists of only the testing phases." }, { "code": null, "e": 421, "s": 313, "text": "STLC starts as soon as requirements are defined or software requirement document is shared by stakeholders." }, { "code": null, "e": 484, "s": 421, "text": "STLC yields a step-by-step process to ensure quality software." }, { "code": null, "e": 918, "s": 484, "text": "In the initial stages of STLC, while the software product or the application is being developed, the testing team analyzes and defines the scope of testing, entry and exit criteria and also the test cases. It helps to reduce the test cycle time and also enhance the product quality.As soon as the development phase is over, testing team is ready with test cases and start the execution. This helps in finding bugs in the early phase." }, { "code": null, "e": 934, "s": 918, "text": "Phases of STLC:" }, { "code": null, "e": 2557, "s": 934, "text": "Requirement Analysis:Requirement Analysis is the first step of Software Testing Life Cycle (STLC). In this phase quality assurance team understands the requirements like what is to be tested. If anything is missing or not understandable then quality assurance team meets with the stakeholders to better understand the detail knowledge of requirement.Test Planning:Test Planning is most efficient phase of software testing life cycle where all testing plans are defined. In this phase manager of the testing team calculates estimated effort and cost for the testing work. This phase gets started once the requirement gathering phase is completed.Test Case Development:The test case development phase gets started once the test planning phase is completed. In this phase testing team note down the detailed test cases. Testing team also prepare the required test data for the testing. When the test cases are prepared then they are reviewed by quality assurance team.Test Environment Setup:Test environment setup is the vital part of the STLC. Basically test environment decides the conditions on which software is tested. This is independent activity and can be started along with test case development. In this process the testing team is not involved. either the developer or the customer creates the testing environment.Test Execution:After the test case development and test environment setup test execution phase gets started. In this phase testing team start executing test cases based on prepared test cases in the earlier step.Test Closure:This is the last stage of STLC in which the process of testing is analyzed." }, { "code": null, "e": 2908, "s": 2557, "text": "Requirement Analysis:Requirement Analysis is the first step of Software Testing Life Cycle (STLC). In this phase quality assurance team understands the requirements like what is to be tested. If anything is missing or not understandable then quality assurance team meets with the stakeholders to better understand the detail knowledge of requirement." }, { "code": null, "e": 3204, "s": 2908, "text": "Test Planning:Test Planning is most efficient phase of software testing life cycle where all testing plans are defined. In this phase manager of the testing team calculates estimated effort and cost for the testing work. This phase gets started once the requirement gathering phase is completed." }, { "code": null, "e": 3525, "s": 3204, "text": "Test Case Development:The test case development phase gets started once the test planning phase is completed. In this phase testing team note down the detailed test cases. Testing team also prepare the required test data for the testing. When the test cases are prepared then they are reviewed by quality assurance team." }, { "code": null, "e": 3883, "s": 3525, "text": "Test Environment Setup:Test environment setup is the vital part of the STLC. Basically test environment decides the conditions on which software is tested. This is independent activity and can be started along with test case development. In this process the testing team is not involved. either the developer or the customer creates the testing environment." }, { "code": null, "e": 4096, "s": 3883, "text": "Test Execution:After the test case development and test environment setup test execution phase gets started. In this phase testing team start executing test cases based on prepared test cases in the earlier step." }, { "code": null, "e": 4185, "s": 4096, "text": "Test Closure:This is the last stage of STLC in which the process of testing is analyzed." }, { "code": null, "e": 4206, "s": 4185, "text": "Software Engineering" } ]
p5.js | fill() Function
04 Sep, 2019 The fill() function is used to fill the color to the shapes. This function supports all types of color object. For example RGB, RGBA, Hex CSS color, and all named color strings. The color object can also be set as string in terms of RGB, RGBA, Hex CSS color or named color string. Syntax: fill( v1, v2, v3, alpha ) or fill( value ) or fill( gray, alpha ) or fill( values ) or fill( color ) Parameters: v1: It is used to set the red or hue value relative to current color range. v2: It is used to set the green or saturation value relative to current color range. v3: It is used to set the blue or brightness value relative to current color range. alpha: It is used to set the transparency of the drawing. value: It is used to set the value of color string. gray: It is used to set the gray value. values: It is an array containing the red, green, blue and alpha value. color: It is used to set the stroke color. Below examples illustrate the fill() function in p5.js: Example 1: function setup() { // Create Canvas of given size createCanvas(400, 300); } function draw() { // Set the background color background(220); // Use fill() function to fill color fill('green') // Draw a line rect(50, 50, 150, 150); // Use noFill() function noFill(); // Draw a line rect(100, 100, 150, 150); } Output: Example 2: function setup() { // Create Canvas of given size createCanvas(400, 300); } function draw() { // Set the background color background(220); // Use noFill() function noFill(); // Draw a circle circle(140, 100, 150); // Use fill() function to fill color fill('green'); // Draw a crrcle circle(240, 100, 150); } Output: Reference: https://p5js.org/reference/#/p5/fill JavaScript-p5.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Sep, 2019" }, { "code": null, "e": 309, "s": 28, "text": "The fill() function is used to fill the color to the shapes. This function supports all types of color object. For example RGB, RGBA, Hex CSS color, and all named color strings. The color object can also be set as string in terms of RGB, RGBA, Hex CSS color or named color string." }, { "code": null, "e": 317, "s": 309, "text": "Syntax:" }, { "code": null, "e": 343, "s": 317, "text": "fill( v1, v2, v3, alpha )" }, { "code": null, "e": 346, "s": 343, "text": "or" }, { "code": null, "e": 360, "s": 346, "text": "fill( value )" }, { "code": null, "e": 363, "s": 360, "text": "or" }, { "code": null, "e": 383, "s": 363, "text": "fill( gray, alpha )" }, { "code": null, "e": 386, "s": 383, "text": "or" }, { "code": null, "e": 401, "s": 386, "text": "fill( values )" }, { "code": null, "e": 404, "s": 401, "text": "or" }, { "code": null, "e": 418, "s": 404, "text": "fill( color )" }, { "code": null, "e": 430, "s": 418, "text": "Parameters:" }, { "code": null, "e": 506, "s": 430, "text": "v1: It is used to set the red or hue value relative to current color range." }, { "code": null, "e": 591, "s": 506, "text": "v2: It is used to set the green or saturation value relative to current color range." }, { "code": null, "e": 675, "s": 591, "text": "v3: It is used to set the blue or brightness value relative to current color range." }, { "code": null, "e": 733, "s": 675, "text": "alpha: It is used to set the transparency of the drawing." }, { "code": null, "e": 785, "s": 733, "text": "value: It is used to set the value of color string." }, { "code": null, "e": 825, "s": 785, "text": "gray: It is used to set the gray value." }, { "code": null, "e": 897, "s": 825, "text": "values: It is an array containing the red, green, blue and alpha value." }, { "code": null, "e": 940, "s": 897, "text": "color: It is used to set the stroke color." }, { "code": null, "e": 996, "s": 940, "text": "Below examples illustrate the fill() function in p5.js:" }, { "code": null, "e": 1007, "s": 996, "text": "Example 1:" }, { "code": "function setup() { // Create Canvas of given size createCanvas(400, 300); } function draw() { // Set the background color background(220); // Use fill() function to fill color fill('green') // Draw a line rect(50, 50, 150, 150); // Use noFill() function noFill(); // Draw a line rect(100, 100, 150, 150); } ", "e": 1389, "s": 1007, "text": null }, { "code": null, "e": 1397, "s": 1389, "text": "Output:" }, { "code": null, "e": 1408, "s": 1397, "text": "Example 2:" }, { "code": "function setup() { // Create Canvas of given size createCanvas(400, 300); } function draw() { // Set the background color background(220); // Use noFill() function noFill(); // Draw a circle circle(140, 100, 150); // Use fill() function to fill color fill('green'); // Draw a crrcle circle(240, 100, 150); } ", "e": 1798, "s": 1408, "text": null }, { "code": null, "e": 1806, "s": 1798, "text": "Output:" }, { "code": null, "e": 1854, "s": 1806, "text": "Reference: https://p5js.org/reference/#/p5/fill" }, { "code": null, "e": 1871, "s": 1854, "text": "JavaScript-p5.js" }, { "code": null, "e": 1882, "s": 1871, "text": "JavaScript" }, { "code": null, "e": 1899, "s": 1882, "text": "Web Technologies" } ]
Kolmogorov-Smirnov Test in R Programming
15 Dec, 2021 The Kolmogorov-Smirnov Test is a type of non-parametric test of the equality of discontinuous and continuous of a 1D probability distribution that is used to compare the sample with the reference probability test (known as one-sample K-S Test) or among two samples (known as two-sample K-S test). A K-S Test quantifies a distance between the cumulative distribution function of the given reference distribution and the empirical distributions of given two samples, or between the empirical distribution of given two samples. In a one-sample K-S test, the distribution that is considered under a null hypothesis can be purely discrete or continuous or mixed. In the two-sample K-S test, the distribution considered under the null hypothesis is generally continuous distribution but it is unrestricted otherwise. The Kolmogorov-Smirnov test can be done very easily in R Programming. The formula for the Kolmogorov-Smirnov test can be given as: where, supx : the supremum of the set of distances Fn(x) : the empirical distribution function for n id observations Xi The empirical distribution function is a distribution function that is associated with the empirical measures of the chosen sample. Being a step function, this cumulative distribution jumps up by a 1/n step at each and every n data points. The K-S test can be performed using the ks.test() function in R. Syntax: ks.text(x, y, ..., alternative = c(“two.sided”, “less”, “greater”), exact= NULL, tol= 1e-8, simulate.p.value = FALSE, B=2000) Parameters: x: numeric vector of data valuesy: numeric vector of data values or a character string which is used to name a cumulative distribution function....: the parameters which are defined by the y value alternative: used to indicate the alternate hypothesis.exact: usually NULL or it indicates a logic that an exact p-value should be computed. tol: an upper bound used for rounding off errors in the data values.simulate.p.value: a logic that checks whether to use Monte Carlo method to compute the p-value.B: an integer value that indicates the number of replicates to be created while using the Monte Carlo method. Let us understand how to execute a K-S Test step by step using an example of a two-sample K-S test. Step 1: At first install the required packages. For performing the K-S test we need to install the “dgof” package using the install.packages() function from the R console. install.packages("dgof") Step 2: After a successful installation of the package, load the required package in our R Script. for that purpose, use the library() function as follows: R # loading the required packagelibrary("dgof") Step 3: Use the rnorm() function and the runif() function to generate to samples say x and y. The rnorm() function is used to generate random variates while the runif() function is used to generate random deviates. R # loading the required packagelibrary(dgof) # generating random variate# sample 1x <- rnorm(50) # generating random deviates# sample 2y <- runif(30) Step 4: Now perform the K-S test on these two samples. For that purpose, use the ks.test() of the dgof package. R # loading the required packagelibrary(dgof) # generating random variate# sample 1x <- rnorm(50) # generating random deviates# sample 2y <- runif(30) # performing the K-S Test# Do x and y come from# the same distribution?ks.test(x, y) Output: Two-sample Kolmogorov-Smirnov test data: x and y D = 0.84, p-value = 5.151e-14 alternative hypothesis: two-sided Being quite sensitive to the difference of shape and location of the empirical cumulative distribution of the chosen two samples, the two-sample K-S test is efficient, and one of the most general and useful non-parametric test. Hence we will see how the graph represents the difference between the two samples. Example: Here we are generating both the samples using the rnorm() functions and then plot them. R # loading the required packagelibrary(dgof) # sample 1# generating a random variatex <- rnorm(50) # sample 2# generating a random variatex2 <- rnorm(50, -1) # plotting the result# visualizationplot(ecdf(x), xlim = range(c(x, x2)), col = "blue")plot(ecdf(x2), add = TRUE, lty = "dashed", col = "red") # performing the K-S# Test on x and x2ks.test(x, x2, alternative = "l") Output: Two-sample Kolmogorov-Smirnov test data: x and x2 D^- = 0.34, p-value = 0.003089 alternative hypothesis: the CDF of x lies below that of y surinderdawra388 data-science Picked R Machine-Learning Machine Learning R Language Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Dec, 2021" }, { "code": null, "e": 909, "s": 28, "text": "The Kolmogorov-Smirnov Test is a type of non-parametric test of the equality of discontinuous and continuous of a 1D probability distribution that is used to compare the sample with the reference probability test (known as one-sample K-S Test) or among two samples (known as two-sample K-S test). A K-S Test quantifies a distance between the cumulative distribution function of the given reference distribution and the empirical distributions of given two samples, or between the empirical distribution of given two samples. In a one-sample K-S test, the distribution that is considered under a null hypothesis can be purely discrete or continuous or mixed. In the two-sample K-S test, the distribution considered under the null hypothesis is generally continuous distribution but it is unrestricted otherwise. The Kolmogorov-Smirnov test can be done very easily in R Programming." }, { "code": null, "e": 970, "s": 909, "text": "The formula for the Kolmogorov-Smirnov test can be given as:" }, { "code": null, "e": 977, "s": 970, "text": "where," }, { "code": null, "e": 1021, "s": 977, "text": "supx : the supremum of the set of distances" }, { "code": null, "e": 1091, "s": 1021, "text": " Fn(x) : the empirical distribution function for n id observations Xi" }, { "code": null, "e": 1332, "s": 1091, "text": "The empirical distribution function is a distribution function that is associated with the empirical measures of the chosen sample. Being a step function, this cumulative distribution jumps up by a 1/n step at each and every n data points. " }, { "code": null, "e": 1398, "s": 1332, "text": "The K-S test can be performed using the ks.test() function in R. " }, { "code": null, "e": 1406, "s": 1398, "text": "Syntax:" }, { "code": null, "e": 1532, "s": 1406, "text": "ks.text(x, y, ..., alternative = c(“two.sided”, “less”, “greater”), exact= NULL, tol= 1e-8, simulate.p.value = FALSE, B=2000)" }, { "code": null, "e": 1544, "s": 1532, "text": "Parameters:" }, { "code": null, "e": 1741, "s": 1544, "text": "x: numeric vector of data valuesy: numeric vector of data values or a character string which is used to name a cumulative distribution function....: the parameters which are defined by the y value" }, { "code": null, "e": 1882, "s": 1741, "text": "alternative: used to indicate the alternate hypothesis.exact: usually NULL or it indicates a logic that an exact p-value should be computed." }, { "code": null, "e": 2155, "s": 1882, "text": "tol: an upper bound used for rounding off errors in the data values.simulate.p.value: a logic that checks whether to use Monte Carlo method to compute the p-value.B: an integer value that indicates the number of replicates to be created while using the Monte Carlo method." }, { "code": null, "e": 2256, "s": 2155, "text": "Let us understand how to execute a K-S Test step by step using an example of a two-sample K-S test. " }, { "code": null, "e": 2428, "s": 2256, "text": "Step 1: At first install the required packages. For performing the K-S test we need to install the “dgof” package using the install.packages() function from the R console." }, { "code": null, "e": 2453, "s": 2428, "text": "install.packages(\"dgof\")" }, { "code": null, "e": 2609, "s": 2453, "text": "Step 2: After a successful installation of the package, load the required package in our R Script. for that purpose, use the library() function as follows:" }, { "code": null, "e": 2611, "s": 2609, "text": "R" }, { "code": "# loading the required packagelibrary(\"dgof\")", "e": 2657, "s": 2611, "text": null }, { "code": null, "e": 2872, "s": 2657, "text": "Step 3: Use the rnorm() function and the runif() function to generate to samples say x and y. The rnorm() function is used to generate random variates while the runif() function is used to generate random deviates." }, { "code": null, "e": 2874, "s": 2872, "text": "R" }, { "code": "# loading the required packagelibrary(dgof) # generating random variate# sample 1x <- rnorm(50) # generating random deviates# sample 2y <- runif(30)", "e": 3023, "s": 2874, "text": null }, { "code": null, "e": 3135, "s": 3023, "text": "Step 4: Now perform the K-S test on these two samples. For that purpose, use the ks.test() of the dgof package." }, { "code": null, "e": 3137, "s": 3135, "text": "R" }, { "code": "# loading the required packagelibrary(dgof) # generating random variate# sample 1x <- rnorm(50) # generating random deviates# sample 2y <- runif(30) # performing the K-S Test# Do x and y come from# the same distribution?ks.test(x, y)", "e": 3371, "s": 3137, "text": null }, { "code": null, "e": 3380, "s": 3371, "text": "Output: " }, { "code": null, "e": 3499, "s": 3380, "text": " Two-sample Kolmogorov-Smirnov test\n\ndata: x and y\nD = 0.84, p-value = 5.151e-14\nalternative hypothesis: two-sided" }, { "code": null, "e": 3810, "s": 3499, "text": "Being quite sensitive to the difference of shape and location of the empirical cumulative distribution of the chosen two samples, the two-sample K-S test is efficient, and one of the most general and useful non-parametric test. Hence we will see how the graph represents the difference between the two samples." }, { "code": null, "e": 3819, "s": 3810, "text": "Example:" }, { "code": null, "e": 3909, "s": 3819, "text": "Here we are generating both the samples using the rnorm() functions and then plot them. " }, { "code": null, "e": 3911, "s": 3909, "text": "R" }, { "code": "# loading the required packagelibrary(dgof) # sample 1# generating a random variatex <- rnorm(50) # sample 2# generating a random variatex2 <- rnorm(50, -1) # plotting the result# visualizationplot(ecdf(x), xlim = range(c(x, x2)), col = \"blue\")plot(ecdf(x2), add = TRUE, lty = \"dashed\", col = \"red\") # performing the K-S# Test on x and x2ks.test(x, x2, alternative = \"l\")", "e": 4303, "s": 3911, "text": null }, { "code": null, "e": 4312, "s": 4303, "text": "Output: " }, { "code": null, "e": 4457, "s": 4312, "text": " Two-sample Kolmogorov-Smirnov test\n\ndata: x and x2\nD^- = 0.34, p-value = 0.003089\nalternative hypothesis: the CDF of x lies below that of y" }, { "code": null, "e": 4476, "s": 4459, "text": "surinderdawra388" }, { "code": null, "e": 4489, "s": 4476, "text": "data-science" }, { "code": null, "e": 4496, "s": 4489, "text": "Picked" }, { "code": null, "e": 4515, "s": 4496, "text": "R Machine-Learning" }, { "code": null, "e": 4532, "s": 4515, "text": "Machine Learning" }, { "code": null, "e": 4543, "s": 4532, "text": "R Language" }, { "code": null, "e": 4560, "s": 4543, "text": "Machine Learning" } ]
YAML - Indentation and Separation
Indentation and separation are two main concepts when you are learning any programming language. This chapter talks about these two concepts related to YAML in detail. YAML does not include any mandatory spaces. Further, there is no need to be consistent. The valid YAML indentation is shown below − a: b: - c - d - e f: "ghi" You should remember the following rules while working with indentation in YAML:Flow blocks must be intended with at least some spaces with surrounding current block level. You should remember the following rules while working with indentation in YAML:Flow blocks must be intended with at least some spaces with surrounding current block level. Flow content of YAML spans multiple lines. The beginning of flow content begins with { or [. Flow content of YAML spans multiple lines. The beginning of flow content begins with { or [. Block list items include same indentation as the surrounding block level because - is considered as a part of indentation. Block list items include same indentation as the surrounding block level because - is considered as a part of indentation. Observe the following code that shows indentation with examples − --- !clarkevans.com/^invoice invoice: 34843 date : 2001-01-23 bill-to: &id001 given : Chris family : Dumars address: lines: | 458 Walkman Dr. Suite #292 city : Royal Oak state : MI postal : 48046 ship-to: *id001 product: - sku : BL394D quantity : 4 description : Basketball price : 450.00 - sku : BL4438H quantity : 1 description : Super Hoop price : 2392.00 tax : 251.42 total: 4443.52 comments: > Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338. Strings are separated using double-quoted string. If you escape the newline characters in a given string, it is completely removed and translated into space value. In this example we have focused listing of animals listed as an array structure with data type of string. Every new element is listed with a prefix of hyphen as mentioned as prefix. - - Cat - Dog - Goldfish - - Python - Lion - Tiger Another example to explain string representation in YAML is mentioned below. errors: messages: already_confirmed: "was already confirmed, please try signing in" confirmation_period_expired: "needs to be confirmed within %{period}, please request a new one" expired: "has expired, please request a new one" not_found: "not found" not_locked: "was not locked" not_saved: one: "1 error prohibited this %{resource} from being saved:" other: "%{count} errors prohibited this %{resource} from being saved:" This example refers to the set of error messages which a user can use just by mentioning the key aspect and to fetch the values accordingly. This pattern of YAML follows the structure of JSON which can be understood by user who is new to YAML.
[ { "code": null, "e": 2350, "s": 2182, "text": "Indentation and separation are two main concepts when you are learning any programming language. This chapter talks about these two concepts related to YAML in detail." }, { "code": null, "e": 2482, "s": 2350, "text": "YAML does not include any mandatory spaces. Further, there is no need to be consistent. The valid YAML indentation is shown below −" }, { "code": null, "e": 2537, "s": 2482, "text": "a:\n b:\n - c\n - d\n - e\nf:\n \"ghi\"" }, { "code": null, "e": 2709, "s": 2537, "text": "You should remember the following rules while working with indentation in YAML:Flow blocks must be intended with at least some spaces with surrounding current block level." }, { "code": null, "e": 2881, "s": 2709, "text": "You should remember the following rules while working with indentation in YAML:Flow blocks must be intended with at least some spaces with surrounding current block level." }, { "code": null, "e": 2974, "s": 2881, "text": "Flow content of YAML spans multiple lines. The beginning of flow content begins with { or [." }, { "code": null, "e": 3067, "s": 2974, "text": "Flow content of YAML spans multiple lines. The beginning of flow content begins with { or [." }, { "code": null, "e": 3190, "s": 3067, "text": "Block list items include same indentation as the surrounding block level because - is considered as a part of indentation." }, { "code": null, "e": 3313, "s": 3190, "text": "Block list items include same indentation as the surrounding block level because - is considered as a part of indentation." }, { "code": null, "e": 3379, "s": 3313, "text": "Observe the following code that shows indentation with examples −" }, { "code": null, "e": 4003, "s": 3379, "text": "--- !clarkevans.com/^invoice\ninvoice: 34843\ndate : 2001-01-23\nbill-to: &id001\n given : Chris\n family : Dumars\n address:\n lines: |\n 458 Walkman Dr.\n Suite #292\n city : Royal Oak\n state : MI\n postal : 48046\nship-to: *id001\nproduct:\n - sku : BL394D\n quantity : 4\n description : Basketball\n price : 450.00\n - sku : BL4438H\n quantity : 1\n description : Super Hoop\n price : 2392.00\ntax : 251.42\ntotal: 4443.52\ncomments: >\n Late afternoon is best.\n Backup contact is Nancy\n Billsmer @ 338-4338." }, { "code": null, "e": 4167, "s": 4003, "text": "Strings are separated using double-quoted string. If you escape the newline characters in a given string, it is completely removed and translated into space value." }, { "code": null, "e": 4349, "s": 4167, "text": "In this example we have focused listing of animals listed as an array structure with data type of string. Every new element is listed with a prefix of hyphen as mentioned as prefix." }, { "code": null, "e": 4407, "s": 4349, "text": "-\n - Cat\n - Dog\n - Goldfish\n-\n - Python\n - Lion\n - Tiger\n" }, { "code": null, "e": 4484, "s": 4407, "text": "Another example to explain string representation in YAML is mentioned below." }, { "code": null, "e": 4994, "s": 4484, "text": " errors:\n messages:\n already_confirmed: \"was already confirmed, please try signing in\"\n confirmation_period_expired: \"needs to be confirmed within %{period}, please request a new one\"\n expired: \"has expired, please request a new one\"\n not_found: \"not found\"\n not_locked: \"was not locked\"\n not_saved:\n one: \"1 error prohibited this %{resource} from being saved:\"\n other: \"%{count} errors prohibited this %{resource} from being saved:\"\n" } ]
Basics Operations of File and Directory in C#
13 Sep, 2021 In this article, we are going to cover how to create, delete and rename directory and also how to delete and rename the file. We can create Directory using CreateDirectory() method present in the Directory class. csharp // C# program to create a directoryusing System;using System.IO; class Program { // Main Method static void Main(string[] args) { Console.WriteLine("Please enter a name for the new directory:"); string DirName = Console.ReadLine(); // Checking if string is empty or not if (DirName != String.Empty) { // Creating the Directory Directory.CreateDirectory(DirName); // Checking Directory is created // Successfully or not if (Directory.Exists(DirName)) { Console.WriteLine("The directory was created!"); Console.ReadKey(); } } }} Output: You will find the Directory with a given name at the specific location. csharp using System;using System.IO; class GFG { // Main Method static void Main(string[] args) { Console.WriteLine("Please enter a name of the directory to renamed:"); string DirName = Console.ReadLine(); // checking directory exist or not if (Directory.Exists(DirName)) { Console.WriteLine("Please enter a new name for this directory:"); string newDirName = Console.ReadLine(); if (newDirName != String.Empty) { // to rename directory Directory.Move(DirName, newDirName); // checking directory has // been renamed or not if (Directory.Exists(newDirName)) { Console.WriteLine("The directory was renamed to " + newDirName); Console.ReadKey(); } } } }} Output: You will find the updated Directory’s name at the specific location. There is no such method called Rename() so we are using the Move() method to rename a directory. Moving and renaming are the same operations in C#. csharp using System;using System.IO; class GFG { // Main Method static void Main(string[] args) { Console.WriteLine("Enter the directory name you want to delete:"); string DirName = Console.ReadLine(); // Checking if Directory Exist or not if (Directory.Exists(DirName)) { // This will delete the // Directory if it is empty Directory.Delete(DirName); // checking if directory if // deleted successfully or not if (Directory.Exists(DirName) == false) Console.WriteLine("Directory deleted successfully..."); } else Console.WriteLine("Directory {0} does not exist!", DirName); Console.ReadKey(); }} Output: You will find the Directory with a given name does not exist anymore at the specified location. If Directory is not empty, then Delete() will throw an exception because it deletes an only empty directory. Directory.Delete(DirName, true); If we pass the extra parameters then the Delete() method is recursive. First, all the files and subdirectories of the specified directory are deleted before deleting the directory. csharp // C# Program for Renaming a fileusing System;using System.IO; class GFG { // Main Method static void Main(string[] args) { Console.WriteLine("Please enter a name of the file to renamed:"); string FileName = Console.ReadLine(); // Checking File exist or not if (File.Exists(FileName)) { Console.WriteLine("Please enter a new name for this file:"); string newFilename = Console.ReadLine(); // Checking if string is null or not if (newFilename != String.Empty) { // Renaming the file File.Move(FileName, newFilename); // checking if the file has been // renamed successfully or not if (File.Exists(newFilename)) { Console.WriteLine("The file was renamed to " + newFilename); Console.ReadKey(); } } } }} Output: You will find the changed file name at the specific location. csharp using System;using System.IO; class GFG { // Main Method static void Main(string[] args) { Console.WriteLine("Enter the file name you want to delete:"); string FileName = Console.ReadLine(); // Checking file exists or not if (File.Exists(FileName)) { // Deleting the file File.Delete(FileName); // Checking if the file is deleted // successfully or not if (File.Exists(FileName) == false) Console.WriteLine("File deleted successfully..."); } else Console.WriteLine("File {0} does not exist!", FileName); Console.ReadKey(); }} Output: You will find there is no such file exists with a given name at the specific location. sagartomar9927 CSharp-File-Handling C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Sep, 2021" }, { "code": null, "e": 156, "s": 28, "text": "In this article, we are going to cover how to create, delete and rename directory and also how to delete and rename the file. " }, { "code": null, "e": 244, "s": 156, "text": "We can create Directory using CreateDirectory() method present in the Directory class. " }, { "code": null, "e": 251, "s": 244, "text": "csharp" }, { "code": "// C# program to create a directoryusing System;using System.IO; class Program { // Main Method static void Main(string[] args) { Console.WriteLine(\"Please enter a name for the new directory:\"); string DirName = Console.ReadLine(); // Checking if string is empty or not if (DirName != String.Empty) { // Creating the Directory Directory.CreateDirectory(DirName); // Checking Directory is created // Successfully or not if (Directory.Exists(DirName)) { Console.WriteLine(\"The directory was created!\"); Console.ReadKey(); } } }}", "e": 943, "s": 251, "text": null }, { "code": null, "e": 952, "s": 943, "text": "Output: " }, { "code": null, "e": 1026, "s": 952, "text": "You will find the Directory with a given name at the specific location. " }, { "code": null, "e": 1035, "s": 1028, "text": "csharp" }, { "code": "using System;using System.IO; class GFG { // Main Method static void Main(string[] args) { Console.WriteLine(\"Please enter a name of the directory to renamed:\"); string DirName = Console.ReadLine(); // checking directory exist or not if (Directory.Exists(DirName)) { Console.WriteLine(\"Please enter a new name for this directory:\"); string newDirName = Console.ReadLine(); if (newDirName != String.Empty) { // to rename directory Directory.Move(DirName, newDirName); // checking directory has // been renamed or not if (Directory.Exists(newDirName)) { Console.WriteLine(\"The directory was renamed to \" + newDirName); Console.ReadKey(); } } } }}", "e": 1927, "s": 1035, "text": null }, { "code": null, "e": 1936, "s": 1927, "text": "Output: " }, { "code": null, "e": 2154, "s": 1936, "text": "You will find the updated Directory’s name at the specific location. There is no such method called Rename() so we are using the Move() method to rename a directory. Moving and renaming are the same operations in C#. " }, { "code": null, "e": 2163, "s": 2156, "text": "csharp" }, { "code": "using System;using System.IO; class GFG { // Main Method static void Main(string[] args) { Console.WriteLine(\"Enter the directory name you want to delete:\"); string DirName = Console.ReadLine(); // Checking if Directory Exist or not if (Directory.Exists(DirName)) { // This will delete the // Directory if it is empty Directory.Delete(DirName); // checking if directory if // deleted successfully or not if (Directory.Exists(DirName) == false) Console.WriteLine(\"Directory deleted successfully...\"); } else Console.WriteLine(\"Directory {0} does not exist!\", DirName); Console.ReadKey(); }}", "e": 2918, "s": 2163, "text": null }, { "code": null, "e": 2927, "s": 2918, "text": "Output: " }, { "code": null, "e": 3133, "s": 2927, "text": "You will find the Directory with a given name does not exist anymore at the specified location. If Directory is not empty, then Delete() will throw an exception because it deletes an only empty directory. " }, { "code": null, "e": 3166, "s": 3133, "text": "Directory.Delete(DirName, true);" }, { "code": null, "e": 3349, "s": 3166, "text": "If we pass the extra parameters then the Delete() method is recursive. First, all the files and subdirectories of the specified directory are deleted before deleting the directory. " }, { "code": null, "e": 3358, "s": 3351, "text": "csharp" }, { "code": "// C# Program for Renaming a fileusing System;using System.IO; class GFG { // Main Method static void Main(string[] args) { Console.WriteLine(\"Please enter a name of the file to renamed:\"); string FileName = Console.ReadLine(); // Checking File exist or not if (File.Exists(FileName)) { Console.WriteLine(\"Please enter a new name for this file:\"); string newFilename = Console.ReadLine(); // Checking if string is null or not if (newFilename != String.Empty) { // Renaming the file File.Move(FileName, newFilename); // checking if the file has been // renamed successfully or not if (File.Exists(newFilename)) { Console.WriteLine(\"The file was renamed to \" + newFilename); Console.ReadKey(); } } } }}", "e": 4338, "s": 3358, "text": null }, { "code": null, "e": 4347, "s": 4338, "text": "Output: " }, { "code": null, "e": 4410, "s": 4347, "text": "You will find the changed file name at the specific location. " }, { "code": null, "e": 4419, "s": 4412, "text": "csharp" }, { "code": "using System;using System.IO; class GFG { // Main Method static void Main(string[] args) { Console.WriteLine(\"Enter the file name you want to delete:\"); string FileName = Console.ReadLine(); // Checking file exists or not if (File.Exists(FileName)) { // Deleting the file File.Delete(FileName); // Checking if the file is deleted // successfully or not if (File.Exists(FileName) == false) Console.WriteLine(\"File deleted successfully...\"); } else Console.WriteLine(\"File {0} does not exist!\", FileName); Console.ReadKey(); }}", "e": 5099, "s": 4419, "text": null }, { "code": null, "e": 5109, "s": 5099, "text": "Output: " }, { "code": null, "e": 5197, "s": 5109, "text": "You will find there is no such file exists with a given name at the specific location. " }, { "code": null, "e": 5212, "s": 5197, "text": "sagartomar9927" }, { "code": null, "e": 5233, "s": 5212, "text": "CSharp-File-Handling" }, { "code": null, "e": 5236, "s": 5233, "text": "C#" } ]
Object Level Lock in Java
08 Jun, 2021 Every object in java has a unique lock. Whenever we are using a synchronized keyword, then only the lock concept will come into the picture. If a thread wants to execute a synchronized method on the given object. First, it has to get a lock of that object. Once the thread got the lock then it is allowed to execute any synchronized method on that object. Once method execution completes automatically thread releases the lock. Acquiring and release lock internally is taken care by JVM and the programmer is not responsible for these activities An object-level lock is a mechanism when we want to synchronize a non-static method or non-static code block such that only one thread will be able to execute the code block on a given instance of the class. If a thread wants to execute a synchronized method on the given object. First, it has to get a lock of that object. Once the thread got the lock then it is allowed to execute any synchronized method on that object. Once method execution completes automatically thread releases the lock. Acquiring and release lock internally is taken care of by JVM and the programmer is not responsible for these activities. Methods: There are different ways we can lock the object in the thread as below: Method 1: public class GeekClass { public synchronized void GeekMethod(){} } Method 2: public class GeekClass { public void GeekMethod(){ synchronized (this) { // other thread safe code } } } Method 3: public class DemoClass { private final Object lock = new Object(); public void demoMethod(){ synchronized (lock) { // other thread safe code } } } Example: Java // Java program to illustrate// Object lock concept // Class// Extending Runnable interfaceclass Geek implements Runnable { // Method of this class public void run() { Lock(); } // Synchronization of non-static methods // (object lock) as different synchronized // non-static methods are called in both threads // Then both threads need to acquire the object lock // After one is acquired, the other thread must wait // for one thread to finish the executing // before the other thread starts to execute. public void Lock() { System.out.println( Thread.currentThread().getName()); synchronized (this) { System.out.println( "in block " + Thread.currentThread().getName()); System.out.println( "in block " + Thread.currentThread().getName() + " end"); } } // Main driver method public static void main(String[] args) { // Creating an object of above class // in the main() method Geek g = new Geek(); // Sharing the same object across two Threads // Here, t1 takes g Thread t1 = new Thread(g); // Here, t2 takes g Thread t2 = new Thread(g); // Creating another object of above class Geek g1 = new Geek(); // Here, t3 takes g1 Thread t3 = new Thread(g1); // setname() method is used to change // name of the thread t1.setName("t1"); t2.setName("t2"); t3.setName("t3"); // start() method beginning the execution of threads // as JVM calls the run() method of thread t1.start(); t2.start(); t3.start(); }} t1 t3 t2 in block t1 in block t3 in block t1 end in block t2 in block t2 end in block t3 end akshaysingh98088 Java-Class and Object Java-Multithreading Picked Java Java-Class and Object Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Java Programming Examples Functional Interfaces in Java Strings in Java Differences between JDK, JRE and JVM Abstraction in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Jun, 2021" }, { "code": null, "e": 574, "s": 28, "text": "Every object in java has a unique lock. Whenever we are using a synchronized keyword, then only the lock concept will come into the picture. If a thread wants to execute a synchronized method on the given object. First, it has to get a lock of that object. Once the thread got the lock then it is allowed to execute any synchronized method on that object. Once method execution completes automatically thread releases the lock. Acquiring and release lock internally is taken care by JVM and the programmer is not responsible for these activities" }, { "code": null, "e": 783, "s": 574, "text": "An object-level lock is a mechanism when we want to synchronize a non-static method or non-static code block such that only one thread will be able to execute the code block on a given instance of the class. " }, { "code": null, "e": 1192, "s": 783, "text": "If a thread wants to execute a synchronized method on the given object. First, it has to get a lock of that object. Once the thread got the lock then it is allowed to execute any synchronized method on that object. Once method execution completes automatically thread releases the lock. Acquiring and release lock internally is taken care of by JVM and the programmer is not responsible for these activities." }, { "code": null, "e": 1273, "s": 1192, "text": "Methods: There are different ways we can lock the object in the thread as below:" }, { "code": null, "e": 1283, "s": 1273, "text": "Method 1:" }, { "code": null, "e": 1354, "s": 1283, "text": "public class GeekClass\n{\n public synchronized void GeekMethod(){}\n}" }, { "code": null, "e": 1364, "s": 1354, "text": "Method 2:" }, { "code": null, "e": 1513, "s": 1364, "text": "public class GeekClass\n{\n public void GeekMethod(){\n synchronized (this)\n {\n // other thread safe code\n }\n }\n}" }, { "code": null, "e": 1523, "s": 1513, "text": "Method 3:" }, { "code": null, "e": 1718, "s": 1523, "text": "public class DemoClass\n{\n private final Object lock = new Object();\n public void demoMethod(){\n synchronized (lock)\n {\n // other thread safe code\n }\n }\n}" }, { "code": null, "e": 1727, "s": 1718, "text": "Example:" }, { "code": null, "e": 1732, "s": 1727, "text": "Java" }, { "code": "// Java program to illustrate// Object lock concept // Class// Extending Runnable interfaceclass Geek implements Runnable { // Method of this class public void run() { Lock(); } // Synchronization of non-static methods // (object lock) as different synchronized // non-static methods are called in both threads // Then both threads need to acquire the object lock // After one is acquired, the other thread must wait // for one thread to finish the executing // before the other thread starts to execute. public void Lock() { System.out.println( Thread.currentThread().getName()); synchronized (this) { System.out.println( \"in block \" + Thread.currentThread().getName()); System.out.println( \"in block \" + Thread.currentThread().getName() + \" end\"); } } // Main driver method public static void main(String[] args) { // Creating an object of above class // in the main() method Geek g = new Geek(); // Sharing the same object across two Threads // Here, t1 takes g Thread t1 = new Thread(g); // Here, t2 takes g Thread t2 = new Thread(g); // Creating another object of above class Geek g1 = new Geek(); // Here, t3 takes g1 Thread t3 = new Thread(g1); // setname() method is used to change // name of the thread t1.setName(\"t1\"); t2.setName(\"t2\"); t3.setName(\"t3\"); // start() method beginning the execution of threads // as JVM calls the run() method of thread t1.start(); t2.start(); t3.start(); }}", "e": 3488, "s": 1732, "text": null }, { "code": null, "e": 3584, "s": 3491, "text": "t1\nt3\nt2\nin block t1\nin block t3\nin block t1 end\nin block t2\nin block t2 end\nin block t3 end" }, { "code": null, "e": 3603, "s": 3586, "text": "akshaysingh98088" }, { "code": null, "e": 3625, "s": 3603, "text": "Java-Class and Object" }, { "code": null, "e": 3645, "s": 3625, "text": "Java-Multithreading" }, { "code": null, "e": 3652, "s": 3645, "text": "Picked" }, { "code": null, "e": 3657, "s": 3652, "text": "Java" }, { "code": null, "e": 3679, "s": 3657, "text": "Java-Class and Object" }, { "code": null, "e": 3684, "s": 3679, "text": "Java" }, { "code": null, "e": 3782, "s": 3684, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3797, "s": 3782, "text": "Stream In Java" }, { "code": null, "e": 3818, "s": 3797, "text": "Introduction to Java" }, { "code": null, "e": 3839, "s": 3818, "text": "Constructors in Java" }, { "code": null, "e": 3858, "s": 3839, "text": "Exceptions in Java" }, { "code": null, "e": 3875, "s": 3858, "text": "Generics in Java" }, { "code": null, "e": 3901, "s": 3875, "text": "Java Programming Examples" }, { "code": null, "e": 3931, "s": 3901, "text": "Functional Interfaces in Java" }, { "code": null, "e": 3947, "s": 3931, "text": "Strings in Java" }, { "code": null, "e": 3984, "s": 3947, "text": "Differences between JDK, JRE and JVM" } ]
Graph Plotting in Python | Set 1
07 Jul, 2022 This series will introduce you to graphing in python with Matplotlib, which is arguably the most popular graphing and data visualization library for Python.InstallationThe easiest way to install matplotlib is to use pip. Type following command in terminal: pip install matplotlib OR, you can download it from here and install it manually. Getting started ( Plotting a line) Python # importing the required moduleimport matplotlib.pyplot as plt # x axis valuesx = [1,2,3]# corresponding y axis valuesy = [2,4,1] # plotting the points plt.plot(x, y) # naming the x axisplt.xlabel('x - axis')# naming the y axisplt.ylabel('y - axis') # giving a title to my graphplt.title('My first graph!') # function to show the plotplt.show() Output: Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. The code seems self-explanatory. Following steps were followed: Define the x-axis and corresponding y-axis values as lists. Plot them on canvas using .plot() function. Give a name to x-axis and y-axis using .xlabel() and .ylabel() functions. Give a title to your plot using .title() function. Finally, to view your plot, we use .show() function. Plotting two or more lines on same plot Python import matplotlib.pyplot as plt # line 1 pointsx1 = [1,2,3]y1 = [2,4,1]# plotting the line 1 points plt.plot(x1, y1, label = "line 1") # line 2 pointsx2 = [1,2,3]y2 = [4,1,3]# plotting the line 2 points plt.plot(x2, y2, label = "line 2") # naming the x axisplt.xlabel('x - axis')# naming the y axisplt.ylabel('y - axis')# giving a title to my graphplt.title('Two lines on same graph!') # show a legend on the plotplt.legend() # function to show the plotplt.show() Output: Here, we plot two lines on the same graph. We differentiate between them by giving them a name(label) which is passed as an argument of the .plot() function. The small rectangular box giving information about the type of line and its color is called a legend. We can add a legend to our plot using .legend() function. Customization of Plots Here, we discuss some elementary customizations applicable to almost any plot. Python import matplotlib.pyplot as plt # x axis valuesx = [1,2,3,4,5,6]# corresponding y axis valuesy = [2,4,1,5,2,6] # plotting the points plt.plot(x, y, color='green', linestyle='dashed', linewidth = 3, marker='o', markerfacecolor='blue', markersize=12) # setting x and y axis rangeplt.ylim(1,8)plt.xlim(1,8) # naming the x axisplt.xlabel('x - axis')# naming the y axisplt.ylabel('y - axis') # giving a title to my graphplt.title('Some cool customizations!') # function to show the plotplt.show() Output: As you can see, we have done several customizations like setting the line-width, line-style, line-color. setting the marker, marker’s face color, marker’s size. overriding the x and y-axis range. If overriding is not done, pyplot module uses the auto-scale feature to set the axis range and scale. Bar Chart Python import matplotlib.pyplot as plt # x-coordinates of left sides of bars left = [1, 2, 3, 4, 5] # heights of barsheight = [10, 24, 36, 40, 5] # labels for barstick_label = ['one', 'two', 'three', 'four', 'five'] # plotting a bar chartplt.bar(left, height, tick_label = tick_label, width = 0.8, color = ['red', 'green']) # naming the x-axisplt.xlabel('x - axis')# naming the y-axisplt.ylabel('y - axis')# plot titleplt.title('My bar chart!') # function to show the plotplt.show() Output : Here, we use plt.bar() function to plot a bar chart. x-coordinates of the left side of bars are passed along with the heights of bars. you can also give some names to x-axis coordinates by defining tick_labels Histogram Python import matplotlib.pyplot as plt # frequenciesages = [2,5,70,40,30,45,50,45,43,40,44, 60,7,13,57,18,90,77,32,21,20,40] # setting the ranges and no. of intervalsrange = (0, 100)bins = 10 # plotting a histogramplt.hist(ages, bins, range, color = 'green', histtype = 'bar', rwidth = 0.8) # x-axis labelplt.xlabel('age')# frequency labelplt.ylabel('No. of people')# plot titleplt.title('My histogram') # function to show the plotplt.show() Output: Here, we use plt.hist() function to plot a histogram. frequencies are passed as the ages list. The range could be set by defining a tuple containing min and max values. The next step is to “bin” the range of values—that is, divide the entire range of values into a series of intervals—and then count how many values fall into each interval. Here we have defined bins = 10. So, there are a total of 100/10 = 10 intervals. Scatter plot Python import matplotlib.pyplot as plt # x-axis valuesx = [1,2,3,4,5,6,7,8,9,10]# y-axis valuesy = [2,4,5,7,6,8,9,11,12,12] # plotting points as a scatter plotplt.scatter(x, y, label= "stars", color= "green", marker= "*", s=30) # x-axis labelplt.xlabel('x - axis')# frequency labelplt.ylabel('y - axis')# plot titleplt.title('My scatter plot!')# showing legendplt.legend() # function to show the plotplt.show() Output: Here, we use plt.scatter() function to plot a scatter plot. As a line, we define x and corresponding y-axis values here as well. marker argument is used to set the character to use as a marker. Its size can be defined using the s parameter. Pie-chart Python import matplotlib.pyplot as plt # defining labelsactivities = ['eat', 'sleep', 'work', 'play'] # portion covered by each labelslices = [3, 7, 8, 6] # color for each labelcolors = ['r', 'y', 'g', 'b'] # plotting the pie chartplt.pie(slices, labels = activities, colors=colors, startangle=90, shadow = True, explode = (0, 0, 0.1, 0), radius = 1.2, autopct = '%1.1f%%') # plotting legendplt.legend() # showing the plotplt.show() The output of above program looks like this: Here, we plot a pie chart by using plt.pie() method. First of all, we define the labels using a list called activities. Then, a portion of each label can be defined using another list called slices. Color for each label is defined using a list called colors. shadow = True will show a shadow beneath each label in pie chart. startangle rotates the start of the pie chart by given degrees counterclockwise from the x-axis. explode is used to set the fraction of radius with which we offset each wedge. autopct is used to format the value of each label. Here, we have set it to show the percentage value only upto 1 decimal place. Plotting curves of given equation Python # importing the required modulesimport matplotlib.pyplot as pltimport numpy as np # setting the x - coordinatesx = np.arange(0, 2*(np.pi), 0.1)# setting the corresponding y - coordinatesy = np.sin(x) # plotting the pointsplt.plot(x, y) # function to show the plotplt.show() The output of above program looks like this: Here, we use NumPy which is a general-purpose array-processing package in python. To set the x-axis values, we use the np.arange() method in which the first two arguments are for range and the third one for step-wise increment. The result is a NumPy array. To get corresponding y-axis values, we simply use the predefined np.sin() method on the NumPy array. Finally, we plot the points by passing x and y arrays to the plt.plot() function. So, in this part, we discussed various types of plots we can create in matplotlib. There are more plots that haven’t been covered but the most significant ones are discussed here – Graph Plotting in Python | Set 2 Graph Plotting in Python | Set 3 Python Programming Tutorial | Graph Plotting in Python | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersPython Programming Tutorial | Graph Plotting in Python | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:35•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=LBR3p0QnrCk" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is contributed by Nikhil 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 review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. kk9826225 sumitgumber28 pujasingg43 Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Jul, 2022" }, { "code": null, "e": 311, "s": 52, "text": "This series will introduce you to graphing in python with Matplotlib, which is arguably the most popular graphing and data visualization library for Python.InstallationThe easiest way to install matplotlib is to use pip. Type following command in terminal: " }, { "code": null, "e": 334, "s": 311, "text": "pip install matplotlib" }, { "code": null, "e": 395, "s": 334, "text": "OR, you can download it from here and install it manually. " }, { "code": null, "e": 430, "s": 395, "text": "Getting started ( Plotting a line)" }, { "code": null, "e": 437, "s": 430, "text": "Python" }, { "code": "# importing the required moduleimport matplotlib.pyplot as plt # x axis valuesx = [1,2,3]# corresponding y axis valuesy = [2,4,1] # plotting the points plt.plot(x, y) # naming the x axisplt.xlabel('x - axis')# naming the y axisplt.ylabel('y - axis') # giving a title to my graphplt.title('My first graph!') # function to show the plotplt.show()", "e": 787, "s": 437, "text": null }, { "code": null, "e": 797, "s": 787, "text": "Output: " }, { "code": null, "e": 806, "s": 797, "text": "Chapters" }, { "code": null, "e": 833, "s": 806, "text": "descriptions off, selected" }, { "code": null, "e": 883, "s": 833, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 906, "s": 883, "text": "captions off, selected" }, { "code": null, "e": 914, "s": 906, "text": "English" }, { "code": null, "e": 938, "s": 914, "text": "This is a modal window." }, { "code": null, "e": 1007, "s": 938, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 1029, "s": 1007, "text": "End of dialog window." }, { "code": null, "e": 1094, "s": 1029, "text": "The code seems self-explanatory. Following steps were followed: " }, { "code": null, "e": 1154, "s": 1094, "text": "Define the x-axis and corresponding y-axis values as lists." }, { "code": null, "e": 1198, "s": 1154, "text": "Plot them on canvas using .plot() function." }, { "code": null, "e": 1272, "s": 1198, "text": "Give a name to x-axis and y-axis using .xlabel() and .ylabel() functions." }, { "code": null, "e": 1323, "s": 1272, "text": "Give a title to your plot using .title() function." }, { "code": null, "e": 1376, "s": 1323, "text": "Finally, to view your plot, we use .show() function." }, { "code": null, "e": 1418, "s": 1378, "text": "Plotting two or more lines on same plot" }, { "code": null, "e": 1425, "s": 1418, "text": "Python" }, { "code": "import matplotlib.pyplot as plt # line 1 pointsx1 = [1,2,3]y1 = [2,4,1]# plotting the line 1 points plt.plot(x1, y1, label = \"line 1\") # line 2 pointsx2 = [1,2,3]y2 = [4,1,3]# plotting the line 2 points plt.plot(x2, y2, label = \"line 2\") # naming the x axisplt.xlabel('x - axis')# naming the y axisplt.ylabel('y - axis')# giving a title to my graphplt.title('Two lines on same graph!') # show a legend on the plotplt.legend() # function to show the plotplt.show()", "e": 1894, "s": 1425, "text": null }, { "code": null, "e": 1904, "s": 1894, "text": "Output: " }, { "code": null, "e": 2064, "s": 1906, "text": "Here, we plot two lines on the same graph. We differentiate between them by giving them a name(label) which is passed as an argument of the .plot() function." }, { "code": null, "e": 2224, "s": 2064, "text": "The small rectangular box giving information about the type of line and its color is called a legend. We can add a legend to our plot using .legend() function." }, { "code": null, "e": 2249, "s": 2226, "text": "Customization of Plots" }, { "code": null, "e": 2328, "s": 2249, "text": "Here, we discuss some elementary customizations applicable to almost any plot." }, { "code": null, "e": 2335, "s": 2328, "text": "Python" }, { "code": "import matplotlib.pyplot as plt # x axis valuesx = [1,2,3,4,5,6]# corresponding y axis valuesy = [2,4,1,5,2,6] # plotting the points plt.plot(x, y, color='green', linestyle='dashed', linewidth = 3, marker='o', markerfacecolor='blue', markersize=12) # setting x and y axis rangeplt.ylim(1,8)plt.xlim(1,8) # naming the x axisplt.xlabel('x - axis')# naming the y axisplt.ylabel('y - axis') # giving a title to my graphplt.title('Some cool customizations!') # function to show the plotplt.show()", "e": 2841, "s": 2335, "text": null }, { "code": null, "e": 2851, "s": 2841, "text": "Output: " }, { "code": null, "e": 2909, "s": 2851, "text": "As you can see, we have done several customizations like " }, { "code": null, "e": 2957, "s": 2909, "text": "setting the line-width, line-style, line-color." }, { "code": null, "e": 3013, "s": 2957, "text": "setting the marker, marker’s face color, marker’s size." }, { "code": null, "e": 3150, "s": 3013, "text": "overriding the x and y-axis range. If overriding is not done, pyplot module uses the auto-scale feature to set the axis range and scale." }, { "code": null, "e": 3164, "s": 3154, "text": "Bar Chart" }, { "code": null, "e": 3171, "s": 3164, "text": "Python" }, { "code": "import matplotlib.pyplot as plt # x-coordinates of left sides of bars left = [1, 2, 3, 4, 5] # heights of barsheight = [10, 24, 36, 40, 5] # labels for barstick_label = ['one', 'two', 'three', 'four', 'five'] # plotting a bar chartplt.bar(left, height, tick_label = tick_label, width = 0.8, color = ['red', 'green']) # naming the x-axisplt.xlabel('x - axis')# naming the y-axisplt.ylabel('y - axis')# plot titleplt.title('My bar chart!') # function to show the plotplt.show()", "e": 3660, "s": 3171, "text": null }, { "code": null, "e": 3670, "s": 3660, "text": "Output : " }, { "code": null, "e": 3725, "s": 3672, "text": "Here, we use plt.bar() function to plot a bar chart." }, { "code": null, "e": 3807, "s": 3725, "text": "x-coordinates of the left side of bars are passed along with the heights of bars." }, { "code": null, "e": 3882, "s": 3807, "text": "you can also give some names to x-axis coordinates by defining tick_labels" }, { "code": null, "e": 3894, "s": 3884, "text": "Histogram" }, { "code": null, "e": 3901, "s": 3894, "text": "Python" }, { "code": "import matplotlib.pyplot as plt # frequenciesages = [2,5,70,40,30,45,50,45,43,40,44, 60,7,13,57,18,90,77,32,21,20,40] # setting the ranges and no. of intervalsrange = (0, 100)bins = 10 # plotting a histogramplt.hist(ages, bins, range, color = 'green', histtype = 'bar', rwidth = 0.8) # x-axis labelplt.xlabel('age')# frequency labelplt.ylabel('No. of people')# plot titleplt.title('My histogram') # function to show the plotplt.show()", "e": 4357, "s": 3901, "text": null }, { "code": null, "e": 4366, "s": 4357, "text": "Output: " }, { "code": null, "e": 4422, "s": 4368, "text": "Here, we use plt.hist() function to plot a histogram." }, { "code": null, "e": 4463, "s": 4422, "text": "frequencies are passed as the ages list." }, { "code": null, "e": 4537, "s": 4463, "text": "The range could be set by defining a tuple containing min and max values." }, { "code": null, "e": 4789, "s": 4537, "text": "The next step is to “bin” the range of values—that is, divide the entire range of values into a series of intervals—and then count how many values fall into each interval. Here we have defined bins = 10. So, there are a total of 100/10 = 10 intervals." }, { "code": null, "e": 4804, "s": 4791, "text": "Scatter plot" }, { "code": null, "e": 4813, "s": 4806, "text": "Python" }, { "code": "import matplotlib.pyplot as plt # x-axis valuesx = [1,2,3,4,5,6,7,8,9,10]# y-axis valuesy = [2,4,5,7,6,8,9,11,12,12] # plotting points as a scatter plotplt.scatter(x, y, label= \"stars\", color= \"green\", marker= \"*\", s=30) # x-axis labelplt.xlabel('x - axis')# frequency labelplt.ylabel('y - axis')# plot titleplt.title('My scatter plot!')# showing legendplt.legend() # function to show the plotplt.show()", "e": 5233, "s": 4813, "text": null }, { "code": null, "e": 5242, "s": 5233, "text": "Output: " }, { "code": null, "e": 5304, "s": 5244, "text": "Here, we use plt.scatter() function to plot a scatter plot." }, { "code": null, "e": 5373, "s": 5304, "text": "As a line, we define x and corresponding y-axis values here as well." }, { "code": null, "e": 5485, "s": 5373, "text": "marker argument is used to set the character to use as a marker. Its size can be defined using the s parameter." }, { "code": null, "e": 5497, "s": 5487, "text": "Pie-chart" }, { "code": null, "e": 5506, "s": 5499, "text": "Python" }, { "code": "import matplotlib.pyplot as plt # defining labelsactivities = ['eat', 'sleep', 'work', 'play'] # portion covered by each labelslices = [3, 7, 8, 6] # color for each labelcolors = ['r', 'y', 'g', 'b'] # plotting the pie chartplt.pie(slices, labels = activities, colors=colors, startangle=90, shadow = True, explode = (0, 0, 0.1, 0), radius = 1.2, autopct = '%1.1f%%') # plotting legendplt.legend() # showing the plotplt.show()", "e": 5953, "s": 5506, "text": null }, { "code": null, "e": 5999, "s": 5953, "text": "The output of above program looks like this: " }, { "code": null, "e": 6054, "s": 6001, "text": "Here, we plot a pie chart by using plt.pie() method." }, { "code": null, "e": 6121, "s": 6054, "text": "First of all, we define the labels using a list called activities." }, { "code": null, "e": 6200, "s": 6121, "text": "Then, a portion of each label can be defined using another list called slices." }, { "code": null, "e": 6260, "s": 6200, "text": "Color for each label is defined using a list called colors." }, { "code": null, "e": 6326, "s": 6260, "text": "shadow = True will show a shadow beneath each label in pie chart." }, { "code": null, "e": 6423, "s": 6326, "text": "startangle rotates the start of the pie chart by given degrees counterclockwise from the x-axis." }, { "code": null, "e": 6502, "s": 6423, "text": "explode is used to set the fraction of radius with which we offset each wedge." }, { "code": null, "e": 6630, "s": 6502, "text": "autopct is used to format the value of each label. Here, we have set it to show the percentage value only upto 1 decimal place." }, { "code": null, "e": 6666, "s": 6632, "text": "Plotting curves of given equation" }, { "code": null, "e": 6675, "s": 6668, "text": "Python" }, { "code": "# importing the required modulesimport matplotlib.pyplot as pltimport numpy as np # setting the x - coordinatesx = np.arange(0, 2*(np.pi), 0.1)# setting the corresponding y - coordinatesy = np.sin(x) # plotting the pointsplt.plot(x, y) # function to show the plotplt.show()", "e": 6952, "s": 6675, "text": null }, { "code": null, "e": 6963, "s": 6952, "text": "The output" }, { "code": null, "e": 7000, "s": 6963, "text": " of above program looks like this: " }, { "code": null, "e": 7084, "s": 7000, "text": "Here, we use NumPy which is a general-purpose array-processing package in python. " }, { "code": null, "e": 7259, "s": 7084, "text": "To set the x-axis values, we use the np.arange() method in which the first two arguments are for range and the third one for step-wise increment. The result is a NumPy array." }, { "code": null, "e": 7360, "s": 7259, "text": "To get corresponding y-axis values, we simply use the predefined np.sin() method on the NumPy array." }, { "code": null, "e": 7442, "s": 7360, "text": "Finally, we plot the points by passing x and y arrays to the plt.plot() function." }, { "code": null, "e": 7625, "s": 7442, "text": "So, in this part, we discussed various types of plots we can create in matplotlib. There are more plots that haven’t been covered but the most significant ones are discussed here – " }, { "code": null, "e": 7658, "s": 7625, "text": "Graph Plotting in Python | Set 2" }, { "code": null, "e": 7691, "s": 7658, "text": "Graph Plotting in Python | Set 3" }, { "code": null, "e": 8619, "s": 7693, "text": "Python Programming Tutorial | Graph Plotting in Python | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersPython Programming Tutorial | Graph Plotting in Python | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:35•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=LBR3p0QnrCk\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 9040, "s": 8619, "text": "This article is contributed by Nikhil 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 review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 9050, "s": 9040, "text": "kk9826225" }, { "code": null, "e": 9064, "s": 9050, "text": "sumitgumber28" }, { "code": null, "e": 9076, "s": 9064, "text": "pujasingg43" }, { "code": null, "e": 9083, "s": 9076, "text": "Python" } ]
How to Access Private Field and Method Using Reflection in Java?
05 Feb, 2021 If we want to access Private Field and method using Reflection we just need to call setAccessible(true) on the field or method object which you want to access. Class.getDeclaredField(String fieldName) or Class.getDeclaredFields() can be used to get private fields. Whereas Class.getDeclaredMethod(String methodName, Class<?>... parameterTypes) or Class.getDeclaredMethods() can be used to get private methods. Below program may not work on online IDEs like, compile and run the below program on offline IDEs only. 1. Accessing private Field Java // Access Private Field Using Reflection in Javaimport java.lang.reflect.Field; // Student class declarationclass Student { // private fields private String name; private int age; // Constructor public Student(String name, int age) { this.name = name; this.age = age; } // Getters and setters public String getName() { return name; } public void setName(String name) { this.name = name; } private int getAge() { return age; } public void setAge(int age) { this.age = age; } // Override toString method to get required // output at terminal @Override public String toString() { return "Employee [name=" + name + ", age=" + age + "]"; }} // Program will throw an exception on online IDE// Compile and run the program on offline IDEclass GFG { public static void main(String[] args) { try { // Student object created Student e = new Student("Kapil", 23); // Create Field object Field privateField = Student.class.getDeclaredField("name"); // Set the accessibility as true privateField.setAccessible(true); // Store the value of private field in variable String name = (String)privateField.get(e); // Print the value System.out.println("Name of Student:" + name); } catch (Exception e) { e.printStackTrace(); } }} Output: Name of Student:Kapil 2. Accessing private Method Java // Access Private Method Using Reflection in Javaimport java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method; // Student class declarationclass Student { // Private fields private String name; private int age; // Constructor public Student(String name, int age) { this.name = name; this.age = age; } // Getters and Setters public String getName() { return name; } public void setName(String name) { this.name = name; } private int getAge() { return age; } public void setAge(int age) { this.age = age; } // Override to string method to get // Required output when called @Override public String toString() { return "Employee [name=" + name + ", age=" + age + "]"; }} class GFG { public static void main(String[] args) { try { // Student class object Student e = new Student("Kapil", 23); // Create Method object Method privateMethod = Student.class.getDeclaredMethod("getAge"); // Set the accessibility as true privateMethod.setAccessible(true); // Store the returned value of // private methods in variable int age = (int)privateMethod.invoke(e); System.out.println("Age of Student: " + age); } catch (Exception e) { e.printStackTrace(); } }} Output: Age of Student: 23 Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Feb, 2021" }, { "code": null, "e": 439, "s": 28, "text": "If we want to access Private Field and method using Reflection we just need to call setAccessible(true) on the field or method object which you want to access. Class.getDeclaredField(String fieldName) or Class.getDeclaredFields() can be used to get private fields. Whereas Class.getDeclaredMethod(String methodName, Class<?>... parameterTypes) or Class.getDeclaredMethods() can be used to get private methods. " }, { "code": null, "e": 544, "s": 439, "text": "Below program may not work on online IDEs like, compile and run the below program on offline IDEs only. " }, { "code": null, "e": 571, "s": 544, "text": "1. Accessing private Field" }, { "code": null, "e": 576, "s": 571, "text": "Java" }, { "code": "// Access Private Field Using Reflection in Javaimport java.lang.reflect.Field; // Student class declarationclass Student { // private fields private String name; private int age; // Constructor public Student(String name, int age) { this.name = name; this.age = age; } // Getters and setters public String getName() { return name; } public void setName(String name) { this.name = name; } private int getAge() { return age; } public void setAge(int age) { this.age = age; } // Override toString method to get required // output at terminal @Override public String toString() { return \"Employee [name=\" + name + \", age=\" + age + \"]\"; }} // Program will throw an exception on online IDE// Compile and run the program on offline IDEclass GFG { public static void main(String[] args) { try { // Student object created Student e = new Student(\"Kapil\", 23); // Create Field object Field privateField = Student.class.getDeclaredField(\"name\"); // Set the accessibility as true privateField.setAccessible(true); // Store the value of private field in variable String name = (String)privateField.get(e); // Print the value System.out.println(\"Name of Student:\" + name); } catch (Exception e) { e.printStackTrace(); } }}", "e": 2070, "s": 576, "text": null }, { "code": null, "e": 2078, "s": 2070, "text": "Output:" }, { "code": null, "e": 2100, "s": 2078, "text": "Name of Student:Kapil" }, { "code": null, "e": 2128, "s": 2100, "text": "2. Accessing private Method" }, { "code": null, "e": 2133, "s": 2128, "text": "Java" }, { "code": "// Access Private Method Using Reflection in Javaimport java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method; // Student class declarationclass Student { // Private fields private String name; private int age; // Constructor public Student(String name, int age) { this.name = name; this.age = age; } // Getters and Setters public String getName() { return name; } public void setName(String name) { this.name = name; } private int getAge() { return age; } public void setAge(int age) { this.age = age; } // Override to string method to get // Required output when called @Override public String toString() { return \"Employee [name=\" + name + \", age=\" + age + \"]\"; }} class GFG { public static void main(String[] args) { try { // Student class object Student e = new Student(\"Kapil\", 23); // Create Method object Method privateMethod = Student.class.getDeclaredMethod(\"getAge\"); // Set the accessibility as true privateMethod.setAccessible(true); // Store the returned value of // private methods in variable int age = (int)privateMethod.invoke(e); System.out.println(\"Age of Student: \" + age); } catch (Exception e) { e.printStackTrace(); } }}", "e": 3580, "s": 2133, "text": null }, { "code": null, "e": 3588, "s": 3580, "text": "Output:" }, { "code": null, "e": 3607, "s": 3588, "text": "Age of Student: 23" }, { "code": null, "e": 3614, "s": 3607, "text": "Picked" }, { "code": null, "e": 3619, "s": 3614, "text": "Java" }, { "code": null, "e": 3633, "s": 3619, "text": "Java Programs" }, { "code": null, "e": 3638, "s": 3633, "text": "Java" }, { "code": null, "e": 3736, "s": 3638, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3751, "s": 3736, "text": "Stream In Java" }, { "code": null, "e": 3772, "s": 3751, "text": "Introduction to Java" }, { "code": null, "e": 3793, "s": 3772, "text": "Constructors in Java" }, { "code": null, "e": 3812, "s": 3793, "text": "Exceptions in Java" }, { "code": null, "e": 3829, "s": 3812, "text": "Generics in Java" }, { "code": null, "e": 3855, "s": 3829, "text": "Java Programming Examples" }, { "code": null, "e": 3889, "s": 3855, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 3936, "s": 3889, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 3974, "s": 3936, "text": "Factory method design pattern in Java" } ]
Rearrange a linked list in to alternate first and last element
15 Nov, 2021 Given a linked list. arrange the linked list in manner of alternate first and last element. Examples: Input : 1->2->3->4->5->6->7->8 Output :1->8->2->7->3->6->4->5 Input :10->11->15->13 Output :10->13->11->15 We have discussed three different solution in Rearrange a given linked list in-place.In this post a different Deque based solution is discussed. Method 1) Create an empty deque 2) Insert all element from the linked list to the deque 3) Insert the element back to the linked list from deque in alternate fashion i.e first then last and so on C++ Java Python Javascript // CPP program to rearrange a linked list in given manner#include <bits/stdc++.h>using namespace std; /* Link list node */struct Node { int data; struct Node* next;}; /* Function to reverse the linked list */void arrange(struct Node* head){ struct Node* temp = head; deque<int> d; // defining a deque // push all the elements of linked list in to deque while (temp != NULL) { d.push_back(temp->data); temp = temp->next; } // Alternatively push the first and last elements // from deque to back to the linked list and pop int i = 0; temp = head; while (!d.empty()) { if (i % 2 == 0) { temp->data = d.front(); d.pop_front(); } else { temp->data = d.back(); d.pop_back(); } i++; temp = temp->next; // increase temp }} /*UTILITY FUNCTIONS*//* Push a node to linked list. Note that this functionchanges the head */void push(struct Node** head_ref, char new_data){ /* allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} // printing the linked listvoid printList(struct Node* head){ struct Node* temp = head; while (temp != NULL) { printf("%d ", temp->data); temp = temp->next; }} /* Driver program to test above function*/int main(){ // Let us create linked list 1->2->3->4 struct Node* head = NULL; push(&head, 5); push(&head, 4); push(&head, 3); push(&head, 2); push(&head, 1); cout << "Given linked list\t"; printList(head); arrange(head); cout << "\nAfter rearrangement\t"; printList(head); return 0;} // Java program to rearrange a linked list in given mannerimport java.util.*;import java.lang.*;import java.io.*; class GFG{ /* Link list node */ static class Node { int data; Node next; Node(int data) { this.data = data; next = null; } } // printing the linked list static void printList(Node head) { Node temp = head; while (temp != null) { System.out.print(temp.data + " "); temp = temp.next; } } /* Function to reverse the linked list */ static void arrange(Node head) { // defining a deque Deque<Integer> deque = new ArrayDeque<>(); Node temp = head; // push all the elements of linked list in to deque while(temp != null) { deque.addLast(temp.data); temp = temp.next; } temp = head; int i = 0; // Alternatively push the first and last elements // from deque to back to the linked list and pop while(!deque.isEmpty()) { if(i % 2 == 0) { temp.data = deque.removeFirst(); } else { temp.data = deque.removeLast(); } i++; temp = temp.next; } } // Driver code public static void main (String[] args) { // Let us create linked list 1->2->3->4->5 Node head = null; head = new Node(1); head.next = new Node(2); head.next.next = new Node(3); head.next.next.next = new Node(4); head.next.next.next.next = new Node(5); System.out.println("Given linked list"); printList(head); arrange(head); System.out.println("\nAfter rearrangement"); printList(head); }} // This code is contributed by nobody_cares. # Python program to rearrange# a linked list in given manner # Link list nodeclass Node: def __init__(self, data): self.data = data self.next = None # Function to reverse the linked listdef arrange( head): temp = head # defining a deque d = [] # push all the elements of linked list in to deque while (temp != None) : d.append(temp.data) temp = temp.next # Alternatively push the first and last elements # from deque to back to the linked list and pop i = 0 temp = head while (len(d) > 0) : if (i % 2 == 0) : temp.data = d[0] d.pop(0) else : temp.data = d[-1] d.pop() i = i + 1 # increase temp temp = temp.next return head # UTILITY FUNCTIONS# Push a node to linked list. Note that this function# changes the headdef push( head_ref, new_data): # allocate node new_node = Node(0) # put in the data new_node.data = new_data # link the old list off the new node new_node.next = (head_ref) # move the head to point to the new node (head_ref) = new_node return head_ref # printing the linked listdef printList( head): temp = head while (temp != None) : print( temp.data,end=" ") temp = temp.next # Driver program to test above function # Let us create linked list 1.2.3.4head = None head = push(head, 5)head = push(head, 4)head = push(head, 3)head = push(head, 2)head = push(head, 1)print("Given linked list\t")printList(head)head = arrange(head)print( "\nAfter rearrangement\t")printList(head) # This code is contributed by Arnab Kundu <script> // Javascript program to rearrange a linked list in given manner /* Link list node */class Node { constructor() { this.data = 0; this.next = null; }}; /* Function to reverse the linked list */function arrange( head){ var temp = head; var d = []; // defining a deque // push all the elements of linked list in to deque while (temp != null) { d.push(temp.data); temp = temp.next; } // Alternatively push the first and last elements // from deque to back to the linked list and pop var i = 0; temp = head; while (d.length!=0) { if (i % 2 == 0) { temp.data = d[0]; d.shift(); } else { temp.data = d[d.length-1]; d.pop(); } i++; temp = temp.next; // increase temp }} /*UTILITY FUNCTIONS*//* Push a node to linked list. Note that this functionchanges the head */function push(head_ref, new_data){ /* allocate node */ var new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list off the new node */ new_node.next = (head_ref); /* move the head to point to the new node */ (head_ref) = new_node; return head_ref;} // printing the linked listfunction printList(head){ var temp = head; while (temp != null) { document.write(temp.data+ " "); temp = temp.next; }} /* Driver program to test above function*/// Let us create linked list 1.2.3.4var head = null;head = push(head, 5);head = push(head, 4);head = push(head, 3);head = push(head, 2);head = push(head, 1);document.write( "Given linked list ");printList(head);arrange(head);document.write( "<br>After rearrangement ");printList(head); </script> Output: Given linked list 1 2 3 4 5 After rearrangement 1 5 2 4 3 Time Complexity : O(n) VishalBachchas Akanksha_Rai shubham_singh nobody_cares andrew1234 rutvik_56 saurabh1990aror simranarora5sos arorakashish0911 cpp-deque deque Linked List Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures What is Data Structure: Types, Classifications and Applications Types of Linked List Circular Singly Linked List | Insertion Find first node of loop in a linked list Add two numbers represented by linked lists | Set 2 Flattening a Linked List Real-time application of Data Structures Insert a node at a specific position in a linked list Clone a linked list with next and random pointer | Set 1
[ { "code": null, "e": 52, "s": 24, "text": "\n15 Nov, 2021" }, { "code": null, "e": 144, "s": 52, "text": "Given a linked list. arrange the linked list in manner of alternate first and last element." }, { "code": null, "e": 155, "s": 144, "text": "Examples: " }, { "code": null, "e": 263, "s": 155, "text": "Input : 1->2->3->4->5->6->7->8\nOutput :1->8->2->7->3->6->4->5\n\nInput :10->11->15->13\nOutput :10->13->11->15" }, { "code": null, "e": 408, "s": 263, "text": "We have discussed three different solution in Rearrange a given linked list in-place.In this post a different Deque based solution is discussed." }, { "code": null, "e": 605, "s": 408, "text": "Method 1) Create an empty deque 2) Insert all element from the linked list to the deque 3) Insert the element back to the linked list from deque in alternate fashion i.e first then last and so on " }, { "code": null, "e": 609, "s": 605, "text": "C++" }, { "code": null, "e": 614, "s": 609, "text": "Java" }, { "code": null, "e": 621, "s": 614, "text": "Python" }, { "code": null, "e": 632, "s": 621, "text": "Javascript" }, { "code": "// CPP program to rearrange a linked list in given manner#include <bits/stdc++.h>using namespace std; /* Link list node */struct Node { int data; struct Node* next;}; /* Function to reverse the linked list */void arrange(struct Node* head){ struct Node* temp = head; deque<int> d; // defining a deque // push all the elements of linked list in to deque while (temp != NULL) { d.push_back(temp->data); temp = temp->next; } // Alternatively push the first and last elements // from deque to back to the linked list and pop int i = 0; temp = head; while (!d.empty()) { if (i % 2 == 0) { temp->data = d.front(); d.pop_front(); } else { temp->data = d.back(); d.pop_back(); } i++; temp = temp->next; // increase temp }} /*UTILITY FUNCTIONS*//* Push a node to linked list. Note that this functionchanges the head */void push(struct Node** head_ref, char new_data){ /* allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} // printing the linked listvoid printList(struct Node* head){ struct Node* temp = head; while (temp != NULL) { printf(\"%d \", temp->data); temp = temp->next; }} /* Driver program to test above function*/int main(){ // Let us create linked list 1->2->3->4 struct Node* head = NULL; push(&head, 5); push(&head, 4); push(&head, 3); push(&head, 2); push(&head, 1); cout << \"Given linked list\\t\"; printList(head); arrange(head); cout << \"\\nAfter rearrangement\\t\"; printList(head); return 0;}", "e": 2486, "s": 632, "text": null }, { "code": "// Java program to rearrange a linked list in given mannerimport java.util.*;import java.lang.*;import java.io.*; class GFG{ /* Link list node */ static class Node { int data; Node next; Node(int data) { this.data = data; next = null; } } // printing the linked list static void printList(Node head) { Node temp = head; while (temp != null) { System.out.print(temp.data + \" \"); temp = temp.next; } } /* Function to reverse the linked list */ static void arrange(Node head) { // defining a deque Deque<Integer> deque = new ArrayDeque<>(); Node temp = head; // push all the elements of linked list in to deque while(temp != null) { deque.addLast(temp.data); temp = temp.next; } temp = head; int i = 0; // Alternatively push the first and last elements // from deque to back to the linked list and pop while(!deque.isEmpty()) { if(i % 2 == 0) { temp.data = deque.removeFirst(); } else { temp.data = deque.removeLast(); } i++; temp = temp.next; } } // Driver code public static void main (String[] args) { // Let us create linked list 1->2->3->4->5 Node head = null; head = new Node(1); head.next = new Node(2); head.next.next = new Node(3); head.next.next.next = new Node(4); head.next.next.next.next = new Node(5); System.out.println(\"Given linked list\"); printList(head); arrange(head); System.out.println(\"\\nAfter rearrangement\"); printList(head); }} // This code is contributed by nobody_cares.", "e": 4394, "s": 2486, "text": null }, { "code": "# Python program to rearrange# a linked list in given manner # Link list nodeclass Node: def __init__(self, data): self.data = data self.next = None # Function to reverse the linked listdef arrange( head): temp = head # defining a deque d = [] # push all the elements of linked list in to deque while (temp != None) : d.append(temp.data) temp = temp.next # Alternatively push the first and last elements # from deque to back to the linked list and pop i = 0 temp = head while (len(d) > 0) : if (i % 2 == 0) : temp.data = d[0] d.pop(0) else : temp.data = d[-1] d.pop() i = i + 1 # increase temp temp = temp.next return head # UTILITY FUNCTIONS# Push a node to linked list. Note that this function# changes the headdef push( head_ref, new_data): # allocate node new_node = Node(0) # put in the data new_node.data = new_data # link the old list off the new node new_node.next = (head_ref) # move the head to point to the new node (head_ref) = new_node return head_ref # printing the linked listdef printList( head): temp = head while (temp != None) : print( temp.data,end=\" \") temp = temp.next # Driver program to test above function # Let us create linked list 1.2.3.4head = None head = push(head, 5)head = push(head, 4)head = push(head, 3)head = push(head, 2)head = push(head, 1)print(\"Given linked list\\t\")printList(head)head = arrange(head)print( \"\\nAfter rearrangement\\t\")printList(head) # This code is contributed by Arnab Kundu", "e": 6074, "s": 4394, "text": null }, { "code": "<script> // Javascript program to rearrange a linked list in given manner /* Link list node */class Node { constructor() { this.data = 0; this.next = null; }}; /* Function to reverse the linked list */function arrange( head){ var temp = head; var d = []; // defining a deque // push all the elements of linked list in to deque while (temp != null) { d.push(temp.data); temp = temp.next; } // Alternatively push the first and last elements // from deque to back to the linked list and pop var i = 0; temp = head; while (d.length!=0) { if (i % 2 == 0) { temp.data = d[0]; d.shift(); } else { temp.data = d[d.length-1]; d.pop(); } i++; temp = temp.next; // increase temp }} /*UTILITY FUNCTIONS*//* Push a node to linked list. Note that this functionchanges the head */function push(head_ref, new_data){ /* allocate node */ var new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list off the new node */ new_node.next = (head_ref); /* move the head to point to the new node */ (head_ref) = new_node; return head_ref;} // printing the linked listfunction printList(head){ var temp = head; while (temp != null) { document.write(temp.data+ \" \"); temp = temp.next; }} /* Driver program to test above function*/// Let us create linked list 1.2.3.4var head = null;head = push(head, 5);head = push(head, 4);head = push(head, 3);head = push(head, 2);head = push(head, 1);document.write( \"Given linked list \");printList(head);arrange(head);document.write( \"<br>After rearrangement \");printList(head); </script>", "e": 7824, "s": 6074, "text": null }, { "code": null, "e": 7834, "s": 7824, "text": "Output: " }, { "code": null, "e": 7899, "s": 7834, "text": "Given linked list 1 2 3 4 5 \nAfter rearrangement 1 5 2 4 3" }, { "code": null, "e": 7923, "s": 7899, "text": "Time Complexity : O(n) " }, { "code": null, "e": 7938, "s": 7923, "text": "VishalBachchas" }, { "code": null, "e": 7951, "s": 7938, "text": "Akanksha_Rai" }, { "code": null, "e": 7965, "s": 7951, "text": "shubham_singh" }, { "code": null, "e": 7978, "s": 7965, "text": "nobody_cares" }, { "code": null, "e": 7989, "s": 7978, "text": "andrew1234" }, { "code": null, "e": 7999, "s": 7989, "text": "rutvik_56" }, { "code": null, "e": 8015, "s": 7999, "text": "saurabh1990aror" }, { "code": null, "e": 8031, "s": 8015, "text": "simranarora5sos" }, { "code": null, "e": 8048, "s": 8031, "text": "arorakashish0911" }, { "code": null, "e": 8058, "s": 8048, "text": "cpp-deque" }, { "code": null, "e": 8064, "s": 8058, "text": "deque" }, { "code": null, "e": 8076, "s": 8064, "text": "Linked List" }, { "code": null, "e": 8088, "s": 8076, "text": "Linked List" }, { "code": null, "e": 8186, "s": 8088, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8218, "s": 8186, "text": "Introduction to Data Structures" }, { "code": null, "e": 8282, "s": 8218, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 8303, "s": 8282, "text": "Types of Linked List" }, { "code": null, "e": 8343, "s": 8303, "text": "Circular Singly Linked List | Insertion" }, { "code": null, "e": 8384, "s": 8343, "text": "Find first node of loop in a linked list" }, { "code": null, "e": 8436, "s": 8384, "text": "Add two numbers represented by linked lists | Set 2" }, { "code": null, "e": 8461, "s": 8436, "text": "Flattening a Linked List" }, { "code": null, "e": 8502, "s": 8461, "text": "Real-time application of Data Structures" }, { "code": null, "e": 8556, "s": 8502, "text": "Insert a node at a specific position in a linked list" } ]
How to do Templating using ExpressJS in Node.js ?
08 Apr, 2021 Template Engine : A template engine basically helps us to use the static template files with minimal code. At runtime, the template engine replaces all the variables with actual values at the client-side. Templating Engine Examples: EJS (Embedded JavaScript Templating) Pug Mustache In this article we are going to use EJS engine. Setting up NPM packages:npm init -y Setting up NPM packages: npm init -y Installing Dependencies npm install ejs express --save npm install ejs express --save Basic ExpressJS Server: Javascript const express = require('express');const app = express(); app.get('/' , (req , res)=>{ res.send("GeeksforGeeks");}) app.listen(4000 , ()=>{ console.log("server is running on port 4000");}) Output: Adding of EJS Engine: Here we need to set ejs as our view engine. Javascript const express = require('express');const app = express(); app.set('view engine', 'ejs'); app.get('/' , (req , res)=>{ res.send("GeeksforGeeks");}) app.listen(4000 , ()=>{ console.log("server is running on port 4000");}) index.ejs <!--Ejs File--><!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"></head><body> <h1>GeeksforGeeks</h1></body></html> Output: output Rendering of EJS file: Javascript const express = require('express');const app = express(); app.set('view engine', 'ejs'); app.get('/:name' , (req , res)=>{ res.render("index" , { data : req.params.name });}) app.listen(4000 , ()=>{ console.log("server is running on port 4000");}) Storing of data : Here we have to store the data var name = "<%= data %>". Javascript <!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"> <script type="text/javascript"> var name = "<%= data %>" setTimeout(()=>{ document.getElementById('hello').innerHTML = name; },1000); </script></head><body> <h1 id="hello"></h1></body></html> Output: EJS-Templating Language Express.js Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. JWT Authentication with Node.js Installation of Node.js on Windows Difference between dependencies, devDependencies and peerDependencies Mongoose Populate() Method Mongoose find() Function Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Apr, 2021" }, { "code": null, "e": 233, "s": 28, "text": "Template Engine : A template engine basically helps us to use the static template files with minimal code. At runtime, the template engine replaces all the variables with actual values at the client-side." }, { "code": null, "e": 261, "s": 233, "text": "Templating Engine Examples:" }, { "code": null, "e": 298, "s": 261, "text": "EJS (Embedded JavaScript Templating)" }, { "code": null, "e": 302, "s": 298, "text": "Pug" }, { "code": null, "e": 311, "s": 302, "text": "Mustache" }, { "code": null, "e": 359, "s": 311, "text": "In this article we are going to use EJS engine." }, { "code": null, "e": 395, "s": 359, "text": "Setting up NPM packages:npm init -y" }, { "code": null, "e": 420, "s": 395, "text": "Setting up NPM packages:" }, { "code": null, "e": 432, "s": 420, "text": "npm init -y" }, { "code": null, "e": 487, "s": 432, "text": "Installing Dependencies npm install ejs express --save" }, { "code": null, "e": 518, "s": 487, "text": "npm install ejs express --save" }, { "code": null, "e": 542, "s": 518, "text": "Basic ExpressJS Server:" }, { "code": null, "e": 553, "s": 542, "text": "Javascript" }, { "code": "const express = require('express');const app = express(); app.get('/' , (req , res)=>{ res.send(\"GeeksforGeeks\");}) app.listen(4000 , ()=>{ console.log(\"server is running on port 4000\");})", "e": 752, "s": 553, "text": null }, { "code": null, "e": 760, "s": 752, "text": "Output:" }, { "code": null, "e": 826, "s": 760, "text": "Adding of EJS Engine: Here we need to set ejs as our view engine." }, { "code": null, "e": 837, "s": 826, "text": "Javascript" }, { "code": "const express = require('express');const app = express(); app.set('view engine', 'ejs'); app.get('/' , (req , res)=>{ res.send(\"GeeksforGeeks\");}) app.listen(4000 , ()=>{ console.log(\"server is running on port 4000\");})", "e": 1066, "s": 837, "text": null }, { "code": null, "e": 1076, "s": 1066, "text": "index.ejs" }, { "code": "<!--Ejs File--><!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"></head><body> <h1>GeeksforGeeks</h1></body></html>", "e": 1349, "s": 1076, "text": null }, { "code": null, "e": 1357, "s": 1349, "text": "Output:" }, { "code": null, "e": 1364, "s": 1357, "text": "output" }, { "code": null, "e": 1387, "s": 1364, "text": "Rendering of EJS file:" }, { "code": null, "e": 1398, "s": 1387, "text": "Javascript" }, { "code": "const express = require('express');const app = express(); app.set('view engine', 'ejs'); app.get('/:name' , (req , res)=>{ res.render(\"index\" , { data : req.params.name });}) app.listen(4000 , ()=>{ console.log(\"server is running on port 4000\");})", "e": 1665, "s": 1398, "text": null }, { "code": null, "e": 1741, "s": 1665, "text": "Storing of data : Here we have to store the data var name = \"<%= data %>\"." }, { "code": null, "e": 1752, "s": 1741, "text": "Javascript" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <script type=\"text/javascript\"> var name = \"<%= data %>\" setTimeout(()=>{ document.getElementById('hello').innerHTML = name; },1000); </script></head><body> <h1 id=\"hello\"></h1></body></html>", "e": 2186, "s": 1752, "text": null }, { "code": null, "e": 2194, "s": 2186, "text": "Output:" }, { "code": null, "e": 2218, "s": 2194, "text": "EJS-Templating Language" }, { "code": null, "e": 2229, "s": 2218, "text": "Express.js" }, { "code": null, "e": 2236, "s": 2229, "text": "Picked" }, { "code": null, "e": 2244, "s": 2236, "text": "Node.js" }, { "code": null, "e": 2261, "s": 2244, "text": "Web Technologies" }, { "code": null, "e": 2359, "s": 2261, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2391, "s": 2359, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 2426, "s": 2391, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 2496, "s": 2426, "text": "Difference between dependencies, devDependencies and peerDependencies" }, { "code": null, "e": 2523, "s": 2496, "text": "Mongoose Populate() Method" }, { "code": null, "e": 2548, "s": 2523, "text": "Mongoose find() Function" }, { "code": null, "e": 2610, "s": 2548, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2671, "s": 2610, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2721, "s": 2671, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 2764, "s": 2721, "text": "How to fetch data from an API in ReactJS ?" } ]
How does jQuery Datepicker onchange event work?
To work with jQuery Datepicker onchange(), use the datepicker onSelect event. This will show which date we added currently and changed to. You can try to run the following code to learn how to work jQuery Datepicker onchange: Live Demo <!Doctype html> <html> <head> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> $( function() { $(".date").datepicker({ onSelect: function(dateText) { display("Selected date: " + dateText + ", Current Selected Value= " + this.value); $(this).change(); } }).on("change", function() { display("Change event"); }); function display(msg) { $("<p>").html(msg).appendTo(document.body); } }); </script> </head> <body> Date: <input type='text' class='date' id="datepicker"> </body> </html>
[ { "code": null, "e": 1326, "s": 1187, "text": "To work with jQuery Datepicker onchange(), use the datepicker onSelect event. This will show which date we added currently and changed to." }, { "code": null, "e": 1413, "s": 1326, "text": "You can try to run the following code to learn how to work jQuery Datepicker onchange:" }, { "code": null, "e": 1423, "s": 1413, "text": "Live Demo" }, { "code": null, "e": 2147, "s": 1423, "text": "<!Doctype html>\n<html>\n<head>\n <link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\">\n <script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script>\n <script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script>\n <script>\n $( function() {\n \n $(\".date\").datepicker({\n onSelect: function(dateText) {\n display(\"Selected date: \" + dateText + \", Current Selected Value= \" + this.value);\n $(this).change();\n }\n }).on(\"change\", function() {\n display(\"Change event\");\n });\n\n function display(msg) {\n $(\"<p>\").html(msg).appendTo(document.body);\n }\n });\n \n </script>\n</head>\n<body>\n \nDate: <input type='text' class='date' id=\"datepicker\">\n\n</body>\n</html>" } ]
turtle.down() method in Python
16 Jul, 2020 The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support. The turtle.down() method is used to pull back the pen down on the screen. It gives drawing on moving to another position or direction. turtle.down() or turtle.pd() or turtle.pendown() Here, this method can be called with three names as written above i.e; it has Aliases: pendown | pd | down. There is no argument required for this method. Below is the implementation of the above method with some examples : Example 1: Python3 # import packageimport turtle # forward the turtle (drawing)turtle.forward(50) # up the turtleturtle.up() # forward the turtle (no drawing)turtle.forward(50) # down the turtleturtle.down() # forward the turtle (drawing)turtle.forward(50) Output : Example 2: Python3 # import packageimport turtle # forward the turtle (drawing)turtle.forward(50) # turn right 90 degreesturtle.right(90) # up the turtleturtle.up() # forward the turtle (no drawing)turtle.forward(50) # down the turtleturtle.down() # turn right 90 degreesturtle.right(90) # forward the turtle (drawing)turtle.forward(50) Output : Python-turtle Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Jul, 2020" }, { "code": null, "e": 245, "s": 28, "text": "The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support." }, { "code": null, "e": 381, "s": 245, "text": "The turtle.down() method is used to pull back the pen down on the screen. It gives drawing on moving to another position or direction. " }, { "code": null, "e": 431, "s": 381, "text": "turtle.down() or turtle.pd() or turtle.pendown()\n" }, { "code": null, "e": 586, "s": 431, "text": "Here, this method can be called with three names as written above i.e; it has Aliases: pendown | pd | down. There is no argument required for this method." }, { "code": null, "e": 655, "s": 586, "text": "Below is the implementation of the above method with some examples :" }, { "code": null, "e": 666, "s": 655, "text": "Example 1:" }, { "code": null, "e": 674, "s": 666, "text": "Python3" }, { "code": "# import packageimport turtle # forward the turtle (drawing)turtle.forward(50) # up the turtleturtle.up() # forward the turtle (no drawing)turtle.forward(50) # down the turtleturtle.down() # forward the turtle (drawing)turtle.forward(50)", "e": 919, "s": 674, "text": null }, { "code": null, "e": 928, "s": 919, "text": "Output :" }, { "code": null, "e": 939, "s": 928, "text": "Example 2:" }, { "code": null, "e": 947, "s": 939, "text": "Python3" }, { "code": "# import packageimport turtle # forward the turtle (drawing)turtle.forward(50) # turn right 90 degreesturtle.right(90) # up the turtleturtle.up() # forward the turtle (no drawing)turtle.forward(50) # down the turtleturtle.down() # turn right 90 degreesturtle.right(90) # forward the turtle (drawing)turtle.forward(50)", "e": 1274, "s": 947, "text": null }, { "code": null, "e": 1283, "s": 1274, "text": "Output :" }, { "code": null, "e": 1297, "s": 1283, "text": "Python-turtle" }, { "code": null, "e": 1304, "s": 1297, "text": "Python" } ]
Static vs. Non-Static method in C#
Declare a member function as static. Such functions can access only static variables. The static functions exist even before the object is created. A static class cannot be instantiated and can only contain static members. Static methods is set using static keyword − public static int getNum() { return num; } The following example demonstrates the use of static and non-static methods − using System; namespace StaticVarApplication { class StaticVar { public static int num; public void count() { num++; } public static int getNum() { return num; } } class StaticTester { static void Main(string[] args) { StaticVar s = new StaticVar(); s.count(); s.count(); s.count(); s.count(); s.count(); s.count(); Console.WriteLine("Variable num: {0}", StaticVar.getNum()); Console.ReadKey(); } } }
[ { "code": null, "e": 1335, "s": 1187, "text": "Declare a member function as static. Such functions can access only static variables. The static functions exist even before the object is created." }, { "code": null, "e": 1410, "s": 1335, "text": "A static class cannot be instantiated and can only contain static members." }, { "code": null, "e": 1455, "s": 1410, "text": "Static methods is set using static keyword −" }, { "code": null, "e": 1501, "s": 1455, "text": "public static int getNum() {\n return num;\n}" }, { "code": null, "e": 1579, "s": 1501, "text": "The following example demonstrates the use of static and non-static methods −" }, { "code": null, "e": 2139, "s": 1579, "text": "using System;\n\nnamespace StaticVarApplication {\n class StaticVar {\n public static int num;\n\n public void count() {\n num++;\n }\n\n public static int getNum() {\n return num;\n }\n }\n\n class StaticTester {\n static void Main(string[] args) {\n StaticVar s = new StaticVar();\n\n s.count();\n s.count();\n s.count();\n s.count();\n s.count();\n s.count();\n\n Console.WriteLine(\"Variable num: {0}\", StaticVar.getNum());\n Console.ReadKey();\n }\n }\n}" } ]
Tryit Editor v3.7
Tryit: The outline property
[]
Character class \p{javaWhitespace} Java regex in java.
This character class \p{javaWhitespace} matches spaces. This class matches the characters which returns true when passed as a parameter to the isWhitespace() method of the java.lang.Character class. Live Demo import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExample { public static void main(String args[]) { //Reading String from user System.out.println("Enter a string"); Scanner sc = new Scanner(System.in); String input = sc.nextLine(); //Regular expression String regex = "[\\p{javaWhitespace}]"; //Compiling the regular expression Pattern pattern = Pattern.compile(regex); //Retrieving the matcher object Matcher matcher = pattern.matcher(input); int count = 0; while(matcher.find()) { count++; } System.out.println("Number of upper case characters: "+count); } } Enter a string hello welcome to tutorialspoint Number of upper case characters: 3 Live Demo import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Example { public static void main( String args[] ) { //Regular expression to match lower case letters String regex = "^\\p{javaWhitespace}+$"; //Getting the input data Scanner sc = new Scanner(System.in); System.out.println("Enter 5 input strings: "); String input[] = new String[5]; for (int i=0; i<5; i++) { input[i] = sc.nextLine(); } //Creating a Pattern object Pattern p = Pattern.compile(regex); System.out.println("Strings with only upper case characters: "); for(int i=0; i<5;i++) { //Creating a Matcher object Matcher m = p.matcher(input[i]); if(m.matches()) { System.out.println(m.group()); } } } } Enter 5 input strings: Raju RAMU rahman radha SUnDar* Strings with only upper case characters: RAMU
[ { "code": null, "e": 1261, "s": 1062, "text": "This character class \\p{javaWhitespace} matches spaces. This class matches the characters which returns true when passed as a parameter to the isWhitespace() method of the java.lang.Character class." }, { "code": null, "e": 1272, "s": 1261, "text": " Live Demo" }, { "code": null, "e": 1991, "s": 1272, "text": "import java.util.Scanner;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class RegexExample {\n public static void main(String args[]) {\n //Reading String from user\n System.out.println(\"Enter a string\");\n Scanner sc = new Scanner(System.in);\n String input = sc.nextLine();\n //Regular expression\n String regex = \"[\\\\p{javaWhitespace}]\";\n //Compiling the regular expression\n Pattern pattern = Pattern.compile(regex);\n //Retrieving the matcher object\n Matcher matcher = pattern.matcher(input);\n int count = 0;\n while(matcher.find()) {\n count++;\n }\n System.out.println(\"Number of upper case characters: \"+count);\n }\n}" }, { "code": null, "e": 2073, "s": 1991, "text": "Enter a string\nhello welcome to tutorialspoint\nNumber of upper case characters: 3" }, { "code": null, "e": 2084, "s": 2073, "text": " Live Demo" }, { "code": null, "e": 2937, "s": 2084, "text": "import java.util.Scanner;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class Example {\n public static void main( String args[] ) {\n //Regular expression to match lower case letters\n String regex = \"^\\\\p{javaWhitespace}+$\";\n //Getting the input data\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter 5 input strings: \");\n String input[] = new String[5];\n for (int i=0; i<5; i++) {\n input[i] = sc.nextLine();\n }\n //Creating a Pattern object\n Pattern p = Pattern.compile(regex);\n System.out.println(\"Strings with only upper case characters: \");\n for(int i=0; i<5;i++) {\n //Creating a Matcher object\n Matcher m = p.matcher(input[i]);\n if(m.matches()) {\n System.out.println(m.group());\n }\n }\n }\n}" }, { "code": null, "e": 3037, "s": 2937, "text": "Enter 5 input strings:\nRaju\nRAMU\nrahman\nradha\nSUnDar*\nStrings with only upper case characters:\nRAMU" } ]
Spring Boot Multiple Data Sources 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 Here I am going to show how to configure multiple data sources in spring boot. Spring Boot multiple data sources configuration are advantageous to connect with different databases in a single spring boot application. Technologies. Spring Boot 1.5.1.RELEASE Java 1.8 Hibernate 5.0.1 Maven MySql Since we are going to work with multiple data sources, we need to have multiple databases in our local machine to access them. Step 1: Open MySql command prompt and log in with your credentials. Step 2: Create two different databases by passing the below command : mysql>create database db1; Query OK, 1 row affected (0.10 sec) mysql>use db1; // Create person table under db1 CREATE TABLE person ( id int(11) NOT NULL AUTO_INCREMENT, name varchar(50) DEFAULT NULL, city varchar(50) DEFAULT NULL, PRIMARY KEY (`id`) ) mysql> create database db2; Query OK, 1 row affected (0.9 sec) mysql>use db2; // Create department table under db2 CREATE TABLE department ( id int(11) NOT NULL AUTO_INCREMENT, name varchar(50) DEFAULT NULL, PRIMARY KEY (`id`) ) Now two databases are ready to use. We are going to get access these two from our Spring Boot Multiple Data Sources example. Recommended: Spring Boot JPA Integration A typical Maven project structure. <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>org.springframework.samples.service.service</groupId> <artifactId>SpringBoot_JPA_Multiple_DataSource</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <properties> <java.version>1.8</java.version> </properties> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.1.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> <repositories> <repository> <id>spring-releases</id> <name>Spring Releases</name> <url>https://repo.spring.io/libs-release</url> </repository> <repository> <id>org.jboss.repository.releases</id> <name>JBoss Maven Release Repository</name> <url>https://repository.jboss.org/nexus/content/repositories/releases</url> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>spring-releases</id> <name>Spring Releases</name> <url>https://repo.spring.io/libs-release</url> </pluginRepository> </pluginRepositories> </project> Define two database configurations in a single application.properties file like below. jdbc.driver-class-name:com.mysql.jdbc.Driver jdbc.show-sql:true #First Datasource (DB1) db1.datasource.url:jdbc:mysql://localhost:3306/db1?useSSL=false db1.datasource.username:root db1.datasource.password:12345 #Second Datasource (DB2) db2.datasource.url:jdbc:mysql://localhost:3306/db2?useSSL=false db2.datasource.username:root db2.datasource.password:54321 spring.jooq.sql-dialect=org.hibernate.dialect.MySQL5Dialect Since we are going to get access to two different databases (db1, db2), we need to configure each data source configuration separately like: package com.onlinetutorialspoint.config; import java.util.HashMap; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.core.env.Environment; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; @Configuration @EnableJpaRepositories(basePackages = {"com.onlinetutorialspoint.repository.db1"}, entityManagerFactoryRef = "db1EntityManager", transactionManagerRef = "db1TransactionManager") public class DB1_DataSource { @Autowired private Environment env; @Bean @Primary public LocalContainerEntityManagerFactoryBean db1EntityManager() { LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(db1Datasource()); em.setPackagesToScan(new String[]{"com.onlinetutorialspoint.model.db1"}); em.setPersistenceUnitName("db1EntityManager"); HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); em.setJpaVendorAdapter(vendorAdapter); HashMap<string, object=""> properties = new HashMap<>(); properties.put("hibernate.dialect", env.getProperty("hibernate.dialect")); properties.put("hibernate.show-sql", env.getProperty("jdbc.show-sql")); em.setJpaPropertyMap(properties); return em; } @Primary @Bean public DataSource db1Datasource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName( env.getProperty("jdbc.driver-class-name")); dataSource.setUrl(env.getProperty("db1.datasource.url")); dataSource.setUsername(env.getProperty("db1.datasource.username")); dataSource.setPassword(env.getProperty("db1.datasource.password")); return dataSource; } @Primary @Bean public PlatformTransactionManager db1TransactionManager() { JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory( db1EntityManager().getObject()); return transactionManager; } } @Primary: This annotation indicates that a bean should be given as primary preference when multiple qualified beans were autowired on a single-valued dependency. In our case, we have two different data sources, so that we should have to declare anyone as a primary data source between two (or among all of them). Recommended: Spring Boot Hibernate Integration. package com.onlinetutorialspoint.config; import java.util.HashMap; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; @Configuration @EnableJpaRepositories(basePackages = {"com.onlinetutorialspoint.repository.db2"}, entityManagerFactoryRef = "db2EntityManager", transactionManagerRef = "db2TransactionManager") public class DB2_DataSource { @Autowired private Environment env; @Bean public LocalContainerEntityManagerFactoryBean db2EntityManager() { LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(db2Datasource()); em.setPackagesToScan( new String[]{"com.onlinetutorialspoint.model.db2"}); em.setPersistenceUnitName("db2EntityManager"); HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); em.setJpaVendorAdapter(vendorAdapter); HashMap<string, object=""> properties = new HashMap<>(); properties.put("hibernate.dialect", env.getProperty("hibernate.dialect")); properties.put("hibernate.show-sql", env.getProperty("jdbc.show-sql")); em.setJpaPropertyMap(properties); return em; } @Bean public DataSource db2Datasource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName( env.getProperty("jdbc.driver-class-name")); dataSource.setUrl(env.getProperty("db2.datasource.url")); dataSource.setUsername(env.getProperty("db2.datasource.username")); dataSource.setPassword(env.getProperty("db2.datasource.password")); return dataSource; } @Bean public PlatformTransactionManager db2TransactionManager() { JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory( db2EntityManager().getObject()); return transactionManager; } } package com.onlinetutorialspoint.repository.db1; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import com.onlinetutorialspoint.model.db1.Person; @Repository public interface PersonRepository extends CrudRepository<person, long="">{ } package com.onlinetutorialspoint.repository.db2; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import com.onlinetutorialspoint.model.db1.Person; import com.onlinetutorialspoint.model.db2.Department; @Repository public interface DepartmentRepository extends CrudRepository<department, long="">{ } package com.onlinetutorialspoint.model.db1; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "person") public class Person { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; @Column(name="city") private String city; public Person() { super(); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } @Override public String toString() { return "Person [pid=" + id + ", pName=" + name + ", pCity=" + city + "]"; } } package com.onlinetutorialspoint.model.db2; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "department") public class Department { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; public Department() { super(); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Department [id=" + id + ", Name=" + name +"]"; } } package com.onlinetutorialspoint.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.onlinetutorialspoint.model.db1.Person; import com.onlinetutorialspoint.repository.db1.PersonRepository; @Service public class PersonService { @Autowired PersonRepository personRepo; public List getAllPersons() { return (List) personRepo.findAll(); } public Person savePerson(Person person) { return personRepo.save(person); } } package com.onlinetutorialspoint.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.onlinetutorialspoint.model.db2.Department; import com.onlinetutorialspoint.repository.db2.DepartmentRepository; @Service public class DepartmentService { @Autowired DepartmentRepository deptRepo; public List getAllDepartment() { return (List) deptRepo.findAll(); } public Department saveDepartment(Department dept) { return deptRepo.save(dept); } } package com.onlinetutorialspoint; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import com.onlinetutorialspoint.model.db1.Person; import com.onlinetutorialspoint.model.db2.Department; import com.onlinetutorialspoint.repository.db1.PersonRepository; import com.onlinetutorialspoint.service.DepartmentService; import com.onlinetutorialspoint.service.PersonService; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class); } @Autowired PersonService personService; @Autowired DepartmentService deptService; @Autowired @Bean public CommandLineRunner run(PersonRepository repository) { return (args) -> { //savePersonDetails(); //saveDepartmentDetails(); getAllPerson(); getDepartments(); }; } public Person savePersonDetails(){ Person person = new Person(); person.setName("Chandra Shekhar Goka"); person.setCity("Hyderabad"); return personService.savePerson(person); } public Department saveDepartmentDetails(){ Department dept = new Department(); dept.setName("IT"); return deptService.saveDepartment(dept); } public void getPersonDetails(){ } public void getAllPerson(){ List persons = personService.getAllPersons(); persons.forEach(System.out::println); } public void getDepartments(){ List depts = deptService.getAllDepartment(); depts.forEach(System.out::println); } } mvn clean install; mvn spring-boot:run [INFO] Scanning for projects... [INFO] [INFO] ------------------------------------------------------------------------ [INFO] Building SpringBoot_JPA_Multiple_DataSource 0.0.1-SNAPSHOT [INFO] ------------------------------------------------------------------------ [INFO] [INFO] >>> spring-boot-maven-plugin:1.5.1.RELEASE:run (default-cli) > test-compile @ SpringBoot_JPA_Multiple_DataSource >>> [INFO] [INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ SpringBoot_JPA_Multiple_DataSource --- [INFO] Using 'UTF-8' encoding to copy filtered resources. [INFO] Copying 1 resource [INFO] Copying 2 resources [INFO] [INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ SpringBoot_JPA_Multiple_DataSource --- [INFO] Nothing to compile - all classes are up to date [INFO] [INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ SpringBoot_JPA_Multiple_DataSource --- [INFO] Using 'UTF-8' encoding to copy filtered resources. [INFO] skip non existing resourceDirectory /home/chandrashekhar/Documents/Spring-Class/SpringBoot_JPA_Multiple_DataSource/src/test/resources [INFO] [INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ SpringBoot_JPA_Multiple_DataSource --- [INFO] Nothing to compile - all classes are up to date [INFO] [INFO] <<< spring-boot-maven-plugin:1.5.1.RELEASE:run (default-cli) < test-compile @ SpringBoot_JPA_Multiple_DataSource <<< [INFO] [INFO] --- spring-boot-maven-plugin:1.5.1.RELEASE:run (default-cli) @ SpringBoot_JPA_Multiple_DataSource --- . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v1.5.1.RELEASE) INFO Application - Starting Application on goka with PID 8808 (/home/chandrashekhar/Documents/Spring-Class/SpringBoot_JPA_Multiple_DataSource/target/classes started by chandrashekhar in /home/chandrashekhar/Documents/Spring-Class/SpringBoot_JPA_Multiple_DataSource) INFO Application - No active profile set, falling back to default profiles: default INFO AnnotationConfigApplicationContext - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@73a7b154: startup date [Sat Jun 24 14:36:09 IST 2017]; root of context hierarchy INFO DriverManagerDataSource - Loaded JDBC driver: com.mysql.jdbc.Driver INFO LocalContainerEntityManagerFactoryBean - Building JPA container EntityManagerFactory for persistence unit 'db1EntityManager' INFO LogHelper - HHH000204: Processing PersistenceUnitInfo [ name: db1EntityManager ...] INFO Version - HHH000412: Hibernate Core {5.0.11.Final} INFO Environment - HHH000206: hibernate.properties not found INFO Environment - HHH000021: Bytecode provider name : javassist INFO Version - HCANN000001: Hibernate Commons Annotations {5.0.1.Final} INFO Dialect - HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect INFO LocalContainerEntityManagerFactoryBean - Initialized JPA EntityManagerFactory for persistence unit 'db1EntityManager' INFO DriverManagerDataSource - Loaded JDBC driver: com.mysql.jdbc.Driver INFO LocalContainerEntityManagerFactoryBean - Building JPA container EntityManagerFactory for persistence unit 'db2EntityManager' INFO LogHelper - HHH000204: Processing PersistenceUnitInfo [ name: db2EntityManager ...] INFO Dialect - HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect INFO LocalContainerEntityManagerFactoryBean - Initialized JPA EntityManagerFactory for persistence unit 'db2EntityManager' INFO AnnotationMBeanExporter - Registering beans for JMX exposure on startup INFO QueryTranslatorFactoryInitiator - HHH000397: Using ASTQueryTranslatorFactory Person [pid=1, pName=Chandra Shekhar Goka, pCity=Hyderabad] Person [pid=2, pName=Rahul, pCity=Vijayawada] INFO QueryTranslatorFactoryInitiator - HHH000397: Using ASTQueryTranslatorFactory Department [id=1, Name=IT] INFO Application - Started Application in 8.902 seconds (JVM running for 25.604) [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 16.005 s [INFO] Finished at: 2017-06-24T14:36:17+05:30 [INFO] Final Memory: 36M/262M [INFO] ------------------------------------------------------------------------ INFO AnnotationConfigApplicationContext - Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@73a7b154: startup date [Sat Jun 24 14:36:09 IST 2017]; root of context hierarchy INFO AnnotationMBeanExporter - Unregistering JMX-exposed beans on shutdown INFO LocalContainerEntityManagerFactoryBean - Closing JPA EntityManagerFactory for persistence unit 'db2EntityManager' INFO LocalContainerEntityManagerFactoryBean - Closing JPA EntityManagerFactory for persistence unit 'db1EntityManager' Run the Application : On the above log statements you can see two data different sources data -Person and Department data. Spring Boot Multiple Data Sources Example File size: 45 KB Downloads: 2627 Spring Boot Hibernate Integration Example Spring Boot H2 Database + JDBC Template Example Spring Boot JNDI Configuration – External Tomcat Spring Boot Hazelcast Cache Example How to use Spring Boot Random Port Spring Boot JdbcTemplate CRUD Operations Mysql Spring Boot EhCache Example Spring Boot MongoDB + Spring Data Example Spring Boot Redis Data Example CRUD Operations Spring Boot JPA Integration Example Spring Boot Security MySQL Database Integration Example Simple Spring Boot Example Spring Boot How to change the Tomcat to Jetty Server Java JList Multiple Selection Example How to Send Mail Spring Boot Example Spring Boot Hibernate Integration Example Spring Boot H2 Database + JDBC Template Example Spring Boot JNDI Configuration – External Tomcat Spring Boot Hazelcast Cache Example How to use Spring Boot Random Port Spring Boot JdbcTemplate CRUD Operations Mysql Spring Boot EhCache Example Spring Boot MongoDB + Spring Data Example Spring Boot Redis Data Example CRUD Operations Spring Boot JPA Integration Example Spring Boot Security MySQL Database Integration Example Simple Spring Boot Example Spring Boot How to change the Tomcat to Jetty Server Java JList Multiple Selection Example How to Send Mail Spring Boot Example Ramu December 27, 2017 at 6:56 am - Reply Its great to know about this site and tq for ur valuable tutorials. Jayant June 4, 2018 at 12:54 pm - Reply What if I have the person table in both the databases and depending on some run time parameter I would then decide where to store the data in db1.person or db2.person? How do I configure this? saravanan June 15, 2018 at 11:19 am - Reply can i able to map(@manytoone) those person and Department table?since its in different schema Val August 9, 2018 at 4:48 am - Reply youre example isn’t working Gato October 4, 2018 at 2:02 am - Reply What if the 2 databases have different types? Say db1 is MySQL, db2 is SQL Server, how do you implement it? Pooja March 10, 2022 at 7:49 pm - Reply thank you Ramu December 27, 2017 at 6:56 am - Reply Its great to know about this site and tq for ur valuable tutorials. Its great to know about this site and tq for ur valuable tutorials. Jayant June 4, 2018 at 12:54 pm - Reply What if I have the person table in both the databases and depending on some run time parameter I would then decide where to store the data in db1.person or db2.person? How do I configure this? What if I have the person table in both the databases and depending on some run time parameter I would then decide where to store the data in db1.person or db2.person? How do I configure this? saravanan June 15, 2018 at 11:19 am - Reply can i able to map(@manytoone) those person and Department table?since its in different schema can i able to map(@manytoone) those person and Department table?since its in different schema Val August 9, 2018 at 4:48 am - Reply youre example isn’t working youre example isn’t working Gato October 4, 2018 at 2:02 am - Reply What if the 2 databases have different types? Say db1 is MySQL, db2 is SQL Server, how do you implement it? What if the 2 databases have different types? Say db1 is MySQL, db2 is SQL Server, how do you implement it? Pooja March 10, 2022 at 7:49 pm - Reply thank you thank you Δ 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": 615, "s": 398, "text": "Here I am going to show how to configure multiple data sources in spring boot. Spring Boot multiple data sources configuration are advantageous to connect with different databases in a single spring boot application." }, { "code": null, "e": 629, "s": 615, "text": "Technologies." }, { "code": null, "e": 655, "s": 629, "text": "Spring Boot 1.5.1.RELEASE" }, { "code": null, "e": 664, "s": 655, "text": "Java 1.8" }, { "code": null, "e": 680, "s": 664, "text": "Hibernate 5.0.1" }, { "code": null, "e": 686, "s": 680, "text": "Maven" }, { "code": null, "e": 692, "s": 686, "text": "MySql" }, { "code": null, "e": 819, "s": 692, "text": "Since we are going to work with multiple data sources, we need to have multiple databases in our local machine to access them." }, { "code": null, "e": 887, "s": 819, "text": "Step 1: Open MySql command prompt and log in with your credentials." }, { "code": null, "e": 957, "s": 887, "text": "Step 2: Create two different databases by passing the below command :" }, { "code": null, "e": 1448, "s": 957, "text": "mysql>create database db1;\n\nQuery OK, 1 row affected (0.10 sec)\n\nmysql>use db1;\n\n// Create person table under db1\n\nCREATE TABLE person (\nid int(11) NOT NULL AUTO_INCREMENT,\nname varchar(50) DEFAULT NULL,\ncity varchar(50) DEFAULT NULL,\nPRIMARY KEY (`id`)\n)\n\nmysql> create database db2;\n\nQuery OK, 1 row affected (0.9 sec)\n\nmysql>use db2;\n\n// Create department table under db2\n\nCREATE TABLE department (\nid int(11) NOT NULL AUTO_INCREMENT,\nname varchar(50) DEFAULT NULL,\nPRIMARY KEY (`id`)\n)\n" }, { "code": null, "e": 1573, "s": 1448, "text": "Now two databases are ready to use. We are going to get access these two from our Spring Boot Multiple Data Sources example." }, { "code": null, "e": 1614, "s": 1573, "text": "Recommended: Spring Boot JPA Integration" }, { "code": null, "e": 1649, "s": 1614, "text": "A typical Maven project structure." }, { "code": null, "e": 3598, "s": 1649, "text": "<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 <groupId>org.springframework.samples.service.service</groupId>\n <artifactId>SpringBoot_JPA_Multiple_DataSource</artifactId>\n <version>0.0.1-SNAPSHOT</version>\n <packaging>war</packaging>\n <properties>\n <java.version>1.8</java.version>\n </properties>\n <parent>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-parent</artifactId>\n <version>1.5.1.RELEASE</version>\n </parent>\n <dependencies>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-data-jpa</artifactId>\n </dependency>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-test</artifactId>\n <scope>test</scope>\n </dependency>\n <dependency>\n <groupId>mysql</groupId>\n <artifactId>mysql-connector-java</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 <repositories>\n <repository>\n <id>spring-releases</id>\n <name>Spring Releases</name>\n <url>https://repo.spring.io/libs-release</url>\n </repository>\n <repository>\n <id>org.jboss.repository.releases</id>\n <name>JBoss Maven Release Repository</name>\n <url>https://repository.jboss.org/nexus/content/repositories/releases</url>\n </repository>\n </repositories>\n <pluginRepositories>\n <pluginRepository>\n <id>spring-releases</id>\n <name>Spring Releases</name>\n <url>https://repo.spring.io/libs-release</url>\n </pluginRepository>\n </pluginRepositories>\n</project>" }, { "code": null, "e": 3685, "s": 3598, "text": "Define two database configurations in a single application.properties file like below." }, { "code": null, "e": 4108, "s": 3685, "text": "jdbc.driver-class-name:com.mysql.jdbc.Driver\njdbc.show-sql:true\n\n#First Datasource (DB1)\ndb1.datasource.url:jdbc:mysql://localhost:3306/db1?useSSL=false\ndb1.datasource.username:root\ndb1.datasource.password:12345\n\n#Second Datasource (DB2)\ndb2.datasource.url:jdbc:mysql://localhost:3306/db2?useSSL=false\ndb2.datasource.username:root\ndb2.datasource.password:54321\n\nspring.jooq.sql-dialect=org.hibernate.dialect.MySQL5Dialect\n" }, { "code": null, "e": 4249, "s": 4108, "text": "Since we are going to get access to two different databases (db1, db2), we need to configure each data source configuration separately like:" }, { "code": null, "e": 6993, "s": 4249, "text": "package com.onlinetutorialspoint.config;\n\nimport java.util.HashMap;\n\nimport javax.sql.DataSource;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.context.annotation.Primary;\nimport org.springframework.core.env.Environment;\nimport org.springframework.data.jpa.repository.config.EnableJpaRepositories;\nimport org.springframework.jdbc.datasource.DriverManagerDataSource;\nimport org.springframework.orm.jpa.JpaTransactionManager;\nimport org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;\nimport org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;\nimport org.springframework.transaction.PlatformTransactionManager;\n\n@Configuration\n@EnableJpaRepositories(basePackages = {\"com.onlinetutorialspoint.repository.db1\"},\n entityManagerFactoryRef = \"db1EntityManager\",\n transactionManagerRef = \"db1TransactionManager\")\npublic class DB1_DataSource {\n @Autowired\n private Environment env;\n @Bean\n @Primary\n public LocalContainerEntityManagerFactoryBean db1EntityManager() {\n LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();\n em.setDataSource(db1Datasource());\n em.setPackagesToScan(new String[]{\"com.onlinetutorialspoint.model.db1\"});\n em.setPersistenceUnitName(\"db1EntityManager\");\n HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();\n em.setJpaVendorAdapter(vendorAdapter);\n HashMap<string, object=\"\"> properties = new HashMap<>();\n properties.put(\"hibernate.dialect\",\n env.getProperty(\"hibernate.dialect\"));\n properties.put(\"hibernate.show-sql\",\n env.getProperty(\"jdbc.show-sql\"));\n em.setJpaPropertyMap(properties);\n return em;\n }\n\n @Primary\n @Bean\n public DataSource db1Datasource() {\n\n DriverManagerDataSource dataSource\n = new DriverManagerDataSource();\n dataSource.setDriverClassName(\n env.getProperty(\"jdbc.driver-class-name\"));\n dataSource.setUrl(env.getProperty(\"db1.datasource.url\"));\n dataSource.setUsername(env.getProperty(\"db1.datasource.username\"));\n dataSource.setPassword(env.getProperty(\"db1.datasource.password\"));\n\n return dataSource;\n }\n\n @Primary\n @Bean\n public PlatformTransactionManager db1TransactionManager() {\n\n JpaTransactionManager transactionManager\n = new JpaTransactionManager();\n transactionManager.setEntityManagerFactory(\n db1EntityManager().getObject());\n return transactionManager;\n }\n}\n" }, { "code": null, "e": 7306, "s": 6993, "text": "@Primary: This annotation indicates that a bean should be given as primary preference when multiple qualified beans were autowired on a single-valued dependency. In our case, we have two different data sources, so that we should have to declare anyone as a primary data source between two (or among all of them)." }, { "code": null, "e": 7354, "s": 7306, "text": "Recommended: Spring Boot Hibernate Integration." }, { "code": null, "e": 10054, "s": 7354, "text": "package com.onlinetutorialspoint.config;\n\nimport java.util.HashMap;\n\nimport javax.sql.DataSource;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.core.env.Environment;\nimport org.springframework.data.jpa.repository.config.EnableJpaRepositories;\nimport org.springframework.jdbc.datasource.DriverManagerDataSource;\nimport org.springframework.orm.jpa.JpaTransactionManager;\nimport org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;\nimport org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;\nimport org.springframework.transaction.PlatformTransactionManager;\n\n\n@Configuration\n@EnableJpaRepositories(basePackages = {\"com.onlinetutorialspoint.repository.db2\"},\n entityManagerFactoryRef = \"db2EntityManager\",\n transactionManagerRef = \"db2TransactionManager\")\npublic class DB2_DataSource {\n\n @Autowired\n private Environment env;\n\n @Bean\n public LocalContainerEntityManagerFactoryBean db2EntityManager() {\n LocalContainerEntityManagerFactoryBean em\n = new LocalContainerEntityManagerFactoryBean();\n em.setDataSource(db2Datasource());\n em.setPackagesToScan(\n new String[]{\"com.onlinetutorialspoint.model.db2\"});\n em.setPersistenceUnitName(\"db2EntityManager\");\n HibernateJpaVendorAdapter vendorAdapter\n = new HibernateJpaVendorAdapter();\n em.setJpaVendorAdapter(vendorAdapter);\n HashMap<string, object=\"\"> properties = new HashMap<>();\n properties.put(\"hibernate.dialect\",\n env.getProperty(\"hibernate.dialect\"));\n properties.put(\"hibernate.show-sql\",\n env.getProperty(\"jdbc.show-sql\"));\n em.setJpaPropertyMap(properties);\n return em;\n }\n\n @Bean\n public DataSource db2Datasource() {\n DriverManagerDataSource dataSource\n = new DriverManagerDataSource();\n dataSource.setDriverClassName(\n env.getProperty(\"jdbc.driver-class-name\"));\n dataSource.setUrl(env.getProperty(\"db2.datasource.url\"));\n dataSource.setUsername(env.getProperty(\"db2.datasource.username\"));\n dataSource.setPassword(env.getProperty(\"db2.datasource.password\"));\n\n return dataSource;\n }\n\n @Bean\n public PlatformTransactionManager db2TransactionManager() {\n JpaTransactionManager transactionManager\n = new JpaTransactionManager();\n transactionManager.setEntityManagerFactory(\n db2EntityManager().getObject());\n return transactionManager;\n }\n}\n" }, { "code": null, "e": 10353, "s": 10054, "text": "package com.onlinetutorialspoint.repository.db1;\nimport org.springframework.data.repository.CrudRepository;\nimport org.springframework.stereotype.Repository;\n\nimport com.onlinetutorialspoint.model.db1.Person;\n@Repository\npublic interface PersonRepository extends CrudRepository<person, long=\"\">{\n}\n" }, { "code": null, "e": 10715, "s": 10353, "text": "package com.onlinetutorialspoint.repository.db2;\nimport org.springframework.data.repository.CrudRepository;\nimport org.springframework.stereotype.Repository;\n\nimport com.onlinetutorialspoint.model.db1.Person;\nimport com.onlinetutorialspoint.model.db2.Department;\n@Repository\npublic interface DepartmentRepository extends CrudRepository<department, long=\"\">{\n}\n\n" }, { "code": null, "e": 11758, "s": 10715, "text": "package com.onlinetutorialspoint.model.db1;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"person\")\npublic class Person {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n private String name;\n @Column(name=\"city\")\n private String city;\n\n public Person() {\n super();\n }\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getCity() {\n return city;\n }\n\n public void setCity(String city) {\n this.city = city;\n }\n\n @Override\n public String toString() {\n return \"Person [pid=\" + id + \", pName=\" + name + \", pCity=\" + city\n + \"]\";\n }\n\n}\n" }, { "code": null, "e": 12564, "s": 11758, "text": "package com.onlinetutorialspoint.model.db2;\n\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"department\")\npublic class Department {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n private String name;\n public Department() {\n super();\n }\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n @Override\n public String toString() {\n return \"Department [id=\" + id + \", Name=\" + name +\"]\";\n }\n\n}\n" }, { "code": null, "e": 13126, "s": 12564, "text": "package com.onlinetutorialspoint.service;\n\nimport java.util.List;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\n\nimport com.onlinetutorialspoint.model.db1.Person;\nimport com.onlinetutorialspoint.repository.db1.PersonRepository;\n\n@Service\npublic class PersonService {\n @Autowired\n PersonRepository personRepo;\n\n public List getAllPersons() {\n return (List) personRepo.findAll();\n }\n\n public Person savePerson(Person person) {\n return personRepo.save(person);\n }\n}\n\n" }, { "code": null, "e": 13708, "s": 13126, "text": "package com.onlinetutorialspoint.service;\n\nimport java.util.List;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\n\nimport com.onlinetutorialspoint.model.db2.Department;\nimport com.onlinetutorialspoint.repository.db2.DepartmentRepository;\n\n@Service\npublic class DepartmentService {\n @Autowired\n DepartmentRepository deptRepo;\n\n public List getAllDepartment() {\n return (List) deptRepo.findAll();\n }\n\n public Department saveDepartment(Department dept) {\n return deptRepo.save(dept);\n }\n}\n" }, { "code": null, "e": 15608, "s": 13708, "text": "package com.onlinetutorialspoint;\n\nimport java.util.List;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.CommandLineRunner;\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.context.annotation.Bean;\n\nimport com.onlinetutorialspoint.model.db1.Person;\nimport com.onlinetutorialspoint.model.db2.Department;\nimport com.onlinetutorialspoint.repository.db1.PersonRepository;\nimport com.onlinetutorialspoint.service.DepartmentService;\nimport com.onlinetutorialspoint.service.PersonService;\n\n@SpringBootApplication\npublic class Application {\n public static void main(String[] args) {\n SpringApplication.run(Application.class);\n }\n @Autowired\n PersonService personService;\n @Autowired\n DepartmentService deptService;\n \n @Autowired \n @Bean\n public CommandLineRunner run(PersonRepository repository) {\n return (args) -> {\n //savePersonDetails();\n //saveDepartmentDetails();\n getAllPerson();\n getDepartments();\n };\n }\n \n public Person savePersonDetails(){\n Person person = new Person();\n person.setName(\"Chandra Shekhar Goka\");\n person.setCity(\"Hyderabad\");\n return personService.savePerson(person);\n }\n \n public Department saveDepartmentDetails(){\n Department dept = new Department();\n dept.setName(\"IT\");\n return deptService.saveDepartment(dept);\n }\n \n public void getPersonDetails(){\n \n }\n \n public void getAllPerson(){\n List persons = personService.getAllPersons();\n persons.forEach(System.out::println);\n }\n \n public void getDepartments(){\n List depts = deptService.getAllDepartment();\n depts.forEach(System.out::println);\n }\n \n}\n" }, { "code": null, "e": 20567, "s": 15608, "text": "mvn clean install;\nmvn spring-boot:run\n[INFO] Scanning for projects...\n[INFO]\n[INFO] ------------------------------------------------------------------------\n[INFO] Building SpringBoot_JPA_Multiple_DataSource 0.0.1-SNAPSHOT\n[INFO] ------------------------------------------------------------------------\n[INFO]\n[INFO] >>> spring-boot-maven-plugin:1.5.1.RELEASE:run (default-cli) > test-compile @ SpringBoot_JPA_Multiple_DataSource >>>\n[INFO]\n[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ SpringBoot_JPA_Multiple_DataSource ---\n[INFO] Using 'UTF-8' encoding to copy filtered resources.\n[INFO] Copying 1 resource\n[INFO] Copying 2 resources\n[INFO]\n[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ SpringBoot_JPA_Multiple_DataSource ---\n[INFO] Nothing to compile - all classes are up to date\n[INFO]\n[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ SpringBoot_JPA_Multiple_DataSource ---\n[INFO] Using 'UTF-8' encoding to copy filtered resources.\n[INFO] skip non existing resourceDirectory /home/chandrashekhar/Documents/Spring-Class/SpringBoot_JPA_Multiple_DataSource/src/test/resources\n[INFO]\n[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ SpringBoot_JPA_Multiple_DataSource ---\n[INFO] Nothing to compile - all classes are up to date\n[INFO]\n[INFO] <<< spring-boot-maven-plugin:1.5.1.RELEASE:run (default-cli) < test-compile @ SpringBoot_JPA_Multiple_DataSource <<<\n[INFO]\n[INFO] --- spring-boot-maven-plugin:1.5.1.RELEASE:run (default-cli) @ SpringBoot_JPA_Multiple_DataSource ---\n\n. ____ _ __ _ _\n/\\\\ / ___'_ __ _ _(_)_ __ __ _ \\ \\ \\ \\\n( ( )\\___ | '_ | '_| | '_ \\/ _` | \\ \\ \\ \\\n\\\\/ ___)| |_)| | | | | || (_| | ) ) ) )\n' |____| .__|_| |_|_| |_\\__, | / / / /\n=========|_|==============|___/=/_/_/_/\n:: Spring Boot :: (v1.5.1.RELEASE)\n\nINFO Application - Starting Application on goka with PID 8808 (/home/chandrashekhar/Documents/Spring-Class/SpringBoot_JPA_Multiple_DataSource/target/classes started by chandrashekhar in /home/chandrashekhar/Documents/Spring-Class/SpringBoot_JPA_Multiple_DataSource)\nINFO Application - No active profile set, falling back to default profiles: default\nINFO AnnotationConfigApplicationContext - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@73a7b154: startup date [Sat Jun 24 14:36:09 IST 2017]; root of context hierarchy\nINFO DriverManagerDataSource - Loaded JDBC driver: com.mysql.jdbc.Driver\nINFO LocalContainerEntityManagerFactoryBean - Building JPA container EntityManagerFactory for persistence unit 'db1EntityManager'\nINFO LogHelper - HHH000204: Processing PersistenceUnitInfo [\nname: db1EntityManager\n...]\nINFO Version - HHH000412: Hibernate Core {5.0.11.Final}\nINFO Environment - HHH000206: hibernate.properties not found\nINFO Environment - HHH000021: Bytecode provider name : javassist\nINFO Version - HCANN000001: Hibernate Commons Annotations {5.0.1.Final}\nINFO Dialect - HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect\nINFO LocalContainerEntityManagerFactoryBean - Initialized JPA EntityManagerFactory for persistence unit 'db1EntityManager'\nINFO DriverManagerDataSource - Loaded JDBC driver: com.mysql.jdbc.Driver\nINFO LocalContainerEntityManagerFactoryBean - Building JPA container EntityManagerFactory for persistence unit 'db2EntityManager'\nINFO LogHelper - HHH000204: Processing PersistenceUnitInfo [\nname: db2EntityManager\n...]\nINFO Dialect - HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect\nINFO LocalContainerEntityManagerFactoryBean - Initialized JPA EntityManagerFactory for persistence unit 'db2EntityManager'\nINFO AnnotationMBeanExporter - Registering beans for JMX exposure on startup\nINFO QueryTranslatorFactoryInitiator - HHH000397: Using ASTQueryTranslatorFactory\nPerson [pid=1, pName=Chandra Shekhar Goka, pCity=Hyderabad]\nPerson [pid=2, pName=Rahul, pCity=Vijayawada]\nINFO QueryTranslatorFactoryInitiator - HHH000397: Using ASTQueryTranslatorFactory\nDepartment [id=1, Name=IT]\nINFO Application - Started Application in 8.902 seconds (JVM running for 25.604)\n[INFO] ------------------------------------------------------------------------\n[INFO] BUILD SUCCESS\n[INFO] ------------------------------------------------------------------------\n[INFO] Total time: 16.005 s\n[INFO] Finished at: 2017-06-24T14:36:17+05:30\n[INFO] Final Memory: 36M/262M\n[INFO] ------------------------------------------------------------------------\nINFO AnnotationConfigApplicationContext - Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@73a7b154: startup date [Sat Jun 24 14:36:09 IST 2017]; root of context hierarchy\nINFO AnnotationMBeanExporter - Unregistering JMX-exposed beans on shutdown\nINFO LocalContainerEntityManagerFactoryBean - Closing JPA EntityManagerFactory for persistence unit 'db2EntityManager'\nINFO LocalContainerEntityManagerFactoryBean - Closing JPA EntityManagerFactory for persistence unit 'db1EntityManager'" }, { "code": null, "e": 20589, "s": 20567, "text": "Run the Application :" }, { "code": null, "e": 20691, "s": 20589, "text": "On the above log statements you can see two data different sources data -Person and Department data.\n" }, { "code": null, "e": 20770, "s": 20691, "text": "\n\nSpring Boot Multiple Data Sources Example\n\nFile size: 45 KB\nDownloads: 2627\n" }, { "code": null, "e": 21393, "s": 20770, "text": "\nSpring Boot Hibernate Integration Example\nSpring Boot H2 Database + JDBC Template Example\nSpring Boot JNDI Configuration – External Tomcat\nSpring Boot Hazelcast Cache Example\nHow to use Spring Boot Random Port\nSpring Boot JdbcTemplate CRUD Operations Mysql\nSpring Boot EhCache Example\nSpring Boot MongoDB + Spring Data Example\nSpring Boot Redis Data Example CRUD Operations\nSpring Boot JPA Integration Example\nSpring Boot Security MySQL Database Integration Example\nSimple Spring Boot Example\nSpring Boot How to change the Tomcat to Jetty Server\nJava JList Multiple Selection Example\nHow to Send Mail Spring Boot Example\n" }, { "code": null, "e": 21435, "s": 21393, "text": "Spring Boot Hibernate Integration Example" }, { "code": null, "e": 21483, "s": 21435, "text": "Spring Boot H2 Database + JDBC Template Example" }, { "code": null, "e": 21532, "s": 21483, "text": "Spring Boot JNDI Configuration – External Tomcat" }, { "code": null, "e": 21568, "s": 21532, "text": "Spring Boot Hazelcast Cache Example" }, { "code": null, "e": 21603, "s": 21568, "text": "How to use Spring Boot Random Port" }, { "code": null, "e": 21650, "s": 21603, "text": "Spring Boot JdbcTemplate CRUD Operations Mysql" }, { "code": null, "e": 21678, "s": 21650, "text": "Spring Boot EhCache Example" }, { "code": null, "e": 21720, "s": 21678, "text": "Spring Boot MongoDB + Spring Data Example" }, { "code": null, "e": 21767, "s": 21720, "text": "Spring Boot Redis Data Example CRUD Operations" }, { "code": null, "e": 21803, "s": 21767, "text": "Spring Boot JPA Integration Example" }, { "code": null, "e": 21859, "s": 21803, "text": "Spring Boot Security MySQL Database Integration Example" }, { "code": null, "e": 21886, "s": 21859, "text": "Simple Spring Boot Example" }, { "code": null, "e": 21939, "s": 21886, "text": "Spring Boot How to change the Tomcat to Jetty Server" }, { "code": null, "e": 21977, "s": 21939, "text": "Java JList Multiple Selection Example" }, { "code": null, "e": 22014, "s": 21977, "text": "How to Send Mail Spring Boot Example" }, { "code": null, "e": 22827, "s": 22014, "text": "\n\n\n\n\n\nRamu\nDecember 27, 2017 at 6:56 am - Reply \n\nIts great to know about this site and tq for ur valuable tutorials.\n\n\n\n\n\n\n\n\n\nJayant\nJune 4, 2018 at 12:54 pm - Reply \n\nWhat if I have the person table in both the databases and depending on some run time parameter I would then decide where to store the data in db1.person or db2.person? How do I configure this?\n\n\n\n\n\n\n\n\n\nsaravanan\nJune 15, 2018 at 11:19 am - Reply \n\ncan i able to map(@manytoone) those person and Department table?since its in different schema\n\n\n\n\n\n\n\n\n\nVal\nAugust 9, 2018 at 4:48 am - Reply \n\nyoure example isn’t working\n\n\n\n\n\n\n\n\n\nGato\nOctober 4, 2018 at 2:02 am - Reply \n\nWhat if the 2 databases have different types? Say db1 is MySQL, db2 is SQL Server, how do you implement it?\n\n\n\n\n\n\n\n\n\nPooja\nMarch 10, 2022 at 7:49 pm - Reply \n\nthank you\n\n\n\n\n" }, { "code": null, "e": 22948, "s": 22827, "text": "\n\n\n\n\nRamu\nDecember 27, 2017 at 6:56 am - Reply \n\nIts great to know about this site and tq for ur valuable tutorials.\n\n\n\n" }, { "code": null, "e": 23016, "s": 22948, "text": "Its great to know about this site and tq for ur valuable tutorials." }, { "code": null, "e": 23260, "s": 23016, "text": "\n\n\n\n\nJayant\nJune 4, 2018 at 12:54 pm - Reply \n\nWhat if I have the person table in both the databases and depending on some run time parameter I would then decide where to store the data in db1.person or db2.person? How do I configure this?\n\n\n\n" }, { "code": null, "e": 23453, "s": 23260, "text": "What if I have the person table in both the databases and depending on some run time parameter I would then decide where to store the data in db1.person or db2.person? How do I configure this?" }, { "code": null, "e": 23602, "s": 23453, "text": "\n\n\n\n\nsaravanan\nJune 15, 2018 at 11:19 am - Reply \n\ncan i able to map(@manytoone) those person and Department table?since its in different schema\n\n\n\n" }, { "code": null, "e": 23696, "s": 23602, "text": "can i able to map(@manytoone) those person and Department table?since its in different schema" }, { "code": null, "e": 23773, "s": 23696, "text": "\n\n\n\n\nVal\nAugust 9, 2018 at 4:48 am - Reply \n\nyoure example isn’t working\n\n\n\n" }, { "code": null, "e": 23801, "s": 23773, "text": "youre example isn’t working" }, { "code": null, "e": 23960, "s": 23801, "text": "\n\n\n\n\nGato\nOctober 4, 2018 at 2:02 am - Reply \n\nWhat if the 2 databases have different types? Say db1 is MySQL, db2 is SQL Server, how do you implement it?\n\n\n\n" }, { "code": null, "e": 24068, "s": 23960, "text": "What if the 2 databases have different types? Say db1 is MySQL, db2 is SQL Server, how do you implement it?" }, { "code": null, "e": 24129, "s": 24068, "text": "\n\n\n\n\nPooja\nMarch 10, 2022 at 7:49 pm - Reply \n\nthank you\n\n\n\n" }, { "code": null, "e": 24139, "s": 24129, "text": "thank you" }, { "code": null, "e": 24145, "s": 24143, "text": "Δ" }, { "code": null, "e": 24172, "s": 24145, "text": " Spring Boot – Hello World" }, { "code": null, "e": 24199, "s": 24172, "text": " Spring Boot – MVC Example" }, { "code": null, "e": 24233, "s": 24199, "text": " Spring Boot- Change Context Path" }, { "code": null, "e": 24274, "s": 24233, "text": " Spring Boot – Change Tomcat Port Number" }, { "code": null, "e": 24319, "s": 24274, "text": " Spring Boot – Change Tomcat to Jetty Server" }, { "code": null, "e": 24357, "s": 24319, "text": " Spring Boot – Tomcat session timeout" }, { "code": null, "e": 24391, "s": 24357, "text": " Spring Boot – Enable Random Port" }, { "code": null, "e": 24422, "s": 24391, "text": " Spring Boot – Properties File" }, { "code": null, "e": 24456, "s": 24422, "text": " Spring Boot – Beans Lazy Loading" }, { "code": null, "e": 24489, "s": 24456, "text": " Spring Boot – Set Favicon image" }, { "code": null, "e": 24522, "s": 24489, "text": " Spring Boot – Set Custom Banner" }, { "code": null, "e": 24562, "s": 24522, "text": " Spring Boot – Set Application TimeZone" }, { "code": null, "e": 24587, "s": 24562, "text": " Spring Boot – Send Mail" }, { "code": null, "e": 24618, "s": 24587, "text": " Spring Boot – FileUpload Ajax" }, { "code": null, "e": 24642, "s": 24618, "text": " Spring Boot – Actuator" }, { "code": null, "e": 24688, "s": 24642, "text": " Spring Boot – Actuator Database Health Check" }, { "code": null, "e": 24711, "s": 24688, "text": " Spring Boot – Swagger" }, { "code": null, "e": 24738, "s": 24711, "text": " Spring Boot – Enable CORS" }, { "code": null, "e": 24784, "s": 24738, "text": " Spring Boot – External Apache ActiveMQ Setup" }, { "code": null, "e": 24824, "s": 24784, "text": " Spring Boot – Inmemory Apache ActiveMq" }, { "code": null, "e": 24853, "s": 24824, "text": " Spring Boot – Scheduler Job" }, { "code": null, "e": 24887, "s": 24853, "text": " Spring Boot – Exception Handling" }, { "code": null, "e": 24917, "s": 24887, "text": " Spring Boot – Hibernate CRUD" }, { "code": null, "e": 24953, "s": 24917, "text": " Spring Boot – JPA Integration CRUD" }, { "code": null, "e": 24986, "s": 24953, "text": " Spring Boot – JPA DataRest CRUD" }, { "code": null, "e": 25019, "s": 24986, "text": " Spring Boot – JdbcTemplate CRUD" }, { "code": null, "e": 25063, "s": 25019, "text": " Spring Boot – Multiple Data Sources Config" }, { "code": null, "e": 25097, "s": 25063, "text": " Spring Boot – JNDI Configuration" }, { "code": null, "e": 25129, "s": 25097, "text": " Spring Boot – H2 Database CRUD" }, { "code": null, "e": 25157, "s": 25129, "text": " Spring Boot – MongoDB CRUD" }, { "code": null, "e": 25188, "s": 25157, "text": " Spring Boot – Redis Data CRUD" }, { "code": null, "e": 25229, "s": 25188, "text": " Spring Boot – MVC Login Form Validation" }, { "code": null, "e": 25263, "s": 25229, "text": " Spring Boot – Custom Error Pages" }, { "code": null, "e": 25288, "s": 25263, "text": " Spring Boot – iText PDF" }, { "code": null, "e": 25322, "s": 25288, "text": " Spring Boot – Enable SSL (HTTPs)" }, { "code": null, "e": 25358, "s": 25322, "text": " Spring Boot – Basic Authentication" }, { "code": null, "e": 25404, "s": 25358, "text": " Spring Boot – In Memory Basic Authentication" }, { "code": null, "e": 25455, "s": 25404, "text": " Spring Boot – Security MySQL Database Integration" }, { "code": null, "e": 25497, "s": 25455, "text": " Spring Boot – Redis Cache – Redis Server" }, { "code": null, "e": 25528, "s": 25497, "text": " Spring Boot – Hazelcast Cache" }, { "code": null, "e": 25551, "s": 25528, "text": " Spring Boot – EhCache" }, { "code": null, "e": 25581, "s": 25551, "text": " Spring Boot – Kafka Producer" }, { "code": null, "e": 25611, "s": 25581, "text": " Spring Boot – Kafka Consumer" }, { "code": null, "e": 25660, "s": 25611, "text": " Spring Boot – Kafka JSON Message to Kafka Topic" }, { "code": null, "e": 25694, "s": 25660, "text": " Spring Boot – RabbitMQ Publisher" }, { "code": null, "e": 25727, "s": 25694, "text": " Spring Boot – RabbitMQ Consumer" }, { "code": null, "e": 25756, "s": 25727, "text": " Spring Boot – SOAP Consumer" }, { "code": null, "e": 25788, "s": 25756, "text": " Spring Boot – Soap WebServices" }, { "code": null, "e": 25825, "s": 25788, "text": " Spring Boot – Batch Csv to Database" }, { "code": null, "e": 25854, "s": 25825, "text": " Spring Boot – Eureka Server" }, { "code": null, "e": 25883, "s": 25854, "text": " Spring Boot – MockMvc JUnit" } ]
Kibana - Working With Coordinate Map
Coordinate maps in Kibana will show you the geographic area and mark the area with circles based on aggregation you specify. The Bucket aggregation used for coordinate map is geohash aggregation. For this type of aggregation, your index which you are going to use should have a field of type geo point. The geo point is combination of latitude and longitude. We will create an index using Kibana dev tools and add bulk data to it. We will add mapping and add the geo_point type that we need. The data that we are going to use is shown here − {"index":{"_id":1}} {"location": "2.089330000000046,41.47367000000008", "city": "SantCugat"} {"index":{"_id":2}} {"location": "2.2947825000000677,41.601800991000076", "city": "Granollers"} {"index":{"_id":3}} {"location": "2.1105957495300474,41.5496295760424", "city": "Sabadell"} {"index":{"_id":4}} {"location": "2.132605678083895,41.5370461908878", "city": "Barbera"} {"index":{"_id":5}} {"location": "2.151270020052683,41.497779918345415", "city": "Cerdanyola"} {"index":{"_id":6}} {"location": "2.1364609496220606,41.371303520399344", "city": "Barcelona"} {"index":{"_id":7}} {"location": "2.0819450306711165,41.385491966414705", "city": "Sant Just Desvern"} {"index":{"_id":8}} {"location": "2.00532082278266,41.542294286427385", "city": "Rubi"} {"index":{"_id":9}} {"location": "1.9560805366930398,41.56142635214226", "city": "Viladecavalls"} {"index":{"_id":10}} {"location": "2.09205348251486,41.39327140161001", "city": "Esplugas de Llobregat"} Now, run the following commands in Kibana Dev Tools as shown below − PUT /cities { "mappings": { "_doc": { "properties": { "location": { "type": "geo_point" } } } } } POST /cities/_city/_bulk?refresh {"index":{"_id":1}} {"location": "2.089330000000046,41.47367000000008", "city": "SantCugat"} {"index":{"_id":2}} {"location": "2.2947825000000677,41.601800991000076", "city": "Granollers"} {"index":{"_id":3}} {"location": "2.1105957495300474,41.5496295760424", "city": "Sabadell"} {"index":{"_id":4}} {"location": "2.132605678083895,41.5370461908878", "city": "Barbera"} {"index":{"_id":5}} {"location": "2.151270020052683,41.497779918345415", "city": "Cerdanyola"} {"index":{"_id":6}} {"location": "2.1364609496220606,41.371303520399344", "city": "Barcelona"} {"index":{"_id":7}} {"location": "2.0819450306711165,41.385491966414705", "city": "Sant Just Desvern"} {"index":{"_id":8}} {"location": "2.00532082278266,41.542294286427385", "city": "Rubi"} {"index":{"_id":9}} {"location": "1.9560805366930398,41.56142635214226", "city": "Viladecavalls"} {"index":{"_id":10}} {"location": "2.09205348251486,41.3s9327140161001", "city": "Esplugas de Llobregat"} Now, run the above commands in Kibana dev tools − The above will create index name cities of type _doc and the field location is of type geo_point. Now let’s add data to the index: cities − We are done creating index name cites with data. Now let us Create index pattern for cities using Management tab. The details of fields inside cities index are shown here − We can see that location is of type geo_point. We can now use it to create visualization. Go to Visualization and select coordinate maps. Select the index pattern cities and configure the Aggregation metric and bucket as shown below − If you click on Analyze button, you can see the following screen − Based on the longitude and latitude, the circles are plotted on the map as shown above. Print Add Notes Bookmark this page
[ { "code": null, "e": 2230, "s": 2105, "text": "Coordinate maps in Kibana will show you the geographic area and mark the area with circles based on aggregation you specify." }, { "code": null, "e": 2464, "s": 2230, "text": "The Bucket aggregation used for coordinate map is geohash aggregation. For this type of aggregation, your index which you are going to use should have a field of type geo point. The geo point is combination of latitude and longitude." }, { "code": null, "e": 2597, "s": 2464, "text": "We will create an index using Kibana dev tools and add bulk data to it. We will add mapping and add the geo_point type that we need." }, { "code": null, "e": 2647, "s": 2597, "text": "The data that we are going to use is shown here −" }, { "code": null, "e": 3603, "s": 2647, "text": "{\"index\":{\"_id\":1}}\n{\"location\": \"2.089330000000046,41.47367000000008\", \"city\": \"SantCugat\"}\n{\"index\":{\"_id\":2}}\n{\"location\": \"2.2947825000000677,41.601800991000076\", \"city\": \"Granollers\"}\n{\"index\":{\"_id\":3}}\n{\"location\": \"2.1105957495300474,41.5496295760424\", \"city\": \"Sabadell\"}\n{\"index\":{\"_id\":4}}\n{\"location\": \"2.132605678083895,41.5370461908878\", \"city\": \"Barbera\"}\n{\"index\":{\"_id\":5}}\n{\"location\": \"2.151270020052683,41.497779918345415\", \"city\": \"Cerdanyola\"}\n{\"index\":{\"_id\":6}}\n{\"location\": \"2.1364609496220606,41.371303520399344\", \"city\": \"Barcelona\"}\n{\"index\":{\"_id\":7}}\n{\"location\": \"2.0819450306711165,41.385491966414705\", \"city\": \"Sant Just Desvern\"}\n{\"index\":{\"_id\":8}}\n{\"location\": \"2.00532082278266,41.542294286427385\", \"city\": \"Rubi\"}\n{\"index\":{\"_id\":9}}\n{\"location\": \"1.9560805366930398,41.56142635214226\", \"city\": \"Viladecavalls\"}\n{\"index\":{\"_id\":10}}\n{\"location\": \"2.09205348251486,41.39327140161001\", \"city\": \"Esplugas de Llobregat\"}\n" }, { "code": null, "e": 3672, "s": 3603, "text": "Now, run the following commands in Kibana Dev Tools as shown below −" }, { "code": null, "e": 4836, "s": 3672, "text": "PUT /cities\n{\n \"mappings\": {\n \"_doc\": {\n \"properties\": {\n \"location\": {\n \"type\": \"geo_point\"\n }\n }\n }\n }\n}\n\nPOST /cities/_city/_bulk?refresh\n{\"index\":{\"_id\":1}}\n{\"location\": \"2.089330000000046,41.47367000000008\", \"city\": \"SantCugat\"}\n{\"index\":{\"_id\":2}}\n{\"location\": \"2.2947825000000677,41.601800991000076\", \"city\": \"Granollers\"}\n{\"index\":{\"_id\":3}}\n{\"location\": \"2.1105957495300474,41.5496295760424\", \"city\": \"Sabadell\"}\n{\"index\":{\"_id\":4}}\n{\"location\": \"2.132605678083895,41.5370461908878\", \"city\": \"Barbera\"}\n{\"index\":{\"_id\":5}}\n{\"location\": \"2.151270020052683,41.497779918345415\", \"city\": \"Cerdanyola\"}\n{\"index\":{\"_id\":6}}\n{\"location\": \"2.1364609496220606,41.371303520399344\", \"city\": \"Barcelona\"}\n{\"index\":{\"_id\":7}}\n{\"location\": \"2.0819450306711165,41.385491966414705\", \"city\": \"Sant Just Desvern\"}\n{\"index\":{\"_id\":8}}\n{\"location\": \"2.00532082278266,41.542294286427385\", \"city\": \"Rubi\"}\n{\"index\":{\"_id\":9}}\n{\"location\": \"1.9560805366930398,41.56142635214226\", \"city\": \"Viladecavalls\"}\n{\"index\":{\"_id\":10}}\n{\"location\": \"2.09205348251486,41.3s9327140161001\", \"city\": \"Esplugas de Llobregat\"}\n" }, { "code": null, "e": 4886, "s": 4836, "text": "Now, run the above commands in Kibana dev tools −" }, { "code": null, "e": 4984, "s": 4886, "text": "The above will create index name cities of type _doc and the field location is of type geo_point." }, { "code": null, "e": 5026, "s": 4984, "text": "Now let’s add data to the index: cities −" }, { "code": null, "e": 5140, "s": 5026, "text": "We are done creating index name cites with data. Now let us Create index pattern for cities using Management tab." }, { "code": null, "e": 5199, "s": 5140, "text": "The details of fields inside cities index are shown here −" }, { "code": null, "e": 5289, "s": 5199, "text": "We can see that location is of type geo_point. We can now use it to create visualization." }, { "code": null, "e": 5337, "s": 5289, "text": "Go to Visualization and select coordinate maps." }, { "code": null, "e": 5434, "s": 5337, "text": "Select the index pattern cities and configure the Aggregation metric and bucket as shown below −" }, { "code": null, "e": 5501, "s": 5434, "text": "If you click on Analyze button, you can see the following screen −" }, { "code": null, "e": 5589, "s": 5501, "text": "Based on the longitude and latitude, the circles are plotted on the map as shown above." }, { "code": null, "e": 5596, "s": 5589, "text": " Print" }, { "code": null, "e": 5607, "s": 5596, "text": " Add Notes" } ]
Change Font Size in Matplotlib - GeeksforGeeks
03 Jan, 2021 Matplotlib library mainly used to create 2-dimensional graphs and plots. It has a module named pyplot which makes things easy for plotting. To change the font size in Matplotlib, the two methods given below can be used with appropriate parameters: Method 1: matplotlib.rcParams.update() rcParams is an instance of matplotlib library for handling default matplotlib values hence to change default the font size we just have to pass value to the key font.size Approach: Import module Create data Set rcParams.update() with value to the font.size key. Normally plot the data Display plot Example: Python3 import matplotlib.pyplot as plt # setting font sizeto 30plt.rcParams.update({'font.size': 30}) x = [1, 2, 3, 4, 5, 6]y = [0, 2, 4, 6, 8, 10] # plotting a plotplt.plot(x, y) # setting title nameplt.title("Title") # setting x axis labelplt.xlabel("x axis") # setting y axis labelplt.ylabel("y axis") plt.show() Output: Method 2: matplotlib.rc(group, **kwargs): This function sets the current rc params. The group is the grouping for the rc like line, font, axes etc and kwargs is a dictionary attribute name and value pairs. Approach: Import module Create data Create a font dictionary to pass value of the font Supply this font value to rc() Normally plot the data Display data Example: Python3 import matplotlib.pyplot as plt # creating a dictionaryfont = {'size': 10} # using rc functionplt.rc('font', **font) x = [1, 2, 3, 4, 5, 6]y = [0, 2, 4, 6, 8, 10] # plotting a plotplt.plot(x, y) # setting title nameplt.title("Title") # setting x axis labelplt.xlabel("x axis") # setting y axis labelplt.ylabel("y axis") plt.show() Output: Picked Python-matplotlib Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? Selecting rows in pandas DataFrame based on conditions How to drop one or multiple columns in Pandas Dataframe Python | Get unique values from a list How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | os.path.join() method Defaultdict in Python Create a directory in Python Python Classes and Objects
[ { "code": null, "e": 24212, "s": 24184, "text": "\n03 Jan, 2021" }, { "code": null, "e": 24461, "s": 24212, "text": "Matplotlib library mainly used to create 2-dimensional graphs and plots. It has a module named pyplot which makes things easy for plotting. To change the font size in Matplotlib, the two methods given below can be used with appropriate parameters: " }, { "code": null, "e": 24501, "s": 24461, "text": "Method 1: matplotlib.rcParams.update() " }, { "code": null, "e": 24672, "s": 24501, "text": "rcParams is an instance of matplotlib library for handling default matplotlib values hence to change default the font size we just have to pass value to the key font.size" }, { "code": null, "e": 24682, "s": 24672, "text": "Approach:" }, { "code": null, "e": 24696, "s": 24682, "text": "Import module" }, { "code": null, "e": 24708, "s": 24696, "text": "Create data" }, { "code": null, "e": 24763, "s": 24708, "text": "Set rcParams.update() with value to the font.size key." }, { "code": null, "e": 24786, "s": 24763, "text": "Normally plot the data" }, { "code": null, "e": 24799, "s": 24786, "text": "Display plot" }, { "code": null, "e": 24808, "s": 24799, "text": "Example:" }, { "code": null, "e": 24816, "s": 24808, "text": "Python3" }, { "code": "import matplotlib.pyplot as plt # setting font sizeto 30plt.rcParams.update({'font.size': 30}) x = [1, 2, 3, 4, 5, 6]y = [0, 2, 4, 6, 8, 10] # plotting a plotplt.plot(x, y) # setting title nameplt.title(\"Title\") # setting x axis labelplt.xlabel(\"x axis\") # setting y axis labelplt.ylabel(\"y axis\") plt.show()", "e": 25132, "s": 24816, "text": null }, { "code": null, "e": 25140, "s": 25132, "text": "Output:" }, { "code": null, "e": 25182, "s": 25140, "text": "Method 2: matplotlib.rc(group, **kwargs):" }, { "code": null, "e": 25347, "s": 25182, "text": "This function sets the current rc params. The group is the grouping for the rc like line, font, axes etc and kwargs is a dictionary attribute name and value pairs. " }, { "code": null, "e": 25357, "s": 25347, "text": "Approach:" }, { "code": null, "e": 25371, "s": 25357, "text": "Import module" }, { "code": null, "e": 25383, "s": 25371, "text": "Create data" }, { "code": null, "e": 25434, "s": 25383, "text": "Create a font dictionary to pass value of the font" }, { "code": null, "e": 25465, "s": 25434, "text": "Supply this font value to rc()" }, { "code": null, "e": 25488, "s": 25465, "text": "Normally plot the data" }, { "code": null, "e": 25501, "s": 25488, "text": "Display data" }, { "code": null, "e": 25510, "s": 25501, "text": "Example:" }, { "code": null, "e": 25518, "s": 25510, "text": "Python3" }, { "code": "import matplotlib.pyplot as plt # creating a dictionaryfont = {'size': 10} # using rc functionplt.rc('font', **font) x = [1, 2, 3, 4, 5, 6]y = [0, 2, 4, 6, 8, 10] # plotting a plotplt.plot(x, y) # setting title nameplt.title(\"Title\") # setting x axis labelplt.xlabel(\"x axis\") # setting y axis labelplt.ylabel(\"y axis\") plt.show()", "e": 25859, "s": 25518, "text": null }, { "code": null, "e": 25867, "s": 25859, "text": "Output:" }, { "code": null, "e": 25874, "s": 25867, "text": "Picked" }, { "code": null, "e": 25892, "s": 25874, "text": "Python-matplotlib" }, { "code": null, "e": 25916, "s": 25892, "text": "Technical Scripter 2020" }, { "code": null, "e": 25923, "s": 25916, "text": "Python" }, { "code": null, "e": 25942, "s": 25923, "text": "Technical Scripter" }, { "code": null, "e": 26040, "s": 25942, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26049, "s": 26040, "text": "Comments" }, { "code": null, "e": 26062, "s": 26049, "text": "Old Comments" }, { "code": null, "e": 26094, "s": 26062, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26149, "s": 26094, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26205, "s": 26149, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26244, "s": 26205, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26286, "s": 26244, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26328, "s": 26286, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26359, "s": 26328, "text": "Python | os.path.join() method" }, { "code": null, "e": 26381, "s": 26359, "text": "Defaultdict in Python" }, { "code": null, "e": 26410, "s": 26381, "text": "Create a directory in Python" } ]
Instruction type DCR R in 8085 Microprocessor
In 8085 Instruction set, DCR is a mnemonic, which stands for ‘DeCRement’ and ‘R’ stands for any of the following registers, or memory location M pointed by HL pair. R = A, B, C, D, E, H, L, or M This instruction is used to decrease the content of register R. Also we can say it will subtract 1 from the register R content. And the decremented value will be stored on to the register R itself. As it is an arithmetic instruction, so all flags, except Cy flag, are affected depending on the result. In those assembly language code where we require down counter, there we can use this instruction. So by design as mentioned, Cy flag is not affected by the execution of this instruction. As R can have any of the eight register values, so eight opcodes for this type of instruction are possible. It occupies only 1-Byte in memory. Let us consider DCR M is an example instruction of this type. It is a 1-Byte instruction. Let us consider HL register pair is having initial content of 16-bit address as 4050H. And at memory location 4050H the content is ABH. So the result of execution of this instruction has been depicted in the following tracing table (HL) (4050H) (F) Actually, internally, 8085 performs this decrement operation by adding the 2's complement of 01H to ABH. So if the 4050H initial memory location content is 00H, then after execution of the instruction DCR M, the content would be FFH. Summary − So this instruction DCR M requires 1-Bytes, 3-Machine Cycles (Opcode Fetch, Memory Read, Memory Write) and 10 T-States for execution as shown in the timing diagram.
[ { "code": null, "e": 1227, "s": 1062, "text": "In 8085 Instruction set, DCR is a mnemonic, which stands for ‘DeCRement’ and ‘R’ stands for any of the following registers, or memory location M pointed by HL pair." }, { "code": null, "e": 1258, "s": 1227, "text": "R = A, B, C, D, E, H, L, or M\n" }, { "code": null, "e": 1747, "s": 1258, "text": "This instruction is used to decrease the content of register R. Also we can say it will subtract 1 from the register R content. And the decremented value will be stored on to the register R itself. As it is an arithmetic instruction, so all flags, except Cy flag, are affected depending on the result. In those assembly language code where we require down counter, there we can use this instruction. So by design as mentioned, Cy flag is not affected by the execution of this instruction." }, { "code": null, "e": 1890, "s": 1747, "text": "As R can have any of the eight register values, so eight opcodes for this type of instruction are possible. It occupies only 1-Byte in memory." }, { "code": null, "e": 2212, "s": 1890, "text": "Let us consider DCR M is an example instruction of this type. It is a 1-Byte instruction. Let us consider HL register pair is having initial content of 16-bit address as 4050H. And at memory location 4050H the content is ABH. So the result of execution of this instruction has been depicted in the following tracing table" }, { "code": null, "e": 2217, "s": 2212, "text": "(HL)" }, { "code": null, "e": 2225, "s": 2217, "text": "(4050H)" }, { "code": null, "e": 2229, "s": 2225, "text": "(F)" }, { "code": null, "e": 2463, "s": 2229, "text": "Actually, internally, 8085 performs this decrement operation by adding the 2's complement of 01H to ABH. So if the 4050H initial memory location content is 00H, then after execution of the instruction DCR M, the content would be FFH." }, { "code": null, "e": 2638, "s": 2463, "text": "Summary − So this instruction DCR M requires 1-Bytes, 3-Machine Cycles (Opcode Fetch, Memory Read, Memory Write) and 10 T-States for execution as shown in the timing diagram." } ]
Instant toString() method in Java
The range of values for a field can be obtained using the range() method in the Instant class in Java. This method requires a single parameter i.e. the ChronoField for which the range of values are required and it returns the range of valid values for the ChronoField. A program that demonstrates this is given as follows − Live Demo import java.time.*; import java.time.temporal.ChronoField; import java.time.temporal.ValueRange; public class Demo { public static void main(String[] args) { Instant i = Instant.now(); ValueRange range1 = i.range(ChronoField.MILLI_OF_SECOND); ValueRange range2 = i.range(ChronoField.MICRO_OF_SECOND); ValueRange range3 = i.range(ChronoField.NANO_OF_SECOND); System.out.println("The current Instant is: " + i); System.out.println("\nThe Range of MILLI_OF_SECOND is: " + range1); System.out.println("The Range of MICRO_OF_SECOND is: " + range2); System.out.println("The Range of NANO_OF_SECOND is: " + range3); } } The current Instant is: 2019-02-13T09:09:31.210Z The Range of MILLI_OF_SECOND is: 0 - 999 The Range of MICRO_OF_SECOND is: 0 - 999999 The Range of NANO_OF_SECOND is: 0 - 999999999 Now let us understand the above program. First, the current instant is displayed. Then the range of MILLI_OF_SECOND, MICRO_OF_SECOND and NANO_OF_SECOND is printed using the range() method. A code snippet that demonstrates this is as follows − Instant i = Instant.now(); ValueRange range1 = i.range(ChronoField.MILLI_OF_SECOND); ValueRange range2 = i.range(ChronoField.MICRO_OF_SECOND); ValueRange range3 = i.range(ChronoField.NANO_OF_SECOND); System.out.println("The current Instant is: " + i); System.out.println("\nThe Range of MILLI_OF_SECOND is: " + range1); System.out.println("The Range of MICRO_OF_SECOND is: " + range2); System.out.println("The Range of NANO_OF_SECOND is: " + range3);
[ { "code": null, "e": 1331, "s": 1062, "text": "The range of values for a field can be obtained using the range() method in the Instant class in Java. This method requires a single parameter i.e. the ChronoField for which the range of values are required and it returns the range of valid values for the ChronoField." }, { "code": null, "e": 1386, "s": 1331, "text": "A program that demonstrates this is given as follows −" }, { "code": null, "e": 1397, "s": 1386, "text": " Live Demo" }, { "code": null, "e": 2061, "s": 1397, "text": "import java.time.*;\nimport java.time.temporal.ChronoField;\nimport java.time.temporal.ValueRange;\npublic class Demo {\n public static void main(String[] args) {\n Instant i = Instant.now();\n ValueRange range1 = i.range(ChronoField.MILLI_OF_SECOND);\n ValueRange range2 = i.range(ChronoField.MICRO_OF_SECOND);\n ValueRange range3 = i.range(ChronoField.NANO_OF_SECOND);\n System.out.println(\"The current Instant is: \" + i);\n System.out.println(\"\\nThe Range of MILLI_OF_SECOND is: \" + range1);\n System.out.println(\"The Range of MICRO_OF_SECOND is: \" + range2);\n System.out.println(\"The Range of NANO_OF_SECOND is: \" + range3);\n}\n}" }, { "code": null, "e": 2241, "s": 2061, "text": "The current Instant is: 2019-02-13T09:09:31.210Z\nThe Range of MILLI_OF_SECOND is: 0 - 999\nThe Range of MICRO_OF_SECOND is: 0 - 999999\nThe Range of NANO_OF_SECOND is: 0 - 999999999" }, { "code": null, "e": 2282, "s": 2241, "text": "Now let us understand the above program." }, { "code": null, "e": 2484, "s": 2282, "text": "First, the current instant is displayed. Then the range of MILLI_OF_SECOND, MICRO_OF_SECOND and NANO_OF_SECOND is printed using the range() method. A code snippet that demonstrates this is as follows −" }, { "code": null, "e": 2935, "s": 2484, "text": "Instant i = Instant.now();\nValueRange range1 = i.range(ChronoField.MILLI_OF_SECOND);\nValueRange range2 = i.range(ChronoField.MICRO_OF_SECOND);\nValueRange range3 = i.range(ChronoField.NANO_OF_SECOND);\nSystem.out.println(\"The current Instant is: \" + i);\nSystem.out.println(\"\\nThe Range of MILLI_OF_SECOND is: \" + range1);\nSystem.out.println(\"The Range of MICRO_OF_SECOND is: \" + range2);\nSystem.out.println(\"The Range of NANO_OF_SECOND is: \" + range3);" } ]
Jackson Annotations - @JsonUnwrapped
@JsonUnwrapped is used to unwrap values of objects during serialization or de-serialization. import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import com.fasterxml.jackson.annotation.JsonUnwrapped; import com.fasterxml.jackson.databind.ObjectMapper; public class JacksonTester { public static void main(String args[]) throws IOException, ParseException{ ObjectMapper mapper = new ObjectMapper(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy"); Date date = simpleDateFormat.parse("20-12-1984"); Student.Name name = new Student.Name(); name.first = "Jane"; name.last = "Doe"; Student student = new Student(1, name); String jsonString = mapper .writerWithDefaultPrettyPrinter() .writeValueAsString(student); System.out.println(jsonString); } } class Student { public int id; @JsonUnwrapped public Name name; Student(int id, Name name){ this.id = id; this.name = name; } static class Name { public String first; public String last; } } { "id" : 1, "first" : "Jane", "last" : "Doe" } Print Add Notes Bookmark this page
[ { "code": null, "e": 2568, "s": 2475, "text": "@JsonUnwrapped is used to unwrap values of objects during serialization or de-serialization." }, { "code": null, "e": 3628, "s": 2568, "text": "import java.io.IOException;\nimport java.text.ParseException;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\n\nimport com.fasterxml.jackson.annotation.JsonUnwrapped;\nimport com.fasterxml.jackson.databind.ObjectMapper;\n\npublic class JacksonTester {\n public static void main(String args[]) throws IOException, ParseException{\n ObjectMapper mapper = new ObjectMapper();\n SimpleDateFormat simpleDateFormat = new SimpleDateFormat(\"dd-MM-yyyy\");\n Date date = simpleDateFormat.parse(\"20-12-1984\");\n Student.Name name = new Student.Name();\n name.first = \"Jane\";\n name.last = \"Doe\";\n Student student = new Student(1, name);\n String jsonString = mapper\n .writerWithDefaultPrettyPrinter()\n .writeValueAsString(student);\n System.out.println(jsonString);\n }\n}\nclass Student {\n public int id; \n @JsonUnwrapped\n public Name name;\n Student(int id, Name name){\n this.id = id;\n this.name = name;\n }\n static class Name {\n public String first;\n public String last;\n }\n}" }, { "code": null, "e": 3685, "s": 3628, "text": "{\n \"id\" : 1,\n \"first\" : \"Jane\",\n \"last\" : \"Doe\"\n}\n" }, { "code": null, "e": 3692, "s": 3685, "text": " Print" }, { "code": null, "e": 3703, "s": 3692, "text": " Add Notes" } ]
How to find different elements between two string vectors in R?
Just like numerical vectors, we can find the different elements between two string vectors if there exists any. For this purpose, we can use setdiff function. For example, if we have a vector V1 that contains a, b, c, d, e, f and the other vector V2 that contains a, e, h, k, l, p, r, u, v, w then the different elements between these two vectors can be found as setdiff(V1,V2). Live Demo x1<-LETTERS[1:26] x1 [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" [20] "T" "U" "V" "W" "X" "Y" "Z" Live Demo x2<-LETTERS[5:21] x2 [1] "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" "T" "U" setdiff(x1,x2) [1] "A" "B" "C" "D" "V" "W" "X" "Y" "Z" Live Demo x3<-c("Alabama", "Alaska", "American Samoa", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "District of Columbia", "Florida", "Georgia", "Guam", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Minor Outlying Islands", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Northern Mariana Islands", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Puerto Rico", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "U.S. Virgin Islands", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming") x3 [1] "Alabama" "Alaska" [3] "American Samoa" "Arizona" [5] "Arkansas" "California" [7] "Colorado" "Connecticut" [9] "Delaware" "District of Columbia" [11] "Florida" "Georgia" [13] "Guam" "Hawaii" [15] "Idaho" "Illinois" [17] "Indiana" "Iowa" [19] "Kansas" "Kentucky" [21] "Louisiana" "Maine" [23] "Maryland" "Massachusetts" [25] "Michigan" "Minnesota" [27] "Minor Outlying Islands" "Mississippi" [29] "Missouri" "Montana" [31] "Nebraska" "Nevada" [33] "New Hampshire" "New Jersey" [35] "New Mexico" "New York" [37] "North Carolina" "North Dakota" [39] "Northern Mariana Islands" "Ohio" [41] "Oklahoma" "Oregon" [43] "Pennsylvania" "Puerto Rico" [45] "Rhode Island" "South Carolina" [47] "South Dakota" "Tennessee" [49] "Texas" "U.S. Virgin Islands" [51] "Utah" "Vermont" [53] "Virginia" "Washington" [55] "West Virginia" "Wisconsin" [57] "Wyoming" Live Demo x4<-c("Alabama", "Alaska", "American Samoa", "Arizona", "Arkansas", "California","Florida", "Georgia", "Guam", "Hawaii", "Idaho", "Louisiana", "Maine", "Maryland", "Mississippi", "Missouri", "New Jersey", "New Mexico", "New York", "North Carolina", "Puerto Rico", "Rhode Island", "South Carolina", "South Dakota", "Tennessee") x4 [1] "Alabama" "Alaska" "American Samoa" "Arizona" [5] "Arkansas" "California" "Florida" "Georgia" [9] "Guam" "Hawaii" "Idaho" "Louisiana" [13] "Maine" "Maryland" "Mississippi" "Missouri" [17] "New Jersey" "New Mexico" "New York" "North Carolina" [21] "Puerto Rico" "Rhode Island" "South Carolina" "South Dakota" [25] "Tennessee" setdiff(x3,x4) [1] "Colorado" "Connecticut" [3] "Delaware" "District of Columbia" [5] "Illinois" "Indiana" [7] "Iowa" "Kansas" [9] "Kentucky" "Massachusetts" [11] "Michigan" "Minnesota" [13] "Minor Outlying Islands" "Montana" [15] "Nebraska" "Nevada" [17] "New Hampshire" "North Dakota" [19] "Northern Mariana Islands" "Ohio" [21] "Oklahoma" "Oregon" [23] "Pennsylvania" "Texas" [25] "U.S. Virgin Islands" "Utah" [27] "Vermont" "Virginia" [29] "Washington" "West Virginia" [31] "Wisconsin" "Wyoming" Live Demo x5<-c("AK", "AL", "AR", "AS", "AZ", "CA", "CO", "CT", "DC", "DE", "FL", "GA", "GU", "HI", "IA", "ID", "IL", "IN", "KS", "KY", "LA", "MA", "MD", "ME", "MI", "MN", "MO", "MP", "MS", "MT", "NC", "ND", "NE", "NH", "NJ", "NM", "NV", "NY", "OH", "OK", "OR", "PA", "PR", "RI", "SC", "SD", "TN", "TX", "UM", "UT", "VA", "VI", "VT", "WA", "WI", "WV", "WY") x5 [1] "AK" "AL" "AR" "AS" "AZ" "CA" "CO" "CT" "DC" "DE" "FL" "GA" "GU" "HI" "IA" [16] "ID" "IL" "IN" "KS" "KY" "LA" "MA" "MD" "ME" "MI" "MN" "MO" "MP" "MS" "MT" [31] "NC" "ND" "NE" "NH" "NJ" "NM" "NV" "NY" "OH" "OK" "OR" "PA" "PR" "RI" "SC" [46] "SD" "TN" "TX" "UM" "UT" "VA" "VI" "VT" "WA" "WI" "WV" "WY" Live Demo x6<-c("AK", "CA", "CO", "CT", "HI", "IA", "ID", "IL", "MD", "ME", "MI", "MN", "MO", "MP", "MS", "MT", "NC", "ND", "NE", "NH", "OR", "PA", "PR", "RI", "SC") x6 [1] "AK" "CA" "CO" "CT" "HI" "IA" "ID" "IL" "MD" "ME" "MI" "MN" "MO" "MP" "MS" [16] "MT" "NC" "ND" "NE" "NH" "OR" "PA" "PR" "RI" "SC"
[ { "code": null, "e": 1441, "s": 1062, "text": "Just like numerical vectors, we can find the different elements between two string vectors if there exists any. For this purpose, we can use setdiff function. For example, if we have a vector V1 that contains a, b, c, d, e, f and the other vector V2 that contains a, e, h, k, l, p, r, u, v, w then the different elements between these two vectors can be found as setdiff(V1,V2)." }, { "code": null, "e": 1452, "s": 1441, "text": " Live Demo" }, { "code": null, "e": 1473, "s": 1452, "text": "x1<-LETTERS[1:26]\nx1" }, { "code": null, "e": 1586, "s": 1473, "text": "[1] \"A\" \"B\" \"C\" \"D\" \"E\" \"F\" \"G\" \"H\" \"I\" \"J\" \"K\" \"L\" \"M\" \"N\" \"O\" \"P\" \"Q\" \"R\" \"S\"\n[20] \"T\" \"U\" \"V\" \"W\" \"X\" \"Y\" \"Z\"" }, { "code": null, "e": 1597, "s": 1586, "text": " Live Demo" }, { "code": null, "e": 1618, "s": 1597, "text": "x2<-LETTERS[5:21]\nx2" }, { "code": null, "e": 1745, "s": 1618, "text": "[1] \"E\" \"F\" \"G\" \"H\" \"I\" \"J\" \"K\" \"L\" \"M\" \"N\" \"O\" \"P\" \"Q\" \"R\" \"S\" \"T\" \"U\"\nsetdiff(x1,x2)\n[1] \"A\" \"B\" \"C\" \"D\" \"V\" \"W\" \"X\" \"Y\" \"Z\"" }, { "code": null, "e": 1756, "s": 1745, "text": " Live Demo" }, { "code": null, "e": 2529, "s": 1756, "text": "x3<-c(\"Alabama\", \"Alaska\", \"American Samoa\", \"Arizona\", \"Arkansas\", \"California\", \"Colorado\", \"Connecticut\", \"Delaware\", \"District of Columbia\", \"Florida\", \"Georgia\", \"Guam\", \"Hawaii\", \"Idaho\", \"Illinois\", \"Indiana\", \"Iowa\", \"Kansas\", \"Kentucky\", \"Louisiana\", \"Maine\", \"Maryland\", \"Massachusetts\", \"Michigan\", \"Minnesota\", \"Minor Outlying Islands\", \"Mississippi\", \"Missouri\", \"Montana\", \"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\", \"New Mexico\", \"New York\", \"North Carolina\", \"North Dakota\", \"Northern Mariana Islands\", \"Ohio\", \"Oklahoma\", \"Oregon\", \"Pennsylvania\", \"Puerto Rico\", \"Rhode Island\", \"South Carolina\", \"South Dakota\", \"Tennessee\", \"Texas\", \"U.S. Virgin Islands\", \"Utah\", \"Vermont\", \"Virginia\", \"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\")\nx3" }, { "code": null, "e": 3377, "s": 2529, "text": "[1] \"Alabama\" \"Alaska\"\n[3] \"American Samoa\" \"Arizona\"\n[5] \"Arkansas\" \"California\"\n[7] \"Colorado\" \"Connecticut\"\n[9] \"Delaware\" \"District of Columbia\"\n [11] \"Florida\" \"Georgia\"\n[13] \"Guam\" \"Hawaii\"\n[15] \"Idaho\" \"Illinois\"\n[17] \"Indiana\" \"Iowa\"\n[19] \"Kansas\" \"Kentucky\"\n[21] \"Louisiana\" \"Maine\"\n[23] \"Maryland\" \"Massachusetts\"\n[25] \"Michigan\" \"Minnesota\"\n[27] \"Minor Outlying Islands\" \"Mississippi\"\n[29] \"Missouri\" \"Montana\"\n[31] \"Nebraska\" \"Nevada\"\n[33] \"New Hampshire\" \"New Jersey\"\n[35] \"New Mexico\" \"New York\"\n[37] \"North Carolina\" \"North Dakota\"\n[39] \"Northern Mariana Islands\" \"Ohio\"\n[41] \"Oklahoma\" \"Oregon\"\n[43] \"Pennsylvania\" \"Puerto Rico\"\n[45] \"Rhode Island\" \"South Carolina\"\n[47] \"South Dakota\" \"Tennessee\"\n[49] \"Texas\" \"U.S. Virgin Islands\"\n[51] \"Utah\" \"Vermont\"\n[53] \"Virginia\" \"Washington\"\n[55] \"West Virginia\" \"Wisconsin\"\n[57] \"Wyoming\"" }, { "code": null, "e": 3388, "s": 3377, "text": " Live Demo" }, { "code": null, "e": 3718, "s": 3388, "text": "x4<-c(\"Alabama\", \"Alaska\", \"American Samoa\", \"Arizona\", \"Arkansas\", \"California\",\"Florida\", \"Georgia\", \"Guam\", \"Hawaii\", \"Idaho\", \"Louisiana\", \"Maine\", \"Maryland\", \"Mississippi\", \"Missouri\", \"New Jersey\", \"New Mexico\", \"New York\", \"North Carolina\", \"Puerto Rico\", \"Rhode Island\", \"South Carolina\", \"South Dakota\", \"Tennessee\")\nx4" }, { "code": null, "e": 4547, "s": 3718, "text": "[1] \"Alabama\" \"Alaska\" \"American Samoa\" \"Arizona\"\n[5] \"Arkansas\" \"California\" \"Florida\" \"Georgia\"\n[9] \"Guam\" \"Hawaii\" \"Idaho\" \"Louisiana\"\n[13] \"Maine\" \"Maryland\" \"Mississippi\" \"Missouri\"\n[17] \"New Jersey\" \"New Mexico\" \"New York\" \"North Carolina\"\n[21] \"Puerto Rico\" \"Rhode Island\" \"South Carolina\" \"South Dakota\"\n[25] \"Tennessee\"\nsetdiff(x3,x4)\n[1] \"Colorado\" \"Connecticut\"\n[3] \"Delaware\" \"District of Columbia\"\n[5] \"Illinois\" \"Indiana\"\n[7] \"Iowa\" \"Kansas\"\n[9] \"Kentucky\" \"Massachusetts\"\n[11] \"Michigan\" \"Minnesota\"\n[13] \"Minor Outlying Islands\" \"Montana\"\n[15] \"Nebraska\" \"Nevada\"\n[17] \"New Hampshire\" \"North Dakota\"\n[19] \"Northern Mariana Islands\" \"Ohio\"\n[21] \"Oklahoma\" \"Oregon\"\n[23] \"Pennsylvania\" \"Texas\"\n[25] \"U.S. Virgin Islands\" \"Utah\"\n[27] \"Vermont\" \"Virginia\"\n[29] \"Washington\" \"West Virginia\"\n[31] \"Wisconsin\" \"Wyoming\"" }, { "code": null, "e": 4558, "s": 4547, "text": " Live Demo" }, { "code": null, "e": 4909, "s": 4558, "text": "x5<-c(\"AK\", \"AL\", \"AR\", \"AS\", \"AZ\", \"CA\", \"CO\", \"CT\", \"DC\", \"DE\", \"FL\", \"GA\", \"GU\", \"HI\", \"IA\", \"ID\", \"IL\", \"IN\", \"KS\", \"KY\", \"LA\", \"MA\", \"MD\", \"ME\", \"MI\", \"MN\", \"MO\", \"MP\", \"MS\", \"MT\", \"NC\", \"ND\", \"NE\", \"NH\", \"NJ\", \"NM\", \"NV\", \"NY\", \"OH\", \"OK\", \"OR\", \"PA\", \"PR\", \"RI\", \"SC\", \"SD\", \"TN\", \"TX\", \"UM\", \"UT\", \"VA\", \"VI\", \"VT\", \"WA\", \"WI\", \"WV\", \"WY\")\nx5" }, { "code": null, "e": 5213, "s": 4909, "text": "[1] \"AK\" \"AL\" \"AR\" \"AS\" \"AZ\" \"CA\" \"CO\" \"CT\" \"DC\" \"DE\" \"FL\" \"GA\" \"GU\" \"HI\" \"IA\"\n[16] \"ID\" \"IL\" \"IN\" \"KS\" \"KY\" \"LA\" \"MA\" \"MD\" \"ME\" \"MI\" \"MN\" \"MO\" \"MP\" \"MS\" \"MT\"\n[31] \"NC\" \"ND\" \"NE\" \"NH\" \"NJ\" \"NM\" \"NV\" \"NY\" \"OH\" \"OK\" \"OR\" \"PA\" \"PR\" \"RI\" \"SC\"\n[46] \"SD\" \"TN\" \"TX\" \"UM\" \"UT\" \"VA\" \"VI\" \"VT\" \"WA\" \"WI\" \"WV\" \"WY\"" }, { "code": null, "e": 5224, "s": 5213, "text": " Live Demo" }, { "code": null, "e": 5383, "s": 5224, "text": "x6<-c(\"AK\", \"CA\", \"CO\", \"CT\", \"HI\", \"IA\", \"ID\", \"IL\", \"MD\", \"ME\", \"MI\", \"MN\", \"MO\", \"MP\", \"MS\", \"MT\", \"NC\", \"ND\", \"NE\", \"NH\", \"OR\", \"PA\", \"PR\", \"RI\", \"SC\")\nx6" }, { "code": null, "e": 5517, "s": 5383, "text": "[1] \"AK\" \"CA\" \"CO\" \"CT\" \"HI\" \"IA\" \"ID\" \"IL\" \"MD\" \"ME\" \"MI\" \"MN\" \"MO\" \"MP\" \"MS\"\n[16] \"MT\" \"NC\" \"ND\" \"NE\" \"NH\" \"OR\" \"PA\" \"PR\" \"RI\" \"SC\"" } ]
How to do basic form validation using JavaScript?
JavaScript provides a way to validate form's data on the client's computer before sending it to the web server. Basic form validation includes the form to be checked to make sure all the mandatory fields are filled in. It would require just a loop through each field in the form and check for data. You can try to run the following code to implement basic form validation in JavaScript − <html> <head> <title>Form Validation</title> <script> // Form validation function validate(){ if( document.myForm.Name.value == "" ) { alert( "Please provide your name!" ); document.myForm.Name.focus() ; return false; } if( document.myForm.EMail.value == "" ){ alert( "Please provide your Email!" ); document.myForm.EMail.focus() ; return false; } if( document.myForm.Zip.value == "" || isNaN( document.myForm.Zip.value ) || document.myForm.Zip.value.length != 5 ) { alert( "Please provide a zip in the format #####." ); document.myForm.Zip.focus() ; return false; } if( document.myForm.Country.value == "-1" ){ alert( "Please provide your country!" ); return false; } return( true ); } </script> </head> <body> <form action="/cgi-bin/test.cgi" name="myForm" onsubmit="return(validate());"> <table cellspacing = "2" cellpadding = "2" border = "1"> <tr> <td align = "right">Name</td> <td><input type = "text" name = "Name" /></td> </tr> <tr> <td align = "right">EMail</td> <td><input type = "text" name = "EMail" /></td> </tr> <tr> <td align = "right">Zip Code</td> <td><input type = "text" name = "Zip" /></td> </tr> <tr> <td align = "right">Country</td> <td> <select name = "Country"> <option value = "-1" selected>[choose yours]</option> <option value = "1">USA</option> <option value = "2">UK</option> <option value = "3">INDIA</option> </select> </td> </tr> <tr> <td align = "right"></td> <td><input type = "submit" value = "Submit" /></td> </tr> </table> </form> </body> </html>
[ { "code": null, "e": 1175, "s": 1062, "text": "JavaScript provides a way to validate form's data on the client's computer before sending it to the web server. " }, { "code": null, "e": 1362, "s": 1175, "text": "Basic form validation includes the form to be checked to make sure all the mandatory fields are filled in. It would require just a loop through each field in the form and check for data." }, { "code": null, "e": 1451, "s": 1362, "text": "You can try to run the following code to implement basic form validation in JavaScript −" }, { "code": null, "e": 3750, "s": 1451, "text": "<html>\n <head>\n <title>Form Validation</title>\n <script>\n // Form validation\n function validate(){\n if( document.myForm.Name.value == \"\" ) {\n alert( \"Please provide your name!\" );\n document.myForm.Name.focus() ;\n return false;\n }\n if( document.myForm.EMail.value == \"\" ){\n alert( \"Please provide your Email!\" );\n document.myForm.EMail.focus() ;\n return false;\n }\n if( document.myForm.Zip.value == \"\" ||\n isNaN( document.myForm.Zip.value ) ||\n document.myForm.Zip.value.length != 5 )\n {\n alert( \"Please provide a zip in the format #####.\" );\n document.myForm.Zip.focus() ;\n return false;\n }\n if( document.myForm.Country.value == \"-1\" ){\n alert( \"Please provide your country!\" );\n return false;\n }\n return( true );\n }\n </script>\n </head>\n\n <body>\n <form action=\"/cgi-bin/test.cgi\" name=\"myForm\" onsubmit=\"return(validate());\">\n <table cellspacing = \"2\" cellpadding = \"2\" border = \"1\">\n <tr>\n <td align = \"right\">Name</td>\n <td><input type = \"text\" name = \"Name\" /></td>\n </tr>\n <tr>\n <td align = \"right\">EMail</td>\n <td><input type = \"text\" name = \"EMail\" /></td>\n </tr>\n <tr>\n <td align = \"right\">Zip Code</td>\n <td><input type = \"text\" name = \"Zip\" /></td>\n </tr>\n <tr>\n <td align = \"right\">Country</td>\n <td>\n <select name = \"Country\">\n <option value = \"-1\" selected>[choose yours]</option>\n <option value = \"1\">USA</option>\n <option value = \"2\">UK</option>\n <option value = \"3\">INDIA</option>\n </select>\n </td>\n </tr>\n <tr>\n <td align = \"right\"></td>\n <td><input type = \"submit\" value = \"Submit\" /></td>\n </tr>\n </table>\n </form>\n </body>\n</html>" } ]
Min Coin | Practice | GeeksforGeeks
Given a list of coins of distinct denominations and total amount of money. Find the minimum number of coins required to make up that amount. Output -1 if that money cannot be made up using given coins. You may assume that there are infinite numbers of coins of each type. Example 1: Input: arr = [1, 2, 5], amount = 11 Output: 3 Explanation: 2*5 + 1 = 11. So taking 2 denominations of 5 and 1 denomination of 1, one can make 11. Example 2: Input: arr = [2, 6], amount = 7 Output: -1 Explanation: Not possible to make 7 using denominations 2 and 6. Your Task: You don't need to read or print anything. Your task is to complete the function MinCoin() which takes list of denominations and amount as input parameter and returns miimum number of coins to make up amount. If not possible returns -1. Expected Time Complexity: O(n*amount) Expected Space Complexity: O(amount) Contstraints: 1 <= number of distinct denominations <= 100 1 <= amount <= 104 0 vibhutisingh2 weeks ago def MinCoin(self, nums, amount): # Code here dp=[(amount+1)]*(100001) dp[0]=0 for i in range(len(nums)): for j in range(1,amount+1): if nums[i]<=j: dp[j]=min(dp[j],dp[j-nums[i]]+1) if(dp[amount]>amount): return -1 return dp[amount] 0 vibhutisingh This comment was deleted. +1 spider72 weeks ago int MinCoin(vector<int>nums, int amount){ vector<int> dp(amount+1,amount+1); dp[0] = 0; for(int i=0;i<=amount;i++){ for(int j=0;j<nums.size();j++){ if(nums[j]<=i){ dp[i] = min(dp[i],1+dp[i-nums[j]]); } } } return dp[amount]==amount+1? -1 : dp[amount];} 0 imranwahid2 weeks ago Easy C++ solution using memoization 0 shaileshbaba7282 weeks ago int MinCoin(vector<int>nums, int amount) { //can take any value greater than amount like:amount+1,amount+2,10001 or INT_MAX vector<int> dp(amount+1,10001); //now enter the value for dp[0]=0 dp[0]=0; // it is based on three steps, // 1. pick the current coin=>dp[j-nums[i]]+1, here +1 for picking this coin // 2. dont pick the current coin=>dp[i] value remains same // 3. minimum of both of them for(int i=0;i<nums.size();i++) { for(int j=1;j<=amount;j++) { if(nums[i]<=j) dp[j]=min(dp[j],dp[j-nums[i]]+1); } } if(dp[amount]>amount) return -1; return dp[amount]; } 0 rohitjug19csPremium2 weeks ago JAVA Solution Linear DP public int MinCoin(int[] nums, int amount) { int dp[] = new int[amount+1]; Arrays.fill(dp, Integer.MAX_VALUE); dp[0] = 0; for(int amt=0; amt<=amount; amt++){ int min = Integer.MAX_VALUE; for(int coin : nums) if(coin <= amt)min = Integer.min(min, dp[amt-coin]); if(min != Integer.MAX_VALUE)dp[amt] = 1 + min; } return dp[amount] == Integer.MAX_VALUE ? -1 : dp[amount]; } 0 prasantpoudel332 weeks ago def MinCoin(self, nums, amount): # Code here n = len(nums) i = n - 1 ans=0 while(i >= 0): while (amount >= nums[i]): amount -= nums[i] ans+=1 i -= 1 if ans!=0: return ans return -1 i am getting error in one of the test cases? 2 2512 6 this kind of input. what kind of format is this 0 abhishekkaswan2 weeks ago Easy C++ solution int MinCoin(vector<int>nums, int amount) { //can take any value greater than amount like:amount+1,amount+2,10001 or INT_MAX vector<int> dp(amount+1,10001); //now enter the value for dp[0]=0 dp[0]=0; // it is based on three steps, // 1. pick the current coin=>dp[j-nums[i]]+1, here +1 for picking this coin // 2. dont pick the current coin=>dp[i] value remains same // 3. minimum of both of them for(int i=0;i<nums.size();i++) { for(int j=1;j<=amount;j++) { if(nums[i]<=j) dp[j]=min(dp[j],dp[j-nums[i]]+1); } } if(dp[amount]>amount) return -1; return dp[amount]; } 0 akshitasinghal44442 weeks ago C++ | DP Time - O(n*amt) Space - O(amt) int n=a.size(); vector<int> dp(amt+1,INT_MAX); dp[0]=0; int i,j; for(i=0;i<n;i++) { for(j=1;j<=amt;j++) { if(a[i]<=j && dp[j-a[i]]!=INT_MAX) dp[j]=min(dp[j-a[i]]+1,dp[j]); } } return dp[amt]==INT_MAX?-1:dp[amt]; 0 alistair01112 weeks ago int MinCoin(vector<int>nums, int amount) { // Code here vector<int>dp(amount+1, INT_MAX); dp[0] = 0; for(int i=1; i<amount+1; i++){ int temp = INT_MAX; for(int j = 0; j<nums.size(); j++){ if(i-nums[j]>=0){ temp = min(temp, dp[i-nums[j]]); } } if(temp==INT_MAX){ dp[i] = temp; }else{ dp[i] = temp+1; } // cout<<dp[i]<<" "<<i<<endl; } return dp[amount]==INT_MAX?-1:dp[amount]; } 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": 500, "s": 226, "text": "Given a list of coins of distinct denominations and total amount of money. Find the minimum number of coins required to make up that amount. Output -1 if that money cannot be made up using given coins.\nYou may assume that there are infinite numbers of coins of each type.\n " }, { "code": null, "e": 511, "s": 500, "text": "Example 1:" }, { "code": null, "e": 661, "s": 511, "text": "Input: arr = [1, 2, 5], amount = 11\nOutput: 3\nExplanation: 2*5 + 1 = 11. So taking 2 \ndenominations of 5 and 1 denomination of \n1, one can make 11.\n" }, { "code": null, "e": 672, "s": 661, "text": "Example 2:" }, { "code": null, "e": 782, "s": 672, "text": "Input: arr = [2, 6], amount = 7\nOutput: -1\nExplanation: Not possible to make 7 using \ndenominations 2 and 6.\n" }, { "code": null, "e": 1033, "s": 784, "text": "Your Task:\nYou don't need to read or print anything. Your task is to complete the function MinCoin() which takes list of denominations and amount as input parameter and returns miimum number of coins to make up amount. If not possible returns -1.\n " }, { "code": null, "e": 1110, "s": 1033, "text": "Expected Time Complexity: O(n*amount)\nExpected Space Complexity: O(amount)\n " }, { "code": null, "e": 1188, "s": 1110, "text": "Contstraints:\n1 <= number of distinct denominations <= 100\n1 <= amount <= 104" }, { "code": null, "e": 1190, "s": 1188, "text": "0" }, { "code": null, "e": 1214, "s": 1190, "text": "vibhutisingh2 weeks ago" }, { "code": null, "e": 1494, "s": 1214, "text": "def MinCoin(self, nums, amount):\n\t\t# Code here\n\t\tdp=[(amount+1)]*(100001)\n\t\tdp[0]=0\n\t\tfor i in range(len(nums)):\n\t\t for j in range(1,amount+1):\n\t\t if nums[i]<=j:\n\t\t dp[j]=min(dp[j],dp[j-nums[i]]+1)\n\t\tif(dp[amount]>amount):\n\t\t return -1\n\t\treturn dp[amount]" }, { "code": null, "e": 1496, "s": 1494, "text": "0" }, { "code": null, "e": 1509, "s": 1496, "text": "vibhutisingh" }, { "code": null, "e": 1535, "s": 1509, "text": "This comment was deleted." }, { "code": null, "e": 1538, "s": 1535, "text": "+1" }, { "code": null, "e": 1557, "s": 1538, "text": "spider72 weeks ago" }, { "code": null, "e": 1866, "s": 1557, "text": "int MinCoin(vector<int>nums, int amount){ vector<int> dp(amount+1,amount+1); dp[0] = 0; for(int i=0;i<=amount;i++){ for(int j=0;j<nums.size();j++){ if(nums[j]<=i){ dp[i] = min(dp[i],1+dp[i-nums[j]]); } } } return dp[amount]==amount+1? -1 : dp[amount];}" }, { "code": null, "e": 1868, "s": 1866, "text": "0" }, { "code": null, "e": 1890, "s": 1868, "text": "imranwahid2 weeks ago" }, { "code": null, "e": 1926, "s": 1890, "text": "Easy C++ solution using memoization" }, { "code": null, "e": 1928, "s": 1926, "text": "0" }, { "code": null, "e": 1955, "s": 1928, "text": "shaileshbaba7282 weeks ago" }, { "code": null, "e": 2631, "s": 1955, "text": "int MinCoin(vector<int>nums, int amount)\n\t{\n\t //can take any value greater than amount like:amount+1,amount+2,10001 or INT_MAX\t\n\t vector<int> dp(amount+1,10001);\n\t //now enter the value for dp[0]=0\n\t dp[0]=0;\n\t // it is based on three steps,\n\t // 1. pick the current coin=>dp[j-nums[i]]+1, here +1 for picking this coin\n\t // 2. dont pick the current coin=>dp[i] value remains same\n\t // 3. minimum of both of them \n\t for(int i=0;i<nums.size();i++)\n\t {\n\t for(int j=1;j<=amount;j++)\n\t {\n\t if(nums[i]<=j)\n\t dp[j]=min(dp[j],dp[j-nums[i]]+1);\n\t }\n\t }\n\t if(dp[amount]>amount)\n\t return -1;\n\t return dp[amount]; \n\t}" }, { "code": null, "e": 2633, "s": 2631, "text": "0" }, { "code": null, "e": 2664, "s": 2633, "text": "rohitjug19csPremium2 weeks ago" }, { "code": null, "e": 2688, "s": 2664, "text": "JAVA Solution Linear DP" }, { "code": null, "e": 3171, "s": 2688, "text": "public int MinCoin(int[] nums, int amount)\n {\n int dp[] = new int[amount+1];\n Arrays.fill(dp, Integer.MAX_VALUE);\n dp[0] = 0;\n for(int amt=0; amt<=amount; amt++){\n int min = Integer.MAX_VALUE;\n for(int coin : nums)\n if(coin <= amt)min = Integer.min(min, dp[amt-coin]);\n \n if(min != Integer.MAX_VALUE)dp[amt] = 1 + min;\n }\n \n return dp[amount] == Integer.MAX_VALUE ? -1 : dp[amount];\n }" }, { "code": null, "e": 3173, "s": 3171, "text": "0" }, { "code": null, "e": 3200, "s": 3173, "text": "prasantpoudel332 weeks ago" }, { "code": null, "e": 3494, "s": 3200, "text": "def MinCoin(self, nums, amount):\n\t\t# Code here\n\t\tn = len(nums) \n i = n - 1\n ans=0\n while(i >= 0):\n while (amount >= nums[i]):\n amount -= nums[i]\n ans+=1\n i -= 1\n if ans!=0:\n return ans\n return -1" }, { "code": null, "e": 3539, "s": 3494, "text": "i am getting error in one of the test cases?" }, { "code": null, "e": 3548, "s": 3539, "text": "2 2512 6" }, { "code": null, "e": 3568, "s": 3548, "text": "this kind of input." }, { "code": null, "e": 3596, "s": 3568, "text": "what kind of format is this" }, { "code": null, "e": 3598, "s": 3596, "text": "0" }, { "code": null, "e": 3624, "s": 3598, "text": "abhishekkaswan2 weeks ago" }, { "code": null, "e": 3642, "s": 3624, "text": "Easy C++ solution" }, { "code": null, "e": 4318, "s": 3642, "text": "int MinCoin(vector<int>nums, int amount)\n\t{\n\t //can take any value greater than amount like:amount+1,amount+2,10001 or INT_MAX\t\n\t vector<int> dp(amount+1,10001);\n\t //now enter the value for dp[0]=0\n\t dp[0]=0;\n\t // it is based on three steps,\n\t // 1. pick the current coin=>dp[j-nums[i]]+1, here +1 for picking this coin\n\t // 2. dont pick the current coin=>dp[i] value remains same\n\t // 3. minimum of both of them \n\t for(int i=0;i<nums.size();i++)\n\t {\n\t for(int j=1;j<=amount;j++)\n\t {\n\t if(nums[i]<=j)\n\t dp[j]=min(dp[j],dp[j-nums[i]]+1);\n\t }\n\t }\n\t if(dp[amount]>amount)\n\t return -1;\n\t return dp[amount]; \n\t}" }, { "code": null, "e": 4320, "s": 4318, "text": "0" }, { "code": null, "e": 4350, "s": 4320, "text": "akshitasinghal44442 weeks ago" }, { "code": null, "e": 4359, "s": 4350, "text": "C++ | DP" }, { "code": null, "e": 4375, "s": 4359, "text": "Time - O(n*amt)" }, { "code": null, "e": 4390, "s": 4375, "text": "Space - O(amt)" }, { "code": null, "e": 4704, "s": 4390, "text": "\t\tint n=a.size();\n\t vector<int> dp(amt+1,INT_MAX);\n\t dp[0]=0;\n\t int i,j;\n\t \n\t for(i=0;i<n;i++)\n\t {\n\t for(j=1;j<=amt;j++)\n\t {\n\t if(a[i]<=j && dp[j-a[i]]!=INT_MAX)\n\t dp[j]=min(dp[j-a[i]]+1,dp[j]);\n\t }\n\t }\n\t \n\t return dp[amt]==INT_MAX?-1:dp[amt];" }, { "code": null, "e": 4706, "s": 4704, "text": "0" }, { "code": null, "e": 4730, "s": 4706, "text": "alistair01112 weeks ago" }, { "code": null, "e": 5255, "s": 4730, "text": "int MinCoin(vector<int>nums, int amount)\n{\n // Code here\n vector<int>dp(amount+1, INT_MAX);\n dp[0] = 0;\n \n for(int i=1; i<amount+1; i++){\n int temp = INT_MAX;\n for(int j = 0; j<nums.size(); j++){\n if(i-nums[j]>=0){\n temp = min(temp, dp[i-nums[j]]);\n }\n }\n if(temp==INT_MAX){\n dp[i] = temp;\n }else{\n dp[i] = temp+1;\n }\n // cout<<dp[i]<<\" \"<<i<<endl;\n }\n return dp[amount]==INT_MAX?-1:dp[amount];\n}" }, { "code": null, "e": 5401, "s": 5255, "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": 5437, "s": 5401, "text": " Login to access your submissions. " }, { "code": null, "e": 5447, "s": 5437, "text": "\nProblem\n" }, { "code": null, "e": 5457, "s": 5447, "text": "\nContest\n" }, { "code": null, "e": 5520, "s": 5457, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5668, "s": 5520, "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": 5876, "s": 5668, "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": 5982, "s": 5876, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Check whether two strings contain same characters in same order - GeeksforGeeks
27 Sep, 2021 Given two strings s1 and s2, the task is to find whether the two string contain the same characters that occur in the same order. For example: string “Geeks” and string “Geks” contain the same characters in same order. Examples: Input: s1 = “Geeks”, s2 = “Geks” Output: Yes Input: s1 = “Arnab”, s2 = “Andrew” Output: No Approach: We have two strings now we have to check whether the strings contain the same characters in the same order. So we will replace the contiguous similar element with a single element i.e. if we have “eee”, we will replace it with a single “e”. Now we will check that both the strings are equal or not. If equal then print Yes else No. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <iostream>using namespace std; string getString(char x){ // string class has a constructor // that allows us to specify size of // string as first parameter and character // to be filled in given size as second // parameter. string s(1, x); return s;} // Function that returns true if// the given strings contain same// characters in same orderbool solve(string s1, string s2){ // Get the first character of both strings string a = getString(s1[0]), b = getString(s2[0]); // Now if there are adjacent similar character // remove that character from s1 for (int i = 1; i < s1.length(); i++) if (s1[i] != s1[i - 1]) { a += getString(s1[i]); } // Now if there are adjacent similar character // remove that character from s2 for (int i = 1; i < s2.length(); i++) if (s2[i] != s2[i - 1]) { b += getString(s2[i]); } // If both the strings are equal // then return true if (a == b) return true; return false;} // Driver codeint main(){ string s1 = "Geeks", s2 = "Geks"; if (solve(s1, s2)) cout << "Yes"; else cout << "No"; return 0;} // Java implementation of the approachclass temp{static String getString(char x){ // String class has a constructor // that allows us to specify size of // String as first parameter and character // to be filled in given size as second // parameter. String s = String.valueOf(x); return s;} // Function that returns true if// the given Strings contain same// characters in same orderstatic boolean solve(String s1, String s2){ // Get the first character of both Strings String a = getString(s1.charAt(0)), b = getString(s2.charAt(0)); // Now if there are adjacent similar character // remove that character from s1 for (int i = 1; i < s1.length(); i++) if (s1.charAt(i) != s1.charAt(i - 1)) { a += getString(s1.charAt(i)); } // Now if there are adjacent similar character // remove that character from s2 for (int i = 1; i < s2.length(); i++) if (s2.charAt(i) != s2.charAt(i - 1)) { b += getString(s2.charAt(i)); } // If both the Strings are equal // then return true if (a.equals(b)) return true; return false;} // Driver codepublic static void main(String[] args){ String s1 = "Geeks", s2 = "Geks"; if (solve(s1, s2)) System.out.print("Yes"); else System.out.print("No");}} // This code is contributed by ankush_953 # Python3 implementation of the approach def getString(x): # string class has a constructor # that allows us to specify the size of # string as first parameter and character # to be filled in given size as the second # parameter. return x # Function that returns true if# the given strings contain same# characters in same orderdef solve(s1, s2): # Get the first character of both strings a = getString(s1[0]) b = getString(s2[0]) # Now if there are adjacent similar character # remove that character from s1 for i in range(1, len(s1)): if s1[i] != s1[i - 1]: a += getString(s1[i]) # Now if there are adjacent similar character # remove that character from s2 for i in range(1, len(s2)): if s2[i] != s2[i - 1]: b += getString(s2[i]) # If both the strings are equal # then return true if a == b: return True return False # Driver codes1 = "Geeks"s2 = "Geks"if solve(s1, s2): print("Yes")else: print("No") # This code is contributed by ankush_953 // C# implementation of the approachusing System; public class temp{ static String getString(char x){ // String class has a constructor // that allows us to specify size of // String as first parameter and character // to be filled in given size as second // parameter. String s = String.Join("",x); return s;} // Function that returns true if// the given Strings contain same// characters in same orderstatic Boolean solve(String s1, String s2){ // Get the first character of both Strings String a = getString(s1[0]), b = getString(s2[0]); // Now if there are adjacent similar character // remove that character from s1 for (int i = 1; i < s1.Length; i++) if (s1[i] != s1[i - 1]) { a += getString(s1[i]); } // Now if there are adjacent similar character // remove that character from s2 for (int i = 1; i < s2.Length; i++) if (s2[i] != s2[i - 1]) { b += getString(s2[i]); } // If both the strings are equal // then return true if (a == b) return true; return false;} // Driver codepublic static void Main(String[] args){ String s1 = "Geeks", s2 = "Geks"; if (solve(s1, s2)) Console.Write("Yes"); else Console.Write("No");}} // This code is contributed by Princi Singh <script> // Javascript implementation of the approach function getString(x){ // string class has a constructor // that allows us to specify size of // string as first parameter and character // to be filled in given size as second // parameter. return x} // Function that returns true if// the given strings contain same// characters in same orderfunction solve(s1, s2){ // Get the first character of both strings var a = getString(s1[0]), b = getString(s2[0]); // Now if there are adjacent similar character // remove that character from s1 for (var i = 1; i < s1.length; i++) if (s1[i] != s1[i - 1]) { a += getString(s1[i]); } // Now if there are adjacent similar character // remove that character from s2 for (var i = 1; i < s2.length; i++) if (s2[i] != s2[i - 1]) { b += getString(s2[i]); } // If both the strings are equal // then return true if (a == b) return true; return false;} // Driver codevar s1 = "Geeks", s2 = "Geks";if (solve(s1, s2)) document.write( "Yes");else document.write( "No"); // This code is contributed by rutvik_56.</script> Yes Using Recursion C++ Java Python C# Javascript #include <iostream> using namespace std;bool checkSequence(string a, string b){ // if length of the b = 0 // then we return true if(b.size() == 0) return true; // if length of a = 0 // that means b is not present in // a so we return false if(a.size() == 0) return false; if(a[0] == b[0]) return checkSequence(a.substr(1), b.substr(1)); else return checkSequence(a.substr(1), b);} int main(){ string s1 = "Geeks", s2 = "Geks"; if (checkSequence(s1, s2)) cout << "Yes"; else cout << "No";} // This code is contributed by SoumikMondal /*package whatever //do not write package name here */ import java.io.*; class GFG { public static boolean checkSequence(String a, String b) { //if length of the b = 0 //then we return true if(b.length()==0) return true; //if length of a = 0 //that means b is not present in //a so we return false if(a.length() == 0) return false; if(a.charAt(0) == b.charAt(0)) return checkSequence(a.substring(1), b.substring(1)); else return checkSequence(a.substring(1), b); } public static void main(String[] args) { String s1 = "Geeks", s2 = "Geks"; if (checkSequence(s1, s2)) System.out.print("Yes"); else System.out.print("No"); }} # Python3 implementation of approachdef checkSequence(a, b): # if length of the b = 0 # then we return true if len(b) == 0: return True # if length of a = 0 # that means b is not present in # a so we return false if len(a) == 0: return False if(a[0] == b[0]): return checkSequence(a[1:], b[1:]) else: return checkSequence(a[1:], b) if __name__ == '__main__': s1 = "Geeks" s2 = "Geks" if (checkSequence(s1, s2)): print("Yes") else: print("No") # This code is contributed by nirajgusain5 // C# implementation of the approachusing System; public class temp{public static bool checkSequence(String a, String b){ // if length of the b = 0 // then we return true if(b.Length == 0) return true; // if length of a = 0 // that means b is not present in // a so we return false if(a.Length == 0) return false; if(a[0] == b[0]) return checkSequence(a.Substring(1), b.Substring(1)); else return checkSequence(a.Substring(1), b); } // Driver codepublic static void Main(String[] args){ String s1 = "Geeks", s2 = "Geks"; if (checkSequence(s1, s2)) Console.Write("Yes"); else Console.Write("No");}} // This code is contributed by Dharanendra L V. <script> function checkSequence(a, b){ // If length of the b = 0 // then we return true if (b.length == 0) return true; // If length of a = 0 // that means b is not present in // a so we return false if (a.length == 0) return false; if (a[0] == b[0]) return checkSequence(a.substring(1), b.substring(1)); else return checkSequence(a.substring(1), b);} // Driver codelet s1 = "Geeks", s2 = "Geks"; if (checkSequence(s1, s2)) document.write("Yes");else document.write("No"); // This code is contributed by mukesh07 </script> Output: Yes ankush_953 princi singh Code_Mech le0 SoumikMondal rutvik_56 mukesh07 nirajgusain5 dharanendralv23 lexicographic-ordering Competitive Programming Pattern Searching Strings test_cat_june Strings Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 15 Websites for Coding Challenges and Competitions Breadth First Traversal ( BFS ) on a 2D array Shortest path in a directed graph by Dijkstra’s algorithm Count of strings whose prefix match with the given string to a given length k Runtime Errors KMP Algorithm for Pattern Searching Rabin-Karp Algorithm for Pattern Searching Naive algorithm for Pattern Searching Check if a string is substring of another Boyer Moore Algorithm for Pattern Searching
[ { "code": null, "e": 25128, "s": 25100, "text": "\n27 Sep, 2021" }, { "code": null, "e": 25347, "s": 25128, "text": "Given two strings s1 and s2, the task is to find whether the two string contain the same characters that occur in the same order. For example: string “Geeks” and string “Geks” contain the same characters in same order." }, { "code": null, "e": 25358, "s": 25347, "text": "Examples: " }, { "code": null, "e": 25403, "s": 25358, "text": "Input: s1 = “Geeks”, s2 = “Geks” Output: Yes" }, { "code": null, "e": 25450, "s": 25403, "text": "Input: s1 = “Arnab”, s2 = “Andrew” Output: No " }, { "code": null, "e": 25793, "s": 25450, "text": "Approach: We have two strings now we have to check whether the strings contain the same characters in the same order. So we will replace the contiguous similar element with a single element i.e. if we have “eee”, we will replace it with a single “e”. Now we will check that both the strings are equal or not. If equal then print Yes else No. " }, { "code": null, "e": 25845, "s": 25793, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25849, "s": 25845, "text": "C++" }, { "code": null, "e": 25854, "s": 25849, "text": "Java" }, { "code": null, "e": 25862, "s": 25854, "text": "Python3" }, { "code": null, "e": 25865, "s": 25862, "text": "C#" }, { "code": null, "e": 25876, "s": 25865, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <iostream>using namespace std; string getString(char x){ // string class has a constructor // that allows us to specify size of // string as first parameter and character // to be filled in given size as second // parameter. string s(1, x); return s;} // Function that returns true if// the given strings contain same// characters in same orderbool solve(string s1, string s2){ // Get the first character of both strings string a = getString(s1[0]), b = getString(s2[0]); // Now if there are adjacent similar character // remove that character from s1 for (int i = 1; i < s1.length(); i++) if (s1[i] != s1[i - 1]) { a += getString(s1[i]); } // Now if there are adjacent similar character // remove that character from s2 for (int i = 1; i < s2.length(); i++) if (s2[i] != s2[i - 1]) { b += getString(s2[i]); } // If both the strings are equal // then return true if (a == b) return true; return false;} // Driver codeint main(){ string s1 = \"Geeks\", s2 = \"Geks\"; if (solve(s1, s2)) cout << \"Yes\"; else cout << \"No\"; return 0;}", "e": 27096, "s": 25876, "text": null }, { "code": "// Java implementation of the approachclass temp{static String getString(char x){ // String class has a constructor // that allows us to specify size of // String as first parameter and character // to be filled in given size as second // parameter. String s = String.valueOf(x); return s;} // Function that returns true if// the given Strings contain same// characters in same orderstatic boolean solve(String s1, String s2){ // Get the first character of both Strings String a = getString(s1.charAt(0)), b = getString(s2.charAt(0)); // Now if there are adjacent similar character // remove that character from s1 for (int i = 1; i < s1.length(); i++) if (s1.charAt(i) != s1.charAt(i - 1)) { a += getString(s1.charAt(i)); } // Now if there are adjacent similar character // remove that character from s2 for (int i = 1; i < s2.length(); i++) if (s2.charAt(i) != s2.charAt(i - 1)) { b += getString(s2.charAt(i)); } // If both the Strings are equal // then return true if (a.equals(b)) return true; return false;} // Driver codepublic static void main(String[] args){ String s1 = \"Geeks\", s2 = \"Geks\"; if (solve(s1, s2)) System.out.print(\"Yes\"); else System.out.print(\"No\");}} // This code is contributed by ankush_953", "e": 28481, "s": 27096, "text": null }, { "code": "# Python3 implementation of the approach def getString(x): # string class has a constructor # that allows us to specify the size of # string as first parameter and character # to be filled in given size as the second # parameter. return x # Function that returns true if# the given strings contain same# characters in same orderdef solve(s1, s2): # Get the first character of both strings a = getString(s1[0]) b = getString(s2[0]) # Now if there are adjacent similar character # remove that character from s1 for i in range(1, len(s1)): if s1[i] != s1[i - 1]: a += getString(s1[i]) # Now if there are adjacent similar character # remove that character from s2 for i in range(1, len(s2)): if s2[i] != s2[i - 1]: b += getString(s2[i]) # If both the strings are equal # then return true if a == b: return True return False # Driver codes1 = \"Geeks\"s2 = \"Geks\"if solve(s1, s2): print(\"Yes\")else: print(\"No\") # This code is contributed by ankush_953", "e": 29553, "s": 28481, "text": null }, { "code": "// C# implementation of the approachusing System; public class temp{ static String getString(char x){ // String class has a constructor // that allows us to specify size of // String as first parameter and character // to be filled in given size as second // parameter. String s = String.Join(\"\",x); return s;} // Function that returns true if// the given Strings contain same// characters in same orderstatic Boolean solve(String s1, String s2){ // Get the first character of both Strings String a = getString(s1[0]), b = getString(s2[0]); // Now if there are adjacent similar character // remove that character from s1 for (int i = 1; i < s1.Length; i++) if (s1[i] != s1[i - 1]) { a += getString(s1[i]); } // Now if there are adjacent similar character // remove that character from s2 for (int i = 1; i < s2.Length; i++) if (s2[i] != s2[i - 1]) { b += getString(s2[i]); } // If both the strings are equal // then return true if (a == b) return true; return false;} // Driver codepublic static void Main(String[] args){ String s1 = \"Geeks\", s2 = \"Geks\"; if (solve(s1, s2)) Console.Write(\"Yes\"); else Console.Write(\"No\");}} // This code is contributed by Princi Singh", "e": 30880, "s": 29553, "text": null }, { "code": "<script> // Javascript implementation of the approach function getString(x){ // string class has a constructor // that allows us to specify size of // string as first parameter and character // to be filled in given size as second // parameter. return x} // Function that returns true if// the given strings contain same// characters in same orderfunction solve(s1, s2){ // Get the first character of both strings var a = getString(s1[0]), b = getString(s2[0]); // Now if there are adjacent similar character // remove that character from s1 for (var i = 1; i < s1.length; i++) if (s1[i] != s1[i - 1]) { a += getString(s1[i]); } // Now if there are adjacent similar character // remove that character from s2 for (var i = 1; i < s2.length; i++) if (s2[i] != s2[i - 1]) { b += getString(s2[i]); } // If both the strings are equal // then return true if (a == b) return true; return false;} // Driver codevar s1 = \"Geeks\", s2 = \"Geks\";if (solve(s1, s2)) document.write( \"Yes\");else document.write( \"No\"); // This code is contributed by rutvik_56.</script>", "e": 32056, "s": 30880, "text": null }, { "code": null, "e": 32060, "s": 32056, "text": "Yes" }, { "code": null, "e": 32078, "s": 32062, "text": "Using Recursion" }, { "code": null, "e": 32082, "s": 32078, "text": "C++" }, { "code": null, "e": 32087, "s": 32082, "text": "Java" }, { "code": null, "e": 32094, "s": 32087, "text": "Python" }, { "code": null, "e": 32097, "s": 32094, "text": "C#" }, { "code": null, "e": 32108, "s": 32097, "text": "Javascript" }, { "code": "#include <iostream> using namespace std;bool checkSequence(string a, string b){ // if length of the b = 0 // then we return true if(b.size() == 0) return true; // if length of a = 0 // that means b is not present in // a so we return false if(a.size() == 0) return false; if(a[0] == b[0]) return checkSequence(a.substr(1), b.substr(1)); else return checkSequence(a.substr(1), b);} int main(){ string s1 = \"Geeks\", s2 = \"Geks\"; if (checkSequence(s1, s2)) cout << \"Yes\"; else cout << \"No\";} // This code is contributed by SoumikMondal", "e": 32736, "s": 32108, "text": null }, { "code": "/*package whatever //do not write package name here */ import java.io.*; class GFG { public static boolean checkSequence(String a, String b) { //if length of the b = 0 //then we return true if(b.length()==0) return true; //if length of a = 0 //that means b is not present in //a so we return false if(a.length() == 0) return false; if(a.charAt(0) == b.charAt(0)) return checkSequence(a.substring(1), b.substring(1)); else return checkSequence(a.substring(1), b); } public static void main(String[] args) { String s1 = \"Geeks\", s2 = \"Geks\"; if (checkSequence(s1, s2)) System.out.print(\"Yes\"); else System.out.print(\"No\"); }}", "e": 33558, "s": 32736, "text": null }, { "code": "# Python3 implementation of approachdef checkSequence(a, b): # if length of the b = 0 # then we return true if len(b) == 0: return True # if length of a = 0 # that means b is not present in # a so we return false if len(a) == 0: return False if(a[0] == b[0]): return checkSequence(a[1:], b[1:]) else: return checkSequence(a[1:], b) if __name__ == '__main__': s1 = \"Geeks\" s2 = \"Geks\" if (checkSequence(s1, s2)): print(\"Yes\") else: print(\"No\") # This code is contributed by nirajgusain5", "e": 34132, "s": 33558, "text": null }, { "code": "// C# implementation of the approachusing System; public class temp{public static bool checkSequence(String a, String b){ // if length of the b = 0 // then we return true if(b.Length == 0) return true; // if length of a = 0 // that means b is not present in // a so we return false if(a.Length == 0) return false; if(a[0] == b[0]) return checkSequence(a.Substring(1), b.Substring(1)); else return checkSequence(a.Substring(1), b); } // Driver codepublic static void Main(String[] args){ String s1 = \"Geeks\", s2 = \"Geks\"; if (checkSequence(s1, s2)) Console.Write(\"Yes\"); else Console.Write(\"No\");}} // This code is contributed by Dharanendra L V.", "e": 34947, "s": 34132, "text": null }, { "code": "<script> function checkSequence(a, b){ // If length of the b = 0 // then we return true if (b.length == 0) return true; // If length of a = 0 // that means b is not present in // a so we return false if (a.length == 0) return false; if (a[0] == b[0]) return checkSequence(a.substring(1), b.substring(1)); else return checkSequence(a.substring(1), b);} // Driver codelet s1 = \"Geeks\", s2 = \"Geks\"; if (checkSequence(s1, s2)) document.write(\"Yes\");else document.write(\"No\"); // This code is contributed by mukesh07 </script>", "e": 35578, "s": 34947, "text": null }, { "code": null, "e": 35586, "s": 35578, "text": "Output:" }, { "code": null, "e": 35590, "s": 35586, "text": "Yes" }, { "code": null, "e": 35601, "s": 35590, "text": "ankush_953" }, { "code": null, "e": 35614, "s": 35601, "text": "princi singh" }, { "code": null, "e": 35624, "s": 35614, "text": "Code_Mech" }, { "code": null, "e": 35628, "s": 35624, "text": "le0" }, { "code": null, "e": 35641, "s": 35628, "text": "SoumikMondal" }, { "code": null, "e": 35651, "s": 35641, "text": "rutvik_56" }, { "code": null, "e": 35660, "s": 35651, "text": "mukesh07" }, { "code": null, "e": 35673, "s": 35660, "text": "nirajgusain5" }, { "code": null, "e": 35689, "s": 35673, "text": "dharanendralv23" }, { "code": null, "e": 35712, "s": 35689, "text": "lexicographic-ordering" }, { "code": null, "e": 35736, "s": 35712, "text": "Competitive Programming" }, { "code": null, "e": 35754, "s": 35736, "text": "Pattern Searching" }, { "code": null, "e": 35762, "s": 35754, "text": "Strings" }, { "code": null, "e": 35776, "s": 35762, "text": "test_cat_june" }, { "code": null, "e": 35784, "s": 35776, "text": "Strings" }, { "code": null, "e": 35802, "s": 35784, "text": "Pattern Searching" }, { "code": null, "e": 35900, "s": 35802, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35955, "s": 35900, "text": "Top 15 Websites for Coding Challenges and Competitions" }, { "code": null, "e": 36001, "s": 35955, "text": "Breadth First Traversal ( BFS ) on a 2D array" }, { "code": null, "e": 36059, "s": 36001, "text": "Shortest path in a directed graph by Dijkstra’s algorithm" }, { "code": null, "e": 36137, "s": 36059, "text": "Count of strings whose prefix match with the given string to a given length k" }, { "code": null, "e": 36152, "s": 36137, "text": "Runtime Errors" }, { "code": null, "e": 36188, "s": 36152, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 36231, "s": 36188, "text": "Rabin-Karp Algorithm for Pattern Searching" }, { "code": null, "e": 36269, "s": 36231, "text": "Naive algorithm for Pattern Searching" }, { "code": null, "e": 36311, "s": 36269, "text": "Check if a string is substring of another" } ]
Built-in Exceptions in Python - GeeksforGeeks
14 Mar, 2022 All instances in Python must be instances of a class that derives from BaseException. Two exception classes that are not related via subclassing are never equivalent, even if they have the same name. The built-in exceptions can be generated by the interpreter or built-in functions. There are several built-in exceptions in Python that are raised when errors occur. These built-in exceptions can be viewed using the local() built-in functions as follows : >>> locals()['__builtins__'] This returns a dictionary of built-in exceptions, functions and attributes. Base Classes The following exceptions are used mostly as base classes for other exceptions. exception BaseExceptionThis is the base class for all built-in exceptions. It is not meant to be directly inherited by user-defined classes. For, user-defined classes, Exception is used. This class is responsible for creating a string representation of the exception using str() using the arguments passed. An empty string is returned if there are no arguments.args : The args are the tuple of arguments given to the exception constructor.with_traceback(tb) : This method is usually used in exception handling. This method sets tb as the new traceback for the exception and returns the exception object.Code :try: ... except SomeException: tb = sys.exc_info()[2] raise OtherException(...).with_traceback(tb) exception ExceptionThis is the base class for all built-in non-system-exiting exceptions. All user-defined exceptions should also be derived from this class.exception ArithmeticErrorThis class is the base class for those built-in exceptions that are raised for various arithmetic errors such as :OverflowErrorZeroDivisionErrorFloatingPointErrorExample :try: a = 10/0 print (a)except ArithmeticError: print ("This statement is raising an arithmetic exception.")else: print ("Success.")Output :This statement is raising an arithmetic exception. exception BufferErrorThis exception is raised when buffer related operations cannot be performed.exception LookupErrorThis is the base class for those exceptions that are raised when a key or index used on a mapping or sequence is invalid or not found. The exceptions raised are :KeyErrorIndexErrorExample :try: a = [1, 2, 3] print (a[3]) except LookupError: print ("Index out of bound error.")else: print ("Success") Output :Index out of bound error. exception BaseExceptionThis is the base class for all built-in exceptions. It is not meant to be directly inherited by user-defined classes. For, user-defined classes, Exception is used. This class is responsible for creating a string representation of the exception using str() using the arguments passed. An empty string is returned if there are no arguments.args : The args are the tuple of arguments given to the exception constructor.with_traceback(tb) : This method is usually used in exception handling. This method sets tb as the new traceback for the exception and returns the exception object.Code :try: ... except SomeException: tb = sys.exc_info()[2] raise OtherException(...).with_traceback(tb) args : The args are the tuple of arguments given to the exception constructor. with_traceback(tb) : This method is usually used in exception handling. This method sets tb as the new traceback for the exception and returns the exception object.Code :try: ... except SomeException: tb = sys.exc_info()[2] raise OtherException(...).with_traceback(tb) Code : try: ... except SomeException: tb = sys.exc_info()[2] raise OtherException(...).with_traceback(tb) exception ExceptionThis is the base class for all built-in non-system-exiting exceptions. All user-defined exceptions should also be derived from this class. exception ArithmeticErrorThis class is the base class for those built-in exceptions that are raised for various arithmetic errors such as :OverflowErrorZeroDivisionErrorFloatingPointErrorExample :try: a = 10/0 print (a)except ArithmeticError: print ("This statement is raising an arithmetic exception.")else: print ("Success.")Output :This statement is raising an arithmetic exception. OverflowError ZeroDivisionError FloatingPointError Example : try: a = 10/0 print (a)except ArithmeticError: print ("This statement is raising an arithmetic exception.")else: print ("Success.") Output : This statement is raising an arithmetic exception. exception BufferErrorThis exception is raised when buffer related operations cannot be performed. exception LookupErrorThis is the base class for those exceptions that are raised when a key or index used on a mapping or sequence is invalid or not found. The exceptions raised are :KeyErrorIndexErrorExample :try: a = [1, 2, 3] print (a[3]) except LookupError: print ("Index out of bound error.")else: print ("Success") Output :Index out of bound error. KeyError IndexError Example : try: a = [1, 2, 3] print (a[3]) except LookupError: print ("Index out of bound error.")else: print ("Success") Output : Index out of bound error. Concrete exceptions The following exceptions are the exceptions that are usually raised. exception AssertionErrorAn AssertionError is raised when an assert statement fails.Example :assert False, 'The assertion failed' Output :Traceback (most recent call last): File "exceptions_AssertionError.py", line 12, in assert False, 'The assertion failed' AssertionError: The assertion failed exception AttributeErrorAn AttributeError is raised when an attribute reference or assignment fails such as when a non-existent attribute is referenced.Example :class Attributes(object): pass object = Attributes()print (object.attribute)Output :Traceback (most recent call last): File "d912bae549a2b42953bc62da114ae7a7.py", line 5, in print object.attribute AttributeError: 'Attributes' object has no attribute 'attribute' exception EOFErrorAn EOFError is raised when built-in functions like input() hits an end-of-file condition (EOF) without reading any data. The file methods like readline() return an empty string when they hit EOF.Example :while True: data = input('Enter name : ') print ('Hello ', data)Output :Enter Name :Hello Aditi Enter Name :Traceback (most recent call last): File "exceptions_EOFError.py", line 13, in data = raw_input('Enter name :') EOFError: EOF when reading a line exception FloatingPointErrorA FloatingPointError is raised when a floating point operation fails. This exception is always defined, but can only be raised when Python is configured with the–with-fpectl option, or the WANT_SIGFPE_HANDLER symbol is defined in the pyconfig.h file.Example :import math print (math.exp(1000))Output :Traceback (most recent call last): File "", line 1, in FloatingPointError: in math_1 exception GeneratorExitThis exception directly inherits from BaseException instead of Exception since it is technically not an error. A GeneratorExit exception is raised when a generator or coroutine is closed.Example :def my_generator(): try: for i in range(5): print ('Yielding', i) yield i except GeneratorExit: print ('Exiting early') g = my_generator()print (g.next())g.close() Output :Yielding 0 0 Exiting early exception ImportErrorAn ImportError is raised when the import statement is unable to load a module or when the “from list” in from ... import has a name that cannot be found.Example :import module_does_not_existOutput :Traceback (most recent call last): File "exceptions_ImportError_nomodule.py", line 12, in import module_does_not_exist ImportError: No module named module_does_not_exist Example :from exceptions import UserexceptionOutput :Traceback (most recent call last): File "exceptions_ImportError_missingname.py", line 12, in from exceptions import Userexception ImportError: cannot import name Userexception exception ModuleNotFoundErrorThis is the subclass of ImportError which is raised by import when a module could not be found. It is also raised when None is found in sys.modules.exception IndexErrorAn IndexError is raised when a sequence is referenced which is out of range.Example :array = [ 0, 1, 2 ]print (array[3])Output :Traceback (most recent call last): File "exceptions_IndexError.py", line 13, in print array[3] IndexError: list index out of range exception KeyErrorA KeyError is raised when a mapping key is not found in the set of existing keys.Example :array = { 'a':1, 'b':2 }print (array['c'])Output :Traceback (most recent call last): File "exceptions_KeyError.py", line 13, in print array['c'] KeyError: 'c' exception KeyboardInterruptThis error is raised when the user hits the interrupt key such as Control-C or Delete.Example :try: print ('Press Return or Ctrl-C:',) ignored = input()except Exception, err: print ('Caught exception:', err)except KeyboardInterrupt, err: print ('Caught KeyboardInterrupt')else: print ('No exception')Output :Press Return or Ctrl-C: ^CCaught KeyboardInterrupt exception MemoryErrorThis error is raised when an operation runs out of memory.Example :def fact(a): factors = [] for i in range(1, a+1): if a%i == 0: factors.append(i) return factors num = 600851475143print (fact(num))Output :Traceback (most recent call last): File "4af5c316c749aff128df20714536b8f3.py", line 9, in print fact(num) File "4af5c316c749aff128df20714536b8f3.py", line 3, in fact for i in range(1, a+1): MemoryError exception NameErrorThis error is raised when a local or global name is not found. For example, an unqualified variable name.Example :def func(): print ans func()Output :Traceback (most recent call last): File "cfba0a5196b05397e0a23b1b5b8c7e19.py", line 4, in func() File "cfba0a5196b05397e0a23b1b5b8c7e19.py", line 2, in func print ans NameError: global name 'ans' is not defined exception NotImplementedErrorThis exception is derived from RuntimeError. Abstract methods in user defined classed should raise this exception when the derived classes override the method.Example :class BaseClass(object): """Defines the interface""" def __init__(self): super(BaseClass, self).__init__() def do_something(self): """The interface, not implemented""" raise NotImplementedError(self.__class__.__name__ + '.do_something') class SubClass(BaseClass): """Implements the interface""" def do_something(self): """really does something""" print (self.__class__.__name__ + ' doing something!') SubClass().do_something()BaseClass().do_something()Output :Traceback (most recent call last): File "b32fc445850cbc23cd2f081ba1c1d60b.py", line 16, in BaseClass().do_something() File "b32fc445850cbc23cd2f081ba1c1d60b.py", line 7, in do_something raise NotImplementedError(self.__class__.__name__ + '.do_something') NotImplementedError: BaseClass.do_something exception OSError([arg])The OSError exception is raised when a system function returns a system-related error, including I/O failures such as “file not found” or “disk full” errors.Example :def func(): print (ans) func()Output :Traceback (most recent call last): File "442eccd7535a2704adbe372cb731fc0f.py", line 4, in print i, os.ttyname(i) OSError: [Errno 25] Inappropriate ioctl for device exception OverflowErrorThe OverflowError is raised when the result of an arithmetic operation is out of range. Integers raise MemoryError instead of OverflowError. OverflowError is sometimes raised for integers that are outside a required range. Floating point operations are not checked because of the lack of standardization of floating point exception handling in C.Example :import sys print ('Regular integer: (maxint=%s)' % sys.maxint)try: i = sys.maxint * 3 print ('No overflow for ', type(i), 'i =', i)except OverflowError, err: print ('Overflowed at ', i, err) print()print ('Long integer:')for i in range(0, 100, 10): print ('%2d' % i, 2L ** i) print()print ('Floating point values:')try: f = 2.0**i for i in range(100): print (i, f) f = f ** 2except OverflowError, err: print ('Overflowed after ', f, err)Output :Regular integer: (maxint=9223372036854775807) No overflow for i = 27670116110564327421 Long integer: 0 1 10 1024 20 1048576 30 1073741824 40 1099511627776 50 1125899906842624 60 1152921504606846976 70 1180591620717411303424 80 1208925819614629174706176 90 1237940039285380274899124224 Floating point values: 0 1.23794003929e+27 1 1.53249554087e+54 2 2.34854258277e+108 3 5.5156522631e+216 Overflowed after 5.5156522631e+216 (34, 'Numerical result out of range') exception RecursionErrorThe RecursionError is derived from the RuntimeError. This exception is raised when the interpreter detects that the maximum recursion depth is exceeded.exception ReferenceErrorThe ReferenceError is raised when a weak reference proxy is used to access an attribute of the referent after the garbage collection.Example :import gcimport weakref class Foo(object): def __init__(self, name): self.name = name def __del__(self): print ('(Deleting %s)' % self) obj = Foo('obj')p = weakref.proxy(obj) print ('BEFORE:', p.name)obj = Noneprint ('AFTER:', p.name)Output :BEFORE: obj (Deleting ) AFTER: Traceback (most recent call last): File "49d0c29d8fe607b862c02f4e1cb6c756.py", line 17, in print 'AFTER:', p.name ReferenceError: weakly-referenced object no longer exists exception RuntimeErrorThe RuntimeError is raised when no other exception applies. It returns a string indicating what precisely went wrong.exception StopIterationThe StopIteration error is raised by built-in function next() and an iterator‘s __next__() method to signal that all items are produced by the iterator.Example :Arr = [3, 1, 2]i=iter(Arr) print (i)print (i.next())print (i.next())print (i.next())print (i.next())Output : 3 1 2 Traceback (most recent call last): File "2136fa9a620e14f8436bb60d5395cc5b.py", line 8, in print i.next() StopIteration exception SyntaxErrorThe SyntaxError is raised when the parser encounters a syntax error. A syntax error may occur in an import statement or while calling the built-in functions exec() or eval(), or when reading the initial script or standard input.Example :try: print (eval('geeks for geeks'))except SyntaxError, err: print ('Syntax error %s (%s-%s): %s' % \ (err.filename, err.lineno, err.offset, err.text)) print (err)Output :Syntax error (1-9): geeks for geeks invalid syntax (, line 1) exception SystemErrorThe SystemError is raised when the interpreter finds an internal error. The associated value is a string indicating what went wrong.exception SystemExitThe SystemExit is raised when sys.exit() function is called. A call to sys.exit() is translated into an exception to execute clean-up handlers (finally clauses of try statements) and to debug a script without running the risk of losing control.exception TypeErrorTypeError is raised when an operation or function is applied to an object of inappropriate type. This exception returns a string giving details about the type mismatch.Example :arr = ('tuple', ) + 'string'print (arr)Output :Traceback (most recent call last): File "30238c120c0868eba7e13a06c0b1b1e4.py", line 1, in arr = ('tuple', ) + 'string' TypeError: can only concatenate tuple (not "str") to tuple exception UnboundLocalErrorUnboundLocalError is a subclass of NameError which is raised when a reference is made to a local variable in a function or method, but no value has been assigned to that variable.Example :def global_name_error(): print (unknown_global_name) def unbound_local(): local_val = local_val + 1 print (local_val) try: global_name_error()except NameError, err: print ('Global name error:', err) try: unbound_local()except UnboundLocalError, err: print ('Local name error:', err)Output :Global name error: global name 'unknown_global_name' is not defined Local name error: local variable 'local_val' referenced before assignment exception UnicodeErrorThis exception is a subclass of ValueError. UnicodeError is raised when a Unicode-related encoding or decoding error occurs.exception ValueErrorA ValueError is raised when a built-in operation or function receives an argument that has the right type but an invalid value.Example :print (int('a'))Output :Traceback (most recent call last): File "44f00efda935715a3c5468d899080381.py", line 1, in print int('a') ValueError: invalid literal for int() with base 10: 'a' exception ZeroDivisionErrorA ZeroDivisionError is raised when the second argument of a division or modulo operation is zero. This exception returns a string indicating the type of the operands and the operation.Example :print (1/0)Output :Traceback (most recent call last): File "c31d9626b41e53d170a78eac7d98cb85.py", line 1, in print 1/0 ZeroDivisionError: integer division or modulo by zero exception AssertionErrorAn AssertionError is raised when an assert statement fails.Example :assert False, 'The assertion failed' Output :Traceback (most recent call last): File "exceptions_AssertionError.py", line 12, in assert False, 'The assertion failed' AssertionError: The assertion failed Example : assert False, 'The assertion failed' Output : Traceback (most recent call last): File "exceptions_AssertionError.py", line 12, in assert False, 'The assertion failed' AssertionError: The assertion failed exception AttributeErrorAn AttributeError is raised when an attribute reference or assignment fails such as when a non-existent attribute is referenced.Example :class Attributes(object): pass object = Attributes()print (object.attribute)Output :Traceback (most recent call last): File "d912bae549a2b42953bc62da114ae7a7.py", line 5, in print object.attribute AttributeError: 'Attributes' object has no attribute 'attribute' Example : class Attributes(object): pass object = Attributes()print (object.attribute) Output : Traceback (most recent call last): File "d912bae549a2b42953bc62da114ae7a7.py", line 5, in print object.attribute AttributeError: 'Attributes' object has no attribute 'attribute' exception EOFErrorAn EOFError is raised when built-in functions like input() hits an end-of-file condition (EOF) without reading any data. The file methods like readline() return an empty string when they hit EOF.Example :while True: data = input('Enter name : ') print ('Hello ', data)Output :Enter Name :Hello Aditi Enter Name :Traceback (most recent call last): File "exceptions_EOFError.py", line 13, in data = raw_input('Enter name :') EOFError: EOF when reading a line Example : while True: data = input('Enter name : ') print ('Hello ', data) Output : Enter Name :Hello Aditi Enter Name :Traceback (most recent call last): File "exceptions_EOFError.py", line 13, in data = raw_input('Enter name :') EOFError: EOF when reading a line exception FloatingPointErrorA FloatingPointError is raised when a floating point operation fails. This exception is always defined, but can only be raised when Python is configured with the–with-fpectl option, or the WANT_SIGFPE_HANDLER symbol is defined in the pyconfig.h file.Example :import math print (math.exp(1000))Output :Traceback (most recent call last): File "", line 1, in FloatingPointError: in math_1 Example : import math print (math.exp(1000)) Output : Traceback (most recent call last): File "", line 1, in FloatingPointError: in math_1 exception GeneratorExitThis exception directly inherits from BaseException instead of Exception since it is technically not an error. A GeneratorExit exception is raised when a generator or coroutine is closed.Example :def my_generator(): try: for i in range(5): print ('Yielding', i) yield i except GeneratorExit: print ('Exiting early') g = my_generator()print (g.next())g.close() Output :Yielding 0 0 Exiting early Example : def my_generator(): try: for i in range(5): print ('Yielding', i) yield i except GeneratorExit: print ('Exiting early') g = my_generator()print (g.next())g.close() Output : Yielding 0 0 Exiting early exception ImportErrorAn ImportError is raised when the import statement is unable to load a module or when the “from list” in from ... import has a name that cannot be found.Example :import module_does_not_existOutput :Traceback (most recent call last): File "exceptions_ImportError_nomodule.py", line 12, in import module_does_not_exist ImportError: No module named module_does_not_exist Example :from exceptions import UserexceptionOutput :Traceback (most recent call last): File "exceptions_ImportError_missingname.py", line 12, in from exceptions import Userexception ImportError: cannot import name Userexception Example : import module_does_not_exist Output : Traceback (most recent call last): File "exceptions_ImportError_nomodule.py", line 12, in import module_does_not_exist ImportError: No module named module_does_not_exist Example : from exceptions import Userexception Output : Traceback (most recent call last): File "exceptions_ImportError_missingname.py", line 12, in from exceptions import Userexception ImportError: cannot import name Userexception exception ModuleNotFoundErrorThis is the subclass of ImportError which is raised by import when a module could not be found. It is also raised when None is found in sys.modules. exception IndexErrorAn IndexError is raised when a sequence is referenced which is out of range.Example :array = [ 0, 1, 2 ]print (array[3])Output :Traceback (most recent call last): File "exceptions_IndexError.py", line 13, in print array[3] IndexError: list index out of range Example : array = [ 0, 1, 2 ]print (array[3]) Output : Traceback (most recent call last): File "exceptions_IndexError.py", line 13, in print array[3] IndexError: list index out of range exception KeyErrorA KeyError is raised when a mapping key is not found in the set of existing keys.Example :array = { 'a':1, 'b':2 }print (array['c'])Output :Traceback (most recent call last): File "exceptions_KeyError.py", line 13, in print array['c'] KeyError: 'c' Example : array = { 'a':1, 'b':2 }print (array['c']) Output : Traceback (most recent call last): File "exceptions_KeyError.py", line 13, in print array['c'] KeyError: 'c' exception KeyboardInterruptThis error is raised when the user hits the interrupt key such as Control-C or Delete.Example :try: print ('Press Return or Ctrl-C:',) ignored = input()except Exception, err: print ('Caught exception:', err)except KeyboardInterrupt, err: print ('Caught KeyboardInterrupt')else: print ('No exception')Output :Press Return or Ctrl-C: ^CCaught KeyboardInterrupt Example : try: print ('Press Return or Ctrl-C:',) ignored = input()except Exception, err: print ('Caught exception:', err)except KeyboardInterrupt, err: print ('Caught KeyboardInterrupt')else: print ('No exception') Output : Press Return or Ctrl-C: ^CCaught KeyboardInterrupt exception MemoryErrorThis error is raised when an operation runs out of memory.Example :def fact(a): factors = [] for i in range(1, a+1): if a%i == 0: factors.append(i) return factors num = 600851475143print (fact(num))Output :Traceback (most recent call last): File "4af5c316c749aff128df20714536b8f3.py", line 9, in print fact(num) File "4af5c316c749aff128df20714536b8f3.py", line 3, in fact for i in range(1, a+1): MemoryError Example : def fact(a): factors = [] for i in range(1, a+1): if a%i == 0: factors.append(i) return factors num = 600851475143print (fact(num)) Output : Traceback (most recent call last): File "4af5c316c749aff128df20714536b8f3.py", line 9, in print fact(num) File "4af5c316c749aff128df20714536b8f3.py", line 3, in fact for i in range(1, a+1): MemoryError exception NameErrorThis error is raised when a local or global name is not found. For example, an unqualified variable name.Example :def func(): print ans func()Output :Traceback (most recent call last): File "cfba0a5196b05397e0a23b1b5b8c7e19.py", line 4, in func() File "cfba0a5196b05397e0a23b1b5b8c7e19.py", line 2, in func print ans NameError: global name 'ans' is not defined Example : def func(): print ans func() Output : Traceback (most recent call last): File "cfba0a5196b05397e0a23b1b5b8c7e19.py", line 4, in func() File "cfba0a5196b05397e0a23b1b5b8c7e19.py", line 2, in func print ans NameError: global name 'ans' is not defined exception NotImplementedErrorThis exception is derived from RuntimeError. Abstract methods in user defined classed should raise this exception when the derived classes override the method.Example :class BaseClass(object): """Defines the interface""" def __init__(self): super(BaseClass, self).__init__() def do_something(self): """The interface, not implemented""" raise NotImplementedError(self.__class__.__name__ + '.do_something') class SubClass(BaseClass): """Implements the interface""" def do_something(self): """really does something""" print (self.__class__.__name__ + ' doing something!') SubClass().do_something()BaseClass().do_something()Output :Traceback (most recent call last): File "b32fc445850cbc23cd2f081ba1c1d60b.py", line 16, in BaseClass().do_something() File "b32fc445850cbc23cd2f081ba1c1d60b.py", line 7, in do_something raise NotImplementedError(self.__class__.__name__ + '.do_something') NotImplementedError: BaseClass.do_something Example : class BaseClass(object): """Defines the interface""" def __init__(self): super(BaseClass, self).__init__() def do_something(self): """The interface, not implemented""" raise NotImplementedError(self.__class__.__name__ + '.do_something') class SubClass(BaseClass): """Implements the interface""" def do_something(self): """really does something""" print (self.__class__.__name__ + ' doing something!') SubClass().do_something()BaseClass().do_something() Output : Traceback (most recent call last): File "b32fc445850cbc23cd2f081ba1c1d60b.py", line 16, in BaseClass().do_something() File "b32fc445850cbc23cd2f081ba1c1d60b.py", line 7, in do_something raise NotImplementedError(self.__class__.__name__ + '.do_something') NotImplementedError: BaseClass.do_something exception OSError([arg])The OSError exception is raised when a system function returns a system-related error, including I/O failures such as “file not found” or “disk full” errors.Example :def func(): print (ans) func()Output :Traceback (most recent call last): File "442eccd7535a2704adbe372cb731fc0f.py", line 4, in print i, os.ttyname(i) OSError: [Errno 25] Inappropriate ioctl for device Example : def func(): print (ans) func() Output : Traceback (most recent call last): File "442eccd7535a2704adbe372cb731fc0f.py", line 4, in print i, os.ttyname(i) OSError: [Errno 25] Inappropriate ioctl for device exception OverflowErrorThe OverflowError is raised when the result of an arithmetic operation is out of range. Integers raise MemoryError instead of OverflowError. OverflowError is sometimes raised for integers that are outside a required range. Floating point operations are not checked because of the lack of standardization of floating point exception handling in C.Example :import sys print ('Regular integer: (maxint=%s)' % sys.maxint)try: i = sys.maxint * 3 print ('No overflow for ', type(i), 'i =', i)except OverflowError, err: print ('Overflowed at ', i, err) print()print ('Long integer:')for i in range(0, 100, 10): print ('%2d' % i, 2L ** i) print()print ('Floating point values:')try: f = 2.0**i for i in range(100): print (i, f) f = f ** 2except OverflowError, err: print ('Overflowed after ', f, err)Output :Regular integer: (maxint=9223372036854775807) No overflow for i = 27670116110564327421 Long integer: 0 1 10 1024 20 1048576 30 1073741824 40 1099511627776 50 1125899906842624 60 1152921504606846976 70 1180591620717411303424 80 1208925819614629174706176 90 1237940039285380274899124224 Floating point values: 0 1.23794003929e+27 1 1.53249554087e+54 2 2.34854258277e+108 3 5.5156522631e+216 Overflowed after 5.5156522631e+216 (34, 'Numerical result out of range') Example : import sys print ('Regular integer: (maxint=%s)' % sys.maxint)try: i = sys.maxint * 3 print ('No overflow for ', type(i), 'i =', i)except OverflowError, err: print ('Overflowed at ', i, err) print()print ('Long integer:')for i in range(0, 100, 10): print ('%2d' % i, 2L ** i) print()print ('Floating point values:')try: f = 2.0**i for i in range(100): print (i, f) f = f ** 2except OverflowError, err: print ('Overflowed after ', f, err) Output : Regular integer: (maxint=9223372036854775807) No overflow for i = 27670116110564327421 Long integer: 0 1 10 1024 20 1048576 30 1073741824 40 1099511627776 50 1125899906842624 60 1152921504606846976 70 1180591620717411303424 80 1208925819614629174706176 90 1237940039285380274899124224 Floating point values: 0 1.23794003929e+27 1 1.53249554087e+54 2 2.34854258277e+108 3 5.5156522631e+216 Overflowed after 5.5156522631e+216 (34, 'Numerical result out of range') exception RecursionErrorThe RecursionError is derived from the RuntimeError. This exception is raised when the interpreter detects that the maximum recursion depth is exceeded. exception ReferenceErrorThe ReferenceError is raised when a weak reference proxy is used to access an attribute of the referent after the garbage collection.Example :import gcimport weakref class Foo(object): def __init__(self, name): self.name = name def __del__(self): print ('(Deleting %s)' % self) obj = Foo('obj')p = weakref.proxy(obj) print ('BEFORE:', p.name)obj = Noneprint ('AFTER:', p.name)Output :BEFORE: obj (Deleting ) AFTER: Traceback (most recent call last): File "49d0c29d8fe607b862c02f4e1cb6c756.py", line 17, in print 'AFTER:', p.name ReferenceError: weakly-referenced object no longer exists Example : import gcimport weakref class Foo(object): def __init__(self, name): self.name = name def __del__(self): print ('(Deleting %s)' % self) obj = Foo('obj')p = weakref.proxy(obj) print ('BEFORE:', p.name)obj = Noneprint ('AFTER:', p.name) Output : BEFORE: obj (Deleting ) AFTER: Traceback (most recent call last): File "49d0c29d8fe607b862c02f4e1cb6c756.py", line 17, in print 'AFTER:', p.name ReferenceError: weakly-referenced object no longer exists exception RuntimeErrorThe RuntimeError is raised when no other exception applies. It returns a string indicating what precisely went wrong. exception StopIterationThe StopIteration error is raised by built-in function next() and an iterator‘s __next__() method to signal that all items are produced by the iterator.Example :Arr = [3, 1, 2]i=iter(Arr) print (i)print (i.next())print (i.next())print (i.next())print (i.next())Output : 3 1 2 Traceback (most recent call last): File "2136fa9a620e14f8436bb60d5395cc5b.py", line 8, in print i.next() StopIteration Example : Arr = [3, 1, 2]i=iter(Arr) print (i)print (i.next())print (i.next())print (i.next())print (i.next()) Output : 3 1 2 Traceback (most recent call last): File "2136fa9a620e14f8436bb60d5395cc5b.py", line 8, in print i.next() StopIteration exception SyntaxErrorThe SyntaxError is raised when the parser encounters a syntax error. A syntax error may occur in an import statement or while calling the built-in functions exec() or eval(), or when reading the initial script or standard input.Example :try: print (eval('geeks for geeks'))except SyntaxError, err: print ('Syntax error %s (%s-%s): %s' % \ (err.filename, err.lineno, err.offset, err.text)) print (err)Output :Syntax error (1-9): geeks for geeks invalid syntax (, line 1) Example : try: print (eval('geeks for geeks'))except SyntaxError, err: print ('Syntax error %s (%s-%s): %s' % \ (err.filename, err.lineno, err.offset, err.text)) print (err) Output : Syntax error (1-9): geeks for geeks invalid syntax (, line 1) exception SystemErrorThe SystemError is raised when the interpreter finds an internal error. The associated value is a string indicating what went wrong. exception SystemExitThe SystemExit is raised when sys.exit() function is called. A call to sys.exit() is translated into an exception to execute clean-up handlers (finally clauses of try statements) and to debug a script without running the risk of losing control. exception TypeErrorTypeError is raised when an operation or function is applied to an object of inappropriate type. This exception returns a string giving details about the type mismatch.Example :arr = ('tuple', ) + 'string'print (arr)Output :Traceback (most recent call last): File "30238c120c0868eba7e13a06c0b1b1e4.py", line 1, in arr = ('tuple', ) + 'string' TypeError: can only concatenate tuple (not "str") to tuple Example : arr = ('tuple', ) + 'string'print (arr) Output : Traceback (most recent call last): File "30238c120c0868eba7e13a06c0b1b1e4.py", line 1, in arr = ('tuple', ) + 'string' TypeError: can only concatenate tuple (not "str") to tuple exception UnboundLocalErrorUnboundLocalError is a subclass of NameError which is raised when a reference is made to a local variable in a function or method, but no value has been assigned to that variable.Example :def global_name_error(): print (unknown_global_name) def unbound_local(): local_val = local_val + 1 print (local_val) try: global_name_error()except NameError, err: print ('Global name error:', err) try: unbound_local()except UnboundLocalError, err: print ('Local name error:', err)Output :Global name error: global name 'unknown_global_name' is not defined Local name error: local variable 'local_val' referenced before assignment Example : def global_name_error(): print (unknown_global_name) def unbound_local(): local_val = local_val + 1 print (local_val) try: global_name_error()except NameError, err: print ('Global name error:', err) try: unbound_local()except UnboundLocalError, err: print ('Local name error:', err) Output : Global name error: global name 'unknown_global_name' is not defined Local name error: local variable 'local_val' referenced before assignment exception UnicodeErrorThis exception is a subclass of ValueError. UnicodeError is raised when a Unicode-related encoding or decoding error occurs. exception ValueErrorA ValueError is raised when a built-in operation or function receives an argument that has the right type but an invalid value.Example :print (int('a'))Output :Traceback (most recent call last): File "44f00efda935715a3c5468d899080381.py", line 1, in print int('a') ValueError: invalid literal for int() with base 10: 'a' Example : print (int('a')) Output : Traceback (most recent call last): File "44f00efda935715a3c5468d899080381.py", line 1, in print int('a') ValueError: invalid literal for int() with base 10: 'a' exception ZeroDivisionErrorA ZeroDivisionError is raised when the second argument of a division or modulo operation is zero. This exception returns a string indicating the type of the operands and the operation.Example :print (1/0)Output :Traceback (most recent call last): File "c31d9626b41e53d170a78eac7d98cb85.py", line 1, in print 1/0 ZeroDivisionError: integer division or modulo by zero Example : print (1/0) Output : Traceback (most recent call last): File "c31d9626b41e53d170a78eac7d98cb85.py", line 1, in print 1/0 ZeroDivisionError: integer division or modulo by zero This article is contributed by Aditi 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 review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. simmytarika5 Python-Library Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace()
[ { "code": null, "e": 41554, "s": 41526, "text": "\n14 Mar, 2022" }, { "code": null, "e": 41837, "s": 41554, "text": "All instances in Python must be instances of a class that derives from BaseException. Two exception classes that are not related via subclassing are never equivalent, even if they have the same name. The built-in exceptions can be generated by the interpreter or built-in functions." }, { "code": null, "e": 42010, "s": 41837, "text": "There are several built-in exceptions in Python that are raised when errors occur. These built-in exceptions can be viewed using the local() built-in functions as follows :" }, { "code": null, "e": 42040, "s": 42010, "text": ">>> locals()['__builtins__']\n" }, { "code": null, "e": 42116, "s": 42040, "text": "This returns a dictionary of built-in exceptions, functions and attributes." }, { "code": null, "e": 42129, "s": 42116, "text": "Base Classes" }, { "code": null, "e": 42208, "s": 42129, "text": "The following exceptions are used mostly as base classes for other exceptions." }, { "code": null, "e": 43965, "s": 42208, "text": "exception BaseExceptionThis is the base class for all built-in exceptions. It is not meant to be directly inherited by user-defined classes. For, user-defined classes, Exception is used. This class is responsible for creating a string representation of the exception using str() using the arguments passed. An empty string is returned if there are no arguments.args : The args are the tuple of arguments given to the exception constructor.with_traceback(tb) : This method is usually used in exception handling. This method sets tb as the new traceback for the exception and returns the exception object.Code :try:\n ...\nexcept SomeException:\n tb = sys.exc_info()[2]\n raise OtherException(...).with_traceback(tb)\nexception ExceptionThis is the base class for all built-in non-system-exiting exceptions. All user-defined exceptions should also be derived from this class.exception ArithmeticErrorThis class is the base class for those built-in exceptions that are raised for various arithmetic errors such as :OverflowErrorZeroDivisionErrorFloatingPointErrorExample :try: a = 10/0 print (a)except ArithmeticError: print (\"This statement is raising an arithmetic exception.\")else: print (\"Success.\")Output :This statement is raising an arithmetic exception.\nexception BufferErrorThis exception is raised when buffer related operations cannot be performed.exception LookupErrorThis is the base class for those exceptions that are raised when a key or index used on a mapping or sequence is invalid or not found. The exceptions raised are :KeyErrorIndexErrorExample :try: a = [1, 2, 3] print (a[3]) except LookupError: print (\"Index out of bound error.\")else: print (\"Success\") Output :Index out of bound error.\n" }, { "code": null, "e": 44686, "s": 43965, "text": "exception BaseExceptionThis is the base class for all built-in exceptions. It is not meant to be directly inherited by user-defined classes. For, user-defined classes, Exception is used. This class is responsible for creating a string representation of the exception using str() using the arguments passed. An empty string is returned if there are no arguments.args : The args are the tuple of arguments given to the exception constructor.with_traceback(tb) : This method is usually used in exception handling. This method sets tb as the new traceback for the exception and returns the exception object.Code :try:\n ...\nexcept SomeException:\n tb = sys.exc_info()[2]\n raise OtherException(...).with_traceback(tb)\n" }, { "code": null, "e": 44765, "s": 44686, "text": "args : The args are the tuple of arguments given to the exception constructor." }, { "code": null, "e": 45047, "s": 44765, "text": "with_traceback(tb) : This method is usually used in exception handling. This method sets tb as the new traceback for the exception and returns the exception object.Code :try:\n ...\nexcept SomeException:\n tb = sys.exc_info()[2]\n raise OtherException(...).with_traceback(tb)\n" }, { "code": null, "e": 45054, "s": 45047, "text": "Code :" }, { "code": null, "e": 45166, "s": 45054, "text": "try:\n ...\nexcept SomeException:\n tb = sys.exc_info()[2]\n raise OtherException(...).with_traceback(tb)\n" }, { "code": null, "e": 45324, "s": 45166, "text": "exception ExceptionThis is the base class for all built-in non-system-exiting exceptions. All user-defined exceptions should also be derived from this class." }, { "code": null, "e": 45735, "s": 45324, "text": "exception ArithmeticErrorThis class is the base class for those built-in exceptions that are raised for various arithmetic errors such as :OverflowErrorZeroDivisionErrorFloatingPointErrorExample :try: a = 10/0 print (a)except ArithmeticError: print (\"This statement is raising an arithmetic exception.\")else: print (\"Success.\")Output :This statement is raising an arithmetic exception.\n" }, { "code": null, "e": 45749, "s": 45735, "text": "OverflowError" }, { "code": null, "e": 45767, "s": 45749, "text": "ZeroDivisionError" }, { "code": null, "e": 45786, "s": 45767, "text": "FloatingPointError" }, { "code": null, "e": 45796, "s": 45786, "text": "Example :" }, { "code": "try: a = 10/0 print (a)except ArithmeticError: print (\"This statement is raising an arithmetic exception.\")else: print (\"Success.\")", "e": 45952, "s": 45796, "text": null }, { "code": null, "e": 45961, "s": 45952, "text": "Output :" }, { "code": null, "e": 46013, "s": 45961, "text": "This statement is raising an arithmetic exception.\n" }, { "code": null, "e": 46111, "s": 46013, "text": "exception BufferErrorThis exception is raised when buffer related operations cannot be performed." }, { "code": null, "e": 46484, "s": 46111, "text": "exception LookupErrorThis is the base class for those exceptions that are raised when a key or index used on a mapping or sequence is invalid or not found. The exceptions raised are :KeyErrorIndexErrorExample :try: a = [1, 2, 3] print (a[3]) except LookupError: print (\"Index out of bound error.\")else: print (\"Success\") Output :Index out of bound error.\n" }, { "code": null, "e": 46493, "s": 46484, "text": "KeyError" }, { "code": null, "e": 46504, "s": 46493, "text": "IndexError" }, { "code": null, "e": 46514, "s": 46504, "text": "Example :" }, { "code": "try: a = [1, 2, 3] print (a[3]) except LookupError: print (\"Index out of bound error.\")else: print (\"Success\") ", "e": 46643, "s": 46514, "text": null }, { "code": null, "e": 46652, "s": 46643, "text": "Output :" }, { "code": null, "e": 46679, "s": 46652, "text": "Index out of bound error.\n" }, { "code": null, "e": 46699, "s": 46679, "text": "Concrete exceptions" }, { "code": null, "e": 46768, "s": 46699, "text": "The following exceptions are the exceptions that are usually raised." }, { "code": null, "e": 58578, "s": 46768, "text": "exception AssertionErrorAn AssertionError is raised when an assert statement fails.Example :assert False, 'The assertion failed'\nOutput :Traceback (most recent call last):\n File \"exceptions_AssertionError.py\", line 12, in \n assert False, 'The assertion failed'\nAssertionError: The assertion failed\nexception AttributeErrorAn AttributeError is raised when an attribute reference or assignment fails such as when a non-existent attribute is referenced.Example :class Attributes(object): pass object = Attributes()print (object.attribute)Output :Traceback (most recent call last):\n File \"d912bae549a2b42953bc62da114ae7a7.py\", line 5, in \n print object.attribute\nAttributeError: 'Attributes' object has no attribute 'attribute'\nexception EOFErrorAn EOFError is raised when built-in functions like input() hits an end-of-file condition (EOF) without reading any data. The file methods like readline() return an empty string when they hit EOF.Example :while True: data = input('Enter name : ') print ('Hello ', data)Output :Enter Name :Hello Aditi\nEnter Name :Traceback (most recent call last):\n File \"exceptions_EOFError.py\", line 13, in \n data = raw_input('Enter name :')\nEOFError: EOF when reading a line\nexception FloatingPointErrorA FloatingPointError is raised when a floating point operation fails. This exception is always defined, but can only be raised when Python is configured with the–with-fpectl option, or the WANT_SIGFPE_HANDLER symbol is defined in the pyconfig.h file.Example :import math print (math.exp(1000))Output :Traceback (most recent call last):\n File \"\", line 1, in \nFloatingPointError: in math_1\nexception GeneratorExitThis exception directly inherits from BaseException instead of Exception since it is technically not an error. A GeneratorExit exception is raised when a generator or coroutine is closed.Example :def my_generator(): try: for i in range(5): print ('Yielding', i) yield i except GeneratorExit: print ('Exiting early') g = my_generator()print (g.next())g.close() Output :Yielding 0\n0\nExiting early\nexception ImportErrorAn ImportError is raised when the import statement is unable to load a module or when the “from list” in from ... import has a name that cannot be found.Example :import module_does_not_existOutput :Traceback (most recent call last):\n File \"exceptions_ImportError_nomodule.py\", line 12, in \n import module_does_not_exist\nImportError: No module named module_does_not_exist\n\nExample :from exceptions import UserexceptionOutput :Traceback (most recent call last):\n File \"exceptions_ImportError_missingname.py\", line 12, in \n from exceptions import Userexception\nImportError: cannot import name Userexception\n\nexception ModuleNotFoundErrorThis is the subclass of ImportError which is raised by import when a module could not be found. It is also raised when None is found in sys.modules.exception IndexErrorAn IndexError is raised when a sequence is referenced which is out of range.Example :array = [ 0, 1, 2 ]print (array[3])Output :Traceback (most recent call last):\n File \"exceptions_IndexError.py\", line 13, in \n print array[3]\nIndexError: list index out of range\nexception KeyErrorA KeyError is raised when a mapping key is not found in the set of existing keys.Example :array = { 'a':1, 'b':2 }print (array['c'])Output :Traceback (most recent call last):\n File \"exceptions_KeyError.py\", line 13, in \n print array['c']\nKeyError: 'c'\nexception KeyboardInterruptThis error is raised when the user hits the interrupt key such as Control-C or Delete.Example :try: print ('Press Return or Ctrl-C:',) ignored = input()except Exception, err: print ('Caught exception:', err)except KeyboardInterrupt, err: print ('Caught KeyboardInterrupt')else: print ('No exception')Output :Press Return or Ctrl-C: ^CCaught KeyboardInterrupt\nexception MemoryErrorThis error is raised when an operation runs out of memory.Example :def fact(a): factors = [] for i in range(1, a+1): if a%i == 0: factors.append(i) return factors num = 600851475143print (fact(num))Output :Traceback (most recent call last):\n File \"4af5c316c749aff128df20714536b8f3.py\", line 9, in \n print fact(num)\n File \"4af5c316c749aff128df20714536b8f3.py\", line 3, in fact\n for i in range(1, a+1):\nMemoryError\nexception NameErrorThis error is raised when a local or global name is not found. For example, an unqualified variable name.Example :def func(): print ans func()Output :Traceback (most recent call last):\n File \"cfba0a5196b05397e0a23b1b5b8c7e19.py\", line 4, in \n func()\n File \"cfba0a5196b05397e0a23b1b5b8c7e19.py\", line 2, in func\n print ans\nNameError: global name 'ans' is not defined\nexception NotImplementedErrorThis exception is derived from RuntimeError. Abstract methods in user defined classed should raise this exception when the derived classes override the method.Example :class BaseClass(object): \"\"\"Defines the interface\"\"\" def __init__(self): super(BaseClass, self).__init__() def do_something(self): \"\"\"The interface, not implemented\"\"\" raise NotImplementedError(self.__class__.__name__ + '.do_something') class SubClass(BaseClass): \"\"\"Implements the interface\"\"\" def do_something(self): \"\"\"really does something\"\"\" print (self.__class__.__name__ + ' doing something!') SubClass().do_something()BaseClass().do_something()Output :Traceback (most recent call last):\n File \"b32fc445850cbc23cd2f081ba1c1d60b.py\", line 16, in \n BaseClass().do_something()\n File \"b32fc445850cbc23cd2f081ba1c1d60b.py\", line 7, in do_something\n raise NotImplementedError(self.__class__.__name__ + '.do_something')\nNotImplementedError: BaseClass.do_something\nexception OSError([arg])The OSError exception is raised when a system function returns a system-related error, including I/O failures such as “file not found” or “disk full” errors.Example :def func(): print (ans) func()Output :Traceback (most recent call last):\n File \"442eccd7535a2704adbe372cb731fc0f.py\", line 4, in \n print i, os.ttyname(i)\nOSError: [Errno 25] Inappropriate ioctl for device\nexception OverflowErrorThe OverflowError is raised when the result of an arithmetic operation is out of range. Integers raise MemoryError instead of OverflowError. OverflowError is sometimes raised for integers that are outside a required range. Floating point operations are not checked because of the lack of standardization of floating point exception handling in C.Example :import sys print ('Regular integer: (maxint=%s)' % sys.maxint)try: i = sys.maxint * 3 print ('No overflow for ', type(i), 'i =', i)except OverflowError, err: print ('Overflowed at ', i, err) print()print ('Long integer:')for i in range(0, 100, 10): print ('%2d' % i, 2L ** i) print()print ('Floating point values:')try: f = 2.0**i for i in range(100): print (i, f) f = f ** 2except OverflowError, err: print ('Overflowed after ', f, err)Output :Regular integer: (maxint=9223372036854775807)\nNo overflow for i = 27670116110564327421\n\nLong integer:\n 0 1\n10 1024\n20 1048576\n30 1073741824\n40 1099511627776\n50 1125899906842624\n60 1152921504606846976\n70 1180591620717411303424\n80 1208925819614629174706176\n90 1237940039285380274899124224\n\nFloating point values:\n0 1.23794003929e+27\n1 1.53249554087e+54\n2 2.34854258277e+108\n3 5.5156522631e+216\nOverflowed after 5.5156522631e+216 (34, 'Numerical result out of range')\n\nexception RecursionErrorThe RecursionError is derived from the RuntimeError. This exception is raised when the interpreter detects that the maximum recursion depth is exceeded.exception ReferenceErrorThe ReferenceError is raised when a weak reference proxy is used to access an attribute of the referent after the garbage collection.Example :import gcimport weakref class Foo(object): def __init__(self, name): self.name = name def __del__(self): print ('(Deleting %s)' % self) obj = Foo('obj')p = weakref.proxy(obj) print ('BEFORE:', p.name)obj = Noneprint ('AFTER:', p.name)Output :BEFORE: obj\n(Deleting )\nAFTER:\n\nTraceback (most recent call last):\n File \"49d0c29d8fe607b862c02f4e1cb6c756.py\", line 17, in \n print 'AFTER:', p.name\nReferenceError: weakly-referenced object no longer exists\nexception RuntimeErrorThe RuntimeError is raised when no other exception applies. It returns a string indicating what precisely went wrong.exception StopIterationThe StopIteration error is raised by built-in function next() and an iterator‘s __next__() method to signal that all items are produced by the iterator.Example :Arr = [3, 1, 2]i=iter(Arr) print (i)print (i.next())print (i.next())print (i.next())print (i.next())Output :\n3\n1\n2\n\nTraceback (most recent call last):\n File \"2136fa9a620e14f8436bb60d5395cc5b.py\", line 8, in \n print i.next()\nStopIteration\nexception SyntaxErrorThe SyntaxError is raised when the parser encounters a syntax error. A syntax error may occur in an import statement or while calling the built-in functions exec() or eval(), or when reading the initial script or standard input.Example :try: print (eval('geeks for geeks'))except SyntaxError, err: print ('Syntax error %s (%s-%s): %s' % \\ (err.filename, err.lineno, err.offset, err.text)) print (err)Output :Syntax error (1-9): geeks for geeks\ninvalid syntax (, line 1)\nexception SystemErrorThe SystemError is raised when the interpreter finds an internal error. The associated value is a string indicating what went wrong.exception SystemExitThe SystemExit is raised when sys.exit() function is called. A call to sys.exit() is translated into an exception to execute clean-up handlers (finally clauses of try statements) and to debug a script without running the risk of losing control.exception TypeErrorTypeError is raised when an operation or function is applied to an object of inappropriate type. This exception returns a string giving details about the type mismatch.Example :arr = ('tuple', ) + 'string'print (arr)Output :Traceback (most recent call last):\n File \"30238c120c0868eba7e13a06c0b1b1e4.py\", line 1, in \n arr = ('tuple', ) + 'string'\nTypeError: can only concatenate tuple (not \"str\") to tuple\nexception UnboundLocalErrorUnboundLocalError is a subclass of NameError which is raised when a reference is made to a local variable in a function or method, but no value has been assigned to that variable.Example :def global_name_error(): print (unknown_global_name) def unbound_local(): local_val = local_val + 1 print (local_val) try: global_name_error()except NameError, err: print ('Global name error:', err) try: unbound_local()except UnboundLocalError, err: print ('Local name error:', err)Output :Global name error: global name 'unknown_global_name' is not defined\nLocal name error: local variable 'local_val' referenced before assignment\nexception UnicodeErrorThis exception is a subclass of ValueError. UnicodeError is raised when a Unicode-related encoding or decoding error occurs.exception ValueErrorA ValueError is raised when a built-in operation or function receives an argument that has the right type but an invalid value.Example :print (int('a'))Output :Traceback (most recent call last):\n File \"44f00efda935715a3c5468d899080381.py\", line 1, in \n print int('a')\nValueError: invalid literal for int() with base 10: 'a'\nexception ZeroDivisionErrorA ZeroDivisionError is raised when the second argument of a division or modulo operation is zero. This exception returns a string indicating the type of the operands and the operation.Example :print (1/0)Output :Traceback (most recent call last):\n File \"c31d9626b41e53d170a78eac7d98cb85.py\", line 1, in \n print 1/0\nZeroDivisionError: integer division or modulo by zero\n" }, { "code": null, "e": 58881, "s": 58578, "text": "exception AssertionErrorAn AssertionError is raised when an assert statement fails.Example :assert False, 'The assertion failed'\nOutput :Traceback (most recent call last):\n File \"exceptions_AssertionError.py\", line 12, in \n assert False, 'The assertion failed'\nAssertionError: The assertion failed\n" }, { "code": null, "e": 58891, "s": 58881, "text": "Example :" }, { "code": null, "e": 58929, "s": 58891, "text": "assert False, 'The assertion failed'\n" }, { "code": null, "e": 58938, "s": 58929, "text": "Output :" }, { "code": null, "e": 59104, "s": 58938, "text": "Traceback (most recent call last):\n File \"exceptions_AssertionError.py\", line 12, in \n assert False, 'The assertion failed'\nAssertionError: The assertion failed\n" }, { "code": null, "e": 59539, "s": 59104, "text": "exception AttributeErrorAn AttributeError is raised when an attribute reference or assignment fails such as when a non-existent attribute is referenced.Example :class Attributes(object): pass object = Attributes()print (object.attribute)Output :Traceback (most recent call last):\n File \"d912bae549a2b42953bc62da114ae7a7.py\", line 5, in \n print object.attribute\nAttributeError: 'Attributes' object has no attribute 'attribute'\n" }, { "code": null, "e": 59549, "s": 59539, "text": "Example :" }, { "code": "class Attributes(object): pass object = Attributes()print (object.attribute)", "e": 59630, "s": 59549, "text": null }, { "code": null, "e": 59639, "s": 59630, "text": "Output :" }, { "code": null, "e": 59825, "s": 59639, "text": "Traceback (most recent call last):\n File \"d912bae549a2b42953bc62da114ae7a7.py\", line 5, in \n print object.attribute\nAttributeError: 'Attributes' object has no attribute 'attribute'\n" }, { "code": null, "e": 60315, "s": 59825, "text": "exception EOFErrorAn EOFError is raised when built-in functions like input() hits an end-of-file condition (EOF) without reading any data. The file methods like readline() return an empty string when they hit EOF.Example :while True: data = input('Enter name : ') print ('Hello ', data)Output :Enter Name :Hello Aditi\nEnter Name :Traceback (most recent call last):\n File \"exceptions_EOFError.py\", line 13, in \n data = raw_input('Enter name :')\nEOFError: EOF when reading a line\n" }, { "code": null, "e": 60325, "s": 60315, "text": "Example :" }, { "code": "while True: data = input('Enter name : ') print ('Hello ', data)", "e": 60397, "s": 60325, "text": null }, { "code": null, "e": 60406, "s": 60397, "text": "Output :" }, { "code": null, "e": 60595, "s": 60406, "text": "Enter Name :Hello Aditi\nEnter Name :Traceback (most recent call last):\n File \"exceptions_EOFError.py\", line 13, in \n data = raw_input('Enter name :')\nEOFError: EOF when reading a line\n" }, { "code": null, "e": 61014, "s": 60595, "text": "exception FloatingPointErrorA FloatingPointError is raised when a floating point operation fails. This exception is always defined, but can only be raised when Python is configured with the–with-fpectl option, or the WANT_SIGFPE_HANDLER symbol is defined in the pyconfig.h file.Example :import math print (math.exp(1000))Output :Traceback (most recent call last):\n File \"\", line 1, in \nFloatingPointError: in math_1\n" }, { "code": null, "e": 61024, "s": 61014, "text": "Example :" }, { "code": "import math print (math.exp(1000))", "e": 61060, "s": 61024, "text": null }, { "code": null, "e": 61069, "s": 61060, "text": "Output :" }, { "code": null, "e": 61158, "s": 61069, "text": "Traceback (most recent call last):\n File \"\", line 1, in \nFloatingPointError: in math_1\n" }, { "code": null, "e": 61621, "s": 61158, "text": "exception GeneratorExitThis exception directly inherits from BaseException instead of Exception since it is technically not an error. A GeneratorExit exception is raised when a generator or coroutine is closed.Example :def my_generator(): try: for i in range(5): print ('Yielding', i) yield i except GeneratorExit: print ('Exiting early') g = my_generator()print (g.next())g.close() Output :Yielding 0\n0\nExiting early\n" }, { "code": null, "e": 61631, "s": 61621, "text": "Example :" }, { "code": "def my_generator(): try: for i in range(5): print ('Yielding', i) yield i except GeneratorExit: print ('Exiting early') g = my_generator()print (g.next())g.close() ", "e": 61840, "s": 61631, "text": null }, { "code": null, "e": 61849, "s": 61840, "text": "Output :" }, { "code": null, "e": 61877, "s": 61849, "text": "Yielding 0\n0\nExiting early\n" }, { "code": null, "e": 62512, "s": 61877, "text": "exception ImportErrorAn ImportError is raised when the import statement is unable to load a module or when the “from list” in from ... import has a name that cannot be found.Example :import module_does_not_existOutput :Traceback (most recent call last):\n File \"exceptions_ImportError_nomodule.py\", line 12, in \n import module_does_not_exist\nImportError: No module named module_does_not_exist\n\nExample :from exceptions import UserexceptionOutput :Traceback (most recent call last):\n File \"exceptions_ImportError_missingname.py\", line 12, in \n from exceptions import Userexception\nImportError: cannot import name Userexception\n\n" }, { "code": null, "e": 62522, "s": 62512, "text": "Example :" }, { "code": "import module_does_not_exist", "e": 62551, "s": 62522, "text": null }, { "code": null, "e": 62560, "s": 62551, "text": "Output :" }, { "code": null, "e": 62739, "s": 62560, "text": "Traceback (most recent call last):\n File \"exceptions_ImportError_nomodule.py\", line 12, in \n import module_does_not_exist\nImportError: No module named module_does_not_exist\n\n" }, { "code": null, "e": 62749, "s": 62739, "text": "Example :" }, { "code": "from exceptions import Userexception", "e": 62786, "s": 62749, "text": null }, { "code": null, "e": 62795, "s": 62786, "text": "Output :" }, { "code": null, "e": 62980, "s": 62795, "text": "Traceback (most recent call last):\n File \"exceptions_ImportError_missingname.py\", line 12, in \n from exceptions import Userexception\nImportError: cannot import name Userexception\n\n" }, { "code": null, "e": 63158, "s": 62980, "text": "exception ModuleNotFoundErrorThis is the subclass of ImportError which is raised by import when a module could not be found. It is also raised when None is found in sys.modules." }, { "code": null, "e": 63445, "s": 63158, "text": "exception IndexErrorAn IndexError is raised when a sequence is referenced which is out of range.Example :array = [ 0, 1, 2 ]print (array[3])Output :Traceback (most recent call last):\n File \"exceptions_IndexError.py\", line 13, in \n print array[3]\nIndexError: list index out of range\n" }, { "code": null, "e": 63455, "s": 63445, "text": "Example :" }, { "code": "array = [ 0, 1, 2 ]print (array[3])", "e": 63491, "s": 63455, "text": null }, { "code": null, "e": 63500, "s": 63491, "text": "Output :" }, { "code": null, "e": 63639, "s": 63500, "text": "Traceback (most recent call last):\n File \"exceptions_IndexError.py\", line 13, in \n print array[3]\nIndexError: list index out of range\n" }, { "code": null, "e": 63914, "s": 63639, "text": "exception KeyErrorA KeyError is raised when a mapping key is not found in the set of existing keys.Example :array = { 'a':1, 'b':2 }print (array['c'])Output :Traceback (most recent call last):\n File \"exceptions_KeyError.py\", line 13, in \n print array['c']\nKeyError: 'c'\n" }, { "code": null, "e": 63924, "s": 63914, "text": "Example :" }, { "code": "array = { 'a':1, 'b':2 }print (array['c'])", "e": 63967, "s": 63924, "text": null }, { "code": null, "e": 63976, "s": 63967, "text": "Output :" }, { "code": null, "e": 64093, "s": 63976, "text": "Traceback (most recent call last):\n File \"exceptions_KeyError.py\", line 13, in \n print array['c']\nKeyError: 'c'\n" }, { "code": null, "e": 64495, "s": 64093, "text": "exception KeyboardInterruptThis error is raised when the user hits the interrupt key such as Control-C or Delete.Example :try: print ('Press Return or Ctrl-C:',) ignored = input()except Exception, err: print ('Caught exception:', err)except KeyboardInterrupt, err: print ('Caught KeyboardInterrupt')else: print ('No exception')Output :Press Return or Ctrl-C: ^CCaught KeyboardInterrupt\n" }, { "code": null, "e": 64505, "s": 64495, "text": "Example :" }, { "code": "try: print ('Press Return or Ctrl-C:',) ignored = input()except Exception, err: print ('Caught exception:', err)except KeyboardInterrupt, err: print ('Caught KeyboardInterrupt')else: print ('No exception')", "e": 64726, "s": 64505, "text": null }, { "code": null, "e": 64735, "s": 64726, "text": "Output :" }, { "code": null, "e": 64787, "s": 64735, "text": "Press Return or Ctrl-C: ^CCaught KeyboardInterrupt\n" }, { "code": null, "e": 65259, "s": 64787, "text": "exception MemoryErrorThis error is raised when an operation runs out of memory.Example :def fact(a): factors = [] for i in range(1, a+1): if a%i == 0: factors.append(i) return factors num = 600851475143print (fact(num))Output :Traceback (most recent call last):\n File \"4af5c316c749aff128df20714536b8f3.py\", line 9, in \n print fact(num)\n File \"4af5c316c749aff128df20714536b8f3.py\", line 3, in fact\n for i in range(1, a+1):\nMemoryError\n" }, { "code": null, "e": 65269, "s": 65259, "text": "Example :" }, { "code": "def fact(a): factors = [] for i in range(1, a+1): if a%i == 0: factors.append(i) return factors num = 600851475143print (fact(num))", "e": 65430, "s": 65269, "text": null }, { "code": null, "e": 65439, "s": 65430, "text": "Output :" }, { "code": null, "e": 65655, "s": 65439, "text": "Traceback (most recent call last):\n File \"4af5c316c749aff128df20714536b8f3.py\", line 9, in \n print fact(num)\n File \"4af5c316c749aff128df20714536b8f3.py\", line 3, in fact\n for i in range(1, a+1):\nMemoryError\n" }, { "code": null, "e": 66053, "s": 65655, "text": "exception NameErrorThis error is raised when a local or global name is not found. For example, an unqualified variable name.Example :def func(): print ans func()Output :Traceback (most recent call last):\n File \"cfba0a5196b05397e0a23b1b5b8c7e19.py\", line 4, in \n func()\n File \"cfba0a5196b05397e0a23b1b5b8c7e19.py\", line 2, in func\n print ans\nNameError: global name 'ans' is not defined\n" }, { "code": null, "e": 66063, "s": 66053, "text": "Example :" }, { "code": "def func(): print ans func()", "e": 66096, "s": 66063, "text": null }, { "code": null, "e": 66105, "s": 66096, "text": "Output :" }, { "code": null, "e": 66330, "s": 66105, "text": "Traceback (most recent call last):\n File \"cfba0a5196b05397e0a23b1b5b8c7e19.py\", line 4, in \n func()\n File \"cfba0a5196b05397e0a23b1b5b8c7e19.py\", line 2, in func\n print ans\nNameError: global name 'ans' is not defined\n" }, { "code": null, "e": 67352, "s": 66330, "text": "exception NotImplementedErrorThis exception is derived from RuntimeError. Abstract methods in user defined classed should raise this exception when the derived classes override the method.Example :class BaseClass(object): \"\"\"Defines the interface\"\"\" def __init__(self): super(BaseClass, self).__init__() def do_something(self): \"\"\"The interface, not implemented\"\"\" raise NotImplementedError(self.__class__.__name__ + '.do_something') class SubClass(BaseClass): \"\"\"Implements the interface\"\"\" def do_something(self): \"\"\"really does something\"\"\" print (self.__class__.__name__ + ' doing something!') SubClass().do_something()BaseClass().do_something()Output :Traceback (most recent call last):\n File \"b32fc445850cbc23cd2f081ba1c1d60b.py\", line 16, in \n BaseClass().do_something()\n File \"b32fc445850cbc23cd2f081ba1c1d60b.py\", line 7, in do_something\n raise NotImplementedError(self.__class__.__name__ + '.do_something')\nNotImplementedError: BaseClass.do_something\n" }, { "code": null, "e": 67362, "s": 67352, "text": "Example :" }, { "code": "class BaseClass(object): \"\"\"Defines the interface\"\"\" def __init__(self): super(BaseClass, self).__init__() def do_something(self): \"\"\"The interface, not implemented\"\"\" raise NotImplementedError(self.__class__.__name__ + '.do_something') class SubClass(BaseClass): \"\"\"Implements the interface\"\"\" def do_something(self): \"\"\"really does something\"\"\" print (self.__class__.__name__ + ' doing something!') SubClass().do_something()BaseClass().do_something()", "e": 67867, "s": 67362, "text": null }, { "code": null, "e": 67876, "s": 67867, "text": "Output :" }, { "code": null, "e": 68189, "s": 67876, "text": "Traceback (most recent call last):\n File \"b32fc445850cbc23cd2f081ba1c1d60b.py\", line 16, in \n BaseClass().do_something()\n File \"b32fc445850cbc23cd2f081ba1c1d60b.py\", line 7, in do_something\n raise NotImplementedError(self.__class__.__name__ + '.do_something')\nNotImplementedError: BaseClass.do_something\n" }, { "code": null, "e": 68593, "s": 68189, "text": "exception OSError([arg])The OSError exception is raised when a system function returns a system-related error, including I/O failures such as “file not found” or “disk full” errors.Example :def func(): print (ans) func()Output :Traceback (most recent call last):\n File \"442eccd7535a2704adbe372cb731fc0f.py\", line 4, in \n print i, os.ttyname(i)\nOSError: [Errno 25] Inappropriate ioctl for device\n" }, { "code": null, "e": 68603, "s": 68593, "text": "Example :" }, { "code": "def func(): print (ans) func()", "e": 68638, "s": 68603, "text": null }, { "code": null, "e": 68647, "s": 68638, "text": "Output :" }, { "code": null, "e": 68819, "s": 68647, "text": "Traceback (most recent call last):\n File \"442eccd7535a2704adbe372cb731fc0f.py\", line 4, in \n print i, os.ttyname(i)\nOSError: [Errno 25] Inappropriate ioctl for device\n" }, { "code": null, "e": 70150, "s": 68819, "text": "exception OverflowErrorThe OverflowError is raised when the result of an arithmetic operation is out of range. Integers raise MemoryError instead of OverflowError. OverflowError is sometimes raised for integers that are outside a required range. Floating point operations are not checked because of the lack of standardization of floating point exception handling in C.Example :import sys print ('Regular integer: (maxint=%s)' % sys.maxint)try: i = sys.maxint * 3 print ('No overflow for ', type(i), 'i =', i)except OverflowError, err: print ('Overflowed at ', i, err) print()print ('Long integer:')for i in range(0, 100, 10): print ('%2d' % i, 2L ** i) print()print ('Floating point values:')try: f = 2.0**i for i in range(100): print (i, f) f = f ** 2except OverflowError, err: print ('Overflowed after ', f, err)Output :Regular integer: (maxint=9223372036854775807)\nNo overflow for i = 27670116110564327421\n\nLong integer:\n 0 1\n10 1024\n20 1048576\n30 1073741824\n40 1099511627776\n50 1125899906842624\n60 1152921504606846976\n70 1180591620717411303424\n80 1208925819614629174706176\n90 1237940039285380274899124224\n\nFloating point values:\n0 1.23794003929e+27\n1 1.53249554087e+54\n2 2.34854258277e+108\n3 5.5156522631e+216\nOverflowed after 5.5156522631e+216 (34, 'Numerical result out of range')\n\n" }, { "code": null, "e": 70160, "s": 70150, "text": "Example :" }, { "code": "import sys print ('Regular integer: (maxint=%s)' % sys.maxint)try: i = sys.maxint * 3 print ('No overflow for ', type(i), 'i =', i)except OverflowError, err: print ('Overflowed at ', i, err) print()print ('Long integer:')for i in range(0, 100, 10): print ('%2d' % i, 2L ** i) print()print ('Floating point values:')try: f = 2.0**i for i in range(100): print (i, f) f = f ** 2except OverflowError, err: print ('Overflowed after ', f, err)", "e": 70636, "s": 70160, "text": null }, { "code": null, "e": 70645, "s": 70636, "text": "Output :" }, { "code": null, "e": 71115, "s": 70645, "text": "Regular integer: (maxint=9223372036854775807)\nNo overflow for i = 27670116110564327421\n\nLong integer:\n 0 1\n10 1024\n20 1048576\n30 1073741824\n40 1099511627776\n50 1125899906842624\n60 1152921504606846976\n70 1180591620717411303424\n80 1208925819614629174706176\n90 1237940039285380274899124224\n\nFloating point values:\n0 1.23794003929e+27\n1 1.53249554087e+54\n2 2.34854258277e+108\n3 5.5156522631e+216\nOverflowed after 5.5156522631e+216 (34, 'Numerical result out of range')\n\n" }, { "code": null, "e": 71292, "s": 71115, "text": "exception RecursionErrorThe RecursionError is derived from the RuntimeError. This exception is raised when the interpreter detects that the maximum recursion depth is exceeded." }, { "code": null, "e": 71943, "s": 71292, "text": "exception ReferenceErrorThe ReferenceError is raised when a weak reference proxy is used to access an attribute of the referent after the garbage collection.Example :import gcimport weakref class Foo(object): def __init__(self, name): self.name = name def __del__(self): print ('(Deleting %s)' % self) obj = Foo('obj')p = weakref.proxy(obj) print ('BEFORE:', p.name)obj = Noneprint ('AFTER:', p.name)Output :BEFORE: obj\n(Deleting )\nAFTER:\n\nTraceback (most recent call last):\n File \"49d0c29d8fe607b862c02f4e1cb6c756.py\", line 17, in \n print 'AFTER:', p.name\nReferenceError: weakly-referenced object no longer exists\n" }, { "code": null, "e": 71953, "s": 71943, "text": "Example :" }, { "code": "import gcimport weakref class Foo(object): def __init__(self, name): self.name = name def __del__(self): print ('(Deleting %s)' % self) obj = Foo('obj')p = weakref.proxy(obj) print ('BEFORE:', p.name)obj = Noneprint ('AFTER:', p.name)", "e": 72219, "s": 71953, "text": null }, { "code": null, "e": 72228, "s": 72219, "text": "Output :" }, { "code": null, "e": 72440, "s": 72228, "text": "BEFORE: obj\n(Deleting )\nAFTER:\n\nTraceback (most recent call last):\n File \"49d0c29d8fe607b862c02f4e1cb6c756.py\", line 17, in \n print 'AFTER:', p.name\nReferenceError: weakly-referenced object no longer exists\n" }, { "code": null, "e": 72580, "s": 72440, "text": "exception RuntimeErrorThe RuntimeError is raised when no other exception applies. It returns a string indicating what precisely went wrong." }, { "code": null, "e": 73008, "s": 72580, "text": "exception StopIterationThe StopIteration error is raised by built-in function next() and an iterator‘s __next__() method to signal that all items are produced by the iterator.Example :Arr = [3, 1, 2]i=iter(Arr) print (i)print (i.next())print (i.next())print (i.next())print (i.next())Output :\n3\n1\n2\n\nTraceback (most recent call last):\n File \"2136fa9a620e14f8436bb60d5395cc5b.py\", line 8, in \n print i.next()\nStopIteration\n" }, { "code": null, "e": 73018, "s": 73008, "text": "Example :" }, { "code": "Arr = [3, 1, 2]i=iter(Arr) print (i)print (i.next())print (i.next())print (i.next())print (i.next())", "e": 73120, "s": 73018, "text": null }, { "code": null, "e": 73129, "s": 73120, "text": "Output :" }, { "code": null, "e": 73264, "s": 73129, "text": "\n3\n1\n2\n\nTraceback (most recent call last):\n File \"2136fa9a620e14f8436bb60d5395cc5b.py\", line 8, in \n print i.next()\nStopIteration\n" }, { "code": null, "e": 73773, "s": 73264, "text": "exception SyntaxErrorThe SyntaxError is raised when the parser encounters a syntax error. A syntax error may occur in an import statement or while calling the built-in functions exec() or eval(), or when reading the initial script or standard input.Example :try: print (eval('geeks for geeks'))except SyntaxError, err: print ('Syntax error %s (%s-%s): %s' % \\ (err.filename, err.lineno, err.offset, err.text)) print (err)Output :Syntax error (1-9): geeks for geeks\ninvalid syntax (, line 1)\n" }, { "code": null, "e": 73783, "s": 73773, "text": "Example :" }, { "code": "try: print (eval('geeks for geeks'))except SyntaxError, err: print ('Syntax error %s (%s-%s): %s' % \\ (err.filename, err.lineno, err.offset, err.text)) print (err)", "e": 73963, "s": 73783, "text": null }, { "code": null, "e": 73972, "s": 73963, "text": "Output :" }, { "code": null, "e": 74036, "s": 73972, "text": "Syntax error (1-9): geeks for geeks\ninvalid syntax (, line 1)\n" }, { "code": null, "e": 74190, "s": 74036, "text": "exception SystemErrorThe SystemError is raised when the interpreter finds an internal error. The associated value is a string indicating what went wrong." }, { "code": null, "e": 74455, "s": 74190, "text": "exception SystemExitThe SystemExit is raised when sys.exit() function is called. A call to sys.exit() is translated into an exception to execute clean-up handlers (finally clauses of try statements) and to debug a script without running the risk of losing control." }, { "code": null, "e": 74884, "s": 74455, "text": "exception TypeErrorTypeError is raised when an operation or function is applied to an object of inappropriate type. This exception returns a string giving details about the type mismatch.Example :arr = ('tuple', ) + 'string'print (arr)Output :Traceback (most recent call last):\n File \"30238c120c0868eba7e13a06c0b1b1e4.py\", line 1, in \n arr = ('tuple', ) + 'string'\nTypeError: can only concatenate tuple (not \"str\") to tuple\n" }, { "code": null, "e": 74894, "s": 74884, "text": "Example :" }, { "code": "arr = ('tuple', ) + 'string'print (arr)", "e": 74934, "s": 74894, "text": null }, { "code": null, "e": 74943, "s": 74934, "text": "Output :" }, { "code": null, "e": 75129, "s": 74943, "text": "Traceback (most recent call last):\n File \"30238c120c0868eba7e13a06c0b1b1e4.py\", line 1, in \n arr = ('tuple', ) + 'string'\nTypeError: can only concatenate tuple (not \"str\") to tuple\n" }, { "code": null, "e": 75801, "s": 75129, "text": "exception UnboundLocalErrorUnboundLocalError is a subclass of NameError which is raised when a reference is made to a local variable in a function or method, but no value has been assigned to that variable.Example :def global_name_error(): print (unknown_global_name) def unbound_local(): local_val = local_val + 1 print (local_val) try: global_name_error()except NameError, err: print ('Global name error:', err) try: unbound_local()except UnboundLocalError, err: print ('Local name error:', err)Output :Global name error: global name 'unknown_global_name' is not defined\nLocal name error: local variable 'local_val' referenced before assignment\n" }, { "code": null, "e": 75811, "s": 75801, "text": "Example :" }, { "code": "def global_name_error(): print (unknown_global_name) def unbound_local(): local_val = local_val + 1 print (local_val) try: global_name_error()except NameError, err: print ('Global name error:', err) try: unbound_local()except UnboundLocalError, err: print ('Local name error:', err)", "e": 76118, "s": 75811, "text": null }, { "code": null, "e": 76127, "s": 76118, "text": "Output :" }, { "code": null, "e": 76270, "s": 76127, "text": "Global name error: global name 'unknown_global_name' is not defined\nLocal name error: local variable 'local_val' referenced before assignment\n" }, { "code": null, "e": 76417, "s": 76270, "text": "exception UnicodeErrorThis exception is a subclass of ValueError. UnicodeError is raised when a Unicode-related encoding or decoding error occurs." }, { "code": null, "e": 76766, "s": 76417, "text": "exception ValueErrorA ValueError is raised when a built-in operation or function receives an argument that has the right type but an invalid value.Example :print (int('a'))Output :Traceback (most recent call last):\n File \"44f00efda935715a3c5468d899080381.py\", line 1, in \n print int('a')\nValueError: invalid literal for int() with base 10: 'a'\n" }, { "code": null, "e": 76776, "s": 76766, "text": "Example :" }, { "code": "print (int('a'))", "e": 76793, "s": 76776, "text": null }, { "code": null, "e": 76802, "s": 76793, "text": "Output :" }, { "code": null, "e": 76971, "s": 76802, "text": "Traceback (most recent call last):\n File \"44f00efda935715a3c5468d899080381.py\", line 1, in \n print int('a')\nValueError: invalid literal for int() with base 10: 'a'\n" }, { "code": null, "e": 77372, "s": 76971, "text": "exception ZeroDivisionErrorA ZeroDivisionError is raised when the second argument of a division or modulo operation is zero. This exception returns a string indicating the type of the operands and the operation.Example :print (1/0)Output :Traceback (most recent call last):\n File \"c31d9626b41e53d170a78eac7d98cb85.py\", line 1, in \n print 1/0\nZeroDivisionError: integer division or modulo by zero\n" }, { "code": null, "e": 77382, "s": 77372, "text": "Example :" }, { "code": "print (1/0)", "e": 77394, "s": 77382, "text": null }, { "code": null, "e": 77403, "s": 77394, "text": "Output :" }, { "code": null, "e": 77565, "s": 77403, "text": "Traceback (most recent call last):\n File \"c31d9626b41e53d170a78eac7d98cb85.py\", line 1, in \n print 1/0\nZeroDivisionError: integer division or modulo by zero\n" }, { "code": null, "e": 77860, "s": 77565, "text": "This article is contributed by Aditi 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 review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 77985, "s": 77860, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 77998, "s": 77985, "text": "simmytarika5" }, { "code": null, "e": 78013, "s": 77998, "text": "Python-Library" }, { "code": null, "e": 78020, "s": 78013, "text": "Python" }, { "code": null, "e": 78118, "s": 78020, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 78146, "s": 78118, "text": "Read JSON file using Python" }, { "code": null, "e": 78196, "s": 78146, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 78218, "s": 78196, "text": "Python map() function" }, { "code": null, "e": 78262, "s": 78218, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 78297, "s": 78262, "text": "Read a file line by line in Python" }, { "code": null, "e": 78319, "s": 78297, "text": "Enumerate() in Python" }, { "code": null, "e": 78351, "s": 78319, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 78381, "s": 78351, "text": "Iterate over a list in Python" }, { "code": null, "e": 78423, "s": 78381, "text": "Different ways to create Pandas Dataframe" } ]
Scala List dropRight() method with example - GeeksforGeeks
26 Jul, 2019 The dropRight() method is utilized to find all the elements of the list except the last n elements. Method Definition: def dropRight(n: Int): List[A] Return Type: It returns all the elements of the list except the last n elements. Example #1: // Scala program of dropRight()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list val m1 = List(1, 1, 3, 3, 3, 5, 4, 5, 2) // Applying dropRight method val res = m1.dropRight(3) // Displays output println(res) }} List(1, 1, 3, 3, 3, 5) Example #2: // Scala program of dropRight()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list val m1 = List(1, 1, 3, 3, 3, 5, 4, 5, 2) // Applying dropRight method val res = m1.dropRight(10) // Displays output println(res) }} List() 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 Tutorial – Learn Scala with Step By Step Guide Type Casting in Scala Scala Lists Class and Object in Scala Break statement in Scala Scala String substring() method with example Lambda Expression in Scala Scala String replace() method with example Operators in Scala
[ { "code": null, "e": 23747, "s": 23719, "text": "\n26 Jul, 2019" }, { "code": null, "e": 23847, "s": 23747, "text": "The dropRight() method is utilized to find all the elements of the list except the last n elements." }, { "code": null, "e": 23897, "s": 23847, "text": "Method Definition: def dropRight(n: Int): List[A]" }, { "code": null, "e": 23978, "s": 23897, "text": "Return Type: It returns all the elements of the list except the last n elements." }, { "code": null, "e": 23990, "s": 23978, "text": "Example #1:" }, { "code": "// Scala program of dropRight()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list val m1 = List(1, 1, 3, 3, 3, 5, 4, 5, 2) // Applying dropRight method val res = m1.dropRight(3) // Displays output println(res) }}", "e": 24347, "s": 23990, "text": null }, { "code": null, "e": 24371, "s": 24347, "text": "List(1, 1, 3, 3, 3, 5)\n" }, { "code": null, "e": 24383, "s": 24371, "text": "Example #2:" }, { "code": "// Scala program of dropRight()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list val m1 = List(1, 1, 3, 3, 3, 5, 4, 5, 2) // Applying dropRight method val res = m1.dropRight(10) // Displays output println(res) }}", "e": 24741, "s": 24383, "text": null }, { "code": null, "e": 24749, "s": 24741, "text": "List()\n" }, { "code": null, "e": 24755, "s": 24749, "text": "Scala" }, { "code": null, "e": 24766, "s": 24755, "text": "Scala-list" }, { "code": null, "e": 24779, "s": 24766, "text": "Scala-Method" }, { "code": null, "e": 24785, "s": 24779, "text": "Scala" }, { "code": null, "e": 24883, "s": 24785, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24892, "s": 24883, "text": "Comments" }, { "code": null, "e": 24905, "s": 24892, "text": "Old Comments" }, { "code": null, "e": 24958, "s": 24905, "text": "Scala Tutorial – Learn Scala with Step By Step Guide" }, { "code": null, "e": 24980, "s": 24958, "text": "Type Casting in Scala" }, { "code": null, "e": 24992, "s": 24980, "text": "Scala Lists" }, { "code": null, "e": 25018, "s": 24992, "text": "Class and Object in Scala" }, { "code": null, "e": 25043, "s": 25018, "text": "Break statement in Scala" }, { "code": null, "e": 25088, "s": 25043, "text": "Scala String substring() method with example" }, { "code": null, "e": 25115, "s": 25088, "text": "Lambda Expression in Scala" }, { "code": null, "e": 25158, "s": 25115, "text": "Scala String replace() method with example" } ]
HTML Parser in C/C++ - GeeksforGeeks
14 Jul, 2021 HTML Parser is a program/software by which useful statements can be extracted, leaving html tags (like <h1>, <span>, <p> etc) behind. Examples: Input: <h1>Geeks for Geeks</h1>Output: Geeks for Geeks Explanation- <h1> and </h1> are opening and closing heading tags, so they got parsed leaving “Geeks for Geeks” as the output. Input: <p> Geeks for Geeks</p>Output: Geeks for GeeksExplanation- <p> and </p> are opening and closing paragraph tags, so they get parsed and the parser ignores space character, leaving “Geeks for Geeks” as the output. Approach: Let the input string be S of size N. Follow the steps below to solve the problem: Declare two variables, start and end to point to the starting and ending point of the statement. Traverse the string, S uses the variable i and if S[i] is equal to ‘>’, update the start variable to i+1 and break out of the loop. Remove the blank spaces from the start by running a loop while S[start] is equal to ‘ ‘, and increment the start variable by 1 in each iteration. Again, traverse the string, S from start using the variable i and if S[i] is equal to ‘<‘, update the end to i-1 and break out of the loop. Run a loop and print the characters of the string S in the range [start, end]. Below is the implementation of the above approach in C language: // C program for the above approach #include <stdbool.h>#include <stdio.h>#include <string.h> // Function to parse the HTML codevoid parser(char* S){ // Store the length of the // input string int n = strlen(S); int start = 0, end = 0; int i, j; // Traverse the string for (i = 0; i < n; i++) { // If S[i] is '>', update // start to i+1 and break if (S[i] == '>') { start = i + 1; break; } } // Remove the blank spaces while (S[start] == ' ') { start++; } // Traverse the string for (i = start; i < n; i++) { // If S[i] is '<', update // end to i-1 and break if (S[i] == '<') { end = i - 1; break; } } // Print the characters in the // range [start, end] for (j = start; j <= end; j++) { printf("%c", S[j]); } printf("\n");} // Driver Codeint main(){ // Given Input char input1[] = "<h1>This is a statement</h1>"; char input2[] = "<h1> This is a statement with some spaces</h1>"; char input3[] = "<p> This is a statement with some @ #$ ., / special characters</p> "; printf("Parsed Statements:\n"); // Function Call parser(input1); parser(input2); parser(input3); return 0;} Parsed Statements: This is a statement This is a statement with some spaces This is a statement with some @ #$ ., / special characters Below is the implementation of the above approach in C++ language: // C++ program for the// above approach#include <bits/stdc++.h>using namespace std; // Function to parse the// HTML codevoid parser(char* S){ // Store the length of the // input string int n = strlen(S); int start = 0, end = 0; // Traverse the string for (int i = 0; i < n; i++) { // If S[i] is '>', update // start to i+1 and break if (S[i] == '>') { start = i + 1; break; } } // Remove the blank space while (S[start] == ' ') { start++; } // Traverse the string for (int i = start; i < n; i++) { // If S[i] is '<', update // end to i-1 and break if (S[i] == '<') { end = i - 1; break; } } // Print the characters in the // range [start, end] for (int j = start; j <= end; j++) { cout << S[j]; } cout << endl;} // Driver Codeint main(){ // Given Input char input1[] = "<h1>This is a statement</h1>"; char input2[] = "<h1> This is a statement with some spaces</h1>"; char input3[] = "<p> This is a statement with some @ #$ ., / special characters</p> "; cout << "Parsed Statements:\n"; // Function Call parser(input1); parser(input2); parser(input3); return 0;} Parsed Statements: This is a statement This is a statement with some spaces This is a statement with some @ #$ ., / special characters Time Complexity: O(N)Auxiliary Space: O(1) Note: This program parses only one statement at a time. C Programs C++ Programs HTML HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C Program to read contents of Whole File Producer Consumer Problem in C C program to find the length of a string Exit codes in C/C++ with Examples Difference between break and continue statement in C C++ Program for QuickSort C++ program for hashing with chaining Sorting a Map by value in C++ STL cin in C++ delete keyword in C++
[ { "code": null, "e": 24539, "s": 24511, "text": "\n14 Jul, 2021" }, { "code": null, "e": 24674, "s": 24539, "text": "HTML Parser is a program/software by which useful statements can be extracted, leaving html tags (like <h1>, <span>, <p> etc) behind. " }, { "code": null, "e": 24684, "s": 24674, "text": "Examples:" }, { "code": null, "e": 24865, "s": 24684, "text": "Input: <h1>Geeks for Geeks</h1>Output: Geeks for Geeks Explanation- <h1> and </h1> are opening and closing heading tags, so they got parsed leaving “Geeks for Geeks” as the output." }, { "code": null, "e": 25087, "s": 24865, "text": "Input: <p> Geeks for Geeks</p>Output: Geeks for GeeksExplanation- <p> and </p> are opening and closing paragraph tags, so they get parsed and the parser ignores space character, leaving “Geeks for Geeks” as the output." }, { "code": null, "e": 25179, "s": 25087, "text": "Approach: Let the input string be S of size N. Follow the steps below to solve the problem:" }, { "code": null, "e": 25276, "s": 25179, "text": "Declare two variables, start and end to point to the starting and ending point of the statement." }, { "code": null, "e": 25408, "s": 25276, "text": "Traverse the string, S uses the variable i and if S[i] is equal to ‘>’, update the start variable to i+1 and break out of the loop." }, { "code": null, "e": 25554, "s": 25408, "text": "Remove the blank spaces from the start by running a loop while S[start] is equal to ‘ ‘, and increment the start variable by 1 in each iteration." }, { "code": null, "e": 25694, "s": 25554, "text": "Again, traverse the string, S from start using the variable i and if S[i] is equal to ‘<‘, update the end to i-1 and break out of the loop." }, { "code": null, "e": 25773, "s": 25694, "text": "Run a loop and print the characters of the string S in the range [start, end]." }, { "code": null, "e": 25838, "s": 25773, "text": "Below is the implementation of the above approach in C language:" }, { "code": "// C program for the above approach #include <stdbool.h>#include <stdio.h>#include <string.h> // Function to parse the HTML codevoid parser(char* S){ // Store the length of the // input string int n = strlen(S); int start = 0, end = 0; int i, j; // Traverse the string for (i = 0; i < n; i++) { // If S[i] is '>', update // start to i+1 and break if (S[i] == '>') { start = i + 1; break; } } // Remove the blank spaces while (S[start] == ' ') { start++; } // Traverse the string for (i = start; i < n; i++) { // If S[i] is '<', update // end to i-1 and break if (S[i] == '<') { end = i - 1; break; } } // Print the characters in the // range [start, end] for (j = start; j <= end; j++) { printf(\"%c\", S[j]); } printf(\"\\n\");} // Driver Codeint main(){ // Given Input char input1[] = \"<h1>This is a statement</h1>\"; char input2[] = \"<h1> This is a statement with some spaces</h1>\"; char input3[] = \"<p> This is a statement with some @ #$ ., / special characters</p> \"; printf(\"Parsed Statements:\\n\"); // Function Call parser(input1); parser(input2); parser(input3); return 0;}", "e": 27149, "s": 25838, "text": null }, { "code": null, "e": 27285, "s": 27149, "text": "Parsed Statements:\nThis is a statement\nThis is a statement with some spaces\nThis is a statement with some @ #$ ., / special characters\n" }, { "code": null, "e": 27352, "s": 27285, "text": "Below is the implementation of the above approach in C++ language:" }, { "code": "// C++ program for the// above approach#include <bits/stdc++.h>using namespace std; // Function to parse the// HTML codevoid parser(char* S){ // Store the length of the // input string int n = strlen(S); int start = 0, end = 0; // Traverse the string for (int i = 0; i < n; i++) { // If S[i] is '>', update // start to i+1 and break if (S[i] == '>') { start = i + 1; break; } } // Remove the blank space while (S[start] == ' ') { start++; } // Traverse the string for (int i = start; i < n; i++) { // If S[i] is '<', update // end to i-1 and break if (S[i] == '<') { end = i - 1; break; } } // Print the characters in the // range [start, end] for (int j = start; j <= end; j++) { cout << S[j]; } cout << endl;} // Driver Codeint main(){ // Given Input char input1[] = \"<h1>This is a statement</h1>\"; char input2[] = \"<h1> This is a statement with some spaces</h1>\"; char input3[] = \"<p> This is a statement with some @ #$ ., / special characters</p> \"; cout << \"Parsed Statements:\\n\"; // Function Call parser(input1); parser(input2); parser(input3); return 0;}", "e": 28645, "s": 27352, "text": null }, { "code": null, "e": 28782, "s": 28645, "text": "Parsed Statements:\nThis is a statement\nThis is a statement with some spaces\nThis is a statement with some @ #$ ., / special characters\n" }, { "code": null, "e": 28825, "s": 28782, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 28881, "s": 28825, "text": "Note: This program parses only one statement at a time." }, { "code": null, "e": 28892, "s": 28881, "text": "C Programs" }, { "code": null, "e": 28905, "s": 28892, "text": "C++ Programs" }, { "code": null, "e": 28910, "s": 28905, "text": "HTML" }, { "code": null, "e": 28915, "s": 28910, "text": "HTML" }, { "code": null, "e": 29013, "s": 28915, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29022, "s": 29013, "text": "Comments" }, { "code": null, "e": 29035, "s": 29022, "text": "Old Comments" }, { "code": null, "e": 29076, "s": 29035, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 29107, "s": 29076, "text": "Producer Consumer Problem in C" }, { "code": null, "e": 29148, "s": 29107, "text": "C program to find the length of a string" }, { "code": null, "e": 29182, "s": 29148, "text": "Exit codes in C/C++ with Examples" }, { "code": null, "e": 29235, "s": 29182, "text": "Difference between break and continue statement in C" }, { "code": null, "e": 29261, "s": 29235, "text": "C++ Program for QuickSort" }, { "code": null, "e": 29299, "s": 29261, "text": "C++ program for hashing with chaining" }, { "code": null, "e": 29333, "s": 29299, "text": "Sorting a Map by value in C++ STL" }, { "code": null, "e": 29344, "s": 29333, "text": "cin in C++" } ]
Building a streaming pipeline using SQL with Google Data Flow | by Tuan Nguyen | Towards Data Science
Real-time data is data that is delivered the moment it is collected. This enables you to process and query those data to inform decisions or fuel data applications. There are some terminologies out there, such as real-time, near real-time, and batch. The difference between these three is not clearly defined, but you can roughly use the following guideline (IMHO). Real-time: sub-second/minute latency, worst accuracy. Near real-time: 1–5 minutes latency, better accuracy. Batch: anywhere above 5 minutes latency from 1 hour, 1 day to 1 week, best accuracy. Unless you need to process financial transactions, most streaming analytics use cases will fall under the near real-time category. For example, if you run a promotional campaign, you will need to send a message to a customer if their purchase meets certain standards. In this case, you can get away with doing so a couple of minutes after the purchase happen. Having real-time access to data is beneficial to many businesses as data is the lifeblood of many nowadays. Instead of relying on outdated, slow-to-update information, you can access up-to-date information for better decision-making. Most modern data warehouses and BI tools support streaming insert and query, so your company can access real-time metrics. Better yet, many of the decisions can be made autonomously using a streaming pipeline and some business logic. For example, you can notify customers after adding a product to carts but not checked out in the last 30 minutes. Real-time data used to be accessible to well-funded tech startups or corporate with million of dollars budgets. You would typically need a team of data engineers to build and maintain streaming pipelines too. However, with the advancement of cloud computing and the open-source data community, many of these capabilities are opening up for us all. Say you are an e-commerce company, and there is a marketing campaign to reward any customers who spent more than $5,000 and make a new purchase. You want to send an app push to congratulate these customers when they make a new purchase. You also need a real-time dashboard to keep track of how the campaign is going. The development team said they are at capacity and won’t help you with this campaign, so you are on your own. A task like this would typically take two sources of data and combine them. You would need to query your data warehouse to get all customers who spent more than $5,000. You would also need real-time data to capture new transactions within today. This is also known as the lambda architecture, where you have a batch layer that runs at least once a day and a speed layer streaming data in real-time. Assuming that your development team is nice enough to build a streaming source of your order and customer data (this is actually a prerequisite), our architecture would look as follow. In this architecture, new orders (within the day) are streamed to Pub/Sub. The pipeline created by Dataflow will check every new purchase to see if the customer is within the list of customers who spent more than $5,000. The results will be written into two destinations. Results to BigQuery will be used for real-time dashboard with a visualization tool. Results written to Pub/Sub will be used to send push notifications to the winning customer. Here are some prerequisites to getting started: A Google Cloud account An active billing account (you can sign up for the $300 free trial) A Google Cloud project github.com Clone this repo to the Cloudshell by running: # Clone the repo locallygit clone https://github.com/tuanchris/dataflow-sqlcd dataflow-sql# Install requirementspip3 install -r requirements.txt We need two data sources for our streaming pipelines as follow: 1. A BigQuery Batch source — all orders and customers information and is updated daily # This script will create 100 customers with 1000 orderspython3 generate_data.py batch \ --customer_count=100 \ --order_count=1000 \ --project_id=$DEVSHELL_PROJECT_ID# Replace the project_id varaible if you are running locally Select “Authorize” when Cloud shell asks to authenticate your requests. 2. A Pub/Sub topic called orders — a stream of order data that arrives via a subscription to the Pub/Sub topic # Create a Pub/Sub topicgcloud pubsub topics create orders# Generate a stream of order data to Pub/Subpython3 generate_data.py stream \ --customer_range 100 \ --project_id $DEVSHELL_PROJECT_ID To add the Pub/Sub source to BigQuery, follow the following steps: Change the query engine in BigQuery to Cloud Dataflow Engine Change the query engine in BigQuery to Cloud Dataflow Engine 2. From the BigQuery UI, select Add Data and choose Cloud Dataflow sources 3. Add the Pub/Sub topic source 4. Add a schema for the orders topic [ { "name": "event_timestamp", "description": "", "mode": "REQUIRED", "type": "TIMESTAMP" }, { "name": "customer_id", "description": "", "mode": "NULLABLE", "type": "INT64" }, { "name": "amount", "description": "", "mode": "NULLABLE", "type": "FLOAT64" }, { "name": "order_status", "description": "", "mode": "NULLABLE", "type": "STRING" }, { "name": "order_datetime", "description": "", "mode": "NULLABLE", "type": "STRING" }] Write a SQL query Here is a simple SQL query that will answer our business question. WITH eligible_customers AS ( SELECT o.customer_id, SUM(o.amount) AS total_spent FROM bigquery.table.`demobox-313313`.ecommerce.orders o WHERE o.order_status = 'Closed' GROUP BY 1 HAVING total_spent >= 5000)SELECT o.*, ec.total_spentFROM pubsub.topic.`demobox-313313`.orders oINNER JOIN eligible_customers ecUSING (customer_id)WHERE o.order_status != 'Cancelled' We first select the data from the orders table, filter out only “Closed” orders, then group by the customer, calculate total spending, and filter out customers who purchased $5,000 or more. We then inner join the list of eligible customers to any new transactions, filtering out transactions with Cancelled status. You can see that it is easy writing SQL like above, and any Analyst can do it. Be sure to substitute your project_id when trying this out. With the query ready and validate, you can select Create Dataflow job from the BigQuery UI. Configure two destinations as per the image below. You can keep other values to the default one. After creating the Dataflow job, you can see the result below. Follow the link in Job ID to view your Dataflow job and its status. It can take 3–5 minutes for the Dataflow job to startup. After that, you should be able to the pipeline as follow. After the Dataflow job is successfully startup and running, you can go to BigQuery and Pub/Sub to verify that our pipeline is working as intended. With the running Dataflow job, we can see all sorts of job metrics about our pipeline. For example, it takes 11 seconds for the data to be processed by Dataflow, not bad! Be sure to cancel the Dataflow pipeline, delete the Pub/Sub topic, and delete the BigQuery dataset to avoid incurring costs. Real-time data used to be expensive and reserved only for the most skilled Data Engineers. It is still expensive and requires a fair amount of technical knowledge to do. However, with managed tools like SQL Dataflow or open-source alternatives like KSQL for Kafka and Spark SQL, streaming analytics is hopefully democratized and more accessible.
[ { "code": null, "e": 538, "s": 172, "text": "Real-time data is data that is delivered the moment it is collected. This enables you to process and query those data to inform decisions or fuel data applications. There are some terminologies out there, such as real-time, near real-time, and batch. The difference between these three is not clearly defined, but you can roughly use the following guideline (IMHO)." }, { "code": null, "e": 592, "s": 538, "text": "Real-time: sub-second/minute latency, worst accuracy." }, { "code": null, "e": 646, "s": 592, "text": "Near real-time: 1–5 minutes latency, better accuracy." }, { "code": null, "e": 731, "s": 646, "text": "Batch: anywhere above 5 minutes latency from 1 hour, 1 day to 1 week, best accuracy." }, { "code": null, "e": 1091, "s": 731, "text": "Unless you need to process financial transactions, most streaming analytics use cases will fall under the near real-time category. For example, if you run a promotional campaign, you will need to send a message to a customer if their purchase meets certain standards. In this case, you can get away with doing so a couple of minutes after the purchase happen." }, { "code": null, "e": 1448, "s": 1091, "text": "Having real-time access to data is beneficial to many businesses as data is the lifeblood of many nowadays. Instead of relying on outdated, slow-to-update information, you can access up-to-date information for better decision-making. Most modern data warehouses and BI tools support streaming insert and query, so your company can access real-time metrics." }, { "code": null, "e": 1673, "s": 1448, "text": "Better yet, many of the decisions can be made autonomously using a streaming pipeline and some business logic. For example, you can notify customers after adding a product to carts but not checked out in the last 30 minutes." }, { "code": null, "e": 2021, "s": 1673, "text": "Real-time data used to be accessible to well-funded tech startups or corporate with million of dollars budgets. You would typically need a team of data engineers to build and maintain streaming pipelines too. However, with the advancement of cloud computing and the open-source data community, many of these capabilities are opening up for us all." }, { "code": null, "e": 2448, "s": 2021, "text": "Say you are an e-commerce company, and there is a marketing campaign to reward any customers who spent more than $5,000 and make a new purchase. You want to send an app push to congratulate these customers when they make a new purchase. You also need a real-time dashboard to keep track of how the campaign is going. The development team said they are at capacity and won’t help you with this campaign, so you are on your own." }, { "code": null, "e": 2847, "s": 2448, "text": "A task like this would typically take two sources of data and combine them. You would need to query your data warehouse to get all customers who spent more than $5,000. You would also need real-time data to capture new transactions within today. This is also known as the lambda architecture, where you have a batch layer that runs at least once a day and a speed layer streaming data in real-time." }, { "code": null, "e": 3032, "s": 2847, "text": "Assuming that your development team is nice enough to build a streaming source of your order and customer data (this is actually a prerequisite), our architecture would look as follow." }, { "code": null, "e": 3480, "s": 3032, "text": "In this architecture, new orders (within the day) are streamed to Pub/Sub. The pipeline created by Dataflow will check every new purchase to see if the customer is within the list of customers who spent more than $5,000. The results will be written into two destinations. Results to BigQuery will be used for real-time dashboard with a visualization tool. Results written to Pub/Sub will be used to send push notifications to the winning customer." }, { "code": null, "e": 3528, "s": 3480, "text": "Here are some prerequisites to getting started:" }, { "code": null, "e": 3551, "s": 3528, "text": "A Google Cloud account" }, { "code": null, "e": 3619, "s": 3551, "text": "An active billing account (you can sign up for the $300 free trial)" }, { "code": null, "e": 3642, "s": 3619, "text": "A Google Cloud project" }, { "code": null, "e": 3653, "s": 3642, "text": "github.com" }, { "code": null, "e": 3699, "s": 3653, "text": "Clone this repo to the Cloudshell by running:" }, { "code": null, "e": 3844, "s": 3699, "text": "# Clone the repo locallygit clone https://github.com/tuanchris/dataflow-sqlcd dataflow-sql# Install requirementspip3 install -r requirements.txt" }, { "code": null, "e": 3908, "s": 3844, "text": "We need two data sources for our streaming pipelines as follow:" }, { "code": null, "e": 3995, "s": 3908, "text": "1. A BigQuery Batch source — all orders and customers information and is updated daily" }, { "code": null, "e": 4222, "s": 3995, "text": "# This script will create 100 customers with 1000 orderspython3 generate_data.py batch \\ --customer_count=100 \\ --order_count=1000 \\ --project_id=$DEVSHELL_PROJECT_ID# Replace the project_id varaible if you are running locally" }, { "code": null, "e": 4294, "s": 4222, "text": "Select “Authorize” when Cloud shell asks to authenticate your requests." }, { "code": null, "e": 4405, "s": 4294, "text": "2. A Pub/Sub topic called orders — a stream of order data that arrives via a subscription to the Pub/Sub topic" }, { "code": null, "e": 4598, "s": 4405, "text": "# Create a Pub/Sub topicgcloud pubsub topics create orders# Generate a stream of order data to Pub/Subpython3 generate_data.py stream \\ --customer_range 100 \\ --project_id $DEVSHELL_PROJECT_ID" }, { "code": null, "e": 4665, "s": 4598, "text": "To add the Pub/Sub source to BigQuery, follow the following steps:" }, { "code": null, "e": 4726, "s": 4665, "text": "Change the query engine in BigQuery to Cloud Dataflow Engine" }, { "code": null, "e": 4787, "s": 4726, "text": "Change the query engine in BigQuery to Cloud Dataflow Engine" }, { "code": null, "e": 4862, "s": 4787, "text": "2. From the BigQuery UI, select Add Data and choose Cloud Dataflow sources" }, { "code": null, "e": 4894, "s": 4862, "text": "3. Add the Pub/Sub topic source" }, { "code": null, "e": 4931, "s": 4894, "text": "4. Add a schema for the orders topic" }, { "code": null, "e": 5529, "s": 4931, "text": "[ { \"name\": \"event_timestamp\", \"description\": \"\", \"mode\": \"REQUIRED\", \"type\": \"TIMESTAMP\" }, { \"name\": \"customer_id\", \"description\": \"\", \"mode\": \"NULLABLE\", \"type\": \"INT64\" }, { \"name\": \"amount\", \"description\": \"\", \"mode\": \"NULLABLE\", \"type\": \"FLOAT64\" }, { \"name\": \"order_status\", \"description\": \"\", \"mode\": \"NULLABLE\", \"type\": \"STRING\" }, { \"name\": \"order_datetime\", \"description\": \"\", \"mode\": \"NULLABLE\", \"type\": \"STRING\" }]" }, { "code": null, "e": 5547, "s": 5529, "text": "Write a SQL query" }, { "code": null, "e": 5614, "s": 5547, "text": "Here is a simple SQL query that will answer our business question." }, { "code": null, "e": 6006, "s": 5614, "text": "WITH eligible_customers AS ( SELECT o.customer_id, SUM(o.amount) AS total_spent FROM bigquery.table.`demobox-313313`.ecommerce.orders o WHERE o.order_status = 'Closed' GROUP BY 1 HAVING total_spent >= 5000)SELECT o.*, ec.total_spentFROM pubsub.topic.`demobox-313313`.orders oINNER JOIN eligible_customers ecUSING (customer_id)WHERE o.order_status != 'Cancelled'" }, { "code": null, "e": 6321, "s": 6006, "text": "We first select the data from the orders table, filter out only “Closed” orders, then group by the customer, calculate total spending, and filter out customers who purchased $5,000 or more. We then inner join the list of eligible customers to any new transactions, filtering out transactions with Cancelled status." }, { "code": null, "e": 6460, "s": 6321, "text": "You can see that it is easy writing SQL like above, and any Analyst can do it. Be sure to substitute your project_id when trying this out." }, { "code": null, "e": 6649, "s": 6460, "text": "With the query ready and validate, you can select Create Dataflow job from the BigQuery UI. Configure two destinations as per the image below. You can keep other values to the default one." }, { "code": null, "e": 6780, "s": 6649, "text": "After creating the Dataflow job, you can see the result below. Follow the link in Job ID to view your Dataflow job and its status." }, { "code": null, "e": 6895, "s": 6780, "text": "It can take 3–5 minutes for the Dataflow job to startup. After that, you should be able to the pipeline as follow." }, { "code": null, "e": 7042, "s": 6895, "text": "After the Dataflow job is successfully startup and running, you can go to BigQuery and Pub/Sub to verify that our pipeline is working as intended." }, { "code": null, "e": 7213, "s": 7042, "text": "With the running Dataflow job, we can see all sorts of job metrics about our pipeline. For example, it takes 11 seconds for the data to be processed by Dataflow, not bad!" }, { "code": null, "e": 7338, "s": 7213, "text": "Be sure to cancel the Dataflow pipeline, delete the Pub/Sub topic, and delete the BigQuery dataset to avoid incurring costs." } ]
Tryit Editor v3.7
CSS Grid Item Tryit: The grid-column property
[ { "code": null, "e": 23, "s": 9, "text": "CSS Grid Item" } ]
How to read all excel files under a directory as a Pandas DataFrame ?
To read all excel files in a directory, use the Glob module and the read_excel() method. Let’s say the following are our excel files in a directory − Sales1.xlsx Sales2.xlsx At first, set the path where all the excel files are located. Get the excel files and read them using glob − path = "C:\\Users\\amit_\\Desktop\\" filenames = glob.glob(path + "\*.xlsx") print('File names:', filenames) Next, use the for loop to iterate and read all the excels files in a specific directory. We are also using read_excel() − for file in filenames: print("Reading file = ",file) print(pd.read_excel(file)) Following is the complete code − import pandas as pd import glob # getting excel files from Directory Desktop path = "C:\\Users\\amit_\\Desktop\\" # read all the files with extension .xlsx i.e. excel filenames = glob.glob(path + "\*.xlsx") print('File names:', filenames) # for loop to iterate all excel files for file in filenames: # reading excel files print("Reading file = ",file) print(pd.read_excel(file)) This will produce the following output − File names:['C:\\Users\\amit_\\Desktop\\Sales1.xlsx','C:\\Users\\amit_\\Desktop\\Sales2.xlsx'] Reading file = C:\Users\amit_\Desktop\Sales1.xlsx Car Place UnitsSold 0 Audi Bangalore 80 1 Porsche Mumbai 110 2 RollsRoyce Pune 100 Reading file = C:\Users\amit_\Desktop\Sales2.xlsx Car Place UnitsSold 0 BMW Delhi 95 1 Mercedes Hyderabad 80 2 Lamborgini Chandigarh 80
[ { "code": null, "e": 1151, "s": 1062, "text": "To read all excel files in a directory, use the Glob module and the read_excel() method." }, { "code": null, "e": 1212, "s": 1151, "text": "Let’s say the following are our excel files in a directory −" }, { "code": null, "e": 1224, "s": 1212, "text": "Sales1.xlsx" }, { "code": null, "e": 1236, "s": 1224, "text": "Sales2.xlsx" }, { "code": null, "e": 1345, "s": 1236, "text": "At first, set the path where all the excel files are located. Get the excel files and read them using glob −" }, { "code": null, "e": 1455, "s": 1345, "text": "path = \"C:\\\\Users\\\\amit_\\\\Desktop\\\\\"\n\nfilenames = glob.glob(path + \"\\*.xlsx\")\nprint('File names:', filenames)" }, { "code": null, "e": 1577, "s": 1455, "text": "Next, use the for loop to iterate and read all the excels files in a specific directory. We are also using read_excel() −" }, { "code": null, "e": 1663, "s": 1577, "text": "for file in filenames:\n print(\"Reading file = \",file)\n print(pd.read_excel(file))" }, { "code": null, "e": 1696, "s": 1663, "text": "Following is the complete code −" }, { "code": null, "e": 2089, "s": 1696, "text": "import pandas as pd\nimport glob\n\n# getting excel files from Directory Desktop\npath = \"C:\\\\Users\\\\amit_\\\\Desktop\\\\\"\n\n# read all the files with extension .xlsx i.e. excel \nfilenames = glob.glob(path + \"\\*.xlsx\")\nprint('File names:', filenames)\n\n# for loop to iterate all excel files \nfor file in filenames:\n # reading excel files\n print(\"Reading file = \",file)\n print(pd.read_excel(file))" }, { "code": null, "e": 2130, "s": 2089, "text": "This will produce the following output −" }, { "code": null, "e": 2620, "s": 2130, "text": "File names:['C:\\\\Users\\\\amit_\\\\Desktop\\\\Sales1.xlsx','C:\\\\Users\\\\amit_\\\\Desktop\\\\Sales2.xlsx']\n\nReading file = C:\\Users\\amit_\\Desktop\\Sales1.xlsx\n Car Place UnitsSold\n0 Audi Bangalore 80\n1 Porsche Mumbai 110\n2 RollsRoyce Pune 100\n\nReading file = C:\\Users\\amit_\\Desktop\\Sales2.xlsx\n Car Place UnitsSold\n0 BMW Delhi 95\n1 Mercedes Hyderabad 80\n2 Lamborgini Chandigarh 80" } ]
Replace a substring with another string in Julia - replace() Method - GeeksforGeeks
23 Feb, 2021 The replace() is an inbuilt function in julia that is used to replace a word or character with the specified string or character. Syntax: replace(s::AbstractString, pattern=>Word; count::Integer) Parameters: s::AbstractString: Specified string. pattern=>Word: Pattern is searched from the given sentence and then that pattern is replaced with the word. count::Integer: It is a number that is the count of specified pattern available in the sentence. Returns: It returns a new sentence with replaced words. Example 1: Python # Julia program to illustrate# the use of String replace() method # Getting a new sentence with replaced wordsprintln(replace("GFG is a CS portal.", "CS" => "Computer Science"))println(replace("GeeksforGeeks is a CS portal.", "GeeksforGeeks" => "GFG")) Output: Example 2: Python # Julia program to illustrate# the use of String replace() method # Getting a new sentence with replaced wordsprintln(replace("GFG Geeks.", "GFG" => "GeeksforGeeks", count = 1))println(replace("GFG Geeks GFG.", "GFG" => "GeeksforGeeks", count = 2)) Output: arorakashish0911 Julia Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Vectors in Julia Getting rounded value of a number in Julia - round() Method Reshaping array dimensions in Julia | Array reshape() Method Manipulating matrices in Julia Get array dimensions and size of a dimension in Julia - size() Method Tuples in Julia Storing Output on a File in Julia while loop in Julia Taking Input from Users in Julia Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)
[ { "code": null, "e": 23789, "s": 23761, "text": "\n23 Feb, 2021" }, { "code": null, "e": 23920, "s": 23789, "text": "The replace() is an inbuilt function in julia that is used to replace a word or character with the specified string or character. " }, { "code": null, "e": 23929, "s": 23920, "text": "Syntax: " }, { "code": null, "e": 23987, "s": 23929, "text": "replace(s::AbstractString, pattern=>Word; count::Integer)" }, { "code": null, "e": 24001, "s": 23987, "text": "Parameters: " }, { "code": null, "e": 24038, "s": 24001, "text": "s::AbstractString: Specified string." }, { "code": null, "e": 24146, "s": 24038, "text": "pattern=>Word: Pattern is searched from the given sentence and then that pattern is replaced with the word." }, { "code": null, "e": 24243, "s": 24146, "text": "count::Integer: It is a number that is the count of specified pattern available in the sentence." }, { "code": null, "e": 24312, "s": 24243, "text": "Returns: It returns a new sentence with replaced words. Example 1: " }, { "code": null, "e": 24319, "s": 24312, "text": "Python" }, { "code": "# Julia program to illustrate# the use of String replace() method # Getting a new sentence with replaced wordsprintln(replace(\"GFG is a CS portal.\", \"CS\" => \"Computer Science\"))println(replace(\"GeeksforGeeks is a CS portal.\", \"GeeksforGeeks\" => \"GFG\"))", "e": 24572, "s": 24319, "text": null }, { "code": null, "e": 24582, "s": 24572, "text": "Output: " }, { "code": null, "e": 24594, "s": 24582, "text": "Example 2: " }, { "code": null, "e": 24601, "s": 24594, "text": "Python" }, { "code": "# Julia program to illustrate# the use of String replace() method # Getting a new sentence with replaced wordsprintln(replace(\"GFG Geeks.\", \"GFG\" => \"GeeksforGeeks\", count = 1))println(replace(\"GFG Geeks GFG.\", \"GFG\" => \"GeeksforGeeks\", count = 2))", "e": 24850, "s": 24601, "text": null }, { "code": null, "e": 24860, "s": 24850, "text": "Output: " }, { "code": null, "e": 24879, "s": 24862, "text": "arorakashish0911" }, { "code": null, "e": 24885, "s": 24879, "text": "Julia" }, { "code": null, "e": 24983, "s": 24885, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24992, "s": 24983, "text": "Comments" }, { "code": null, "e": 25005, "s": 24992, "text": "Old Comments" }, { "code": null, "e": 25022, "s": 25005, "text": "Vectors in Julia" }, { "code": null, "e": 25082, "s": 25022, "text": "Getting rounded value of a number in Julia - round() Method" }, { "code": null, "e": 25143, "s": 25082, "text": "Reshaping array dimensions in Julia | Array reshape() Method" }, { "code": null, "e": 25174, "s": 25143, "text": "Manipulating matrices in Julia" }, { "code": null, "e": 25244, "s": 25174, "text": "Get array dimensions and size of a dimension in Julia - size() Method" }, { "code": null, "e": 25260, "s": 25244, "text": "Tuples in Julia" }, { "code": null, "e": 25294, "s": 25260, "text": "Storing Output on a File in Julia" }, { "code": null, "e": 25314, "s": 25294, "text": "while loop in Julia" }, { "code": null, "e": 25347, "s": 25314, "text": "Taking Input from Users in Julia" } ]
When to use yield instead of return in Python?
07 Jun, 2022 The yield statement suspends function’s execution and sends a value back to the caller, but retains enough state to enable function to resume where it is left off. When resumed, the function continues execution immediately after the last yield run. This allows its code to produce a series of values over time, rather than computing them at once and sending them back like a list. Let’s see with an example: # A Simple Python program to demonstrate working# of yield # A generator function that yields 1 for the first time,# 2 second time and 3 third timedef simpleGeneratorFun(): yield 1 yield 2 yield 3 # Driver code to check above generator functionfor value in simpleGeneratorFun(): print(value) Output: 1 2 3 Return sends a specified value back to its caller whereas Yield can produce a sequence of values. We should use yield when we want to iterate over a sequence, but don’t want to store the entire sequence in memory. Yield are used in Python generators. A generator function is defined like a normal function, but whenever it needs to generate a value, it does so with the yield keyword rather than return. If the body of a def contains yield, the function automatically becomes a generator function. # A Python program to generate squares from 1# to 100 using yield and therefore generator # An infinite generator function that prints# next square number. It starts with 1def nextSquare(): i = 1 # An Infinite loop to generate squares while True: yield i*i i += 1 # Next execution resumes # from this point # Driver code to test above generator # functionfor num in nextSquare(): if num > 100: break print(num) Output: 1 4 9 16 25 36 49 64 81 100 julthep Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Enumerate() in Python Different ways to create Pandas Dataframe Read a file line by line in Python How to Install PIP on Windows ? Python String | replace() Python OOPs Concepts
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Jun, 2022" }, { "code": null, "e": 433, "s": 52, "text": "The yield statement suspends function’s execution and sends a value back to the caller, but retains enough state to enable function to resume where it is left off. When resumed, the function continues execution immediately after the last yield run. This allows its code to produce a series of values over time, rather than computing them at once and sending them back like a list." }, { "code": null, "e": 460, "s": 433, "text": "Let’s see with an example:" }, { "code": "# A Simple Python program to demonstrate working# of yield # A generator function that yields 1 for the first time,# 2 second time and 3 third timedef simpleGeneratorFun(): yield 1 yield 2 yield 3 # Driver code to check above generator functionfor value in simpleGeneratorFun(): print(value)", "e": 767, "s": 460, "text": null }, { "code": null, "e": 775, "s": 767, "text": "Output:" }, { "code": null, "e": 781, "s": 775, "text": "1\n2\n3" }, { "code": null, "e": 995, "s": 781, "text": "Return sends a specified value back to its caller whereas Yield can produce a sequence of values. We should use yield when we want to iterate over a sequence, but don’t want to store the entire sequence in memory." }, { "code": null, "e": 1279, "s": 995, "text": "Yield are used in Python generators. A generator function is defined like a normal function, but whenever it needs to generate a value, it does so with the yield keyword rather than return. If the body of a def contains yield, the function automatically becomes a generator function." }, { "code": "# A Python program to generate squares from 1# to 100 using yield and therefore generator # An infinite generator function that prints# next square number. It starts with 1def nextSquare(): i = 1 # An Infinite loop to generate squares while True: yield i*i i += 1 # Next execution resumes # from this point # Driver code to test above generator # functionfor num in nextSquare(): if num > 100: break print(num)", "e": 1774, "s": 1279, "text": null }, { "code": null, "e": 1782, "s": 1774, "text": "Output:" }, { "code": null, "e": 1810, "s": 1782, "text": "1\n4\n9\n16\n25\n36\n49\n64\n81\n100" }, { "code": null, "e": 1818, "s": 1810, "text": "julthep" }, { "code": null, "e": 1825, "s": 1818, "text": "Python" }, { "code": null, "e": 1923, "s": 1825, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1951, "s": 1923, "text": "Read JSON file using Python" }, { "code": null, "e": 2001, "s": 1951, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 2023, "s": 2001, "text": "Python map() function" }, { "code": null, "e": 2067, "s": 2023, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 2089, "s": 2067, "text": "Enumerate() in Python" }, { "code": null, "e": 2131, "s": 2089, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2166, "s": 2131, "text": "Read a file line by line in Python" }, { "code": null, "e": 2198, "s": 2166, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2224, "s": 2198, "text": "Python String | replace()" } ]
StringBuilder deleteCharAt() in Java with Examples
29 Jun, 2022 The deleteCharAt(int index) method of StringBuilder class remove the character at the given index from String contained by StringBuilder. This method takes index as a parameter which represents the index of char we want to remove and returns the remaining String as StringBuilder Object. This StringBuilder is shortened by one char after application of this method. Syntax: public StringBuilder deleteCharAt(int index) Parameters: This method accepts one parameter index represents index of the character you want to remove. Return Value: This method returns this StringBuilder object after removing the character. Exception: This method throws StringIndexOutOfBoundsException if the index is less than zero, or index is larger than the length of String. Below programs demonstrate the deleteCharAt() method of StringBuilder Class: Example 1: Java // Java program to demonstrate// the deleteCharAt() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder("WelcomeGeeks"); // print string System.out.println("Before removal String = " + str.toString()); // remove the Character from index 8 StringBuilder afterRemoval = str.deleteCharAt(8); // print string after removal of Character System.out.println("After removal of character" + " at index 8 = " + afterRemoval.toString()); }} Before removal String = WelcomeGeeks After removal of character at index 8 = WelcomeGeks Example 2: Java // Java program to demonstrate// the deleteCharAt() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder("GeeksforGeeks"); // print string System.out.println("Before removal String = " + str.toString()); // remove the Character from index 3 str = str.deleteCharAt(3); // print string after removal of Character System.out.println("After removal of Character" + " from index=3" + " String becomes => " + str.toString()); // remove the substring from index 5 str = str.deleteCharAt(5); // print string after removal of Character System.out.println("After removal of Character" + " from index=5" + " String becomes => " + str.toString()); }} Before removal String = GeeksforGeeks After removal of Character from index=3 String becomes => GeesforGeeks After removal of Character from index=5 String becomes => GeesfrGeeks Example 3: To demonstrate IndexOutOfBoundException Java // Java program to demonstrate// exception thrown by the deleteCharAt() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder("evil dead_01"); try { // make index > length of String StringBuilder afterRemoval = str.deleteCharAt(14); } catch (Exception e) { System.out.println("Exception: " + e); } }} Exception: java.lang.StringIndexOutOfBoundsException: String index out of range: 14 Reference: https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuilder.html#deleteCharAt(int) vinayedula java-basics Java-Functions Java-StringBuilder Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Jun, 2022" }, { "code": null, "e": 402, "s": 28, "text": "The deleteCharAt(int index) method of StringBuilder class remove the character at the given index from String contained by StringBuilder. This method takes index as a parameter which represents the index of char we want to remove and returns the remaining String as StringBuilder Object. This StringBuilder is shortened by one char after application of this method. Syntax:" }, { "code": null, "e": 447, "s": 402, "text": "public StringBuilder deleteCharAt(int index)" }, { "code": null, "e": 872, "s": 447, "text": "Parameters: This method accepts one parameter index represents index of the character you want to remove. Return Value: This method returns this StringBuilder object after removing the character. Exception: This method throws StringIndexOutOfBoundsException if the index is less than zero, or index is larger than the length of String. Below programs demonstrate the deleteCharAt() method of StringBuilder Class: Example 1: " }, { "code": null, "e": 877, "s": 872, "text": "Java" }, { "code": "// Java program to demonstrate// the deleteCharAt() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder(\"WelcomeGeeks\"); // print string System.out.println(\"Before removal String = \" + str.toString()); // remove the Character from index 8 StringBuilder afterRemoval = str.deleteCharAt(8); // print string after removal of Character System.out.println(\"After removal of character\" + \" at index 8 = \" + afterRemoval.toString()); }}", "e": 1598, "s": 877, "text": null }, { "code": null, "e": 1687, "s": 1598, "text": "Before removal String = WelcomeGeeks\nAfter removal of character at index 8 = WelcomeGeks" }, { "code": null, "e": 1699, "s": 1687, "text": "Example 2: " }, { "code": null, "e": 1704, "s": 1699, "text": "Java" }, { "code": "// Java program to demonstrate// the deleteCharAt() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder(\"GeeksforGeeks\"); // print string System.out.println(\"Before removal String = \" + str.toString()); // remove the Character from index 3 str = str.deleteCharAt(3); // print string after removal of Character System.out.println(\"After removal of Character\" + \" from index=3\" + \" String becomes => \" + str.toString()); // remove the substring from index 5 str = str.deleteCharAt(5); // print string after removal of Character System.out.println(\"After removal of Character\" + \" from index=5\" + \" String becomes => \" + str.toString()); }}", "e": 2767, "s": 1704, "text": null }, { "code": null, "e": 2946, "s": 2767, "text": "Before removal String = GeeksforGeeks\nAfter removal of Character from index=3 String becomes => GeesforGeeks\nAfter removal of Character from index=5 String becomes => GeesfrGeeks" }, { "code": null, "e": 2998, "s": 2946, "text": "Example 3: To demonstrate IndexOutOfBoundException " }, { "code": null, "e": 3003, "s": 2998, "text": "Java" }, { "code": "// Java program to demonstrate// exception thrown by the deleteCharAt() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder(\"evil dead_01\"); try { // make index > length of String StringBuilder afterRemoval = str.deleteCharAt(14); } catch (Exception e) { System.out.println(\"Exception: \" + e); } }}", "e": 3564, "s": 3003, "text": null }, { "code": null, "e": 3648, "s": 3564, "text": "Exception: java.lang.StringIndexOutOfBoundsException: String index out of range: 14" }, { "code": null, "e": 3749, "s": 3648, "text": "Reference: https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuilder.html#deleteCharAt(int)" }, { "code": null, "e": 3760, "s": 3749, "text": "vinayedula" }, { "code": null, "e": 3772, "s": 3760, "text": "java-basics" }, { "code": null, "e": 3787, "s": 3772, "text": "Java-Functions" }, { "code": null, "e": 3806, "s": 3787, "text": "Java-StringBuilder" }, { "code": null, "e": 3811, "s": 3806, "text": "Java" }, { "code": null, "e": 3816, "s": 3811, "text": "Java" } ]
Difference between volatile and transient keywords in Java
16 Aug, 2020 Just like any other programming language, Java has a set of keywords which are reserved and have a special meaning. In this article, we will see the difference between the keywords volatile and transient. Before getting into the differences, let us first understand what each of them actually means. Volatile: The Volatile keyword is used to mark the JVM and thread to read its value from primary memory and not utilize cached value present in the thread stack. It is used in concurrent programming in java. Java class GFG extends Thread { // using volatile volatile boolean working = true; // if non-volatile it will // sleep in main and // runtime error will coocur public void run() { long count = 0; while (working) { count++; } System.out.println("Thread terminated." + count); } // Driver code public static void main(String[] args) throws InterruptedException { GFG test = new GFG(); test.start(); Thread.sleep(100); System.out.println("After Sleeping in Main"); test.working = false; test.join(); System.out.println("Working set to " + test.working); }} Output: Volatile Code Output Transient: The Transient keyword is used with the instance variable to eliminate it from the serialization process. During serialization, the value of the transient field or variable is not saved. Java import java.io.*; class Test implements Serializable { // Making Accesskey transient for security transient String accessKey; // Making age transient as age can be // calculated from Date of Birth // and current date. transient int age; // serialize other fields String name, address; public Test(String accessKey, int age, String name, String address) { this.accessKey = accessKey; this.age = age; this.name = name; this.address = address; }} public class GFG { public static void main(String[] args) throws Exception { ObjectInputStream in = new ObjectInputStream( (new FileInputStream( "login_details.txt"))); Test obj = (Test)in.readObject(); /* Transient variable will be shown null due to security reasons.*/ System.out.println("Accesskey: " + obj.accessKey); System.out.println("Age: " + obj.age); System.out.println("Name: " + obj.name); System.out.println("Address: " + obj.address); }} Output: Transient Code Output The following table describes the differences: Java-keyword Difference Between Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Aug, 2020" }, { "code": null, "e": 234, "s": 28, "text": "Just like any other programming language, Java has a set of keywords which are reserved and have a special meaning. In this article, we will see the difference between the keywords volatile and transient. " }, { "code": null, "e": 329, "s": 234, "text": "Before getting into the differences, let us first understand what each of them actually means." }, { "code": null, "e": 339, "s": 329, "text": "Volatile:" }, { "code": null, "e": 537, "s": 339, "text": "The Volatile keyword is used to mark the JVM and thread to read its value from primary memory and not utilize cached value present in the thread stack. It is used in concurrent programming in java." }, { "code": null, "e": 542, "s": 537, "text": "Java" }, { "code": "class GFG extends Thread { // using volatile volatile boolean working = true; // if non-volatile it will // sleep in main and // runtime error will coocur public void run() { long count = 0; while (working) { count++; } System.out.println(\"Thread terminated.\" + count); } // Driver code public static void main(String[] args) throws InterruptedException { GFG test = new GFG(); test.start(); Thread.sleep(100); System.out.println(\"After Sleeping in Main\"); test.working = false; test.join(); System.out.println(\"Working set to \" + test.working); }}", "e": 1282, "s": 542, "text": null }, { "code": null, "e": 1292, "s": 1282, "text": "Output: " }, { "code": null, "e": 1313, "s": 1292, "text": "Volatile Code Output" }, { "code": null, "e": 1324, "s": 1313, "text": "Transient:" }, { "code": null, "e": 1510, "s": 1324, "text": "The Transient keyword is used with the instance variable to eliminate it from the serialization process. During serialization, the value of the transient field or variable is not saved." }, { "code": null, "e": 1515, "s": 1510, "text": "Java" }, { "code": "import java.io.*; class Test implements Serializable { // Making Accesskey transient for security transient String accessKey; // Making age transient as age can be // calculated from Date of Birth // and current date. transient int age; // serialize other fields String name, address; public Test(String accessKey, int age, String name, String address) { this.accessKey = accessKey; this.age = age; this.name = name; this.address = address; }} public class GFG { public static void main(String[] args) throws Exception { ObjectInputStream in = new ObjectInputStream( (new FileInputStream( \"login_details.txt\"))); Test obj = (Test)in.readObject(); /* Transient variable will be shown null due to security reasons.*/ System.out.println(\"Accesskey: \" + obj.accessKey); System.out.println(\"Age: \" + obj.age); System.out.println(\"Name: \" + obj.name); System.out.println(\"Address: \" + obj.address); }}", "e": 2719, "s": 1515, "text": null }, { "code": null, "e": 2727, "s": 2719, "text": "Output:" }, { "code": null, "e": 2749, "s": 2727, "text": "Transient Code Output" }, { "code": null, "e": 2796, "s": 2749, "text": "The following table describes the differences:" }, { "code": null, "e": 2809, "s": 2796, "text": "Java-keyword" }, { "code": null, "e": 2828, "s": 2809, "text": "Difference Between" }, { "code": null, "e": 2833, "s": 2828, "text": "Java" }, { "code": null, "e": 2838, "s": 2833, "text": "Java" } ]
Program for EMI Calculator
24 May, 2021 EMI stand for Equated Monthly Installment. This calculator is used to calculate per month EMI of loan amount if loan amount that is principal, rate of interest and time in years is given as input. Formula: E = (P.r.(1+r)n) / ((1+r)n – 1) Here, P = loan amount i.e principal amount R = Interest rate per month T = Loan time period in year C Java Python3 C# PHP Javascript // EMI Calculator program in C#include <math.h>#include <stdio.h> // Function to calculate EMIfloat emi_calculator(float p, float r, float t){ float emi; r = r / (12 * 100); // one month interest t = t * 12; // one month period emi = (p * r * pow(1 + r, t)) / (pow(1 + r, t) - 1); return (emi);} // Driver Programint main(){ float principal, rate, time, emi; principal = 10000; rate = 10; time = 2; emi = emi_calculator(principal, rate, time); printf("\nMonthly EMI is= %f\n", emi); return 0;} // EMI Calculator program in javaimport java.io.*; public class GFG { // Function to calculate EMI static float emi_calculator(float p, float r, float t) { float emi; r = r / (12 * 100); // one month interest t = t * 12; // one month period emi = (p * r * (float)Math.pow(1 + r, t)) / (float)(Math.pow(1 + r, t) - 1); return (emi); } // Driver Program static public void main (String[] args) { float principal, rate, time, emi; principal = 10000; rate = 10; time = 2; emi = emi_calculator(principal, rate, time); System.out.println("Monthly EMI is = " + emi); }} // This code is contributed by vt_m. # EMI Calculator program in Python def emi_calculator(p, r, t): r = r / (12 * 100) # one month interest t = t * 12 # one month period emi = (p * r * pow(1 + r, t)) / (pow(1 + r, t) - 1) return emi # driver codeprincipal = 10000;rate = 10;time = 2;emi = emi_calculator(principal, rate, time);print("Monthly EMI is= ", emi) # This code is contributed by "Abhishek Sharma 44" // EMI Calculator program in C#using System; public class GFG { // Function to calculate EMI static float emi_calculator(float p, float r, float t) { float emi; r = r / (12 * 100); // one month interest t = t * 12; // one month period emi = (p * r * (float)Math.Pow(1 + r, t)) / (float)(Math.Pow(1 + r, t) - 1); return (emi); } // Driver Program static public void Main () { float principal, rate, time, emi; principal = 10000; rate = 10; time = 2; emi = emi_calculator(principal, rate, time); Console.WriteLine("Monthly EMI is = " + emi); }} // This code is contributed by vt_m. <?php// EMI Calculator program in PHP // Function to calculate EMIfunction emi_calculator($p, $r, $t){ $emi; // one month interest $r = $r / (12 * 100); // one month period $t = $t * 12; $emi = ($p * $r * pow(1 + $r, $t)) / (pow(1 + $r, $t) - 1); return ($emi);} // Driver Code $principal = 10000; $rate = 10; $time = 2; $emi = emi_calculator($principal, $rate, $time); echo "Monthly EMI is = ", $emi; // This code is contributed by anuj_67.?> <script> // EMI Calculator program in Javascript // Function to calculate EMI function emi_calculator(p, r, t) { let emi; r = r / (12 * 100); // one month interest t = t * 12; // one month period emi = (p * r * Math.pow(1 + r, t)) / (Math.pow(1 + r, t) - 1); return (emi + 0.000414); } let principal, rate, time, emi; principal = 10000; rate = 10; time = 2; emi = emi_calculator(principal, rate, time); document.write("Monthly EMI is = " + emi.toFixed(6)); // This code is contributed by divyesh072019</script> Output: Monthly EMI is= 461.449677 Explanation : When we provide amount of money i.e, principal, rate of interest, time and this program will calculate amount of emi. vt_m divyesh072019 School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n24 May, 2021" }, { "code": null, "e": 250, "s": 52, "text": "EMI stand for Equated Monthly Installment. This calculator is used to calculate per month EMI of loan amount if loan amount that is principal, rate of interest and time in years is given as input. " }, { "code": null, "e": 391, "s": 250, "text": "Formula: E = (P.r.(1+r)n) / ((1+r)n – 1) Here, P = loan amount i.e principal amount R = Interest rate per month T = Loan time period in year" }, { "code": null, "e": 395, "s": 393, "text": "C" }, { "code": null, "e": 400, "s": 395, "text": "Java" }, { "code": null, "e": 408, "s": 400, "text": "Python3" }, { "code": null, "e": 411, "s": 408, "text": "C#" }, { "code": null, "e": 415, "s": 411, "text": "PHP" }, { "code": null, "e": 426, "s": 415, "text": "Javascript" }, { "code": "// EMI Calculator program in C#include <math.h>#include <stdio.h> // Function to calculate EMIfloat emi_calculator(float p, float r, float t){ float emi; r = r / (12 * 100); // one month interest t = t * 12; // one month period emi = (p * r * pow(1 + r, t)) / (pow(1 + r, t) - 1); return (emi);} // Driver Programint main(){ float principal, rate, time, emi; principal = 10000; rate = 10; time = 2; emi = emi_calculator(principal, rate, time); printf(\"\\nMonthly EMI is= %f\\n\", emi); return 0;}", "e": 959, "s": 426, "text": null }, { "code": "// EMI Calculator program in javaimport java.io.*; public class GFG { // Function to calculate EMI static float emi_calculator(float p, float r, float t) { float emi; r = r / (12 * 100); // one month interest t = t * 12; // one month period emi = (p * r * (float)Math.pow(1 + r, t)) / (float)(Math.pow(1 + r, t) - 1); return (emi); } // Driver Program static public void main (String[] args) { float principal, rate, time, emi; principal = 10000; rate = 10; time = 2; emi = emi_calculator(principal, rate, time); System.out.println(\"Monthly EMI is = \" + emi); }} // This code is contributed by vt_m.", "e": 1748, "s": 959, "text": null }, { "code": "# EMI Calculator program in Python def emi_calculator(p, r, t): r = r / (12 * 100) # one month interest t = t * 12 # one month period emi = (p * r * pow(1 + r, t)) / (pow(1 + r, t) - 1) return emi # driver codeprincipal = 10000;rate = 10;time = 2;emi = emi_calculator(principal, rate, time);print(\"Monthly EMI is= \", emi) # This code is contributed by \"Abhishek Sharma 44\"", "e": 2133, "s": 1748, "text": null }, { "code": "// EMI Calculator program in C#using System; public class GFG { // Function to calculate EMI static float emi_calculator(float p, float r, float t) { float emi; r = r / (12 * 100); // one month interest t = t * 12; // one month period emi = (p * r * (float)Math.Pow(1 + r, t)) / (float)(Math.Pow(1 + r, t) - 1); return (emi); } // Driver Program static public void Main () { float principal, rate, time, emi; principal = 10000; rate = 10; time = 2; emi = emi_calculator(principal, rate, time); Console.WriteLine(\"Monthly EMI is = \" + emi); }} // This code is contributed by vt_m.", "e": 2887, "s": 2133, "text": null }, { "code": "<?php// EMI Calculator program in PHP // Function to calculate EMIfunction emi_calculator($p, $r, $t){ $emi; // one month interest $r = $r / (12 * 100); // one month period $t = $t * 12; $emi = ($p * $r * pow(1 + $r, $t)) / (pow(1 + $r, $t) - 1); return ($emi);} // Driver Code $principal = 10000; $rate = 10; $time = 2; $emi = emi_calculator($principal, $rate, $time); echo \"Monthly EMI is = \", $emi; // This code is contributed by anuj_67.?>", "e": 3400, "s": 2887, "text": null }, { "code": "<script> // EMI Calculator program in Javascript // Function to calculate EMI function emi_calculator(p, r, t) { let emi; r = r / (12 * 100); // one month interest t = t * 12; // one month period emi = (p * r * Math.pow(1 + r, t)) / (Math.pow(1 + r, t) - 1); return (emi + 0.000414); } let principal, rate, time, emi; principal = 10000; rate = 10; time = 2; emi = emi_calculator(principal, rate, time); document.write(\"Monthly EMI is = \" + emi.toFixed(6)); // This code is contributed by divyesh072019</script>", "e": 4013, "s": 3400, "text": null }, { "code": null, "e": 4023, "s": 4013, "text": "Output: " }, { "code": null, "e": 4050, "s": 4023, "text": "Monthly EMI is= 461.449677" }, { "code": null, "e": 4183, "s": 4050, "text": "Explanation : When we provide amount of money i.e, principal, rate of interest, time and this program will calculate amount of emi. " }, { "code": null, "e": 4188, "s": 4183, "text": "vt_m" }, { "code": null, "e": 4202, "s": 4188, "text": "divyesh072019" }, { "code": null, "e": 4221, "s": 4202, "text": "School Programming" } ]
MoviePy –Saving Video File Clip
01 Aug, 2020 In this article we will see how we can save a video file clip in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. Visual multimedia source that combines a sequence of images to form a moving picture. The video transmits a signal to a screen and processes the order in which the screen captures should be shown. Videos usually have audio components that correspond with the pictures being shown on the screen. In order to do this we will use write_videofile method with the VideoFileClip object Syntax : clip.write_videofile(new_name) Argument : It takes takes string as argument which is new name or location of file Return : It returns None Note : If only new name is given in parameters then the file will get saved in the same folder of the code. Below is the implementation # Import everything needed to edit video clipsfrom moviepy.editor import * # loading video dsa gfg intro videoclip = VideoFileClip("dsa_geek.webm") # getting subclip as video is largeclip = clip.subclip(55, 65) # saving the clipclip.write_videofile("gfg_intro.webm") # showing clipclip.ipython_display(width = 480) Output : Moviepy - Building video gfg_intro.webm. Moviepy - Writing video gfg_intro.webm Moviepy - Done ! Moviepy - video ready gfg_intro.webm Moviepy - Building video __temp__.mp4. Moviepy - Writing video __temp__.mp4 Moviepy - Done ! Moviepy - video ready __temp__.mp4 When we go into the code folder we can see the new file is created, below is how the created file will be Another example # Import everything needed to edit video clipsfrom moviepy.editor import * # loading video gfgclip = VideoFileClip("geeks.mp4") # getting subclip clip = clip.subclip(0, 7) # saving the clipclip.write_videofile("handmade_gfg.mp4") # showing clipclip.ipython_display() Output : Moviepy - Building video handmade_gfg.mp4. MoviePy - Writing audio in handmade_gfgTEMP_MPY_wvf_snd.mp3 MoviePy - Done. Moviepy - Writing video handmade_gfg.mp4 Moviepy - Done ! Moviepy - video ready handmade_gfg.mp4 Moviepy - Building video __temp__.mp4. MoviePy - Writing audio in __temp__TEMP_MPY_wvf_snd.mp3 MoviePy - Done. Moviepy - Writing video __temp__.mp4 Moviepy - Done ! Moviepy - video ready __temp__.mp4 Python-MoviePy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Aug, 2020" }, { "code": null, "e": 503, "s": 28, "text": "In this article we will see how we can save a video file clip in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. Visual multimedia source that combines a sequence of images to form a moving picture. The video transmits a signal to a screen and processes the order in which the screen captures should be shown. Videos usually have audio components that correspond with the pictures being shown on the screen." }, { "code": null, "e": 588, "s": 503, "text": "In order to do this we will use write_videofile method with the VideoFileClip object" }, { "code": null, "e": 628, "s": 588, "text": "Syntax : clip.write_videofile(new_name)" }, { "code": null, "e": 711, "s": 628, "text": "Argument : It takes takes string as argument which is new name or location of file" }, { "code": null, "e": 736, "s": 711, "text": "Return : It returns None" }, { "code": null, "e": 844, "s": 736, "text": "Note : If only new name is given in parameters then the file will get saved in the same folder of the code." }, { "code": null, "e": 872, "s": 844, "text": "Below is the implementation" }, { "code": "# Import everything needed to edit video clipsfrom moviepy.editor import * # loading video dsa gfg intro videoclip = VideoFileClip(\"dsa_geek.webm\") # getting subclip as video is largeclip = clip.subclip(55, 65) # saving the clipclip.write_videofile(\"gfg_intro.webm\") # showing clipclip.ipython_display(width = 480)", "e": 1191, "s": 872, "text": null }, { "code": null, "e": 1200, "s": 1191, "text": "Output :" }, { "code": null, "e": 1705, "s": 1200, "text": "Moviepy - Building video gfg_intro.webm.\nMoviepy - Writing video gfg_intro.webm\n\n \nMoviepy - Done !\nMoviepy - video ready gfg_intro.webm\nMoviepy - Building video __temp__.mp4.\nMoviepy - Writing video __temp__.mp4\n\n \nMoviepy - Done !\nMoviepy - video ready __temp__.mp4\n" }, { "code": null, "e": 1811, "s": 1705, "text": "When we go into the code folder we can see the new file is created, below is how the created file will be" }, { "code": null, "e": 1827, "s": 1811, "text": "Another example" }, { "code": "# Import everything needed to edit video clipsfrom moviepy.editor import * # loading video gfgclip = VideoFileClip(\"geeks.mp4\") # getting subclip clip = clip.subclip(0, 7) # saving the clipclip.write_videofile(\"handmade_gfg.mp4\") # showing clipclip.ipython_display()", "e": 2098, "s": 1827, "text": null }, { "code": null, "e": 2107, "s": 2098, "text": "Output :" }, { "code": null, "e": 3006, "s": 2107, "text": "Moviepy - Building video handmade_gfg.mp4.\nMoviePy - Writing audio in handmade_gfgTEMP_MPY_wvf_snd.mp3\n \nMoviePy - Done.\nMoviepy - Writing video handmade_gfg.mp4\n\n \nMoviepy - Done !\nMoviepy - video ready handmade_gfg.mp4\nMoviepy - Building video __temp__.mp4.\nMoviePy - Writing audio in __temp__TEMP_MPY_wvf_snd.mp3\n \nMoviePy - Done.\nMoviepy - Writing video __temp__.mp4\n\n \nMoviepy - Done !\nMoviepy - video ready __temp__.mp4\n" }, { "code": null, "e": 3021, "s": 3006, "text": "Python-MoviePy" }, { "code": null, "e": 3028, "s": 3021, "text": "Python" } ]
How to get the current position of cursor from output screen in C?
06 Mar, 2019 The given task is to get the current position of the cursor from the output screen in C. Approach: There is a predefined function wherex() in C language that returns the x coordinate of the cursor in the current output screen. And wherey() function that returns the y coordinate of the cursor in current output screen. Both the functions are defined in conio.h headerfile. wherex(): This method returns the horizontal position of the cursor.Syntax:int wherex();Parameters: This method do not accepts any parameters.Return Value: This method returns an integer value in range 1 to 80, or as per the system’s screen size. Syntax: int wherex(); Parameters: This method do not accepts any parameters. Return Value: This method returns an integer value in range 1 to 80, or as per the system’s screen size. wherey(): This method returns the vertical position of the cursor.Syntax:int wherey();Parameters: This method do not accepts any parameters.Return Value: This method returns an integer value in range 1 to 50, or as per the system’s screen size. Syntax: int wherey(); Parameters: This method do not accepts any parameters. Return Value: This method returns an integer value in range 1 to 50, or as per the system’s screen size. Note: This code is according to turbo C. Example 1: // C program to get the current// cursor position from output screen #include <conio.h>#include <stdio.h> void main(){ clrscr(); // print current location of x. printf("current location of x is:%d\n", wherex()); // print the current location of y. print("currentlocation of y is:%d", wherey()); getch();} Output: Example 2: // C program to get the current// cursor position from output screen #include <conio.h>#include <stdio.h> void main(){ clrscr(); // takes the cursor to given coordinates // here at (10, 15). gotoxy(10, 15); // print current location of x. printf("current location of x is:%d\n", wherex()); // print the current location of y. print("currentlocation of y is:%d", wherey()); getch();} Output: References: https://code-reference.com/c/conio.h/wherex https://code-reference.com/c/conio.h/wherey C-Misc C Language C Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Mar, 2019" }, { "code": null, "e": 141, "s": 52, "text": "The given task is to get the current position of the cursor from the output screen in C." }, { "code": null, "e": 425, "s": 141, "text": "Approach: There is a predefined function wherex() in C language that returns the x coordinate of the cursor in the current output screen. And wherey() function that returns the y coordinate of the cursor in current output screen. Both the functions are defined in conio.h headerfile." }, { "code": null, "e": 672, "s": 425, "text": "wherex(): This method returns the horizontal position of the cursor.Syntax:int wherex();Parameters: This method do not accepts any parameters.Return Value: This method returns an integer value in range 1 to 80, or as per the system’s screen size." }, { "code": null, "e": 680, "s": 672, "text": "Syntax:" }, { "code": null, "e": 694, "s": 680, "text": "int wherex();" }, { "code": null, "e": 749, "s": 694, "text": "Parameters: This method do not accepts any parameters." }, { "code": null, "e": 854, "s": 749, "text": "Return Value: This method returns an integer value in range 1 to 80, or as per the system’s screen size." }, { "code": null, "e": 1099, "s": 854, "text": "wherey(): This method returns the vertical position of the cursor.Syntax:int wherey();Parameters: This method do not accepts any parameters.Return Value: This method returns an integer value in range 1 to 50, or as per the system’s screen size." }, { "code": null, "e": 1107, "s": 1099, "text": "Syntax:" }, { "code": null, "e": 1121, "s": 1107, "text": "int wherey();" }, { "code": null, "e": 1176, "s": 1121, "text": "Parameters: This method do not accepts any parameters." }, { "code": null, "e": 1281, "s": 1176, "text": "Return Value: This method returns an integer value in range 1 to 50, or as per the system’s screen size." }, { "code": null, "e": 1322, "s": 1281, "text": "Note: This code is according to turbo C." }, { "code": null, "e": 1333, "s": 1322, "text": "Example 1:" }, { "code": "// C program to get the current// cursor position from output screen #include <conio.h>#include <stdio.h> void main(){ clrscr(); // print current location of x. printf(\"current location of x is:%d\\n\", wherex()); // print the current location of y. print(\"currentlocation of y is:%d\", wherey()); getch();}", "e": 1664, "s": 1333, "text": null }, { "code": null, "e": 1672, "s": 1664, "text": "Output:" }, { "code": null, "e": 1683, "s": 1672, "text": "Example 2:" }, { "code": "// C program to get the current// cursor position from output screen #include <conio.h>#include <stdio.h> void main(){ clrscr(); // takes the cursor to given coordinates // here at (10, 15). gotoxy(10, 15); // print current location of x. printf(\"current location of x is:%d\\n\", wherex()); // print the current location of y. print(\"currentlocation of y is:%d\", wherey()); getch();}", "e": 2103, "s": 1683, "text": null }, { "code": null, "e": 2111, "s": 2103, "text": "Output:" }, { "code": null, "e": 2123, "s": 2111, "text": "References:" }, { "code": null, "e": 2167, "s": 2123, "text": "https://code-reference.com/c/conio.h/wherex" }, { "code": null, "e": 2211, "s": 2167, "text": "https://code-reference.com/c/conio.h/wherey" }, { "code": null, "e": 2218, "s": 2211, "text": "C-Misc" }, { "code": null, "e": 2229, "s": 2218, "text": "C Language" }, { "code": null, "e": 2240, "s": 2229, "text": "C Programs" } ]
What is Water Pollution? Sources, Causes, Prevention
24 Feb, 2022 Water is one of the most important natural resources on the planet, and it has existed for millennia. In reality, the same water we drink has been around in some form or another since the dinosaur era. More than two-thirds of the earth’s surface is covered with water. This equates to1 octillion litres (1,260,000,000,000,000,000,000 litres) of water dispersed over the oceans, rivers, lakes, and streams. Although this is a large amount of water, only about 0.3 % of it is suitable for human consumption. That number has decreased as commercialization and industrialization have developed. Furthermore, water contamination has been caused by inefficient and obsolete techniques, a lack of understanding, and a variety of other factors. The polluting of water bodies is referred to as water pollution. Water pollution occurs when industrial and agricultural effluents contaminate water bodies such as rivers, lakes, oceans, groundwater, and aquifers. When water becomes contaminated, it has a negative impact on all lifeforms that rely on it, whether directly or indirectly. Contamination of water will have long-term consequences. The following are some of the most frequent water pollutants: Industrial effluents Domestic waste Insecticides and pesticides are both used to kill insects. Fertilizers and Detergents Direct Sources, such as industries, waste management facilities, refineries, and other facilities that dump waste and toxic by-products into the nearby water source without treatment, are responsible for some of the water pollution. Pollutants that enter water bodies indirectly include those that enter through groundwater, soil, or the atmosphere as acid rain. Most Anthropogenic causes account for the majority of water contamination. This means that humans are to blame for water pollution. The introduction of pollutants into a body of water is known as water pollution. These can have negative consequences for the species that reside in or interact with the water. However, water contamination can also be caused by natural processes or phenomena. Water is known as the universal solvent because of its ability to dissolve a wide range of compounds. This is also the reason why water pollution is so common. The following are some of the factors that contribute to water pollution: Sewage and wastewater: Many households dump their garbage into bodies of water. Furthermore, houses that do not have access to a municipal treatment facility may use septic tanks, which eventually infiltrate into the soil and pollute groundwater. Industrial effluents and Industrial Usage: Some companies may discharge their untreated wastes directly into bodies of water, such as rivers. Furthermore, a variety of sectors use water as a coolant, resulting in thermal pollution. Increased water temperatures can lead to a fall in oxygen levels, which can kill fish and other species. Eutrophication: Eutrophication occurs when a huge amount of nutrients is injected into a body of water, causing algae to develop rapidly. This can lower the oxygen level in the water, making it impossible for the fish to breathe. Furthermore, this occurrence has the potential to release harmful poisons into the water, which can hurt or kill most species, including people. Deforestation: Soil erosion can be caused by deforestation. When loose soil particles enter a body of water, they can cause the water to become murky. This can make the water muddy, and it also has the ability to harm aquatic organisms mechanically (such as sand particles getting stuck in gills). Agricultural run-offs: Fertilizers and other chemicals found in agricultural run-off can contaminate water. Furthermore, several of these fertilizers have the potential to cause eutrophication. Accidents: Leaks and oil spills are two examples of accidents. Oil spills are very harmful to the environment and marine life. It occurs when incidents involving huge oil tankers, barges, or drilling rigs occur. The Deep Water Horizon oil disaster, which happened on April 20, 2010, was the most well-known. The impact of water pollution is determined by the type and concentration of contaminants. The placement of water bodies is also a key element in determining pollution levels. In the vicinity of metropolitan areas, water bodies are very contaminated. This is the result of industrial and commercial businesses dumping rubbish and harmful substances.Water contamination has a significant impact on aquatic life. It has an effect on their metabolism and behaviour, as well as causing illness and death. Dioxin is a toxin that can cause a variety of issues, ranging from infertility to uncontrolled cell proliferation and cancer. Bioaccumulation of this chemical has been found in fish, chicken, and beef. Before reaching the human body, chemicals like these go up the food chain.Water pollution can have a significant impact on the food chain. It throws the food chain into disarray. Cadmium and lead are hazardous chemicals that, if they enter the food chain via animals (fish eaten by animals, humans), can cause further disruption at higher levels.Pollution affects humans, and diseases such as hepatitis can be contracted through faecal matter in water sources. Infectious disorders such as cholera, etc., can always be caused by poor drinking water treatment and unfit water.Because of water pollution, the ecosystem can be severely harmed, changed, and destructured. In the vicinity of metropolitan areas, water bodies are very contaminated. This is the result of industrial and commercial businesses dumping rubbish and harmful substances. Water contamination has a significant impact on aquatic life. It has an effect on their metabolism and behaviour, as well as causing illness and death. Dioxin is a toxin that can cause a variety of issues, ranging from infertility to uncontrolled cell proliferation and cancer. Bioaccumulation of this chemical has been found in fish, chicken, and beef. Before reaching the human body, chemicals like these go up the food chain. Water pollution can have a significant impact on the food chain. It throws the food chain into disarray. Cadmium and lead are hazardous chemicals that, if they enter the food chain via animals (fish eaten by animals, humans), can cause further disruption at higher levels. Pollution affects humans, and diseases such as hepatitis can be contracted through faecal matter in water sources. Infectious disorders such as cholera, etc., can always be caused by poor drinking water treatment and unfit water. Because of water pollution, the ecosystem can be severely harmed, changed, and destructured. Pollution of the water supply has become a global issue. Because of the uncontrolled and uneven development of linked sectors like industries and agriculture, the perennial threat of a water crisis is intensifying. According to NITI Aayog studies, 21 major Indian cities, including Delhi, may run out of groundwater totally. Now, we’re going to discuss the reasons behind the pollution of the river Ganga and it examines the effective measures taken by the government. Reasons behind the Pollution of Ganga: Industries: In Uttarakhand, there are 4600 industries, 298 of which are significantly polluting. Many enterprises have started operations despite not having obtained authorization from the Uttarakhand pollution control board, and they did so based on a government recommendation that exempted certain groups of industries from obtaining approval. Despite the government’s tight laws, sewage treatment and advanced waste treatment technology are not used.Sewage: Sewage is a significant source of pollution, accounting for 75 % of all pollution. Various types of urban growth lead to sewage contamination in the river. The Ganga Action Plan’s tremendous efforts have failed to ameliorate the situation. According to the research, despite the failure of the Ganga Action Plan, citizens and their representatives living in urban areas along the river’s banks have expressed no opposition. The failure is attributable to the government entities in charge of the plan’s effective implementation. The river’s cleanliness appears to be unimportant to the city dwellers who live around it.Municipal Corporation: The widespread usage of plastic and its inappropriate disposal eventually end up in the river. One of the major causes of pollution in the river has been identified as plastic contamination. To combat the threat of plastic pollution, the government has failed to enact Management and Sewage Waste Rules. Plastic should be outlawed entirely by the government. The authorities are unconcerned about the widespread usage of plastics and the inappropriate management of rubbish before dumping it into the river. Because of plastic waste, water contamination has increased dramatically.Agriculture Waste: Sediments, fertilizers, and animal wastes all contribute to agricultural water contamination. Water pollution has been greatly exacerbated by the unbalanced use of inorganic and other fertilizers. After reaching various other entities, nitrate-rich fertilizers produce hazardous makeup. When large amounts of fertilizers are washed into the river by irrigation, rain, or drainage, the river becomes polluted. To increase the productivity of the land, nitrate-rich fertilizers are utilised. Industries: In Uttarakhand, there are 4600 industries, 298 of which are significantly polluting. Many enterprises have started operations despite not having obtained authorization from the Uttarakhand pollution control board, and they did so based on a government recommendation that exempted certain groups of industries from obtaining approval. Despite the government’s tight laws, sewage treatment and advanced waste treatment technology are not used. Sewage: Sewage is a significant source of pollution, accounting for 75 % of all pollution. Various types of urban growth lead to sewage contamination in the river. The Ganga Action Plan’s tremendous efforts have failed to ameliorate the situation. According to the research, despite the failure of the Ganga Action Plan, citizens and their representatives living in urban areas along the river’s banks have expressed no opposition. The failure is attributable to the government entities in charge of the plan’s effective implementation. The river’s cleanliness appears to be unimportant to the city dwellers who live around it. Municipal Corporation: The widespread usage of plastic and its inappropriate disposal eventually end up in the river. One of the major causes of pollution in the river has been identified as plastic contamination. To combat the threat of plastic pollution, the government has failed to enact Management and Sewage Waste Rules. Plastic should be outlawed entirely by the government. The authorities are unconcerned about the widespread usage of plastics and the inappropriate management of rubbish before dumping it into the river. Because of plastic waste, water contamination has increased dramatically. Agriculture Waste: Sediments, fertilizers, and animal wastes all contribute to agricultural water contamination. Water pollution has been greatly exacerbated by the unbalanced use of inorganic and other fertilizers. After reaching various other entities, nitrate-rich fertilizers produce hazardous makeup. When large amounts of fertilizers are washed into the river by irrigation, rain, or drainage, the river becomes polluted. To increase the productivity of the land, nitrate-rich fertilizers are utilised. Ganga Action Plan The Ganga Action Plan was established in 1986 to combat pollution in the Ganga River. The main goal of this strategy was to clean up the Ganga River by removing pollution caused by trash disposal from cities along the river’s banks. The goal was to clean up the Ganga from Rishikesh to Kolkata. In 1984, the central pollution control board devised a five-year plan to clean up the Ganga. To clean up the Ganga, the central Ganga authority was established in 1985, and a Ganga action plan was initiated in 1986. The Ganga Action Plan’s first phase was launched by late Rajiv Gandhi at Banaras’ Rajendra Prasad Ghat. Its implementation was entrusted to the National Protection Agency. 256 programmes totalling 462 crores were implemented during the first phase of the Ganga Action Plan in Uttar Pradesh, Bihar, and West Bengal. To check the purity of the water, special stations have been set up. The water quality was tested by professionals from Bharat Heavy Electricals Limited and the National Environment Engineering Research Institute. Despite all of the effort, the Ganga action plan failed horribly, despite the fact that crores of dollars were spent on it. Economic pollution has resulted from the failure of such a large plan. In 2001, the government began the second phase of the Ganga Action Plan, which is being implemented by the central pollution board, central public works department, and public works department. Namami Ganga Programme Under the river rehabilitation effort, a flagship Namami Ganga Program was formed under a separate union Water Ministry. The initiative intends to incorporate the Ganga conservation mission, which is in action to clean and conserve the river while also providing socio-economic advantages to the river’s dependent population through job development, improved livelihoods, and health benefits. The Namami Ganga projects have made significant progress in the following areas: Creating sewage treatment capacity: 63 sewerage management projects are now being implemented in the states of Uttarakhand, Uttar Pradesh, Bihar, and West Bengal to increase sewage treatment capacity. In these projects, 12 sewage management projects were launched. Creating riverside development: Construction, management, and refurbishment of 182 ghats and 118 crematoria has begun on 28 riverfront development projects and 33 entry-level projects. River surface cleaning: The collecting of solid floating waste on the ghats and rivers is known as river surface cleaning. These wastes are piped into treatment facilities after being collected. Public Awareness: Seminars, workshops, and conferences, as well as a variety of other activities, are held to educate the public and improve community transmission. Industrial Effluent Monitoring: The Grossly Polluting Industries are regularly monitored. Environmental compliances are checked in industries that follow the stated norm. Without the use of intermediaries, the reports are submitted directly to the central pollution control board. The greatest strategy to avoid large-scale water contamination is to strive to mitigate its negative consequences. We may make a number of minor changes to safeguard ourselves from a frightening future in which water is scarce. Save Water: Our primary goal is to conserve water. Water waste is a big problem around the world, and we are only now becoming aware of it. Small modifications that you may make at home can make a big effect.Better treatment of sewage: As a result, processing waste materials before disposing of them in a water body aids in the reduction of large-scale water pollution. By lowering the hazardous content of the wastewater, agriculture and other businesses may reuse it.Use environmentally friendly products: We can limit the quantity of water pollution created by a household by using soluble items that do not become pollutants. Save Water: Our primary goal is to conserve water. Water waste is a big problem around the world, and we are only now becoming aware of it. Small modifications that you may make at home can make a big effect. Better treatment of sewage: As a result, processing waste materials before disposing of them in a water body aids in the reduction of large-scale water pollution. By lowering the hazardous content of the wastewater, agriculture and other businesses may reuse it. Use environmentally friendly products: We can limit the quantity of water pollution created by a household by using soluble items that do not become pollutants. Question 1: What is thermal water pollution? Answer: The rise and fall in temperature of a natural body of water induced by human intervention is known as thermal pollution. And, unlike chemical pollution, thermal pollution causes a change in the physical qualities of water. Question 2: What is sewage treatment? Answer: The process of cleaning or removing all contaminants, treating wastewater, and making it safe and appropriate for drinking before releasing it into the environment is referred to as wastewater treatment or sewage treatment. Question 3: What are the main causes of water pollution? Answer: Water pollution is caused by a variety of factors. Activities related to industryUrbanizationSocial and religious customsRunoff from agricultureAccidents happen (such as oil spills, nuclear fallouts etc) Activities related to industry Urbanization Social and religious customs Runoff from agriculture Accidents happen (such as oil spills, nuclear fallouts etc) Question 4: What are the effects of water pollution? Answer: Water contamination has the potential to devastate the ecology. Furthermore, hazardous chemicals can enter our bodies through the food chain, causing diseases and death. Question 5: What are the main steps in sewage treatment? Answer: The wastewater treatment process is divided into four stages: Screening, Primary treatment, Secondary treatment, and Final treatment. Question 6: What is Water pollution? Answer: The polluting of water bodies is referred to as water pollution. Water pollution occurs when industrial and agricultural effluents contaminate water bodies such as rivers, lakes, oceans, groundwater, and aquifers. When water becomes contaminated, it has a negative impact on all lifeforms that rely on it, whether directly or indirectly. Contamination of water will have long-term consequences. Question 7: What are the methods of prevention of water pollution? Answer: The greatest strategy to avoid large-scale water contamination is to strive to mitigate its negative consequences. We may make a number of minor changes to safeguard ourselves from a frightening future in which water is scarce. Save Water: Our primary goal is to conserve water. Water waste is a big problem around the world, and we are only now becoming aware of it. Small modifications that you may make at home can make a big effect.Better treatment of sewage: As a result, processing waste materials before disposing of them in a water body aids in the reduction of large-scale water pollution. By lowering the hazardous content of the wastewater, agriculture and other businesses may reuse it.Use environmentally friendly products: We can limit the quantity of water pollution created by a household by using soluble items that do not become pollutants. Save Water: Our primary goal is to conserve water. Water waste is a big problem around the world, and we are only now becoming aware of it. Small modifications that you may make at home can make a big effect. Better treatment of sewage: As a result, processing waste materials before disposing of them in a water body aids in the reduction of large-scale water pollution. By lowering the hazardous content of the wastewater, agriculture and other businesses may reuse it. Use environmentally friendly products: We can limit the quantity of water pollution created by a household by using soluble items that do not become pollutants. rkbhola5 Picked Class 8 School Chemistry School Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Feb, 2022" }, { "code": null, "e": 765, "s": 28, "text": "Water is one of the most important natural resources on the planet, and it has existed for millennia. In reality, the same water we drink has been around in some form or another since the dinosaur era. More than two-thirds of the earth’s surface is covered with water. This equates to1 octillion litres (1,260,000,000,000,000,000,000 litres) of water dispersed over the oceans, rivers, lakes, and streams. Although this is a large amount of water, only about 0.3 % of it is suitable for human consumption. That number has decreased as commercialization and industrialization have developed. Furthermore, water contamination has been caused by inefficient and obsolete techniques, a lack of understanding, and a variety of other factors." }, { "code": null, "e": 1160, "s": 765, "text": "The polluting of water bodies is referred to as water pollution. Water pollution occurs when industrial and agricultural effluents contaminate water bodies such as rivers, lakes, oceans, groundwater, and aquifers. When water becomes contaminated, it has a negative impact on all lifeforms that rely on it, whether directly or indirectly. Contamination of water will have long-term consequences." }, { "code": null, "e": 1222, "s": 1160, "text": "The following are some of the most frequent water pollutants:" }, { "code": null, "e": 1243, "s": 1222, "text": "Industrial effluents" }, { "code": null, "e": 1258, "s": 1243, "text": "Domestic waste" }, { "code": null, "e": 1317, "s": 1258, "text": "Insecticides and pesticides are both used to kill insects." }, { "code": null, "e": 1344, "s": 1317, "text": "Fertilizers and Detergents" }, { "code": null, "e": 1707, "s": 1344, "text": "Direct Sources, such as industries, waste management facilities, refineries, and other facilities that dump waste and toxic by-products into the nearby water source without treatment, are responsible for some of the water pollution. Pollutants that enter water bodies indirectly include those that enter through groundwater, soil, or the atmosphere as acid rain." }, { "code": null, "e": 2099, "s": 1707, "text": "Most Anthropogenic causes account for the majority of water contamination. This means that humans are to blame for water pollution. The introduction of pollutants into a body of water is known as water pollution. These can have negative consequences for the species that reside in or interact with the water. However, water contamination can also be caused by natural processes or phenomena." }, { "code": null, "e": 2333, "s": 2099, "text": "Water is known as the universal solvent because of its ability to dissolve a wide range of compounds. This is also the reason why water pollution is so common. The following are some of the factors that contribute to water pollution:" }, { "code": null, "e": 2580, "s": 2333, "text": "Sewage and wastewater: Many households dump their garbage into bodies of water. Furthermore, houses that do not have access to a municipal treatment facility may use septic tanks, which eventually infiltrate into the soil and pollute groundwater." }, { "code": null, "e": 2917, "s": 2580, "text": "Industrial effluents and Industrial Usage: Some companies may discharge their untreated wastes directly into bodies of water, such as rivers. Furthermore, a variety of sectors use water as a coolant, resulting in thermal pollution. Increased water temperatures can lead to a fall in oxygen levels, which can kill fish and other species." }, { "code": null, "e": 3292, "s": 2917, "text": "Eutrophication: Eutrophication occurs when a huge amount of nutrients is injected into a body of water, causing algae to develop rapidly. This can lower the oxygen level in the water, making it impossible for the fish to breathe. Furthermore, this occurrence has the potential to release harmful poisons into the water, which can hurt or kill most species, including people." }, { "code": null, "e": 3590, "s": 3292, "text": "Deforestation: Soil erosion can be caused by deforestation. When loose soil particles enter a body of water, they can cause the water to become murky. This can make the water muddy, and it also has the ability to harm aquatic organisms mechanically (such as sand particles getting stuck in gills)." }, { "code": null, "e": 3784, "s": 3590, "text": "Agricultural run-offs: Fertilizers and other chemicals found in agricultural run-off can contaminate water. Furthermore, several of these fertilizers have the potential to cause eutrophication." }, { "code": null, "e": 4092, "s": 3784, "text": "Accidents: Leaks and oil spills are two examples of accidents. Oil spills are very harmful to the environment and marine life. It occurs when incidents involving huge oil tankers, barges, or drilling rigs occur. The Deep Water Horizon oil disaster, which happened on April 20, 2010, was the most well-known." }, { "code": null, "e": 4268, "s": 4092, "text": "The impact of water pollution is determined by the type and concentration of contaminants. The placement of water bodies is also a key element in determining pollution levels." }, { "code": null, "e": 5463, "s": 4268, "text": "In the vicinity of metropolitan areas, water bodies are very contaminated. This is the result of industrial and commercial businesses dumping rubbish and harmful substances.Water contamination has a significant impact on aquatic life. It has an effect on their metabolism and behaviour, as well as causing illness and death. Dioxin is a toxin that can cause a variety of issues, ranging from infertility to uncontrolled cell proliferation and cancer. Bioaccumulation of this chemical has been found in fish, chicken, and beef. Before reaching the human body, chemicals like these go up the food chain.Water pollution can have a significant impact on the food chain. It throws the food chain into disarray. Cadmium and lead are hazardous chemicals that, if they enter the food chain via animals (fish eaten by animals, humans), can cause further disruption at higher levels.Pollution affects humans, and diseases such as hepatitis can be contracted through faecal matter in water sources. Infectious disorders such as cholera, etc., can always be caused by poor drinking water treatment and unfit water.Because of water pollution, the ecosystem can be severely harmed, changed, and destructured." }, { "code": null, "e": 5637, "s": 5463, "text": "In the vicinity of metropolitan areas, water bodies are very contaminated. This is the result of industrial and commercial businesses dumping rubbish and harmful substances." }, { "code": null, "e": 6066, "s": 5637, "text": "Water contamination has a significant impact on aquatic life. It has an effect on their metabolism and behaviour, as well as causing illness and death. Dioxin is a toxin that can cause a variety of issues, ranging from infertility to uncontrolled cell proliferation and cancer. Bioaccumulation of this chemical has been found in fish, chicken, and beef. Before reaching the human body, chemicals like these go up the food chain." }, { "code": null, "e": 6339, "s": 6066, "text": "Water pollution can have a significant impact on the food chain. It throws the food chain into disarray. Cadmium and lead are hazardous chemicals that, if they enter the food chain via animals (fish eaten by animals, humans), can cause further disruption at higher levels." }, { "code": null, "e": 6569, "s": 6339, "text": "Pollution affects humans, and diseases such as hepatitis can be contracted through faecal matter in water sources. Infectious disorders such as cholera, etc., can always be caused by poor drinking water treatment and unfit water." }, { "code": null, "e": 6662, "s": 6569, "text": "Because of water pollution, the ecosystem can be severely harmed, changed, and destructured." }, { "code": null, "e": 7131, "s": 6662, "text": "Pollution of the water supply has become a global issue. Because of the uncontrolled and uneven development of linked sectors like industries and agriculture, the perennial threat of a water crisis is intensifying. According to NITI Aayog studies, 21 major Indian cities, including Delhi, may run out of groundwater totally. Now, we’re going to discuss the reasons behind the pollution of the river Ganga and it examines the effective measures taken by the government." }, { "code": null, "e": 7170, "s": 7131, "text": "Reasons behind the Pollution of Ganga:" }, { "code": null, "e": 9364, "s": 7170, "text": "Industries: In Uttarakhand, there are 4600 industries, 298 of which are significantly polluting. Many enterprises have started operations despite not having obtained authorization from the Uttarakhand pollution control board, and they did so based on a government recommendation that exempted certain groups of industries from obtaining approval. Despite the government’s tight laws, sewage treatment and advanced waste treatment technology are not used.Sewage: Sewage is a significant source of pollution, accounting for 75 % of all pollution. Various types of urban growth lead to sewage contamination in the river. The Ganga Action Plan’s tremendous efforts have failed to ameliorate the situation. According to the research, despite the failure of the Ganga Action Plan, citizens and their representatives living in urban areas along the river’s banks have expressed no opposition. The failure is attributable to the government entities in charge of the plan’s effective implementation. The river’s cleanliness appears to be unimportant to the city dwellers who live around it.Municipal Corporation: The widespread usage of plastic and its inappropriate disposal eventually end up in the river. One of the major causes of pollution in the river has been identified as plastic contamination. To combat the threat of plastic pollution, the government has failed to enact Management and Sewage Waste Rules. Plastic should be outlawed entirely by the government. The authorities are unconcerned about the widespread usage of plastics and the inappropriate management of rubbish before dumping it into the river. Because of plastic waste, water contamination has increased dramatically.Agriculture Waste: Sediments, fertilizers, and animal wastes all contribute to agricultural water contamination. Water pollution has been greatly exacerbated by the unbalanced use of inorganic and other fertilizers. After reaching various other entities, nitrate-rich fertilizers produce hazardous makeup. When large amounts of fertilizers are washed into the river by irrigation, rain, or drainage, the river becomes polluted. To increase the productivity of the land, nitrate-rich fertilizers are utilised." }, { "code": null, "e": 9819, "s": 9364, "text": "Industries: In Uttarakhand, there are 4600 industries, 298 of which are significantly polluting. Many enterprises have started operations despite not having obtained authorization from the Uttarakhand pollution control board, and they did so based on a government recommendation that exempted certain groups of industries from obtaining approval. Despite the government’s tight laws, sewage treatment and advanced waste treatment technology are not used." }, { "code": null, "e": 10447, "s": 9819, "text": "Sewage: Sewage is a significant source of pollution, accounting for 75 % of all pollution. Various types of urban growth lead to sewage contamination in the river. The Ganga Action Plan’s tremendous efforts have failed to ameliorate the situation. According to the research, despite the failure of the Ganga Action Plan, citizens and their representatives living in urban areas along the river’s banks have expressed no opposition. The failure is attributable to the government entities in charge of the plan’s effective implementation. The river’s cleanliness appears to be unimportant to the city dwellers who live around it." }, { "code": null, "e": 11052, "s": 10447, "text": "Municipal Corporation: The widespread usage of plastic and its inappropriate disposal eventually end up in the river. One of the major causes of pollution in the river has been identified as plastic contamination. To combat the threat of plastic pollution, the government has failed to enact Management and Sewage Waste Rules. Plastic should be outlawed entirely by the government. The authorities are unconcerned about the widespread usage of plastics and the inappropriate management of rubbish before dumping it into the river. Because of plastic waste, water contamination has increased dramatically." }, { "code": null, "e": 11561, "s": 11052, "text": "Agriculture Waste: Sediments, fertilizers, and animal wastes all contribute to agricultural water contamination. Water pollution has been greatly exacerbated by the unbalanced use of inorganic and other fertilizers. After reaching various other entities, nitrate-rich fertilizers produce hazardous makeup. When large amounts of fertilizers are washed into the river by irrigation, rain, or drainage, the river becomes polluted. To increase the productivity of the land, nitrate-rich fertilizers are utilised." }, { "code": null, "e": 11579, "s": 11561, "text": "Ganga Action Plan" }, { "code": null, "e": 12091, "s": 11579, "text": "The Ganga Action Plan was established in 1986 to combat pollution in the Ganga River. The main goal of this strategy was to clean up the Ganga River by removing pollution caused by trash disposal from cities along the river’s banks. The goal was to clean up the Ganga from Rishikesh to Kolkata. In 1984, the central pollution control board devised a five-year plan to clean up the Ganga. To clean up the Ganga, the central Ganga authority was established in 1985, and a Ganga action plan was initiated in 1986. " }, { "code": null, "e": 12621, "s": 12091, "text": "The Ganga Action Plan’s first phase was launched by late Rajiv Gandhi at Banaras’ Rajendra Prasad Ghat. Its implementation was entrusted to the National Protection Agency. 256 programmes totalling 462 crores were implemented during the first phase of the Ganga Action Plan in Uttar Pradesh, Bihar, and West Bengal. To check the purity of the water, special stations have been set up. The water quality was tested by professionals from Bharat Heavy Electricals Limited and the National Environment Engineering Research Institute. " }, { "code": null, "e": 13010, "s": 12621, "text": "Despite all of the effort, the Ganga action plan failed horribly, despite the fact that crores of dollars were spent on it. Economic pollution has resulted from the failure of such a large plan. In 2001, the government began the second phase of the Ganga Action Plan, which is being implemented by the central pollution board, central public works department, and public works department." }, { "code": null, "e": 13033, "s": 13010, "text": "Namami Ganga Programme" }, { "code": null, "e": 13427, "s": 13033, "text": "Under the river rehabilitation effort, a flagship Namami Ganga Program was formed under a separate union Water Ministry. The initiative intends to incorporate the Ganga conservation mission, which is in action to clean and conserve the river while also providing socio-economic advantages to the river’s dependent population through job development, improved livelihoods, and health benefits. " }, { "code": null, "e": 13508, "s": 13427, "text": "The Namami Ganga projects have made significant progress in the following areas:" }, { "code": null, "e": 13773, "s": 13508, "text": "Creating sewage treatment capacity: 63 sewerage management projects are now being implemented in the states of Uttarakhand, Uttar Pradesh, Bihar, and West Bengal to increase sewage treatment capacity. In these projects, 12 sewage management projects were launched." }, { "code": null, "e": 13958, "s": 13773, "text": "Creating riverside development: Construction, management, and refurbishment of 182 ghats and 118 crematoria has begun on 28 riverfront development projects and 33 entry-level projects." }, { "code": null, "e": 14153, "s": 13958, "text": "River surface cleaning: The collecting of solid floating waste on the ghats and rivers is known as river surface cleaning. These wastes are piped into treatment facilities after being collected." }, { "code": null, "e": 14318, "s": 14153, "text": "Public Awareness: Seminars, workshops, and conferences, as well as a variety of other activities, are held to educate the public and improve community transmission." }, { "code": null, "e": 14599, "s": 14318, "text": "Industrial Effluent Monitoring: The Grossly Polluting Industries are regularly monitored. Environmental compliances are checked in industries that follow the stated norm. Without the use of intermediaries, the reports are submitted directly to the central pollution control board." }, { "code": null, "e": 14827, "s": 14599, "text": "The greatest strategy to avoid large-scale water contamination is to strive to mitigate its negative consequences. We may make a number of minor changes to safeguard ourselves from a frightening future in which water is scarce." }, { "code": null, "e": 15458, "s": 14827, "text": "Save Water: Our primary goal is to conserve water. Water waste is a big problem around the world, and we are only now becoming aware of it. Small modifications that you may make at home can make a big effect.Better treatment of sewage: As a result, processing waste materials before disposing of them in a water body aids in the reduction of large-scale water pollution. By lowering the hazardous content of the wastewater, agriculture and other businesses may reuse it.Use environmentally friendly products: We can limit the quantity of water pollution created by a household by using soluble items that do not become pollutants." }, { "code": null, "e": 15667, "s": 15458, "text": "Save Water: Our primary goal is to conserve water. Water waste is a big problem around the world, and we are only now becoming aware of it. Small modifications that you may make at home can make a big effect." }, { "code": null, "e": 15930, "s": 15667, "text": "Better treatment of sewage: As a result, processing waste materials before disposing of them in a water body aids in the reduction of large-scale water pollution. By lowering the hazardous content of the wastewater, agriculture and other businesses may reuse it." }, { "code": null, "e": 16091, "s": 15930, "text": "Use environmentally friendly products: We can limit the quantity of water pollution created by a household by using soluble items that do not become pollutants." }, { "code": null, "e": 16136, "s": 16091, "text": "Question 1: What is thermal water pollution?" }, { "code": null, "e": 16144, "s": 16136, "text": "Answer:" }, { "code": null, "e": 16367, "s": 16144, "text": "The rise and fall in temperature of a natural body of water induced by human intervention is known as thermal pollution. And, unlike chemical pollution, thermal pollution causes a change in the physical qualities of water." }, { "code": null, "e": 16405, "s": 16367, "text": "Question 2: What is sewage treatment?" }, { "code": null, "e": 16413, "s": 16405, "text": "Answer:" }, { "code": null, "e": 16637, "s": 16413, "text": "The process of cleaning or removing all contaminants, treating wastewater, and making it safe and appropriate for drinking before releasing it into the environment is referred to as wastewater treatment or sewage treatment." }, { "code": null, "e": 16694, "s": 16637, "text": "Question 3: What are the main causes of water pollution?" }, { "code": null, "e": 16702, "s": 16694, "text": "Answer:" }, { "code": null, "e": 16753, "s": 16702, "text": "Water pollution is caused by a variety of factors." }, { "code": null, "e": 16906, "s": 16753, "text": "Activities related to industryUrbanizationSocial and religious customsRunoff from agricultureAccidents happen (such as oil spills, nuclear fallouts etc)" }, { "code": null, "e": 16937, "s": 16906, "text": "Activities related to industry" }, { "code": null, "e": 16950, "s": 16937, "text": "Urbanization" }, { "code": null, "e": 16979, "s": 16950, "text": "Social and religious customs" }, { "code": null, "e": 17003, "s": 16979, "text": "Runoff from agriculture" }, { "code": null, "e": 17063, "s": 17003, "text": "Accidents happen (such as oil spills, nuclear fallouts etc)" }, { "code": null, "e": 17116, "s": 17063, "text": "Question 4: What are the effects of water pollution?" }, { "code": null, "e": 17124, "s": 17116, "text": "Answer:" }, { "code": null, "e": 17294, "s": 17124, "text": "Water contamination has the potential to devastate the ecology. Furthermore, hazardous chemicals can enter our bodies through the food chain, causing diseases and death." }, { "code": null, "e": 17351, "s": 17294, "text": "Question 5: What are the main steps in sewage treatment?" }, { "code": null, "e": 17360, "s": 17351, "text": "Answer: " }, { "code": null, "e": 17422, "s": 17360, "text": "The wastewater treatment process is divided into four stages:" }, { "code": null, "e": 17433, "s": 17422, "text": "Screening," }, { "code": null, "e": 17452, "s": 17433, "text": "Primary treatment," }, { "code": null, "e": 17477, "s": 17452, "text": "Secondary treatment, and" }, { "code": null, "e": 17494, "s": 17477, "text": "Final treatment." }, { "code": null, "e": 17531, "s": 17494, "text": "Question 6: What is Water pollution?" }, { "code": null, "e": 17540, "s": 17531, "text": "Answer: " }, { "code": null, "e": 17935, "s": 17540, "text": "The polluting of water bodies is referred to as water pollution. Water pollution occurs when industrial and agricultural effluents contaminate water bodies such as rivers, lakes, oceans, groundwater, and aquifers. When water becomes contaminated, it has a negative impact on all lifeforms that rely on it, whether directly or indirectly. Contamination of water will have long-term consequences." }, { "code": null, "e": 18002, "s": 17935, "text": "Question 7: What are the methods of prevention of water pollution?" }, { "code": null, "e": 18010, "s": 18002, "text": "Answer:" }, { "code": null, "e": 18238, "s": 18010, "text": "The greatest strategy to avoid large-scale water contamination is to strive to mitigate its negative consequences. We may make a number of minor changes to safeguard ourselves from a frightening future in which water is scarce." }, { "code": null, "e": 18869, "s": 18238, "text": "Save Water: Our primary goal is to conserve water. Water waste is a big problem around the world, and we are only now becoming aware of it. Small modifications that you may make at home can make a big effect.Better treatment of sewage: As a result, processing waste materials before disposing of them in a water body aids in the reduction of large-scale water pollution. By lowering the hazardous content of the wastewater, agriculture and other businesses may reuse it.Use environmentally friendly products: We can limit the quantity of water pollution created by a household by using soluble items that do not become pollutants." }, { "code": null, "e": 19078, "s": 18869, "text": "Save Water: Our primary goal is to conserve water. Water waste is a big problem around the world, and we are only now becoming aware of it. Small modifications that you may make at home can make a big effect." }, { "code": null, "e": 19341, "s": 19078, "text": "Better treatment of sewage: As a result, processing waste materials before disposing of them in a water body aids in the reduction of large-scale water pollution. By lowering the hazardous content of the wastewater, agriculture and other businesses may reuse it." }, { "code": null, "e": 19502, "s": 19341, "text": "Use environmentally friendly products: We can limit the quantity of water pollution created by a household by using soluble items that do not become pollutants." }, { "code": null, "e": 19511, "s": 19502, "text": "rkbhola5" }, { "code": null, "e": 19518, "s": 19511, "text": "Picked" }, { "code": null, "e": 19526, "s": 19518, "text": "Class 8" }, { "code": null, "e": 19543, "s": 19526, "text": "School Chemistry" }, { "code": null, "e": 19559, "s": 19543, "text": "School Learning" } ]
Count Occurences of Anagrams | Practice | GeeksforGeeks
Given a word pat and a text txt. Return the count of the occurences of anagrams of the word in the text. Example 1: Input: txt = forxxorfxdofr pat = for Output: 3 Explanation: for, orf and ofr appears in the txt, hence answer is 3. Example 2: Input: txt = aabaabaa pat = aaba Output: 4 Explanation: aaba is present 4 times in txt. Your Task: Complete the function search() which takes two strings pat, txt, as input parameters and returns an integer denoting the answer. You don't to print answer or take inputs. Expected Time Complexity: O(N) Expected Auxiliary Space: O(26) or O(256) Constraints: 1 <= |pat| <= |txt| <= 105 Both string contains lowercase english letters. 0 sharmaadarsh859in 8 hours //EASY SOLUTION USING SLIDING WINDOW AND MAPS //PLEASE UPVOKE IF FOUND USEFUL class Solution{public:int search(string pat, string txt) { int i=0,j=0; map<char,int>m; map<char,int>n; for(char a='a';a<='z';a++){ m[a]=0; n[a]=0; } for(int i=0;i<pat.size();i++){ m[pat[i]]++; } int count=0; while(j<txt.size()){ n[txt[j]]++; if(j-i+1<pat.size()) j++; else if(j-i+1==pat.size()){ if(m==n) count++; n[txt[i]]--; i++; j++; } } return count;} }; 0 aryanguptta142 days ago // EASY TO UNDERSTAND // C++ SLIDING WINDOW class Solution{public:int search(string pat, string txt) { // code here int k=pat.size(); int res=0; unordered_map<char,int> mp; for(int i=0;i<k;i++) { mp[pat[i]]++; } int count=mp.size(); int i=0,j=0; while(j<txt.size()) { mp[txt[j]]--; if(mp[txt[j]]==0) count--; if((j-i+1)<k) j++; else if((j-i+1)==k) { if(count==0) res++; mp[txt[i]]++; if(mp[txt[i]]==1) count++; i++;j++; } } return res;} }; 0 swetkrmis2 days ago class Solution{public:int search(string pat, string txt) { int n=txt.length(); int k=pat.length(); int i=0,ans=0; int j=0; unordered_map<char,int>mp; unordered_map<char,int>mp1; for(int i=0;i<k;i++){ mp[pat[i]]++; } for(int i=0;i<k;i++){ mp1[txt[i]]++; } i=0; j=k-1; int count=0; while(j<n){ int count1=0; for(auto i:mp){ if(mp1[i.first]!=i.second) break; count1++; } if(count1==mp.size()) count++; mp1[txt[i]]--; i++; j++; mp1[txt[j]]++; } return count;} }; +2 ekansh_g223 days ago //EASY TO UNDERSTAND CODE int search(string pat, string txt) { int n = txt.length(); int k = pat.length(); int i = 0,ans=0; int j =0; unordered_map<char,int>mp; for(int i =0;i<k;i++) { mp[pat[i]]++; } int count=mp.size(); while(j<n){ if(mp.find(txt[j])!=mp.end()) { mp[txt[j]]--; if(mp[txt[j]]==0) { count--; } } if(j-i+1<k) { j++; } else if(j-i+1==k){ if(count==0) { ans++; } if(mp.find(txt[i])!=mp.end()) { mp[txt[i]]++; if(mp[txt[i]]==1) { count++; } } i++; j++; } } return ans;} 0 dibyenducse214 days ago int search(string pat, string txt) { int count=0; vector<int>vtaxt(26, 0); vector<int>ptaxt(26, 0); int len=txt.size(); int y=pat.size(); for(int i=0; i<y; i++){ vtaxt[txt[i]-'a']++; ptaxt[pat[i]-'a']++; } if(vtaxt==ptaxt) count++; for(int j=1; j<(len-y+1); j++) { vtaxt[txt[j+y-1]-'a']+=1; vtaxt[txt[j-1]-'a']-=1; if(vtaxt==ptaxt) count++; } return count;} 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. Make sure you are not using ad-blockers. Disable browser extensions. We recommend using latest version of your browser for best experience. Avoid using static/global variables in coding problems as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases in coding problems 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": 331, "s": 226, "text": "Given a word pat and a text txt. Return the count of the occurences of anagrams of the word in the text." }, { "code": null, "e": 342, "s": 331, "text": "Example 1:" }, { "code": null, "e": 459, "s": 342, "text": "Input:\ntxt = forxxorfxdofr\npat = for\nOutput: 3\nExplanation: for, orf and ofr appears\nin the txt, hence answer is 3.\n" }, { "code": null, "e": 470, "s": 459, "text": "Example 2:" }, { "code": null, "e": 559, "s": 470, "text": "Input:\ntxt = aabaabaa\npat = aaba\nOutput: 4\nExplanation: aaba is present 4 times\nin txt.\n" }, { "code": null, "e": 741, "s": 559, "text": "Your Task:\nComplete the function search() which takes two strings pat, txt, as input parameters and returns an integer denoting the answer. You don't to print answer or take inputs." }, { "code": null, "e": 814, "s": 741, "text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(26) or O(256)" }, { "code": null, "e": 902, "s": 814, "text": "Constraints:\n1 <= |pat| <= |txt| <= 105\nBoth string contains lowercase english letters." }, { "code": null, "e": 906, "s": 904, "text": "0" }, { "code": null, "e": 932, "s": 906, "text": "sharmaadarsh859in 8 hours" }, { "code": null, "e": 978, "s": 932, "text": "//EASY SOLUTION USING SLIDING WINDOW AND MAPS" }, { "code": null, "e": 1010, "s": 978, "text": "//PLEASE UPVOKE IF FOUND USEFUL" }, { "code": null, "e": 1524, "s": 1010, "text": "class Solution{public:int search(string pat, string txt) { int i=0,j=0; map<char,int>m; map<char,int>n; for(char a='a';a<='z';a++){ m[a]=0; n[a]=0; } for(int i=0;i<pat.size();i++){ m[pat[i]]++; } int count=0; while(j<txt.size()){ n[txt[j]]++; if(j-i+1<pat.size()) j++; else if(j-i+1==pat.size()){ if(m==n) count++; n[txt[i]]--; i++; j++; } } return count;}" }, { "code": null, "e": 1527, "s": 1524, "text": "};" }, { "code": null, "e": 1529, "s": 1527, "text": "0" }, { "code": null, "e": 1553, "s": 1529, "text": "aryanguptta142 days ago" }, { "code": null, "e": 1575, "s": 1553, "text": "// EASY TO UNDERSTAND" }, { "code": null, "e": 1598, "s": 1575, "text": "// C++ SLIDING WINDOW " }, { "code": null, "e": 2147, "s": 1602, "text": "class Solution{public:int search(string pat, string txt) { // code here int k=pat.size(); int res=0; unordered_map<char,int> mp; for(int i=0;i<k;i++) { mp[pat[i]]++; } int count=mp.size(); int i=0,j=0; while(j<txt.size()) { mp[txt[j]]--; if(mp[txt[j]]==0) count--; if((j-i+1)<k) j++; else if((j-i+1)==k) { if(count==0) res++; mp[txt[i]]++; if(mp[txt[i]]==1) count++; i++;j++; } } return res;}" }, { "code": null, "e": 2150, "s": 2147, "text": "};" }, { "code": null, "e": 2152, "s": 2150, "text": "0" }, { "code": null, "e": 2172, "s": 2152, "text": "swetkrmis2 days ago" }, { "code": null, "e": 2768, "s": 2172, "text": "class Solution{public:int search(string pat, string txt) { int n=txt.length(); int k=pat.length(); int i=0,ans=0; int j=0; unordered_map<char,int>mp; unordered_map<char,int>mp1; for(int i=0;i<k;i++){ mp[pat[i]]++; } for(int i=0;i<k;i++){ mp1[txt[i]]++; } i=0; j=k-1; int count=0; while(j<n){ int count1=0; for(auto i:mp){ if(mp1[i.first]!=i.second) break; count1++; } if(count1==mp.size()) count++; mp1[txt[i]]--; i++; j++; mp1[txt[j]]++; } return count;}" }, { "code": null, "e": 2771, "s": 2768, "text": "};" }, { "code": null, "e": 2774, "s": 2771, "text": "+2" }, { "code": null, "e": 2795, "s": 2774, "text": "ekansh_g223 days ago" }, { "code": null, "e": 2821, "s": 2795, "text": "//EASY TO UNDERSTAND CODE" }, { "code": null, "e": 3558, "s": 2823, "text": " int search(string pat, string txt) { int n = txt.length(); int k = pat.length(); int i = 0,ans=0; int j =0; unordered_map<char,int>mp; for(int i =0;i<k;i++) { mp[pat[i]]++; } int count=mp.size(); while(j<n){ if(mp.find(txt[j])!=mp.end()) { mp[txt[j]]--; if(mp[txt[j]]==0) { count--; } } if(j-i+1<k) { j++; } else if(j-i+1==k){ if(count==0) { ans++; } if(mp.find(txt[i])!=mp.end()) { mp[txt[i]]++; if(mp[txt[i]]==1) { count++; } } i++; j++; } } return ans;}" }, { "code": null, "e": 3560, "s": 3558, "text": "0" }, { "code": null, "e": 3584, "s": 3560, "text": "dibyenducse214 days ago" }, { "code": null, "e": 4014, "s": 3584, "text": "int search(string pat, string txt) { int count=0; vector<int>vtaxt(26, 0); vector<int>ptaxt(26, 0); int len=txt.size(); int y=pat.size(); for(int i=0; i<y; i++){ vtaxt[txt[i]-'a']++; ptaxt[pat[i]-'a']++; } if(vtaxt==ptaxt) count++; for(int j=1; j<(len-y+1); j++) { vtaxt[txt[j+y-1]-'a']+=1; vtaxt[txt[j-1]-'a']-=1; if(vtaxt==ptaxt) count++; } return count;}" }, { "code": null, "e": 4160, "s": 4014, "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": 4196, "s": 4160, "text": " Login to access your submissions. " }, { "code": null, "e": 4206, "s": 4196, "text": "\nProblem\n" }, { "code": null, "e": 4216, "s": 4206, "text": "\nContest\n" }, { "code": null, "e": 4279, "s": 4216, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4464, "s": 4279, "text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 4748, "s": 4464, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints." }, { "code": null, "e": 4894, "s": 4748, "text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code." }, { "code": null, "e": 4971, "s": 4894, "text": "You can view the solutions submitted by other users from the submission tab." }, { "code": null, "e": 5012, "s": 4971, "text": "Make sure you are not using ad-blockers." }, { "code": null, "e": 5040, "s": 5012, "text": "Disable browser extensions." }, { "code": null, "e": 5111, "s": 5040, "text": "We recommend using latest version of your browser for best experience." }, { "code": null, "e": 5298, "s": 5111, "text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values." } ]
NumPy array in Python
29 Aug, 2020 Python lists are a substitute for arrays, but they fail to deliver the performance required while computing large sets of numerical data. To address this issue we use a python library called NumPy. The word NumPy stands for Numerical Python. NumPy offers an array object called ndarray. They are similar to standard python sequences but differ in certain key factors. Unlike lists, NumPy arrays are of fixed size, and changing the size of an array will lead to the creation of a new array while the original array will be deleted. All the elements in an array are of the same type. Numpy arrays are faster, more efficient, and require less syntax than standard python sequences. Note: Various scientific and mathematical Python-based packages use Numpy. They might take input as an inbuilt Python sequence but they are likely to convert the data into a NumPy array in order to attain faster processing. This explains the need to understand NumPy. Numpy arrays are written mostly in C language. Being written in C, the NumPy arrays are stored in contiguous memory locations which makes them accessible and easier to manipulate. This means that you can get the performance level of a C code with the ease of writing a python program. If you don’t have NumPy installed in your system, you can do so by following these steps. After installing NumPy you can import it in your program like this import numpy as np Here np is a commonly used alias to NumPy. You can use the np alias to create ndarray of a list using the array() method. li = [1,2,3,4] numpyArr = np.array(li) or numpyArr = np.array([1,2,3,4]) The list is passed to the array() method which then returns a NumPy array with the same elements. Example: The following example shows how to initialize a NumPy array from a list. Python3 import numpy as np li = [1, 2, 3, 4]numpyArr = np.array(li)print(numpyArr) Output: [1 2 3 4] The resulting array looks the same as a list but is actually a NumPy object. Example: Let’s take an example to check whether the numpyArr is a NumPy object or not. Python3 import numpy as np li = [1, 2, 3, 4]numpyArr = np.array(li) print("li =", li, "and type(li) =", type(li))print("numpyArr =", numpyArr, "and type(numpyArr) =", type(numpyArr)) Output: li = [1, 2, 3, 4] and type(li) = <class 'list'> numpyArr = [1 2 3 4] and type(numpyArr) = <class 'numpy.ndarray'> As you can see li is a list object whereas numpyArr is an array object of NumPy. You can make ndarray from a tuple using similar syntax. tup = (1,2,3,4) numpyArr = np.array(tup) or numpyArr = np.array((1,2,3,4)) Example: The following example illustrates how to create a NumPy array from a tuple. Python3 import numpy as np tup = (1, 2, 3, 4)numpyArr = np.array(tup) print("tup =", tup, "and type(tup) =", type(tup))print("numpyArr =", numpyArr, "and type(numpyArr) =", type(numpyArr)) Output: tup = (1, 2, 3, 4) and type(tup) = <class 'tuple'> numpyArr = [1 2 3 4] and type(numpyArr) = <class 'numpy.ndarray'> Note that the value of numpyArr remains the same for either of the two conversions. Python numpy-arrayCreation Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n29 Aug, 2020" }, { "code": null, "e": 420, "s": 52, "text": "Python lists are a substitute for arrays, but they fail to deliver the performance required while computing large sets of numerical data. To address this issue we use a python library called NumPy. The word NumPy stands for Numerical Python. NumPy offers an array object called ndarray. They are similar to standard python sequences but differ in certain key factors." }, { "code": null, "e": 583, "s": 420, "text": "Unlike lists, NumPy arrays are of fixed size, and changing the size of an array will lead to the creation of a new array while the original array will be deleted." }, { "code": null, "e": 634, "s": 583, "text": "All the elements in an array are of the same type." }, { "code": null, "e": 731, "s": 634, "text": "Numpy arrays are faster, more efficient, and require less syntax than standard python sequences." }, { "code": null, "e": 999, "s": 731, "text": "Note: Various scientific and mathematical Python-based packages use Numpy. They might take input as an inbuilt Python sequence but they are likely to convert the data into a NumPy array in order to attain faster processing. This explains the need to understand NumPy." }, { "code": null, "e": 1284, "s": 999, "text": "Numpy arrays are written mostly in C language. Being written in C, the NumPy arrays are stored in contiguous memory locations which makes them accessible and easier to manipulate. This means that you can get the performance level of a C code with the ease of writing a python program." }, { "code": null, "e": 1441, "s": 1284, "text": "If you don’t have NumPy installed in your system, you can do so by following these steps. After installing NumPy you can import it in your program like this" }, { "code": null, "e": 1461, "s": 1441, "text": "import numpy as np\n" }, { "code": null, "e": 1504, "s": 1461, "text": "Here np is a commonly used alias to NumPy." }, { "code": null, "e": 1583, "s": 1504, "text": "You can use the np alias to create ndarray of a list using the array() method." }, { "code": null, "e": 1623, "s": 1583, "text": "li = [1,2,3,4]\nnumpyArr = np.array(li)\n" }, { "code": null, "e": 1626, "s": 1623, "text": "or" }, { "code": null, "e": 1658, "s": 1626, "text": "numpyArr = np.array([1,2,3,4])\n" }, { "code": null, "e": 1756, "s": 1658, "text": "The list is passed to the array() method which then returns a NumPy array with the same elements." }, { "code": null, "e": 1765, "s": 1756, "text": "Example:" }, { "code": null, "e": 1839, "s": 1765, "text": "The following example shows how to initialize a NumPy array from a list. " }, { "code": null, "e": 1847, "s": 1839, "text": "Python3" }, { "code": "import numpy as np li = [1, 2, 3, 4]numpyArr = np.array(li)print(numpyArr)", "e": 1923, "s": 1847, "text": null }, { "code": null, "e": 1931, "s": 1923, "text": "Output:" }, { "code": null, "e": 1942, "s": 1931, "text": "[1 2 3 4]\n" }, { "code": null, "e": 2020, "s": 1942, "text": "The resulting array looks the same as a list but is actually a NumPy object. " }, { "code": null, "e": 2107, "s": 2020, "text": "Example: Let’s take an example to check whether the numpyArr is a NumPy object or not." }, { "code": null, "e": 2115, "s": 2107, "text": "Python3" }, { "code": "import numpy as np li = [1, 2, 3, 4]numpyArr = np.array(li) print(\"li =\", li, \"and type(li) =\", type(li))print(\"numpyArr =\", numpyArr, \"and type(numpyArr) =\", type(numpyArr))", "e": 2292, "s": 2115, "text": null }, { "code": null, "e": 2300, "s": 2292, "text": "Output:" }, { "code": null, "e": 2415, "s": 2300, "text": "li = [1, 2, 3, 4] and type(li) = <class 'list'>\nnumpyArr = [1 2 3 4] and type(numpyArr) = <class 'numpy.ndarray'>\n" }, { "code": null, "e": 2496, "s": 2415, "text": "As you can see li is a list object whereas numpyArr is an array object of NumPy." }, { "code": null, "e": 2552, "s": 2496, "text": "You can make ndarray from a tuple using similar syntax." }, { "code": null, "e": 2594, "s": 2552, "text": "tup = (1,2,3,4)\nnumpyArr = np.array(tup)\n" }, { "code": null, "e": 2597, "s": 2594, "text": "or" }, { "code": null, "e": 2629, "s": 2597, "text": "numpyArr = np.array((1,2,3,4))\n" }, { "code": null, "e": 2638, "s": 2629, "text": "Example:" }, { "code": null, "e": 2714, "s": 2638, "text": "The following example illustrates how to create a NumPy array from a tuple." }, { "code": null, "e": 2722, "s": 2714, "text": "Python3" }, { "code": "import numpy as np tup = (1, 2, 3, 4)numpyArr = np.array(tup) print(\"tup =\", tup, \"and type(tup) =\", type(tup))print(\"numpyArr =\", numpyArr, \"and type(numpyArr) =\", type(numpyArr))", "e": 2905, "s": 2722, "text": null }, { "code": null, "e": 2913, "s": 2905, "text": "Output:" }, { "code": null, "e": 3031, "s": 2913, "text": "tup = (1, 2, 3, 4) and type(tup) = <class 'tuple'>\nnumpyArr = [1 2 3 4] and type(numpyArr) = <class 'numpy.ndarray'>\n" }, { "code": null, "e": 3115, "s": 3031, "text": "Note that the value of numpyArr remains the same for either of the two conversions." }, { "code": null, "e": 3142, "s": 3115, "text": "Python numpy-arrayCreation" }, { "code": null, "e": 3155, "s": 3142, "text": "Python-numpy" }, { "code": null, "e": 3162, "s": 3155, "text": "Python" } ]
Python | Pandas Series.to_frame()
05 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.to_frame() function is used to convert the given series object to a dataframe. Syntax: Series.to_frame(name=None) Parameter :name : The passed name should substitute for the series name (if it has one). Returns : data_frame : DataFrame Example #1: Use Series.to_frame() function to convert the given series object to a dataframe. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio', 'Moscow']) # Create the Datetime Indexdidx = pd.DatetimeIndex(start ='2014-08-01 10:00', freq ='W', periods = 6, tz = 'Europe/Berlin') # set the indexsr.index = didx # Print the seriesprint(sr) Output : Now we will use Series.to_frame() function to convert the given series object to a dataframe. # convert to dataframesr.to_frame() Output : As we can see in the output, the Series.to_frame() function has successfully converted the given series object to a dataframe. Example #2: Use Series.to_frame() function to convert the given series object to a dataframe. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([19.5, 16.8, 22.78, 20.124, 18.1002]) # Print the seriesprint(sr) Output : Now we will use Series.to_frame() function to convert the given series object to a dataframe. # convert to dataframesr.to_frame() Output : As we can see in the output, the Series.to_frame() function has successfully converted the given series object to a dataframe. 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": "\n05 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": 378, "s": 285, "text": "Pandas Series.to_frame() function is used to convert the given series object to a dataframe." }, { "code": null, "e": 413, "s": 378, "text": "Syntax: Series.to_frame(name=None)" }, { "code": null, "e": 502, "s": 413, "text": "Parameter :name : The passed name should substitute for the series name (if it has one)." }, { "code": null, "e": 535, "s": 502, "text": "Returns : data_frame : DataFrame" }, { "code": null, "e": 629, "s": 535, "text": "Example #1: Use Series.to_frame() function to convert the given series object to a dataframe." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio', 'Moscow']) # Create the Datetime Indexdidx = pd.DatetimeIndex(start ='2014-08-01 10:00', freq ='W', periods = 6, tz = 'Europe/Berlin') # set the indexsr.index = didx # Print the seriesprint(sr)", "e": 981, "s": 629, "text": null }, { "code": null, "e": 990, "s": 981, "text": "Output :" }, { "code": null, "e": 1084, "s": 990, "text": "Now we will use Series.to_frame() function to convert the given series object to a dataframe." }, { "code": "# convert to dataframesr.to_frame()", "e": 1120, "s": 1084, "text": null }, { "code": null, "e": 1129, "s": 1120, "text": "Output :" }, { "code": null, "e": 1256, "s": 1129, "text": "As we can see in the output, the Series.to_frame() function has successfully converted the given series object to a dataframe." }, { "code": null, "e": 1350, "s": 1256, "text": "Example #2: Use Series.to_frame() function to convert the given series object to a dataframe." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([19.5, 16.8, 22.78, 20.124, 18.1002]) # Print the seriesprint(sr)", "e": 1498, "s": 1350, "text": null }, { "code": null, "e": 1507, "s": 1498, "text": "Output :" }, { "code": null, "e": 1601, "s": 1507, "text": "Now we will use Series.to_frame() function to convert the given series object to a dataframe." }, { "code": "# convert to dataframesr.to_frame()", "e": 1637, "s": 1601, "text": null }, { "code": null, "e": 1646, "s": 1637, "text": "Output :" }, { "code": null, "e": 1773, "s": 1646, "text": "As we can see in the output, the Series.to_frame() function has successfully converted the given series object to a dataframe." }, { "code": null, "e": 1794, "s": 1773, "text": "Python pandas-series" }, { "code": null, "e": 1823, "s": 1794, "text": "Python pandas-series-methods" }, { "code": null, "e": 1837, "s": 1823, "text": "Python-pandas" }, { "code": null, "e": 1844, "s": 1837, "text": "Python" } ]
Python | os.path.expanduser() method
11 Oct, 2021 OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.path module is sub module of OS module in Python used for common pathname manipulation.os.path.expanduser() method in Python is used to expand an initial path component ~( tilde symbol) or ~user in the given path to user’s home directory. On Unix platforms, an initial ~ is replaced by the value of HOME environment variable, if it is set. Otherwise, os.path.expanduser() method search for user’s home directory in password directory using an in-built module pwd. Path containing an initial ~user component is looked up directly in the password directory.On Windows platform, an initial ~ is replaced by the value of HOME and USERPROFILE environment variable, if it is set. Otherwise, HOMEPATH and HOMEDRIVE environment variable will be used. While Path containing an initial ~user component is handled by replacing the last directory component with ~user from the path derived above. Syntax: os.path.expanduser(path)Parameter: path: A path-like object representing a file system path. A path-like object is either a string or bytes object representing a path.Return Type: This method returns a string value which represents the path after expanding an initial path component ~ or ~user in the given path. Code #1: Use of os.path.expanduser() method (On Unix) Python3 # Python program to explain os.path.expanduser() method # importing os.path module import os.path # Pathpath = "~/file.txt" # Expand an initial ~ component# in the given path# using os.path.expanduser() methodfull_path = os.path.expanduser(path) # print the path after# expanding the initial ~ component# in the given pathprint(full_path) # Change the value of# HOME environment variableos.environ["HOME"] = "/home / GeeksForGeeks" # Now, Expand the initial ~ component# in the same path# using os.path.expanduser() methodfull_path = os.path.expanduser(path) # print the path after# expanding initial ~ component# in the given pathprint(full_path) # While expansion, An initial# ~user component is looked# up directly in the password directory. # Path having an initial# ~user componentpath = "~ihritik / file.txt" # Expand the initial ~user# component in the given path# using os.path.expanduser() methodfull_path = os.path.expanduser(path) # print the path after# expanding the initial ~user# component in the given pathprint(full_path) /home/ihritik/file.txt /home/GeeksForGeeks/file.txt /home/ihritik/file.txt Code #2: Use of os.path.expanduser() method (On Windows) Python3 # Python program to explain os.path.expandvars() method # importing os.path module import os.path # On Windows % name % expansions# are supported in addition to# $name and ${name} # Path 1path1 = R"% HOMEPATH %\Directory\file.txt" # Path 2path2 = R"C:\Users\$USERNAME\Directory\file.txt" # Path 3path3 = R"${TEMP}\file.txt" # Expand the environment variables# with their corresponding # value in the given paths exp_var1 = os.path.expandvars(path1)exp_var2 = os.path.expandvars(path2)exp_var3 = os.path.expandvars(path3) # Print the given paths with# environment variables expandedprint(exp_var1)print(exp_var2)print(exp_var3) # In the above example # os.path.expandvars() method# replaced the environment variables# 'HOMEPATH', 'USERNAME' and 'TEMP'# with their corresponding values \\Users\\Hritik\\\Directory\\file.txt C:\\Users\\Hritik\\\Directory\\file.txt C:\\Users\\Hritik\\AppData\\Local\\Temp\\file.txt Code #3: 3: If environment variable does not exists Python3 # Python program to explain os.path.expandvars() method # importing os.path module import os.path # If environment variable # is malformed or does not exists# then the given path will be# left unchanged # Pathpath = R"${MYHOME}/Directory / file.txt" # Expand the environment variables# with their corresponding # value in the given paths exp_var = os.path.expandvars(path) # Print the given patha with# environment variables expandedprint(exp_var) # As 'MYHOME' environment variable# does not exists so# os.path.expandvars() method# will return the given path# unchanged ${MYHOME}/Directory/file.txt Reference: https://docs.python.org/3/library/os.path.html simranarora5sos adnanirshad158 Python OS-path-module python-os-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Oct, 2021" }, { "code": null, "e": 1136, "s": 28, "text": "OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.path module is sub module of OS module in Python used for common pathname manipulation.os.path.expanduser() method in Python is used to expand an initial path component ~( tilde symbol) or ~user in the given path to user’s home directory. On Unix platforms, an initial ~ is replaced by the value of HOME environment variable, if it is set. Otherwise, os.path.expanduser() method search for user’s home directory in password directory using an in-built module pwd. Path containing an initial ~user component is looked up directly in the password directory.On Windows platform, an initial ~ is replaced by the value of HOME and USERPROFILE environment variable, if it is set. Otherwise, HOMEPATH and HOMEDRIVE environment variable will be used. While Path containing an initial ~user component is handled by replacing the last directory component with ~user from the path derived above. " }, { "code": null, "e": 1458, "s": 1136, "text": "Syntax: os.path.expanduser(path)Parameter: path: A path-like object representing a file system path. A path-like object is either a string or bytes object representing a path.Return Type: This method returns a string value which represents the path after expanding an initial path component ~ or ~user in the given path. " }, { "code": null, "e": 1514, "s": 1458, "text": "Code #1: Use of os.path.expanduser() method (On Unix) " }, { "code": null, "e": 1522, "s": 1514, "text": "Python3" }, { "code": "# Python program to explain os.path.expanduser() method # importing os.path module import os.path # Pathpath = \"~/file.txt\" # Expand an initial ~ component# in the given path# using os.path.expanduser() methodfull_path = os.path.expanduser(path) # print the path after# expanding the initial ~ component# in the given pathprint(full_path) # Change the value of# HOME environment variableos.environ[\"HOME\"] = \"/home / GeeksForGeeks\" # Now, Expand the initial ~ component# in the same path# using os.path.expanduser() methodfull_path = os.path.expanduser(path) # print the path after# expanding initial ~ component# in the given pathprint(full_path) # While expansion, An initial# ~user component is looked# up directly in the password directory. # Path having an initial# ~user componentpath = \"~ihritik / file.txt\" # Expand the initial ~user# component in the given path# using os.path.expanduser() methodfull_path = os.path.expanduser(path) # print the path after# expanding the initial ~user# component in the given pathprint(full_path)", "e": 2583, "s": 1522, "text": null }, { "code": null, "e": 2658, "s": 2583, "text": "/home/ihritik/file.txt\n/home/GeeksForGeeks/file.txt\n/home/ihritik/file.txt" }, { "code": null, "e": 2719, "s": 2660, "text": "Code #2: Use of os.path.expanduser() method (On Windows) " }, { "code": null, "e": 2727, "s": 2719, "text": "Python3" }, { "code": "# Python program to explain os.path.expandvars() method # importing os.path module import os.path # On Windows % name % expansions# are supported in addition to# $name and ${name} # Path 1path1 = R\"% HOMEPATH %\\Directory\\file.txt\" # Path 2path2 = R\"C:\\Users\\$USERNAME\\Directory\\file.txt\" # Path 3path3 = R\"${TEMP}\\file.txt\" # Expand the environment variables# with their corresponding # value in the given paths exp_var1 = os.path.expandvars(path1)exp_var2 = os.path.expandvars(path2)exp_var3 = os.path.expandvars(path3) # Print the given paths with# environment variables expandedprint(exp_var1)print(exp_var2)print(exp_var3) # In the above example # os.path.expandvars() method# replaced the environment variables# 'HOMEPATH', 'USERNAME' and 'TEMP'# with their corresponding values", "e": 3534, "s": 2727, "text": null }, { "code": null, "e": 3662, "s": 3534, "text": "\\\\Users\\\\Hritik\\\\\\Directory\\\\file.txt\nC:\\\\Users\\\\Hritik\\\\\\Directory\\\\file.txt\nC:\\\\Users\\\\Hritik\\\\AppData\\\\Local\\\\Temp\\\\file.txt" }, { "code": null, "e": 3718, "s": 3664, "text": "Code #3: 3: If environment variable does not exists " }, { "code": null, "e": 3726, "s": 3718, "text": "Python3" }, { "code": "# Python program to explain os.path.expandvars() method # importing os.path module import os.path # If environment variable # is malformed or does not exists# then the given path will be# left unchanged # Pathpath = R\"${MYHOME}/Directory / file.txt\" # Expand the environment variables# with their corresponding # value in the given paths exp_var = os.path.expandvars(path) # Print the given patha with# environment variables expandedprint(exp_var) # As 'MYHOME' environment variable# does not exists so# os.path.expandvars() method# will return the given path# unchanged", "e": 4316, "s": 3726, "text": null }, { "code": null, "e": 4345, "s": 4316, "text": "${MYHOME}/Directory/file.txt" }, { "code": null, "e": 4406, "s": 4347, "text": "Reference: https://docs.python.org/3/library/os.path.html " }, { "code": null, "e": 4422, "s": 4406, "text": "simranarora5sos" }, { "code": null, "e": 4437, "s": 4422, "text": "adnanirshad158" }, { "code": null, "e": 4459, "s": 4437, "text": "Python OS-path-module" }, { "code": null, "e": 4476, "s": 4459, "text": "python-os-module" }, { "code": null, "e": 4483, "s": 4476, "text": "Python" } ]
HTML5 - Web Forms 2.0
Web Forms 2.0 is an extension to the forms features found in HTML4. Form elements and attributes in HTML5 provide a greater degree of semantic mark-up than HTML4 and free us from a great deal of tedious scripting and styling that was required in HTML4. HTML4 input elements use the type attribute to specify the data type.HTML4 provides following types − text A free-form text field, nominally free of line breaks. password A free-form text field for sensitive information, nominally free of line breaks. checkbox A set of zero or more values from a predefined list. radio An enumerated value. submit A free form of button initiates form submission. file An arbitrary file with a MIME type and optionally a file name. image A coordinate, relative to a particular image's size, with the extra semantic that it must be the last value selected and initiates form submission. hidden An arbitrary string that is not normally displayed to the user. select An enumerated value, much like the radio type. textarea A free-form text field, nominally with no line break restrictions. button A free form of button which can initiates any event related to button. Following is the simple example of using labels, radio buttons, and submit buttons − ... <form action = "http://example.com/cgiscript.pl" method = "post"> <p> <label for = "firstname">first name: </label> <input type = "text" id = "firstname"><br /> <label for = "lastname">last name: </label> <input type = "text" id = "lastname"><br /> <label for = "email">email: </label> <input type = "text" id = "email"><br> <input type = "radio" name = "sex" value = "male"> Male<br> <input type = "radio" name = "sex" value = "female"> Female<br> <input type = "submit" value = "send"> <input type = "reset"> </p> </form> ... Apart from the above-mentioned attributes, HTML5 input elements introduced several new values for the type attribute. These are listed below. NOTE − Try all the following example using latest version of Opera browser. A date and time (year, month, day, hour, minute, second, fractions of a second) encoded according to ISO 8601 with the time zone set to UTC. A date and time (year, month, day, hour, minute, second, fractions of a second) encoded according to ISO 8601, with no time zone information. A date (year, month, day) encoded according to ISO 8601. A date consisting of a year and a month encoded according to ISO 8601. A date consisting of a year and a week number encoded according to ISO 8601. A time (hour, minute, seconds, fractional seconds) encoded according to ISO 8601. It accepts only numerical value. The step attribute specifies the precision, defaulting to 1. The range type is used for input fields that should contain a value from a range of numbers. It accepts only email value. This type is used for input fields that should contain an e-mail address. If you try to submit a simple text, it forces to enter only email address in email@example.com format. It accepts only URL value. This type is used for input fields that should contain a URL address. If you try to submit a simple text, it forces to enter only URL address either in http://www.example.com format or in http://example.com format. HTML5 introduced a new element <output> which is used to represent the result of different types of output, such as output written by a script. You can use the for attribute to specify a relationship between the output element and other elements in the document that affected the calculation (for example, as inputs or parameters). The value of the for attribute is a space-separated list of IDs of other elements. <!DOCTYPE HTML> <html> <head> <script type = "text/javascript"> function showResult() { x = document.forms["myform"]["newinput"].value; document.forms["myform"]["result"].value = x; } </script> </head> <body> <form action = "/cgi-bin/html5.cgi" method = "get" name = "myform"> Enter a value : <input type = "text" name = "newinput" /> <input type = "button" value = "Result" onclick = "showResult();" /> <output name = "result"></output> </form> </body> </html> It will produce the following result − HTML5 introduced a new attribute called placeholder. This attribute on <input> and <textarea> elements provide a hint to the user of what can be entered in the field. The placeholder text must not contain carriage returns or line-feeds. Here is the simple syntax for placeholder attribute − <input type = "text" name = "search" placeholder = "search the web"/> This attribute is supported by latest versions of Mozilla, Safari and Crome browsers only. <!DOCTYPE HTML> <html> <body> <form action = "/cgi-bin/html5.cgi" method = "get"> Enter email : <input type = "email" name = "newinput" placeholder = "email@example.com"/> <input type = "submit" value = "submit" /> </form> </body> </html> This will produce the following result − This is a simple one-step pattern, easily programmed in JavaScript at the time of document load, automatically focus one particular form field. HTML5 introduced a new attribute called autofocus which would be used as follows − <input type = "text" name = "search" autofocus/> This attribute is supported by latest versions of Mozilla, Safari and Chrome browsers only. <!DOCTYPE HTML> <html> <body> <form action = "/cgi-bin/html5.cgi" method = "get"> Enter email : <input type = "text" name = "newinput" autofocus/> <p>Try to submit using Submit button</p> <input type = "submit" value = "submit" /> </form> </body> </html> Now you do not need to have JavaScript for client-side validations like empty text box would never be submitted because HTML5 introduced a new attribute called required which would be used as follows and would insist to have a value − <input type = "text" name = "search" required/> This attribute is supported by latest versions of Mozilla, Safari and Chrome browsers only. <!DOCTYPE HTML> <html> <body> <form action = "/cgi-bin/html5.cgi" method = "get"> Enter email : <input type = "text" name = "newinput" required/> <p>Try to submit using Submit button</p> <input type = "submit" value = "submit" /> </form> </body> </html> It will produce the following result − Try to submit using Submit button 19 Lectures 2 hours Anadi Sharma 16 Lectures 1.5 hours Anadi Sharma 18 Lectures 1.5 hours Frahaan Hussain 57 Lectures 5.5 hours DigiFisk (Programming Is Fun) 54 Lectures 6 hours DigiFisk (Programming Is Fun) 45 Lectures 5.5 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2861, "s": 2608, "text": "Web Forms 2.0 is an extension to the forms features found in HTML4. Form elements and attributes in HTML5 provide a greater degree of semantic mark-up than HTML4 and free us from a great deal of tedious scripting and styling that was required in HTML4." }, { "code": null, "e": 2963, "s": 2861, "text": "HTML4 input elements use the type attribute to specify the data type.HTML4 provides following types −" }, { "code": null, "e": 2968, "s": 2963, "text": "text" }, { "code": null, "e": 3023, "s": 2968, "text": "A free-form text field, nominally free of line breaks." }, { "code": null, "e": 3032, "s": 3023, "text": "password" }, { "code": null, "e": 3113, "s": 3032, "text": "A free-form text field for sensitive information, nominally free of line breaks." }, { "code": null, "e": 3122, "s": 3113, "text": "checkbox" }, { "code": null, "e": 3175, "s": 3122, "text": "A set of zero or more values from a predefined list." }, { "code": null, "e": 3181, "s": 3175, "text": "radio" }, { "code": null, "e": 3202, "s": 3181, "text": "An enumerated value." }, { "code": null, "e": 3209, "s": 3202, "text": "submit" }, { "code": null, "e": 3258, "s": 3209, "text": "A free form of button initiates form submission." }, { "code": null, "e": 3263, "s": 3258, "text": "file" }, { "code": null, "e": 3326, "s": 3263, "text": "An arbitrary file with a MIME type and optionally a file name." }, { "code": null, "e": 3332, "s": 3326, "text": "image" }, { "code": null, "e": 3480, "s": 3332, "text": "A coordinate, relative to a particular image's size, with the extra semantic that it must be the last value selected and initiates form submission." }, { "code": null, "e": 3487, "s": 3480, "text": "hidden" }, { "code": null, "e": 3551, "s": 3487, "text": "An arbitrary string that is not normally displayed to the user." }, { "code": null, "e": 3558, "s": 3551, "text": "select" }, { "code": null, "e": 3605, "s": 3558, "text": "An enumerated value, much like the radio type." }, { "code": null, "e": 3614, "s": 3605, "text": "textarea" }, { "code": null, "e": 3681, "s": 3614, "text": "A free-form text field, nominally with no line break restrictions." }, { "code": null, "e": 3688, "s": 3681, "text": "button" }, { "code": null, "e": 3759, "s": 3688, "text": "A free form of button which can initiates any event related to button." }, { "code": null, "e": 3844, "s": 3759, "text": "Following is the simple example of using labels, radio buttons, and submit buttons −" }, { "code": null, "e": 4465, "s": 3844, "text": "... \n<form action = \"http://example.com/cgiscript.pl\" method = \"post\"> \n <p> \n <label for = \"firstname\">first name: </label> \n <input type = \"text\" id = \"firstname\"><br /> \n \n <label for = \"lastname\">last name: </label> \n <input type = \"text\" id = \"lastname\"><br /> \n \n <label for = \"email\">email: </label> \n <input type = \"text\" id = \"email\"><br> \n \n <input type = \"radio\" name = \"sex\" value = \"male\"> Male<br> \n <input type = \"radio\" name = \"sex\" value = \"female\"> Female<br> \n <input type = \"submit\" value = \"send\"> <input type = \"reset\"> \n </p> \n</form> \n ... " }, { "code": null, "e": 4607, "s": 4465, "text": "Apart from the above-mentioned attributes, HTML5 input elements introduced several new values for the type attribute. These are listed below." }, { "code": null, "e": 4683, "s": 4607, "text": "NOTE − Try all the following example using latest version of Opera browser." }, { "code": null, "e": 4824, "s": 4683, "text": "A date and time (year, month, day, hour, minute, second, fractions of a second) encoded according to ISO 8601 with the time zone set to UTC." }, { "code": null, "e": 4966, "s": 4824, "text": "A date and time (year, month, day, hour, minute, second, fractions of a second) encoded according to ISO 8601, with no time zone information." }, { "code": null, "e": 5023, "s": 4966, "text": "A date (year, month, day) encoded according to ISO 8601." }, { "code": null, "e": 5094, "s": 5023, "text": "A date consisting of a year and a month encoded according to ISO 8601." }, { "code": null, "e": 5171, "s": 5094, "text": "A date consisting of a year and a week number encoded according to ISO 8601." }, { "code": null, "e": 5253, "s": 5171, "text": "A time (hour, minute, seconds, fractional seconds) encoded according to ISO 8601." }, { "code": null, "e": 5347, "s": 5253, "text": "It accepts only numerical value. The step attribute specifies the precision, defaulting to 1." }, { "code": null, "e": 5440, "s": 5347, "text": "The range type is used for input fields that should contain a value from a range of numbers." }, { "code": null, "e": 5646, "s": 5440, "text": "It accepts only email value. This type is used for input fields that should contain an e-mail address. If you try to submit a simple text, it forces to enter only email address in email@example.com format." }, { "code": null, "e": 5888, "s": 5646, "text": "It accepts only URL value. This type is used for input fields that should contain a URL address. If you try to submit a simple text, it forces to enter only URL address either in http://www.example.com format or in http://example.com format." }, { "code": null, "e": 6032, "s": 5888, "text": "HTML5 introduced a new element <output> which is used to represent the result of different types of output, such as output written by a script." }, { "code": null, "e": 6303, "s": 6032, "text": "You can use the for attribute to specify a relationship between the output element and other elements in the document that affected the calculation (for example, as inputs or parameters). The value of the for attribute is a space-separated list of IDs of other elements." }, { "code": null, "e": 6890, "s": 6303, "text": "<!DOCTYPE HTML>\n\n<html>\n <head>\n <script type = \"text/javascript\">\n \n function showResult() {\n x = document.forms[\"myform\"][\"newinput\"].value;\n document.forms[\"myform\"][\"result\"].value = x;\n }\n </script>\n </head>\n \n <body>\n\n <form action = \"/cgi-bin/html5.cgi\" method = \"get\" name = \"myform\">\n Enter a value : <input type = \"text\" name = \"newinput\" />\n <input type = \"button\" value = \"Result\" onclick = \"showResult();\" />\n <output name = \"result\"></output>\n </form>\n\t\t\n </body>\n</html>" }, { "code": null, "e": 6929, "s": 6890, "text": "It will produce the following result −" }, { "code": null, "e": 7166, "s": 6929, "text": "HTML5 introduced a new attribute called placeholder. This attribute on <input> and <textarea> elements provide a hint to the user of what can be entered in the field. The placeholder text must not contain carriage returns or line-feeds." }, { "code": null, "e": 7220, "s": 7166, "text": "Here is the simple syntax for placeholder attribute −" }, { "code": null, "e": 7291, "s": 7220, "text": "<input type = \"text\" name = \"search\" placeholder = \"search the web\"/>\n" }, { "code": null, "e": 7382, "s": 7291, "text": "This attribute is supported by latest versions of Mozilla, Safari and Crome browsers only." }, { "code": null, "e": 7673, "s": 7382, "text": "<!DOCTYPE HTML>\n\n<html>\n <body>\n\n <form action = \"/cgi-bin/html5.cgi\" method = \"get\">\n Enter email : <input type = \"email\" name = \"newinput\" \n placeholder = \"email@example.com\"/>\n <input type = \"submit\" value = \"submit\" />\n </form>\n\n </body>\n</html>" }, { "code": null, "e": 7714, "s": 7673, "text": "This will produce the following result −" }, { "code": null, "e": 7858, "s": 7714, "text": "This is a simple one-step pattern, easily programmed in JavaScript at the time of document load, automatically focus one particular form field." }, { "code": null, "e": 7941, "s": 7858, "text": "HTML5 introduced a new attribute called autofocus which would be used as follows −" }, { "code": null, "e": 7991, "s": 7941, "text": "<input type = \"text\" name = \"search\" autofocus/>\n" }, { "code": null, "e": 8083, "s": 7991, "text": "This attribute is supported by latest versions of Mozilla, Safari and Chrome browsers only." }, { "code": null, "e": 8395, "s": 8083, "text": "<!DOCTYPE HTML>\n\n<html>\n <body>\n \n <form action = \"/cgi-bin/html5.cgi\" method = \"get\">\n Enter email : <input type = \"text\" name = \"newinput\" autofocus/>\n <p>Try to submit using Submit button</p>\n <input type = \"submit\" value = \"submit\" />\n </form>\n \n </body>\n</html>" }, { "code": null, "e": 8630, "s": 8395, "text": "Now you do not need to have JavaScript for client-side validations like empty text box would never be submitted because HTML5 introduced a new attribute called required which would be used as follows and would insist to have a value −" }, { "code": null, "e": 8679, "s": 8630, "text": "<input type = \"text\" name = \"search\" required/>\n" }, { "code": null, "e": 8771, "s": 8679, "text": "This attribute is supported by latest versions of Mozilla, Safari and Chrome browsers only." }, { "code": null, "e": 9082, "s": 8771, "text": "<!DOCTYPE HTML>\n\n<html>\n <body>\n \n <form action = \"/cgi-bin/html5.cgi\" method = \"get\">\n Enter email : <input type = \"text\" name = \"newinput\" required/>\n <p>Try to submit using Submit button</p>\n <input type = \"submit\" value = \"submit\" />\n </form>\n \n </body>\n</html>" }, { "code": null, "e": 9121, "s": 9082, "text": "It will produce the following result −" }, { "code": null, "e": 9155, "s": 9121, "text": "Try to submit using Submit button" }, { "code": null, "e": 9188, "s": 9155, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 9202, "s": 9188, "text": " Anadi Sharma" }, { "code": null, "e": 9237, "s": 9202, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 9251, "s": 9237, "text": " Anadi Sharma" }, { "code": null, "e": 9286, "s": 9251, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 9303, "s": 9286, "text": " Frahaan Hussain" }, { "code": null, "e": 9338, "s": 9303, "text": "\n 57 Lectures \n 5.5 hours \n" }, { "code": null, "e": 9369, "s": 9338, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 9402, "s": 9369, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 9433, "s": 9402, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 9468, "s": 9433, "text": "\n 45 Lectures \n 5.5 hours \n" }, { "code": null, "e": 9499, "s": 9468, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 9506, "s": 9499, "text": " Print" }, { "code": null, "e": 9517, "s": 9506, "text": " Add Notes" } ]
CSS | saturate() Function - GeeksforGeeks
22 Aug, 2019 The saturate() function is an inbuilt function in CSS which is used to super-saturate or desaturates the input image. Syntax: saturate( amount ) Parameters: This function accepts single parameter amount, which holds the amount of conversion. The value of the parameter is set in terms of number or percentage. The value 0% represents completely unsaturated and 100% represents completely saturated you can increase the saturation more. Below example illustrate the saturate() function in CSS: Example: <!DOCTYPE html><html> <head> <title> CSS saturate() Function </title> <style> h1 { color: green; } body { text-align: center; } .saturate_effect { filter: saturate(250%); } </style></head> <body> <h1>GeeksforGeeks</h1> <h4>CSS saturate() function</h4> <img class="saturate_effect" src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png" alt="GeeksforGeeks logo"></body> </html> Output: Supported Browsers: The browsers supported by saturate() function are listed below: Google Chrome Internet Explorer Firefox Opera Safari CSS-Functions CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Types of CSS (Cascading Style Sheet) How to position a div at the bottom of its container using CSS? How to set space between the flexbox ? How to Upload Image into Database and Display it using PHP ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 25739, "s": 25711, "text": "\n22 Aug, 2019" }, { "code": null, "e": 25857, "s": 25739, "text": "The saturate() function is an inbuilt function in CSS which is used to super-saturate or desaturates the input image." }, { "code": null, "e": 25865, "s": 25857, "text": "Syntax:" }, { "code": null, "e": 25884, "s": 25865, "text": "saturate( amount )" }, { "code": null, "e": 26175, "s": 25884, "text": "Parameters: This function accepts single parameter amount, which holds the amount of conversion. The value of the parameter is set in terms of number or percentage. The value 0% represents completely unsaturated and 100% represents completely saturated you can increase the saturation more." }, { "code": null, "e": 26232, "s": 26175, "text": "Below example illustrate the saturate() function in CSS:" }, { "code": null, "e": 26241, "s": 26232, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> CSS saturate() Function </title> <style> h1 { color: green; } body { text-align: center; } .saturate_effect { filter: saturate(250%); } </style></head> <body> <h1>GeeksforGeeks</h1> <h4>CSS saturate() function</h4> <img class=\"saturate_effect\" src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png\" alt=\"GeeksforGeeks logo\"></body> </html>", "e": 26792, "s": 26241, "text": null }, { "code": null, "e": 26800, "s": 26792, "text": "Output:" }, { "code": null, "e": 26884, "s": 26800, "text": "Supported Browsers: The browsers supported by saturate() function are listed below:" }, { "code": null, "e": 26898, "s": 26884, "text": "Google Chrome" }, { "code": null, "e": 26916, "s": 26898, "text": "Internet Explorer" }, { "code": null, "e": 26924, "s": 26916, "text": "Firefox" }, { "code": null, "e": 26930, "s": 26924, "text": "Opera" }, { "code": null, "e": 26937, "s": 26930, "text": "Safari" }, { "code": null, "e": 26951, "s": 26937, "text": "CSS-Functions" }, { "code": null, "e": 26955, "s": 26951, "text": "CSS" }, { "code": null, "e": 26972, "s": 26955, "text": "Web Technologies" }, { "code": null, "e": 27070, "s": 26972, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27118, "s": 27070, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 27155, "s": 27118, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 27219, "s": 27155, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 27258, "s": 27219, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 27319, "s": 27258, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 27359, "s": 27319, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27392, "s": 27359, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27437, "s": 27392, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27480, "s": 27437, "text": "How to fetch data from an API in ReactJS ?" } ]
IntSummaryStatistics getMin() method in Java with Examples - GeeksforGeeks
27 Jun, 2019 The getMin() method of IntSummaryStatistics class in Java is used to get the minimum of records in this IntSummaryStatistics. Syntax: public int getMin() Parameter: This method do not accept any value as parameter. Return Value: This method returns the minimum of the records in this IntSummaryStatistics. Program: // Java program to demonstrate// the above method import java.util.*; public class IntSummaryStatisticsDemo { public static void main(String[] args) { IntSummaryStatistics intSummaryStatistics = new IntSummaryStatistics(); List<Integer> list = Arrays.asList(10, 20, 30, 40, 50); Iterator<Integer> iterator = list.listIterator(); while (iterator.hasNext()) { // Add the integers to the IntSummaryStatistics object intSummaryStatistics.accept(iterator.next()); } System.out.println("The minimum of values is " + intSummaryStatistics.getMin()); }} The minimum of values is 10 Reference: https://docs.oracle.com/javase/10/docs/api/java/util/IntSummaryStatistics.html#getMin() Java - util package Java-Functions Java-IntSummaryStatistics Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Exceptions in Java Constructors in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Comparator Interface in Java with Examples PriorityQueue in Java Internal Working of HashMap in Java
[ { "code": null, "e": 25347, "s": 25319, "text": "\n27 Jun, 2019" }, { "code": null, "e": 25473, "s": 25347, "text": "The getMin() method of IntSummaryStatistics class in Java is used to get the minimum of records in this IntSummaryStatistics." }, { "code": null, "e": 25481, "s": 25473, "text": "Syntax:" }, { "code": null, "e": 25502, "s": 25481, "text": "public int getMin()\n" }, { "code": null, "e": 25563, "s": 25502, "text": "Parameter: This method do not accept any value as parameter." }, { "code": null, "e": 25654, "s": 25563, "text": "Return Value: This method returns the minimum of the records in this IntSummaryStatistics." }, { "code": null, "e": 25663, "s": 25654, "text": "Program:" }, { "code": "// Java program to demonstrate// the above method import java.util.*; public class IntSummaryStatisticsDemo { public static void main(String[] args) { IntSummaryStatistics intSummaryStatistics = new IntSummaryStatistics(); List<Integer> list = Arrays.asList(10, 20, 30, 40, 50); Iterator<Integer> iterator = list.listIterator(); while (iterator.hasNext()) { // Add the integers to the IntSummaryStatistics object intSummaryStatistics.accept(iterator.next()); } System.out.println(\"The minimum of values is \" + intSummaryStatistics.getMin()); }}", "e": 26341, "s": 25663, "text": null }, { "code": null, "e": 26370, "s": 26341, "text": "The minimum of values is 10\n" }, { "code": null, "e": 26469, "s": 26370, "text": "Reference: https://docs.oracle.com/javase/10/docs/api/java/util/IntSummaryStatistics.html#getMin()" }, { "code": null, "e": 26489, "s": 26469, "text": "Java - util package" }, { "code": null, "e": 26504, "s": 26489, "text": "Java-Functions" }, { "code": null, "e": 26530, "s": 26504, "text": "Java-IntSummaryStatistics" }, { "code": null, "e": 26535, "s": 26530, "text": "Java" }, { "code": null, "e": 26540, "s": 26535, "text": "Java" }, { "code": null, "e": 26638, "s": 26540, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26653, "s": 26638, "text": "Stream In Java" }, { "code": null, "e": 26672, "s": 26653, "text": "Exceptions in Java" }, { "code": null, "e": 26693, "s": 26672, "text": "Constructors in Java" }, { "code": null, "e": 26723, "s": 26693, "text": "Functional Interfaces in Java" }, { "code": null, "e": 26769, "s": 26723, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 26786, "s": 26769, "text": "Generics in Java" }, { "code": null, "e": 26807, "s": 26786, "text": "Introduction to Java" }, { "code": null, "e": 26850, "s": 26807, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 26872, "s": 26850, "text": "PriorityQueue in Java" } ]
Data Structure and Algorithms - Quick Sort
Quick sort is a highly efficient sorting algorithm and is based on partitioning of array of data into smaller arrays. A large array is partitioned into two arrays one of which holds values smaller than the specified value, say pivot, based on which the partition is made and another array holds values greater than the pivot value. Quicksort partitions an array and then calls itself recursively twice to sort the two resulting subarrays. This algorithm is quite efficient for large-sized data sets as its average and worst-case complexity are O(n2), respectively. Following animated representation explains how to find the pivot value in an array. The pivot value divides the list into two parts. And recursively, we find the pivot for each sub-lists until all lists contains only one element. Based on our understanding of partitioning in quick sort, we will now try to write an algorithm for it, which is as follows. Step 1 − Choose the highest index value has pivot Step 2 − Take two variables to point left and right of the list excluding pivot Step 3 − left points to the low index Step 4 − right points to the high Step 5 − while value at left is less than pivot move right Step 6 − while value at right is greater than pivot move left Step 7 − if both step 5 and step 6 does not match swap left and right Step 8 − if left ≥ right, the point where they met is new pivot The pseudocode for the above algorithm can be derived as − function partitionFunc(left, right, pivot) leftPointer = left rightPointer = right - 1 while True do while A[++leftPointer] < pivot do //do-nothing end while while rightPointer > 0 && A[--rightPointer] > pivot do //do-nothing end while if leftPointer >= rightPointer break else swap leftPointer,rightPointer end if end while swap leftPointer,right return leftPointer end function Using pivot algorithm recursively, we end up with smaller possible partitions. Each partition is then processed for quick sort. We define recursive algorithm for quicksort as follows − Step 1 − Make the right-most index value pivot Step 2 − partition the array using pivot value Step 3 − quicksort left partition recursively Step 4 − quicksort right partition recursively To get more into it, let see the pseudocode for quick sort algorithm − procedure quickSort(left, right) if right-left <= 0 return else pivot = A[right] partition = partitionFunc(left, right, pivot) quickSort(left,partition-1) quickSort(partition+1,right) end if end procedure To know about quick sort implementation in C programming language, please click here. 42 Lectures 1.5 hours Ravi Kiran 141 Lectures 13 hours Arnab Chakraborty 26 Lectures 8.5 hours Parth Panjabi 65 Lectures 6 hours Arnab Chakraborty 75 Lectures 13 hours Eduonix Learning Solutions 64 Lectures 10.5 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2912, "s": 2580, "text": "Quick sort is a highly efficient sorting algorithm and is based on partitioning of array of data into smaller arrays. A large array is partitioned into two arrays one of which holds values smaller than the specified value, say pivot, based on which the partition is made and another array holds values greater than the pivot value." }, { "code": null, "e": 3145, "s": 2912, "text": "Quicksort partitions an array and then calls itself recursively twice to sort the two resulting subarrays. This algorithm is quite efficient for large-sized data sets as its average and worst-case complexity are O(n2), respectively." }, { "code": null, "e": 3229, "s": 3145, "text": "Following animated representation explains how to find the pivot value in an array." }, { "code": null, "e": 3375, "s": 3229, "text": "The pivot value divides the list into two parts. And recursively, we find the pivot for each sub-lists until all lists contains only one element." }, { "code": null, "e": 3500, "s": 3375, "text": "Based on our understanding of partitioning in quick sort, we will now try to write an algorithm for it, which is as follows." }, { "code": null, "e": 3958, "s": 3500, "text": "Step 1 − Choose the highest index value has pivot\nStep 2 − Take two variables to point left and right of the list excluding pivot\nStep 3 − left points to the low index\nStep 4 − right points to the high\nStep 5 − while value at left is less than pivot move right\nStep 6 − while value at right is greater than pivot move left\nStep 7 − if both step 5 and step 6 does not match swap left and right\nStep 8 − if left ≥ right, the point where they met is new pivot\n" }, { "code": null, "e": 4017, "s": 3958, "text": "The pseudocode for the above algorithm can be derived as −" }, { "code": null, "e": 4545, "s": 4017, "text": "function partitionFunc(left, right, pivot)\n leftPointer = left\n rightPointer = right - 1\n\n while True do\n while A[++leftPointer] < pivot do\n //do-nothing \n end while\n\t\t\n while rightPointer > 0 && A[--rightPointer] > pivot do\n //do-nothing \n end while\n\t\t\n if leftPointer >= rightPointer\n break\n else \n swap leftPointer,rightPointer\n end if\n\t\t\n end while \n\t\n swap leftPointer,right\n return leftPointer\n\t\nend function" }, { "code": null, "e": 4730, "s": 4545, "text": "Using pivot algorithm recursively, we end up with smaller possible partitions. Each partition is then processed for quick sort. We define recursive algorithm for quicksort as follows −" }, { "code": null, "e": 4918, "s": 4730, "text": "Step 1 − Make the right-most index value pivot\nStep 2 − partition the array using pivot value\nStep 3 − quicksort left partition recursively\nStep 4 − quicksort right partition recursively\n" }, { "code": null, "e": 4989, "s": 4918, "text": "To get more into it, let see the pseudocode for quick sort algorithm −" }, { "code": null, "e": 5249, "s": 4989, "text": "procedure quickSort(left, right)\n\n if right-left <= 0\n return\n else \n pivot = A[right]\n partition = partitionFunc(left, right, pivot)\n quickSort(left,partition-1)\n quickSort(partition+1,right) \n end if\t\t\n \nend procedure" }, { "code": null, "e": 5335, "s": 5249, "text": "To know about quick sort implementation in C programming language, please click here." }, { "code": null, "e": 5370, "s": 5335, "text": "\n 42 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5382, "s": 5370, "text": " Ravi Kiran" }, { "code": null, "e": 5417, "s": 5382, "text": "\n 141 Lectures \n 13 hours \n" }, { "code": null, "e": 5436, "s": 5417, "text": " Arnab Chakraborty" }, { "code": null, "e": 5471, "s": 5436, "text": "\n 26 Lectures \n 8.5 hours \n" }, { "code": null, "e": 5486, "s": 5471, "text": " Parth Panjabi" }, { "code": null, "e": 5519, "s": 5486, "text": "\n 65 Lectures \n 6 hours \n" }, { "code": null, "e": 5538, "s": 5519, "text": " Arnab Chakraborty" }, { "code": null, "e": 5572, "s": 5538, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 5600, "s": 5572, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5636, "s": 5600, "text": "\n 64 Lectures \n 10.5 hours \n" }, { "code": null, "e": 5664, "s": 5636, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5671, "s": 5664, "text": " Print" }, { "code": null, "e": 5682, "s": 5671, "text": " Add Notes" } ]
Lazy Propagation in Segment Tree - GeeksforGeeks
29 Mar, 2022 Segment tree is introduced in previous post with an example of range sum problem. We have used the same “Sum of given Range” problem to explain Lazy propagation How does update work in Simple Segment Tree? In the previous post, update function was called to update only a single value in array. Please note that a single value update in array may cause multiple updates in Segment Tree as there may be many segment tree nodes that have a single array element in their ranges.Below is simple logic used in previous post. 1) Start with root of segment tree. 2) If array index to be updated is not in current node’s range, then return 3) Else update current node and recur for children.Below is code taken from previous post. CPP /* A recursive function to update the nodes which have the given index in their range. The following are parameters tree[] --> segment tree si --> index of current node in segment tree. Initial value is passed as 0. ss and se --> Starting and ending indexes of array elements covered under this node of segment tree. Initial values passed as 0 and n-1. i --> index of the element to be updated. This index is in input array. diff --> Value to be added to all nodes which have array index i in range */void updateValueUtil(int tree[], int ss, int se, int i, int diff, int si){ // Base Case: If the input index lies outside the range // of this segment if (i < ss || i > se) return; // If the input index is in range of this node, then // update the value of the node and its children st[si] = st[si] + diff; if (se != ss) { int mid = getMid(ss, se); updateValueUtil(st, ss, mid, i, diff, 2*si + 1); updateValueUtil(st, mid+1, se, i, diff, 2*si + 2); }} What if there are updates on a range of array indexes? For example add 10 to all values at indexes from 2 to 7 in array. The above update has to be called for every index from 2 to 7. We can avoid multiple calls by writing a function updateRange() that updates nodes accordingly. CPP /* Function to update segment tree for range update in inputarray. si -> index of current node in segment tree ss and se -> Starting and ending indexes of elements for which current nodes stores sum. us and ue -> starting and ending indexes of update query diff -> which we need to add in the range us to ue */void updateRangeUtil(int si, int ss, int se, int us, int ue, int diff){ // out of range if (ss>se || ss>ue || se<us) return ; // Current node is a leaf node if (ss==se) { // Add the difference to current node tree[si] += diff; return; } // If not a leaf node, recur for children. int mid = (ss+se)/2; updateRangeUtil(si*2+1, ss, mid, us, ue, diff); updateRangeUtil(si*2+2, mid+1, se, us, ue, diff); // Use the result of children calls to update this // node tree[si] = tree[si*2+1] + tree[si*2+2];} Lazy Propagation – An optimization to make range updates fasterWhen there are many updates and updates are done on a range, we can postpone some updates (avoid recursive calls in update) and do those updates only when required.Please remember that a node in segment tree stores or represents result of a query for a range of indexes. And if this node’s range lies within the update operation range, then all descendants of the node must also be updated. For example consider the node with value 27 in above diagram, this node stores sum of values at indexes from 3 to 5. If our update query is for range 2 to 5, then we need to update this node and all descendants of this node. With Lazy propagation, we update only node with value 27 and postpone updates to its children by storing this update information in separate nodes called lazy nodes or values. We create an array lazy[] which represents lazy node. Size of lazy[] is same as array that represents segment tree, which is tree[] in below code.The idea is to initialize all elements of lazy[] as 0. A value 0 in lazy[i] indicates that there are no pending updates on node i in segment tree. A non-zero value of lazy[i] means that this amount needs to be added to node i in segment tree before making any query to the node.Below is modified update method. // To update segment tree for change in array // values at array indexes from us to ue. updateRange(us, ue) 1) If current segment tree node has any pending update, then first add that pending update to current node. 2) If current node's range lies completely in update query range. ....a) Update current node ....b) Postpone updates to children by setting lazy value for children nodes. 3) If current node's range overlaps with update range, follow the same approach as above simple update. ...a) Recur for left and right children. ...b) Update current node using results of left and right calls. Is there any change in Query Function also? Since we have changed update to postpone its operations, there may be problems if a query is made to a node that is yet to be updated. So we need to update our query method also which is getSumUtil in previous post. The getSumUtil() now first checks if there is a pending update and if there is, then updates the node. Once it makes sure that pending update is done, it works same as the previous getSumUtil().Below are programs to demonstrate working of Lazy Propagation. C++ Java Python3 C# // Program to show segment tree to demonstrate lazy// propagation#include <stdio.h>#include <math.h>#define MAX 1000 // Ideally, we should not use global variables and large// constant-sized arrays, we have done it here for simplicity.int tree[MAX] = {0}; // To store segment treeint lazy[MAX] = {0}; // To store pending updates /* si -> index of current node in segment tree ss and se -> Starting and ending indexes of elements for which current nodes stores sum. us and ue -> starting and ending indexes of update query diff -> which we need to add in the range us to ue */void updateRangeUtil(int si, int ss, int se, int us, int ue, int diff){ // If lazy value is non-zero for current node of segment // tree, then there are some pending updates. So we need // to make sure that the pending updates are done before // making new updates. Because this value may be used by // parent after recursive calls (See last line of this // function) if (lazy[si] != 0) { // Make pending updates using value stored in lazy // nodes tree[si] += (se-ss+1)*lazy[si]; // checking if it is not leaf node because if // it is leaf node then we cannot go further if (ss != se) { // We can postpone updating children we don't // need their new values now. // Since we are not yet updating children of si, // we need to set lazy flags for the children lazy[si*2 + 1] += lazy[si]; lazy[si*2 + 2] += lazy[si]; } // Set the lazy value for current node as 0 as it // has been updated lazy[si] = 0; } // out of range if (ss>se || ss>ue || se<us) return ; // Current segment is fully in range if (ss>=us && se<=ue) { // Add the difference to current node tree[si] += (se-ss+1)*diff; // same logic for checking leaf node or not if (ss != se) { // This is where we store values in lazy nodes, // rather than updating the segment tree itself // Since we don't need these updated values now // we postpone updates by storing values in lazy[] lazy[si*2 + 1] += diff; lazy[si*2 + 2] += diff; } return; } // If not completely in rang, but overlaps, recur for // children, int mid = (ss+se)/2; updateRangeUtil(si*2+1, ss, mid, us, ue, diff); updateRangeUtil(si*2+2, mid+1, se, us, ue, diff); // And use the result of children calls to update this // node tree[si] = tree[si*2+1] + tree[si*2+2];} // Function to update a range of values in segment// tree/* us and eu -> starting and ending indexes of update query ue -> ending index of update query diff -> which we need to add in the range us to ue */void updateRange(int n, int us, int ue, int diff){ updateRangeUtil(0, 0, n-1, us, ue, diff);} /* A recursive function to get the sum of values in given range of the array. The following are parameters for this function. si --> Index of current node in the segment tree. Initially 0 is passed as root is always at' index 0 ss & se --> Starting and ending indexes of the segment represented by current node, i.e., tree[si] qs & qe --> Starting and ending indexes of query range */int getSumUtil(int ss, int se, int qs, int qe, int si){ // If lazy flag is set for current node of segment tree, // then there are some pending updates. So we need to // make sure that the pending updates are done before // processing the sub sum query if (lazy[si] != 0) { // Make pending updates to this node. Note that this // node represents sum of elements in arr[ss..se] and // all these elements must be increased by lazy[si] tree[si] += (se-ss+1)*lazy[si]; // checking if it is not leaf node because if // it is leaf node then we cannot go further if (ss != se) { // Since we are not yet updating children os si, // we need to set lazy values for the children lazy[si*2+1] += lazy[si]; lazy[si*2+2] += lazy[si]; } // unset the lazy value for current node as it has // been updated lazy[si] = 0; } // Out of range if (ss>se || ss>qe || se<qs) return 0; // At this point we are sure that pending lazy updates // are done for current node. So we can return value // (same as it was for query in our previous post) // If this segment lies in range if (ss>=qs && se<=qe) return tree[si]; // If a part of this segment overlaps with the given // range int mid = (ss + se)/2; return getSumUtil(ss, mid, qs, qe, 2*si+1) + getSumUtil(mid+1, se, qs, qe, 2*si+2);} // Return sum of elements in range from index qs (query// start) to qe (query end). It mainly uses getSumUtil()int getSum(int n, int qs, int qe){ // Check for erroneous input values if (qs < 0 || qe > n-1 || qs > qe) { printf("Invalid Input"); return -1; } return getSumUtil(0, n-1, qs, qe, 0);} // A recursive function that constructs Segment Tree for// array[ss..se]. si is index of current node in segment// tree st.void constructSTUtil(int arr[], int ss, int se, int si){ // out of range as ss can never be greater than se if (ss > se) return ; // If there is one element in array, store it in // current node of segment tree and return if (ss == se) { tree[si] = arr[ss]; return; } // If there are more than one elements, then recur // for left and right subtrees and store the sum // of values in this node int mid = (ss + se)/2; constructSTUtil(arr, ss, mid, si*2+1); constructSTUtil(arr, mid+1, se, si*2+2); tree[si] = tree[si*2 + 1] + tree[si*2 + 2];} /* Function to construct segment tree from given array. This function allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */void constructST(int arr[], int n){ // Fill the allocated memory st constructSTUtil(arr, 0, n-1, 0);} // Driver program to test above functionsint main(){ int arr[] = {1, 3, 5, 7, 9, 11}; int n = sizeof(arr)/sizeof(arr[0]); // Build segment tree from given array constructST(arr, n); // Print sum of values in array from index 1 to 3 printf("Sum of values in given range = %d\n", getSum(n, 1, 3)); // Add 10 to all nodes at indexes from 1 to 5. updateRange(n, 1, 5, 10); // Find sum after the value is updated printf("Updated sum of values in given range = %d\n", getSum( n, 1, 3)); return 0;} // Java program to demonstrate lazy propagation in segment treeclass LazySegmentTree{ final int MAX = 1000; // Max tree size int tree[] = new int[MAX]; // To store segment tree int lazy[] = new int[MAX]; // To store pending updates /* si -> index of current node in segment tree ss and se -> Starting and ending indexes of elements for which current nodes stores sum. us and eu -> starting and ending indexes of update query ue -> ending index of update query diff -> which we need to add in the range us to ue */ void updateRangeUtil(int si, int ss, int se, int us, int ue, int diff) { // If lazy value is non-zero for current node of segment // tree, then there are some pending updates. So we need // to make sure that the pending updates are done before // making new updates. Because this value may be used by // parent after recursive calls (See last line of this // function) if (lazy[si] != 0) { // Make pending updates using value stored in lazy // nodes tree[si] += (se - ss + 1) * lazy[si]; // checking if it is not leaf node because if // it is leaf node then we cannot go further if (ss != se) { // We can postpone updating children we don't // need their new values now. // Since we are not yet updating children of si, // we need to set lazy flags for the children lazy[si * 2 + 1] += lazy[si]; lazy[si * 2 + 2] += lazy[si]; } // Set the lazy value for current node as 0 as it // has been updated lazy[si] = 0; } // out of range if (ss > se || ss > ue || se < us) return; // Current segment is fully in range if (ss >= us && se <= ue) { // Add the difference to current node tree[si] += (se - ss + 1) * diff; // same logic for checking leaf node or not if (ss != se) { // This is where we store values in lazy nodes, // rather than updating the segment tree itself // Since we don't need these updated values now // we postpone updates by storing values in lazy[] lazy[si * 2 + 1] += diff; lazy[si * 2 + 2] += diff; } return; } // If not completely in rang, but overlaps, recur for // children, int mid = (ss + se) / 2; updateRangeUtil(si * 2 + 1, ss, mid, us, ue, diff); updateRangeUtil(si * 2 + 2, mid + 1, se, us, ue, diff); // And use the result of children calls to update this // node tree[si] = tree[si * 2 + 1] + tree[si * 2 + 2]; } // Function to update a range of values in segment // tree /* us and eu -> starting and ending indexes of update query ue -> ending index of update query diff -> which we need to add in the range us to ue */ void updateRange(int n, int us, int ue, int diff) { updateRangeUtil(0, 0, n - 1, us, ue, diff); } /* A recursive function to get the sum of values in given range of the array. The following are parameters for this function. si --> Index of current node in the segment tree. Initially 0 is passed as root is always at' index 0 ss & se --> Starting and ending indexes of the segment represented by current node, i.e., tree[si] qs & qe --> Starting and ending indexes of query range */ int getSumUtil(int ss, int se, int qs, int qe, int si) { // If lazy flag is set for current node of segment tree, // then there are some pending updates. So we need to // make sure that the pending updates are done before // processing the sub sum query if (lazy[si] != 0) { // Make pending updates to this node. Note that this // node represents sum of elements in arr[ss..se] and // all these elements must be increased by lazy[si] tree[si] += (se - ss + 1) * lazy[si]; // checking if it is not leaf node because if // it is leaf node then we cannot go further if (ss != se) { // Since we are not yet updating children os si, // we need to set lazy values for the children lazy[si * 2 + 1] += lazy[si]; lazy[si * 2 + 2] += lazy[si]; } // unset the lazy value for current node as it has // been updated lazy[si] = 0; } // Out of range if (ss > se || ss > qe || se < qs) return 0; // At this point sure, pending lazy updates are done // for current node. So we can return value (same as // was for query in our previous post) // If this segment lies in range if (ss >= qs && se <= qe) return tree[si]; // If a part of this segment overlaps with the given // range int mid = (ss + se) / 2; return getSumUtil(ss, mid, qs, qe, 2 * si + 1) + getSumUtil(mid + 1, se, qs, qe, 2 * si + 2); } // Return sum of elements in range from index qs (query // start) to qe (query end). It mainly uses getSumUtil() int getSum(int n, int qs, int qe) { // Check for erroneous input values if (qs < 0 || qe > n - 1 || qs > qe) { System.out.println("Invalid Input"); return -1; } return getSumUtil(0, n - 1, qs, qe, 0); } /* A recursive function that constructs Segment Tree for array[ss..se]. si is index of current node in segment tree st. */ void constructSTUtil(int arr[], int ss, int se, int si) { // out of range as ss can never be greater than se if (ss > se) return; /* If there is one element in array, store it in current node of segment tree and return */ if (ss == se) { tree[si] = arr[ss]; return; } /* If there are more than one elements, then recur for left and right subtrees and store the sum of values in this node */ int mid = (ss + se) / 2; constructSTUtil(arr, ss, mid, si * 2 + 1); constructSTUtil(arr, mid + 1, se, si * 2 + 2); tree[si] = tree[si * 2 + 1] + tree[si * 2 + 2]; } /* Function to construct segment tree from given array. This function allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */ void constructST(int arr[], int n) { // Fill the allocated memory st constructSTUtil(arr, 0, n - 1, 0); } // Driver program to test above functions public static void main(String args[]) { int arr[] = {1, 3, 5, 7, 9, 11}; int n = arr.length; LazySegmentTree tree = new LazySegmentTree(); // Build segment tree from given array tree.constructST(arr, n); // Print sum of values in array from index 1 to 3 System.out.println("Sum of values in given range = " + tree.getSum(n, 1, 3)); // Add 10 to all nodes at indexes from 1 to 5. tree.updateRange(n, 1, 5, 10); // Find sum after the value is updated System.out.println("Updated sum of values in given range = " + tree.getSum(n, 1, 3)); }}// This Code is contributed by Ankur Narain Verma # Python3 implementation of the approachMAX = 1000 # Ideally, we should not use global variables# and large constant-sized arrays, we have# done it here for simplicity.tree = [0] * MAX; # To store segment treelazy = [0] * MAX; # To store pending updates """ si -> index of current node in segment tree ss and se -> Starting and ending indexes of elements for which current nodes stores sum. us and ue -> starting and ending indexes of update query diff -> which we need to add in the range us to ue """def updateRangeUtil(si, ss, se, us, ue, diff) : # If lazy value is non-zero for current node # of segment tree, then there are some # pending updates. So we need to make sure # that the pending updates are done before # making new updates. Because this value may be # used by parent after recursive calls # (See last line of this function) if (lazy[si] != 0) : # Make pending updates using value # stored in lazy nodes tree[si] += (se - ss + 1) * lazy[si]; # checking if it is not leaf node because if # it is leaf node then we cannot go further if (ss != se) : # We can postpone updating children we don't # need their new values now. # Since we are not yet updating children of si, # we need to set lazy flags for the children lazy[si * 2 + 1] += lazy[si]; lazy[si * 2 + 2] += lazy[si]; # Set the lazy value for current node # as 0 as it has been updated lazy[si] = 0; # out of range if (ss > se or ss > ue or se < us) : return ; # Current segment is fully in range if (ss >= us and se <= ue) : # Add the difference to current node tree[si] += (se - ss + 1) * diff; # same logic for checking leaf node or not if (ss != se) : # This is where we store values in lazy nodes, # rather than updating the segment tree itself # Since we don't need these updated values now # we postpone updates by storing values in lazy[] lazy[si * 2 + 1] += diff; lazy[si * 2 + 2] += diff; return; # If not completely in rang, but overlaps, # recur for children, mid = (ss + se) // 2; updateRangeUtil(si * 2 + 1, ss, mid, us, ue, diff); updateRangeUtil(si * 2 + 2, mid + 1, se, us, ue, diff); # And use the result of children calls # to update this node tree[si] = tree[si * 2 + 1] + \ tree[si * 2 + 2]; # Function to update a range of values# in segment tree ''' us and eu -> starting and ending indexes of update query ue -> ending index of update query diff -> which we need to add in the range us to ue '''def updateRange(n, us, ue, diff) : updateRangeUtil(0, 0, n - 1, us, ue, diff); ''' A recursive function to get the sum of values in given range of the array. The following are parameters for this function. si --> Index of current node in the segment tree. Initially 0 is passed as root is always at' index 0 ss & se --> Starting and ending indexes of the segment represented by current node, i.e., tree[si] qs & qe --> Starting and ending indexes of query range '''def getSumUtil(ss, se, qs, qe, si) : # If lazy flag is set for current node # of segment tree, then there are # some pending updates. So we need to # make sure that the pending updates are # done before processing the sub sum query if (lazy[si] != 0) : # Make pending updates to this node. # Note that this node represents sum of # elements in arr[ss..se] and all these # elements must be increased by lazy[si] tree[si] += (se - ss + 1) * lazy[si]; # checking if it is not leaf node because if # it is leaf node then we cannot go further if (ss != se) : # Since we are not yet updating children os si, # we need to set lazy values for the children lazy[si * 2 + 1] += lazy[si]; lazy[si * 2 + 2] += lazy[si]; # unset the lazy value for current node # as it has been updated lazy[si] = 0; # Out of range if (ss > se or ss > qe or se < qs) : return 0; # At this point we are sure that # pending lazy updates are done for # current node. So we can return value # (same as it was for query in our previous post) # If this segment lies in range if (ss >= qs and se <= qe) : return tree[si]; # If a part of this segment overlaps # with the given range mid = (ss + se) // 2; return (getSumUtil(ss, mid, qs, qe, 2 * si + 1) + getSumUtil(mid + 1, se, qs, qe, 2 * si + 2)); # Return sum of elements in range from# index qs (query start) to qe (query end).# It mainly uses getSumUtil()def getSum(n, qs, qe) : # Check for erroneous input values if (qs < 0 or qe > n - 1 or qs > qe) : print("Invalid Input"); return -1; return getSumUtil(0, n - 1, qs, qe, 0); # A recursive function that constructs# Segment Tree for array[ss..se].# si is index of current node in segment# tree st.def constructSTUtil(arr, ss, se, si) : # out of range as ss can never be # greater than se if (ss > se) : return ; # If there is one element in array, # store it in current node of # segment tree and return if (ss == se) : tree[si] = arr[ss]; return; # If there are more than one elements, # then recur for left and right subtrees # and store the sum of values in this node mid = (ss + se) // 2; constructSTUtil(arr, ss, mid, si * 2 + 1); constructSTUtil(arr, mid + 1, se, si * 2 + 2); tree[si] = tree[si * 2 + 1] + tree[si * 2 + 2]; ''' Function to construct segment treefrom given array. This function allocates memoryfor segment tree and calls constructSTUtil()to fill the allocated memory '''def constructST(arr, n) : # Fill the allocated memory st constructSTUtil(arr, 0, n - 1, 0); # Driver Codeif __name__ == "__main__" : arr = [1, 3, 5, 7, 9, 11]; n = len(arr); # Build segment tree from given array constructST(arr, n); # Print sum of values in array from index 1 to 3 print("Sum of values in given range =", getSum(n, 1, 3)); # Add 10 to all nodes at indexes from 1 to 5. updateRange(n, 1, 5, 10); # Find sum after the value is updated print("Updated sum of values in given range =", getSum( n, 1, 3)); # This code is contributed by AnkitRai01 // C# program to demonstrate lazy// propagation in segment treeusing System; public class LazySegmentTree{ static readonly int MAX = 1000; // Max tree size int []tree = new int[MAX]; // To store segment tree int []lazy = new int[MAX]; // To store pending updates /* si -> index of current node in segment tree ss and se -> Starting and ending indexes of elements for which current nodes stores sum. us and eu -> starting and ending indexes of update query ue -> ending index of update query diff -> which we need to add in the range us to ue */ void updateRangeUtil(int si, int ss, int se, int us, int ue, int diff) { // If lazy value is non-zero // for current node of segment // tree, then there are some // pending updates. So we need // to make sure that the pending // updates are done before making // new updates. Because this // value may be used by parent // after recursive calls (See last // line of this function) if (lazy[si] != 0) { // Make pending updates using value // stored in lazy nodes tree[si] += (se - ss + 1) * lazy[si]; // checking if it is not leaf node because if // it is leaf node then we cannot go further if (ss != se) { // We can postpone updating children // we don't need their new values now. // Since we are not yet updating children of si, // we need to set lazy flags for the children lazy[si * 2 + 1] += lazy[si]; lazy[si * 2 + 2] += lazy[si]; } // Set the lazy value for current node // as 0 as it has been updated lazy[si] = 0; } // out of range if (ss > se || ss > ue || se < us) return; // Current segment is fully in range if (ss >= us && se <= ue) { // Add the difference to current node tree[si] += (se - ss + 1) * diff; // same logic for checking leaf node or not if (ss != se) { // This is where we store values in lazy nodes, // rather than updating the segment tree itself // Since we don't need these updated values now // we postpone updates by storing values in lazy[] lazy[si * 2 + 1] += diff; lazy[si * 2 + 2] += diff; } return; } // If not completely in rang, but // overlaps, recur for children, int mid = (ss + se) / 2; updateRangeUtil(si * 2 + 1, ss, mid, us, ue, diff); updateRangeUtil(si * 2 + 2, mid + 1, se, us, ue, diff); // And use the result of children calls to update this // node tree[si] = tree[si * 2 + 1] + tree[si * 2 + 2]; } // Function to update a range of values in segment // tree /* us and eu -> starting and ending indexes of update query ue -> ending index of update query diff -> which we need to add in the range us to ue */ void updateRange(int n, int us, int ue, int diff) { updateRangeUtil(0, 0, n - 1, us, ue, diff); } /* A recursive function to get the sum of values in given range of the array. The following are parameters for this function. si --> Index of current node in the segment tree. Initially 0 is passed as root is always at' index 0 ss & se --> Starting and ending indexes of the segment represented by current node, i.e., tree[si] qs & qe --> Starting and ending indexes of query range */ int getSumUtil(int ss, int se, int qs, int qe, int si) { // If lazy flag is set for current node // of segment tree, then there are // some pending updates. So we need to // make sure that the pending updates // are done before processing // the sub sum query if (lazy[si] != 0) { // Make pending updates to this // node. Note that this node // represents sum of elements // in arr[ss..se] and all these // elements must be increased by lazy[si] tree[si] += (se - ss + 1) * lazy[si]; // checking if it is not leaf node because if // it is leaf node then we cannot go further if (ss != se) { // Since we are not yet // updating children os si, // we need to set lazy values // for the children lazy[si * 2 + 1] += lazy[si]; lazy[si * 2 + 2] += lazy[si]; } // unset the lazy value for current // node as it has been updated lazy[si] = 0; } // Out of range if (ss > se || ss > qe || se < qs) return 0; // At this point sure, pending lazy updates are done // for current node. So we can return value (same as // was for query in our previous post) // If this segment lies in range if (ss >= qs && se <= qe) return tree[si]; // If a part of this segment overlaps // with the given range int mid = (ss + se) / 2; return getSumUtil(ss, mid, qs, qe, 2 * si + 1) + getSumUtil(mid + 1, se, qs, qe, 2 * si + 2); } // Return sum of elements in range from index qs (query // start) to qe (query end). It mainly uses getSumUtil() int getSum(int n, int qs, int qe) { // Check for erroneous input values if (qs < 0 || qe > n - 1 || qs > qe) { Console.WriteLine("Invalid Input"); return -1; } return getSumUtil(0, n - 1, qs, qe, 0); } /* A recursive function that constructs Segment Tree for array[ss..se]. si is index of current node in segment tree st. */ void constructSTUtil(int []arr, int ss, int se, int si) { // out of range as ss can // never be greater than se if (ss > se) return; /* If there is one element in array, store it in current node of segment tree and return */ if (ss == se) { tree[si] = arr[ss]; return; } /* If there are more than one elements, then recur for left and right subtrees and store the sum of values in this node */ int mid = (ss + se) / 2; constructSTUtil(arr, ss, mid, si * 2 + 1); constructSTUtil(arr, mid + 1, se, si * 2 + 2); tree[si] = tree[si * 2 + 1] + tree[si * 2 + 2]; } /* Function to construct segment tree from given array. This function allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */ void constructST(int []arr, int n) { // Fill the allocated memory st constructSTUtil(arr, 0, n - 1, 0); } // Driver program to test above functions public static void Main(String []args) { int []arr = {1, 3, 5, 7, 9, 11}; int n = arr.Length; LazySegmentTree tree = new LazySegmentTree(); // Build segment tree from given array tree.constructST(arr, n); // Print sum of values in array from index 1 to 3 Console.WriteLine("Sum of values in given range = " + tree.getSum(n, 1, 3)); // Add 10 to all nodes at indexes from 1 to 5. tree.updateRange(n, 1, 5, 10); // Find sum after the value is updated Console.WriteLine("Updated sum of values in given range = " + tree.getSum(n, 1, 3)); }} // This code contributed by Rajput-Ji Output: Sum of values in given range = 15 Updated sum of values in given range = 45 Time Complexity: O(n) Auxiliary Space: O(MAX) YouTubeGeeksforGeeks507K subscribersLazy Propagation in Segment Tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:06•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=UKH4Zgfa4kI" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is contributed by Ankit Mittal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Rajput-Ji ankthon nidhi_biet surinderdawra388 rishavnitro array-range-queries Segment-Tree Advanced Data Structure Segment-Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Agents in Artificial Intelligence Decision Tree Introduction with example AVL Tree | Set 2 (Deletion) Red-Black Tree | Set 2 (Insert) Disjoint Set Data Structures Ordered Set and GNU C++ PBDS Insert Operation in B-Tree Binary Indexed Tree or Fenwick Tree Binomial Heap Design a Chess Game
[ { "code": null, "e": 26103, "s": 26075, "text": "\n29 Mar, 2022" }, { "code": null, "e": 26266, "s": 26103, "text": "Segment tree is introduced in previous post with an example of range sum problem. We have used the same “Sum of given Range” problem to explain Lazy propagation " }, { "code": null, "e": 26830, "s": 26266, "text": "How does update work in Simple Segment Tree? In the previous post, update function was called to update only a single value in array. Please note that a single value update in array may cause multiple updates in Segment Tree as there may be many segment tree nodes that have a single array element in their ranges.Below is simple logic used in previous post. 1) Start with root of segment tree. 2) If array index to be updated is not in current node’s range, then return 3) Else update current node and recur for children.Below is code taken from previous post. " }, { "code": null, "e": 26834, "s": 26830, "text": "CPP" }, { "code": "/* A recursive function to update the nodes which have the given index in their range. The following are parameters tree[] --> segment tree si --> index of current node in segment tree. Initial value is passed as 0. ss and se --> Starting and ending indexes of array elements covered under this node of segment tree. Initial values passed as 0 and n-1. i --> index of the element to be updated. This index is in input array. diff --> Value to be added to all nodes which have array index i in range */void updateValueUtil(int tree[], int ss, int se, int i, int diff, int si){ // Base Case: If the input index lies outside the range // of this segment if (i < ss || i > se) return; // If the input index is in range of this node, then // update the value of the node and its children st[si] = st[si] + diff; if (se != ss) { int mid = getMid(ss, se); updateValueUtil(st, ss, mid, i, diff, 2*si + 1); updateValueUtil(st, mid+1, se, i, diff, 2*si + 2); }}", "e": 27958, "s": 26834, "text": null }, { "code": null, "e": 28239, "s": 27958, "text": "What if there are updates on a range of array indexes? For example add 10 to all values at indexes from 2 to 7 in array. The above update has to be called for every index from 2 to 7. We can avoid multiple calls by writing a function updateRange() that updates nodes accordingly. " }, { "code": null, "e": 28243, "s": 28239, "text": "CPP" }, { "code": "/* Function to update segment tree for range update in inputarray. si -> index of current node in segment tree ss and se -> Starting and ending indexes of elements for which current nodes stores sum. us and ue -> starting and ending indexes of update query diff -> which we need to add in the range us to ue */void updateRangeUtil(int si, int ss, int se, int us, int ue, int diff){ // out of range if (ss>se || ss>ue || se<us) return ; // Current node is a leaf node if (ss==se) { // Add the difference to current node tree[si] += diff; return; } // If not a leaf node, recur for children. int mid = (ss+se)/2; updateRangeUtil(si*2+1, ss, mid, us, ue, diff); updateRangeUtil(si*2+2, mid+1, se, us, ue, diff); // Use the result of children calls to update this // node tree[si] = tree[si*2+1] + tree[si*2+2];}", "e": 29168, "s": 28243, "text": null }, { "code": null, "e": 30481, "s": 29168, "text": "Lazy Propagation – An optimization to make range updates fasterWhen there are many updates and updates are done on a range, we can postpone some updates (avoid recursive calls in update) and do those updates only when required.Please remember that a node in segment tree stores or represents result of a query for a range of indexes. And if this node’s range lies within the update operation range, then all descendants of the node must also be updated. For example consider the node with value 27 in above diagram, this node stores sum of values at indexes from 3 to 5. If our update query is for range 2 to 5, then we need to update this node and all descendants of this node. With Lazy propagation, we update only node with value 27 and postpone updates to its children by storing this update information in separate nodes called lazy nodes or values. We create an array lazy[] which represents lazy node. Size of lazy[] is same as array that represents segment tree, which is tree[] in below code.The idea is to initialize all elements of lazy[] as 0. A value 0 in lazy[i] indicates that there are no pending updates on node i in segment tree. A non-zero value of lazy[i] means that this amount needs to be added to node i in segment tree before making any query to the node.Below is modified update method. " }, { "code": null, "e": 31110, "s": 30481, "text": "// To update segment tree for change in array\n// values at array indexes from us to ue.\nupdateRange(us, ue)\n1) If current segment tree node has any pending\n update, then first add that pending update to\n current node.\n2) If current node's range lies completely in \n update query range.\n....a) Update current node\n....b) Postpone updates to children by setting \n lazy value for children nodes.\n3) If current node's range overlaps with update \n range, follow the same approach as above simple\n update.\n...a) Recur for left and right children.\n...b) Update current node using results of left \n and right calls." }, { "code": null, "e": 31627, "s": 31110, "text": "Is there any change in Query Function also? Since we have changed update to postpone its operations, there may be problems if a query is made to a node that is yet to be updated. So we need to update our query method also which is getSumUtil in previous post. The getSumUtil() now first checks if there is a pending update and if there is, then updates the node. Once it makes sure that pending update is done, it works same as the previous getSumUtil().Below are programs to demonstrate working of Lazy Propagation." }, { "code": null, "e": 31631, "s": 31627, "text": "C++" }, { "code": null, "e": 31636, "s": 31631, "text": "Java" }, { "code": null, "e": 31644, "s": 31636, "text": "Python3" }, { "code": null, "e": 31647, "s": 31644, "text": "C#" }, { "code": "// Program to show segment tree to demonstrate lazy// propagation#include <stdio.h>#include <math.h>#define MAX 1000 // Ideally, we should not use global variables and large// constant-sized arrays, we have done it here for simplicity.int tree[MAX] = {0}; // To store segment treeint lazy[MAX] = {0}; // To store pending updates /* si -> index of current node in segment tree ss and se -> Starting and ending indexes of elements for which current nodes stores sum. us and ue -> starting and ending indexes of update query diff -> which we need to add in the range us to ue */void updateRangeUtil(int si, int ss, int se, int us, int ue, int diff){ // If lazy value is non-zero for current node of segment // tree, then there are some pending updates. So we need // to make sure that the pending updates are done before // making new updates. Because this value may be used by // parent after recursive calls (See last line of this // function) if (lazy[si] != 0) { // Make pending updates using value stored in lazy // nodes tree[si] += (se-ss+1)*lazy[si]; // checking if it is not leaf node because if // it is leaf node then we cannot go further if (ss != se) { // We can postpone updating children we don't // need their new values now. // Since we are not yet updating children of si, // we need to set lazy flags for the children lazy[si*2 + 1] += lazy[si]; lazy[si*2 + 2] += lazy[si]; } // Set the lazy value for current node as 0 as it // has been updated lazy[si] = 0; } // out of range if (ss>se || ss>ue || se<us) return ; // Current segment is fully in range if (ss>=us && se<=ue) { // Add the difference to current node tree[si] += (se-ss+1)*diff; // same logic for checking leaf node or not if (ss != se) { // This is where we store values in lazy nodes, // rather than updating the segment tree itself // Since we don't need these updated values now // we postpone updates by storing values in lazy[] lazy[si*2 + 1] += diff; lazy[si*2 + 2] += diff; } return; } // If not completely in rang, but overlaps, recur for // children, int mid = (ss+se)/2; updateRangeUtil(si*2+1, ss, mid, us, ue, diff); updateRangeUtil(si*2+2, mid+1, se, us, ue, diff); // And use the result of children calls to update this // node tree[si] = tree[si*2+1] + tree[si*2+2];} // Function to update a range of values in segment// tree/* us and eu -> starting and ending indexes of update query ue -> ending index of update query diff -> which we need to add in the range us to ue */void updateRange(int n, int us, int ue, int diff){ updateRangeUtil(0, 0, n-1, us, ue, diff);} /* A recursive function to get the sum of values in given range of the array. The following are parameters for this function. si --> Index of current node in the segment tree. Initially 0 is passed as root is always at' index 0 ss & se --> Starting and ending indexes of the segment represented by current node, i.e., tree[si] qs & qe --> Starting and ending indexes of query range */int getSumUtil(int ss, int se, int qs, int qe, int si){ // If lazy flag is set for current node of segment tree, // then there are some pending updates. So we need to // make sure that the pending updates are done before // processing the sub sum query if (lazy[si] != 0) { // Make pending updates to this node. Note that this // node represents sum of elements in arr[ss..se] and // all these elements must be increased by lazy[si] tree[si] += (se-ss+1)*lazy[si]; // checking if it is not leaf node because if // it is leaf node then we cannot go further if (ss != se) { // Since we are not yet updating children os si, // we need to set lazy values for the children lazy[si*2+1] += lazy[si]; lazy[si*2+2] += lazy[si]; } // unset the lazy value for current node as it has // been updated lazy[si] = 0; } // Out of range if (ss>se || ss>qe || se<qs) return 0; // At this point we are sure that pending lazy updates // are done for current node. So we can return value // (same as it was for query in our previous post) // If this segment lies in range if (ss>=qs && se<=qe) return tree[si]; // If a part of this segment overlaps with the given // range int mid = (ss + se)/2; return getSumUtil(ss, mid, qs, qe, 2*si+1) + getSumUtil(mid+1, se, qs, qe, 2*si+2);} // Return sum of elements in range from index qs (query// start) to qe (query end). It mainly uses getSumUtil()int getSum(int n, int qs, int qe){ // Check for erroneous input values if (qs < 0 || qe > n-1 || qs > qe) { printf(\"Invalid Input\"); return -1; } return getSumUtil(0, n-1, qs, qe, 0);} // A recursive function that constructs Segment Tree for// array[ss..se]. si is index of current node in segment// tree st.void constructSTUtil(int arr[], int ss, int se, int si){ // out of range as ss can never be greater than se if (ss > se) return ; // If there is one element in array, store it in // current node of segment tree and return if (ss == se) { tree[si] = arr[ss]; return; } // If there are more than one elements, then recur // for left and right subtrees and store the sum // of values in this node int mid = (ss + se)/2; constructSTUtil(arr, ss, mid, si*2+1); constructSTUtil(arr, mid+1, se, si*2+2); tree[si] = tree[si*2 + 1] + tree[si*2 + 2];} /* Function to construct segment tree from given array. This function allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */void constructST(int arr[], int n){ // Fill the allocated memory st constructSTUtil(arr, 0, n-1, 0);} // Driver program to test above functionsint main(){ int arr[] = {1, 3, 5, 7, 9, 11}; int n = sizeof(arr)/sizeof(arr[0]); // Build segment tree from given array constructST(arr, n); // Print sum of values in array from index 1 to 3 printf(\"Sum of values in given range = %d\\n\", getSum(n, 1, 3)); // Add 10 to all nodes at indexes from 1 to 5. updateRange(n, 1, 5, 10); // Find sum after the value is updated printf(\"Updated sum of values in given range = %d\\n\", getSum( n, 1, 3)); return 0;}", "e": 38447, "s": 31647, "text": null }, { "code": "// Java program to demonstrate lazy propagation in segment treeclass LazySegmentTree{ final int MAX = 1000; // Max tree size int tree[] = new int[MAX]; // To store segment tree int lazy[] = new int[MAX]; // To store pending updates /* si -> index of current node in segment tree ss and se -> Starting and ending indexes of elements for which current nodes stores sum. us and eu -> starting and ending indexes of update query ue -> ending index of update query diff -> which we need to add in the range us to ue */ void updateRangeUtil(int si, int ss, int se, int us, int ue, int diff) { // If lazy value is non-zero for current node of segment // tree, then there are some pending updates. So we need // to make sure that the pending updates are done before // making new updates. Because this value may be used by // parent after recursive calls (See last line of this // function) if (lazy[si] != 0) { // Make pending updates using value stored in lazy // nodes tree[si] += (se - ss + 1) * lazy[si]; // checking if it is not leaf node because if // it is leaf node then we cannot go further if (ss != se) { // We can postpone updating children we don't // need their new values now. // Since we are not yet updating children of si, // we need to set lazy flags for the children lazy[si * 2 + 1] += lazy[si]; lazy[si * 2 + 2] += lazy[si]; } // Set the lazy value for current node as 0 as it // has been updated lazy[si] = 0; } // out of range if (ss > se || ss > ue || se < us) return; // Current segment is fully in range if (ss >= us && se <= ue) { // Add the difference to current node tree[si] += (se - ss + 1) * diff; // same logic for checking leaf node or not if (ss != se) { // This is where we store values in lazy nodes, // rather than updating the segment tree itself // Since we don't need these updated values now // we postpone updates by storing values in lazy[] lazy[si * 2 + 1] += diff; lazy[si * 2 + 2] += diff; } return; } // If not completely in rang, but overlaps, recur for // children, int mid = (ss + se) / 2; updateRangeUtil(si * 2 + 1, ss, mid, us, ue, diff); updateRangeUtil(si * 2 + 2, mid + 1, se, us, ue, diff); // And use the result of children calls to update this // node tree[si] = tree[si * 2 + 1] + tree[si * 2 + 2]; } // Function to update a range of values in segment // tree /* us and eu -> starting and ending indexes of update query ue -> ending index of update query diff -> which we need to add in the range us to ue */ void updateRange(int n, int us, int ue, int diff) { updateRangeUtil(0, 0, n - 1, us, ue, diff); } /* A recursive function to get the sum of values in given range of the array. The following are parameters for this function. si --> Index of current node in the segment tree. Initially 0 is passed as root is always at' index 0 ss & se --> Starting and ending indexes of the segment represented by current node, i.e., tree[si] qs & qe --> Starting and ending indexes of query range */ int getSumUtil(int ss, int se, int qs, int qe, int si) { // If lazy flag is set for current node of segment tree, // then there are some pending updates. So we need to // make sure that the pending updates are done before // processing the sub sum query if (lazy[si] != 0) { // Make pending updates to this node. Note that this // node represents sum of elements in arr[ss..se] and // all these elements must be increased by lazy[si] tree[si] += (se - ss + 1) * lazy[si]; // checking if it is not leaf node because if // it is leaf node then we cannot go further if (ss != se) { // Since we are not yet updating children os si, // we need to set lazy values for the children lazy[si * 2 + 1] += lazy[si]; lazy[si * 2 + 2] += lazy[si]; } // unset the lazy value for current node as it has // been updated lazy[si] = 0; } // Out of range if (ss > se || ss > qe || se < qs) return 0; // At this point sure, pending lazy updates are done // for current node. So we can return value (same as // was for query in our previous post) // If this segment lies in range if (ss >= qs && se <= qe) return tree[si]; // If a part of this segment overlaps with the given // range int mid = (ss + se) / 2; return getSumUtil(ss, mid, qs, qe, 2 * si + 1) + getSumUtil(mid + 1, se, qs, qe, 2 * si + 2); } // Return sum of elements in range from index qs (query // start) to qe (query end). It mainly uses getSumUtil() int getSum(int n, int qs, int qe) { // Check for erroneous input values if (qs < 0 || qe > n - 1 || qs > qe) { System.out.println(\"Invalid Input\"); return -1; } return getSumUtil(0, n - 1, qs, qe, 0); } /* A recursive function that constructs Segment Tree for array[ss..se]. si is index of current node in segment tree st. */ void constructSTUtil(int arr[], int ss, int se, int si) { // out of range as ss can never be greater than se if (ss > se) return; /* If there is one element in array, store it in current node of segment tree and return */ if (ss == se) { tree[si] = arr[ss]; return; } /* If there are more than one elements, then recur for left and right subtrees and store the sum of values in this node */ int mid = (ss + se) / 2; constructSTUtil(arr, ss, mid, si * 2 + 1); constructSTUtil(arr, mid + 1, se, si * 2 + 2); tree[si] = tree[si * 2 + 1] + tree[si * 2 + 2]; } /* Function to construct segment tree from given array. This function allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */ void constructST(int arr[], int n) { // Fill the allocated memory st constructSTUtil(arr, 0, n - 1, 0); } // Driver program to test above functions public static void main(String args[]) { int arr[] = {1, 3, 5, 7, 9, 11}; int n = arr.length; LazySegmentTree tree = new LazySegmentTree(); // Build segment tree from given array tree.constructST(arr, n); // Print sum of values in array from index 1 to 3 System.out.println(\"Sum of values in given range = \" + tree.getSum(n, 1, 3)); // Add 10 to all nodes at indexes from 1 to 5. tree.updateRange(n, 1, 5, 10); // Find sum after the value is updated System.out.println(\"Updated sum of values in given range = \" + tree.getSum(n, 1, 3)); }}// This Code is contributed by Ankur Narain Verma", "e": 46149, "s": 38447, "text": null }, { "code": "# Python3 implementation of the approachMAX = 1000 # Ideally, we should not use global variables# and large constant-sized arrays, we have# done it here for simplicity.tree = [0] * MAX; # To store segment treelazy = [0] * MAX; # To store pending updates \"\"\" si -> index of current node in segment tree ss and se -> Starting and ending indexes of elements for which current nodes stores sum. us and ue -> starting and ending indexes of update query diff -> which we need to add in the range us to ue \"\"\"def updateRangeUtil(si, ss, se, us, ue, diff) : # If lazy value is non-zero for current node # of segment tree, then there are some # pending updates. So we need to make sure # that the pending updates are done before # making new updates. Because this value may be # used by parent after recursive calls # (See last line of this function) if (lazy[si] != 0) : # Make pending updates using value # stored in lazy nodes tree[si] += (se - ss + 1) * lazy[si]; # checking if it is not leaf node because if # it is leaf node then we cannot go further if (ss != se) : # We can postpone updating children we don't # need their new values now. # Since we are not yet updating children of si, # we need to set lazy flags for the children lazy[si * 2 + 1] += lazy[si]; lazy[si * 2 + 2] += lazy[si]; # Set the lazy value for current node # as 0 as it has been updated lazy[si] = 0; # out of range if (ss > se or ss > ue or se < us) : return ; # Current segment is fully in range if (ss >= us and se <= ue) : # Add the difference to current node tree[si] += (se - ss + 1) * diff; # same logic for checking leaf node or not if (ss != se) : # This is where we store values in lazy nodes, # rather than updating the segment tree itself # Since we don't need these updated values now # we postpone updates by storing values in lazy[] lazy[si * 2 + 1] += diff; lazy[si * 2 + 2] += diff; return; # If not completely in rang, but overlaps, # recur for children, mid = (ss + se) // 2; updateRangeUtil(si * 2 + 1, ss, mid, us, ue, diff); updateRangeUtil(si * 2 + 2, mid + 1, se, us, ue, diff); # And use the result of children calls # to update this node tree[si] = tree[si * 2 + 1] + \\ tree[si * 2 + 2]; # Function to update a range of values# in segment tree ''' us and eu -> starting and ending indexes of update query ue -> ending index of update query diff -> which we need to add in the range us to ue '''def updateRange(n, us, ue, diff) : updateRangeUtil(0, 0, n - 1, us, ue, diff); ''' A recursive function to get the sum of values in given range of the array. The following are parameters for this function. si --> Index of current node in the segment tree. Initially 0 is passed as root is always at' index 0 ss & se --> Starting and ending indexes of the segment represented by current node, i.e., tree[si] qs & qe --> Starting and ending indexes of query range '''def getSumUtil(ss, se, qs, qe, si) : # If lazy flag is set for current node # of segment tree, then there are # some pending updates. So we need to # make sure that the pending updates are # done before processing the sub sum query if (lazy[si] != 0) : # Make pending updates to this node. # Note that this node represents sum of # elements in arr[ss..se] and all these # elements must be increased by lazy[si] tree[si] += (se - ss + 1) * lazy[si]; # checking if it is not leaf node because if # it is leaf node then we cannot go further if (ss != se) : # Since we are not yet updating children os si, # we need to set lazy values for the children lazy[si * 2 + 1] += lazy[si]; lazy[si * 2 + 2] += lazy[si]; # unset the lazy value for current node # as it has been updated lazy[si] = 0; # Out of range if (ss > se or ss > qe or se < qs) : return 0; # At this point we are sure that # pending lazy updates are done for # current node. So we can return value # (same as it was for query in our previous post) # If this segment lies in range if (ss >= qs and se <= qe) : return tree[si]; # If a part of this segment overlaps # with the given range mid = (ss + se) // 2; return (getSumUtil(ss, mid, qs, qe, 2 * si + 1) + getSumUtil(mid + 1, se, qs, qe, 2 * si + 2)); # Return sum of elements in range from# index qs (query start) to qe (query end).# It mainly uses getSumUtil()def getSum(n, qs, qe) : # Check for erroneous input values if (qs < 0 or qe > n - 1 or qs > qe) : print(\"Invalid Input\"); return -1; return getSumUtil(0, n - 1, qs, qe, 0); # A recursive function that constructs# Segment Tree for array[ss..se].# si is index of current node in segment# tree st.def constructSTUtil(arr, ss, se, si) : # out of range as ss can never be # greater than se if (ss > se) : return ; # If there is one element in array, # store it in current node of # segment tree and return if (ss == se) : tree[si] = arr[ss]; return; # If there are more than one elements, # then recur for left and right subtrees # and store the sum of values in this node mid = (ss + se) // 2; constructSTUtil(arr, ss, mid, si * 2 + 1); constructSTUtil(arr, mid + 1, se, si * 2 + 2); tree[si] = tree[si * 2 + 1] + tree[si * 2 + 2]; ''' Function to construct segment treefrom given array. This function allocates memoryfor segment tree and calls constructSTUtil()to fill the allocated memory '''def constructST(arr, n) : # Fill the allocated memory st constructSTUtil(arr, 0, n - 1, 0); # Driver Codeif __name__ == \"__main__\" : arr = [1, 3, 5, 7, 9, 11]; n = len(arr); # Build segment tree from given array constructST(arr, n); # Print sum of values in array from index 1 to 3 print(\"Sum of values in given range =\", getSum(n, 1, 3)); # Add 10 to all nodes at indexes from 1 to 5. updateRange(n, 1, 5, 10); # Find sum after the value is updated print(\"Updated sum of values in given range =\", getSum( n, 1, 3)); # This code is contributed by AnkitRai01", "e": 52890, "s": 46149, "text": null }, { "code": "// C# program to demonstrate lazy// propagation in segment treeusing System; public class LazySegmentTree{ static readonly int MAX = 1000; // Max tree size int []tree = new int[MAX]; // To store segment tree int []lazy = new int[MAX]; // To store pending updates /* si -> index of current node in segment tree ss and se -> Starting and ending indexes of elements for which current nodes stores sum. us and eu -> starting and ending indexes of update query ue -> ending index of update query diff -> which we need to add in the range us to ue */ void updateRangeUtil(int si, int ss, int se, int us, int ue, int diff) { // If lazy value is non-zero // for current node of segment // tree, then there are some // pending updates. So we need // to make sure that the pending // updates are done before making // new updates. Because this // value may be used by parent // after recursive calls (See last // line of this function) if (lazy[si] != 0) { // Make pending updates using value // stored in lazy nodes tree[si] += (se - ss + 1) * lazy[si]; // checking if it is not leaf node because if // it is leaf node then we cannot go further if (ss != se) { // We can postpone updating children // we don't need their new values now. // Since we are not yet updating children of si, // we need to set lazy flags for the children lazy[si * 2 + 1] += lazy[si]; lazy[si * 2 + 2] += lazy[si]; } // Set the lazy value for current node // as 0 as it has been updated lazy[si] = 0; } // out of range if (ss > se || ss > ue || se < us) return; // Current segment is fully in range if (ss >= us && se <= ue) { // Add the difference to current node tree[si] += (se - ss + 1) * diff; // same logic for checking leaf node or not if (ss != se) { // This is where we store values in lazy nodes, // rather than updating the segment tree itself // Since we don't need these updated values now // we postpone updates by storing values in lazy[] lazy[si * 2 + 1] += diff; lazy[si * 2 + 2] += diff; } return; } // If not completely in rang, but // overlaps, recur for children, int mid = (ss + se) / 2; updateRangeUtil(si * 2 + 1, ss, mid, us, ue, diff); updateRangeUtil(si * 2 + 2, mid + 1, se, us, ue, diff); // And use the result of children calls to update this // node tree[si] = tree[si * 2 + 1] + tree[si * 2 + 2]; } // Function to update a range of values in segment // tree /* us and eu -> starting and ending indexes of update query ue -> ending index of update query diff -> which we need to add in the range us to ue */ void updateRange(int n, int us, int ue, int diff) { updateRangeUtil(0, 0, n - 1, us, ue, diff); } /* A recursive function to get the sum of values in given range of the array. The following are parameters for this function. si --> Index of current node in the segment tree. Initially 0 is passed as root is always at' index 0 ss & se --> Starting and ending indexes of the segment represented by current node, i.e., tree[si] qs & qe --> Starting and ending indexes of query range */ int getSumUtil(int ss, int se, int qs, int qe, int si) { // If lazy flag is set for current node // of segment tree, then there are // some pending updates. So we need to // make sure that the pending updates // are done before processing // the sub sum query if (lazy[si] != 0) { // Make pending updates to this // node. Note that this node // represents sum of elements // in arr[ss..se] and all these // elements must be increased by lazy[si] tree[si] += (se - ss + 1) * lazy[si]; // checking if it is not leaf node because if // it is leaf node then we cannot go further if (ss != se) { // Since we are not yet // updating children os si, // we need to set lazy values // for the children lazy[si * 2 + 1] += lazy[si]; lazy[si * 2 + 2] += lazy[si]; } // unset the lazy value for current // node as it has been updated lazy[si] = 0; } // Out of range if (ss > se || ss > qe || se < qs) return 0; // At this point sure, pending lazy updates are done // for current node. So we can return value (same as // was for query in our previous post) // If this segment lies in range if (ss >= qs && se <= qe) return tree[si]; // If a part of this segment overlaps // with the given range int mid = (ss + se) / 2; return getSumUtil(ss, mid, qs, qe, 2 * si + 1) + getSumUtil(mid + 1, se, qs, qe, 2 * si + 2); } // Return sum of elements in range from index qs (query // start) to qe (query end). It mainly uses getSumUtil() int getSum(int n, int qs, int qe) { // Check for erroneous input values if (qs < 0 || qe > n - 1 || qs > qe) { Console.WriteLine(\"Invalid Input\"); return -1; } return getSumUtil(0, n - 1, qs, qe, 0); } /* A recursive function that constructs Segment Tree for array[ss..se]. si is index of current node in segment tree st. */ void constructSTUtil(int []arr, int ss, int se, int si) { // out of range as ss can // never be greater than se if (ss > se) return; /* If there is one element in array, store it in current node of segment tree and return */ if (ss == se) { tree[si] = arr[ss]; return; } /* If there are more than one elements, then recur for left and right subtrees and store the sum of values in this node */ int mid = (ss + se) / 2; constructSTUtil(arr, ss, mid, si * 2 + 1); constructSTUtil(arr, mid + 1, se, si * 2 + 2); tree[si] = tree[si * 2 + 1] + tree[si * 2 + 2]; } /* Function to construct segment tree from given array. This function allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */ void constructST(int []arr, int n) { // Fill the allocated memory st constructSTUtil(arr, 0, n - 1, 0); } // Driver program to test above functions public static void Main(String []args) { int []arr = {1, 3, 5, 7, 9, 11}; int n = arr.Length; LazySegmentTree tree = new LazySegmentTree(); // Build segment tree from given array tree.constructST(arr, n); // Print sum of values in array from index 1 to 3 Console.WriteLine(\"Sum of values in given range = \" + tree.getSum(n, 1, 3)); // Add 10 to all nodes at indexes from 1 to 5. tree.updateRange(n, 1, 5, 10); // Find sum after the value is updated Console.WriteLine(\"Updated sum of values in given range = \" + tree.getSum(n, 1, 3)); }} // This code contributed by Rajput-Ji", "e": 60772, "s": 52890, "text": null }, { "code": null, "e": 60780, "s": 60772, "text": "Output:" }, { "code": null, "e": 60857, "s": 60780, "text": "Sum of values in given range = 15\nUpdated sum of values in given range = 45 " }, { "code": null, "e": 60879, "s": 60857, "text": "Time Complexity: O(n)" }, { "code": null, "e": 60904, "s": 60879, "text": "Auxiliary Space: O(MAX) " }, { "code": null, "e": 61735, "s": 60904, "text": "YouTubeGeeksforGeeks507K subscribersLazy Propagation in Segment Tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:06•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=UKH4Zgfa4kI\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 61905, "s": 61735, "text": "This article is contributed by Ankit Mittal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 61915, "s": 61905, "text": "Rajput-Ji" }, { "code": null, "e": 61923, "s": 61915, "text": "ankthon" }, { "code": null, "e": 61934, "s": 61923, "text": "nidhi_biet" }, { "code": null, "e": 61951, "s": 61934, "text": "surinderdawra388" }, { "code": null, "e": 61963, "s": 61951, "text": "rishavnitro" }, { "code": null, "e": 61983, "s": 61963, "text": "array-range-queries" }, { "code": null, "e": 61996, "s": 61983, "text": "Segment-Tree" }, { "code": null, "e": 62020, "s": 61996, "text": "Advanced Data Structure" }, { "code": null, "e": 62033, "s": 62020, "text": "Segment-Tree" }, { "code": null, "e": 62131, "s": 62033, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 62165, "s": 62131, "text": "Agents in Artificial Intelligence" }, { "code": null, "e": 62205, "s": 62165, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 62233, "s": 62205, "text": "AVL Tree | Set 2 (Deletion)" }, { "code": null, "e": 62265, "s": 62233, "text": "Red-Black Tree | Set 2 (Insert)" }, { "code": null, "e": 62294, "s": 62265, "text": "Disjoint Set Data Structures" }, { "code": null, "e": 62323, "s": 62294, "text": "Ordered Set and GNU C++ PBDS" }, { "code": null, "e": 62350, "s": 62323, "text": "Insert Operation in B-Tree" }, { "code": null, "e": 62386, "s": 62350, "text": "Binary Indexed Tree or Fenwick Tree" }, { "code": null, "e": 62400, "s": 62386, "text": "Binomial Heap" } ]
Average of first n even natural numbers - GeeksforGeeks
24 Mar, 2021 Given a number n then Find the Average of first n even natural numbers Ex.= 2 + 4 + 6 + 8 + 10 + 12 +.........+ 2n. Examples : Input : 7 Output : 8 (2 + 4 + 6 + 8 + 10 + 12 + 14)/7 = 8 Input : 5 Output : 6 (2 + 4 + 6 + 8 + 10)/5 = 6 Naive Approach:- In this program iterate the loop , finding total sum of first n even numbers and divided by n.it take 0(N) time. C++ Java Python3 C# PHP Javascript // C++ implementation to find Average// of sum of first n natural even numbers#include <bits/stdc++.h>using namespace std; // function to find average of// sum of first n even numbersint avg_of_even_num(int n){ // sum of first n even numbers int sum = 0; for (int i = 1; i <= n; i++) sum += 2*i; // calculating Average return sum/n;} // Driver Codeint main(){ int n = 9; cout << avg_of_even_num(n); return 0;} // java implementation to find Average// of sum of first n natural even numberimport java.io.*; class GFG { // function to find average of // sum of first n even numbers static int avg_of_even_num(int n) { // sum of first n even numbers int sum = 0; for (int i = 1; i <= n; i++) sum += 2*i; // calculating Average return (sum / n); } public static void main (String[] args) { int n = 9; System.out.print(avg_of_even_num(n)); }} // this code is contributed by 'vt_m' # Python3 implementation to# find Average of sum of# first n natural even# number # Function to find average# of sum of first n even# numbersdef avg_of_even_num(n): # sum of first n even # numbers sum=0 for i in range(1, n + 1): sum=sum + 2 * i # calculating Average return sum / n n=9print(avg_of_even_num(n)) # This code is contributed by upendra singh bartwal // C# implementation to find// Average of sum of first// n natural even numberusing System; class GFG { // function to find average of // sum of first n even numbers static int avg_of_even_num(int n) { // sum of first n even numbers int sum = 0; for (int i = 1; i <= n; i++) sum += 2 * i; // calculating Average return (sum / n); } // driver code public static void Main () { int n = 9; Console.Write(avg_of_even_num(n)); }} // This code is contributed by 'vt_m' <?php// PHP implementation to find Average// of sum of first n natural even numbers // function to find average of// sum of first n even numbersfunction avg_of_even_num($n){ // sum of first n even numbers $sum = 0; for ($i = 1; $i <= $n; $i++) $sum += 2 * $i; // calculating Average return $sum / $n;} // Driver Code$n = 9;echo(avg_of_even_num($n)); // This code is contributed by Ajit.?> <script>// javascript implementation to find Average// of sum of first n natural even numbers // function to find average of// sum of first n even numbersfunction avg_of_even_num( n){ // sum of first n even numbers let sum = 0; for (let i = 1; i <= n; i++) sum += 2*i; // calculating Average return sum/n;} // Driver Code let n = 9; document.write(avg_of_even_num(n)); // This code is contributed by todaysgaurav </script> Output : 10 Time Complexity : O(N) Method 2 :- The idea is the sum of first n even number is n(n+1), for find the Average of first n even numbers divide by n, hence formula is n(n + 1) / n = ( n + 1). i.e. Average of first n even numbers is n+1. it take 0(1) time. Avg of sum of N even natural number = (N + 1) Proof Sum of first n terms of an A.P.(Arithmetic Progression) = (n/2) * [2*a + (n-1)*d].....(i) where, a is the first term of the series and d is the difference between the adjacent terms of the series. Here, a = 2, d = 2, applying these values to eq.(i), get Sum = (n/2) * [2*2 + (n-1)*2] = (n/2) * [4 + 2*n - 2] = (n/2) * (2*n + 2) = n * (n + 1) finding the Avg so divided by n = n*(n+1)/n = (n+1) C++ Java Python3 C# PHP Javascript // CPP Program to find the average// of sum of first n even numbers#include <bits/stdc++.h>using namespace std; // Return the average of sum// of first n even numbersint avg_of_even_num(int n){ return n+1;} // Driver Codeint main(){ int n = 8; cout << avg_of_even_num(n) << endl; return 0;} // Java Program to find the average// of sum of first n even numbersimport java.io.*; class GFG{ // Return the average of sum // of first n even numbers static int avg_of_even_num(int n) { return n + 1; } public static void main (String[] args) { int n = 8; System.out.println(avg_of_even_num(n)); }} // This code is contributed by vt_m # Python 3 Program to# find the average# of sum of first n# even numbers # Return the average of sum# of first n even numbersdef avg_of_even_num(n) : return n+1 # Driven Programn = 8print(avg_of_even_num(n)) # This code is contributed# by Nikita Tiwari. // C# Program to find the average// of sum of first n even numbersusing System; class GFG { // Return the average of sum // of first n even numbers static int avg_of_even_num(int n) { return n + 1; } // driver code public static void Main () { int n = 8; Console.Write(avg_of_even_num(n)); }} // This code is contributed by vt_m <?php// PHP Program to find the average// of sum of first n even numbers // Return the average of sum// of first n even numbersfunction avg_of_even_num($n){ return $n + 1;} // Driver Code$n = 8;echo(avg_of_even_num($n)); // This code is contributed by Ajit.?> <script>// javascript Program to find the average// of sum of first n even numbers // Return the average of sum// of first n even numbersfunction avg_of_even_num(n){ return n + 1;}var n = 8;document.write(avg_of_even_num(n)); // This code is contributed by Amit Katiyar</script> Output: 9 Time Complexity : O(1) jit_t todaysgaurav amit143katiyar series Mathematical Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Print all possible combinations of r elements in a given array of size n Operators in C / C++ Program for factorial of a number Find minimum number of coins that make a given value The Knight's tour problem | Backtracking-1 Program for Decimal to Binary Conversion Program to find sum of elements in a given array
[ { "code": null, "e": 26791, "s": 26763, "text": "\n24 Mar, 2021" }, { "code": null, "e": 26920, "s": 26791, "text": "Given a number n then Find the Average of first n even natural numbers Ex.= 2 + 4 + 6 + 8 + 10 + 12 +.........+ 2n. Examples : " }, { "code": null, "e": 27030, "s": 26920, "text": "Input : 7\nOutput : 8\n(2 + 4 + 6 + 8 + 10 + 12 + 14)/7 = 8 \n\nInput : 5\nOutput : 6\n(2 + 4 + 6 + 8 + 10)/5 = 6" }, { "code": null, "e": 27163, "s": 27032, "text": "Naive Approach:- In this program iterate the loop , finding total sum of first n even numbers and divided by n.it take 0(N) time. " }, { "code": null, "e": 27167, "s": 27163, "text": "C++" }, { "code": null, "e": 27172, "s": 27167, "text": "Java" }, { "code": null, "e": 27180, "s": 27172, "text": "Python3" }, { "code": null, "e": 27183, "s": 27180, "text": "C#" }, { "code": null, "e": 27187, "s": 27183, "text": "PHP" }, { "code": null, "e": 27198, "s": 27187, "text": "Javascript" }, { "code": "// C++ implementation to find Average// of sum of first n natural even numbers#include <bits/stdc++.h>using namespace std; // function to find average of// sum of first n even numbersint avg_of_even_num(int n){ // sum of first n even numbers int sum = 0; for (int i = 1; i <= n; i++) sum += 2*i; // calculating Average return sum/n;} // Driver Codeint main(){ int n = 9; cout << avg_of_even_num(n); return 0;}", "e": 27640, "s": 27198, "text": null }, { "code": "// java implementation to find Average// of sum of first n natural even numberimport java.io.*; class GFG { // function to find average of // sum of first n even numbers static int avg_of_even_num(int n) { // sum of first n even numbers int sum = 0; for (int i = 1; i <= n; i++) sum += 2*i; // calculating Average return (sum / n); } public static void main (String[] args) { int n = 9; System.out.print(avg_of_even_num(n)); }} // this code is contributed by 'vt_m'", "e": 28194, "s": 27640, "text": null }, { "code": "# Python3 implementation to# find Average of sum of# first n natural even# number # Function to find average# of sum of first n even# numbersdef avg_of_even_num(n): # sum of first n even # numbers sum=0 for i in range(1, n + 1): sum=sum + 2 * i # calculating Average return sum / n n=9print(avg_of_even_num(n)) # This code is contributed by upendra singh bartwal", "e": 28592, "s": 28194, "text": null }, { "code": "// C# implementation to find// Average of sum of first// n natural even numberusing System; class GFG { // function to find average of // sum of first n even numbers static int avg_of_even_num(int n) { // sum of first n even numbers int sum = 0; for (int i = 1; i <= n; i++) sum += 2 * i; // calculating Average return (sum / n); } // driver code public static void Main () { int n = 9; Console.Write(avg_of_even_num(n)); }} // This code is contributed by 'vt_m'", "e": 29146, "s": 28592, "text": null }, { "code": "<?php// PHP implementation to find Average// of sum of first n natural even numbers // function to find average of// sum of first n even numbersfunction avg_of_even_num($n){ // sum of first n even numbers $sum = 0; for ($i = 1; $i <= $n; $i++) $sum += 2 * $i; // calculating Average return $sum / $n;} // Driver Code$n = 9;echo(avg_of_even_num($n)); // This code is contributed by Ajit.?>", "e": 29558, "s": 29146, "text": null }, { "code": "<script>// javascript implementation to find Average// of sum of first n natural even numbers // function to find average of// sum of first n even numbersfunction avg_of_even_num( n){ // sum of first n even numbers let sum = 0; for (let i = 1; i <= n; i++) sum += 2*i; // calculating Average return sum/n;} // Driver Code let n = 9; document.write(avg_of_even_num(n)); // This code is contributed by todaysgaurav </script>", "e": 30011, "s": 29558, "text": null }, { "code": null, "e": 30022, "s": 30011, "text": "Output : " }, { "code": null, "e": 30027, "s": 30022, "text": " 10" }, { "code": null, "e": 30282, "s": 30027, "text": "Time Complexity : O(N) Method 2 :- The idea is the sum of first n even number is n(n+1), for find the Average of first n even numbers divide by n, hence formula is n(n + 1) / n = ( n + 1). i.e. Average of first n even numbers is n+1. it take 0(1) time. " }, { "code": null, "e": 30346, "s": 30282, "text": " Avg of sum of N even natural number = (N + 1)" }, { "code": null, "e": 30354, "s": 30346, "text": "Proof " }, { "code": null, "e": 30801, "s": 30354, "text": "Sum of first n terms of an A.P.(Arithmetic Progression)\n= (n/2) * [2*a + (n-1)*d].....(i)\nwhere, a is the first term of the series and d is\nthe difference between the adjacent terms of the series.\n\nHere, a = 2, d = 2, applying these values to eq.(i), get\nSum = (n/2) * [2*2 + (n-1)*2]\n = (n/2) * [4 + 2*n - 2]\n = (n/2) * (2*n + 2)\n = n * (n + 1)\n\n finding the Avg so divided by n = n*(n+1)/n\n = (n+1)" }, { "code": null, "e": 30807, "s": 30803, "text": "C++" }, { "code": null, "e": 30812, "s": 30807, "text": "Java" }, { "code": null, "e": 30820, "s": 30812, "text": "Python3" }, { "code": null, "e": 30823, "s": 30820, "text": "C#" }, { "code": null, "e": 30827, "s": 30823, "text": "PHP" }, { "code": null, "e": 30838, "s": 30827, "text": "Javascript" }, { "code": "// CPP Program to find the average// of sum of first n even numbers#include <bits/stdc++.h>using namespace std; // Return the average of sum// of first n even numbersint avg_of_even_num(int n){ return n+1;} // Driver Codeint main(){ int n = 8; cout << avg_of_even_num(n) << endl; return 0;}", "e": 31145, "s": 30838, "text": null }, { "code": "// Java Program to find the average// of sum of first n even numbersimport java.io.*; class GFG{ // Return the average of sum // of first n even numbers static int avg_of_even_num(int n) { return n + 1; } public static void main (String[] args) { int n = 8; System.out.println(avg_of_even_num(n)); }} // This code is contributed by vt_m", "e": 31548, "s": 31145, "text": null }, { "code": "# Python 3 Program to# find the average# of sum of first n# even numbers # Return the average of sum# of first n even numbersdef avg_of_even_num(n) : return n+1 # Driven Programn = 8print(avg_of_even_num(n)) # This code is contributed# by Nikita Tiwari.", "e": 31821, "s": 31548, "text": null }, { "code": "// C# Program to find the average// of sum of first n even numbersusing System; class GFG { // Return the average of sum // of first n even numbers static int avg_of_even_num(int n) { return n + 1; } // driver code public static void Main () { int n = 8; Console.Write(avg_of_even_num(n)); }} // This code is contributed by vt_m", "e": 32222, "s": 31821, "text": null }, { "code": "<?php// PHP Program to find the average// of sum of first n even numbers // Return the average of sum// of first n even numbersfunction avg_of_even_num($n){ return $n + 1;} // Driver Code$n = 8;echo(avg_of_even_num($n)); // This code is contributed by Ajit.?>", "e": 32489, "s": 32222, "text": null }, { "code": "<script>// javascript Program to find the average// of sum of first n even numbers // Return the average of sum// of first n even numbersfunction avg_of_even_num(n){ return n + 1;}var n = 8;document.write(avg_of_even_num(n)); // This code is contributed by Amit Katiyar</script>", "e": 32771, "s": 32489, "text": null }, { "code": null, "e": 32781, "s": 32771, "text": "Output: " }, { "code": null, "e": 32783, "s": 32781, "text": "9" }, { "code": null, "e": 32808, "s": 32783, "text": "Time Complexity : O(1) " }, { "code": null, "e": 32814, "s": 32808, "text": "jit_t" }, { "code": null, "e": 32827, "s": 32814, "text": "todaysgaurav" }, { "code": null, "e": 32842, "s": 32827, "text": "amit143katiyar" }, { "code": null, "e": 32849, "s": 32842, "text": "series" }, { "code": null, "e": 32862, "s": 32849, "text": "Mathematical" }, { "code": null, "e": 32875, "s": 32862, "text": "Mathematical" }, { "code": null, "e": 32882, "s": 32875, "text": "series" }, { "code": null, "e": 32980, "s": 32882, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33004, "s": 32980, "text": "Merge two sorted arrays" }, { "code": null, "e": 33047, "s": 33004, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 33061, "s": 33047, "text": "Prime Numbers" }, { "code": null, "e": 33134, "s": 33061, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 33155, "s": 33134, "text": "Operators in C / C++" }, { "code": null, "e": 33189, "s": 33155, "text": "Program for factorial of a number" }, { "code": null, "e": 33242, "s": 33189, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 33285, "s": 33242, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 33326, "s": 33285, "text": "Program for Decimal to Binary Conversion" } ]
How to Create a Morse Code Converter Android App? - GeeksforGeeks
01 Sep, 2020 Morse code is a way in which one can encode characters and text using dots and dashes. The international Morse codes contain 26 letters of the alphabets and some non-English letters that are Arabic numerals as well as some punctuation. In Morse code, there is no difference between the upper and lower case letters. The transmission of the Morse Code is measured in dot durations. The Morse Code Converter App is an app that is used to convert the given statements to Morse Code. This is done by using Android Studio. The Languages that are used are Java and XML. So in this article lets create a Morse Code Converter Android App using the Java language. This project also involves the conversion of the Morse Code into relevant Statements. It means both encoding and decoding can be done using this Android app. The software tools required in this project are: ANDROID-STUDIO IDE (1.0.2)SDK having API level-21(minimum version)JAVA 7 and aboveAn android smartphone – version 4.2.2(Jelly bean and above) (only for testing the software) ANDROID-STUDIO IDE (1.0.2) SDK having API level-21(minimum version) JAVA 7 and above An android smartphone – version 4.2.2(Jelly bean and above) (only for testing the software) Step 1: Create a New Project To create a new project in Android Studio please refer How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Create a Round Button This step is optional (only if you want a black button with round corners). In the project tab, in the left-hand corner of the screen, click on the app folder. Then, click on the res folder. Then, right-click on the drawable folder and select New then select Drawable Resource file. Give this resource file a name. Remember one can use only lower case letters for the name of the resource file. Write the code below to create a resource file for black buttons with round corners. Use this resource file as background in the XML code of buttons to get black buttons with round corners. mybutton.xml <?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android"> <item> <shape android:shape="rectangle"> <corners android:radius="15dip" /> <stroke android:width="1dip" android:color="#5e7974" /> <gradient android:angle="-90" android:endColor="#091037" android:startColor="#0C000E" /> </shape> </item></selector> In case one wants to use the default button or some other button then skip this optional step and don’t include the resource file in the background of the buttons. Step 3: Working with activity_main.xml file Open the activity_main.xml file and start writing the xml code. Create 2 EditTexts in the xml file. One for writing the input and the other one for displaying the output. EditTexts are used because on clicking on the EditTexts the text can be selected and copied which will be very useful in sending the coded/uncoded message some other person using any messaging app. Make 3 Buttons: Encode, Decode and Clear.The Encode Button will take the input as text from the input EditText and then encode it into morse code and display it in the output EditText.The Decode Button will take the morse code as input from the input EditText and then decode it into alphabets and numbers and display it in the output EditText.The Clear Button will clear the input and output EditTexts. The Encode Button will take the input as text from the input EditText and then encode it into morse code and display it in the output EditText. The Decode Button will take the morse code as input from the input EditText and then decode it into alphabets and numbers and display it in the output EditText. The Clear Button will clear the input and output EditTexts. Give id’s to all the EditTexts and Buttons. The complete xml code is given below: activity_main.xml <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#006600" android:padding="25dp" tools:context=".MainActivity"> <TextView android:id="@+id/tvgfg" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="-8dp" android:gravity="center" android:text="GfG" android:textAlignment="center" android:textColor="#000" android:textSize="25sp" android:textStyle="italic" /> <EditText android:id="@+id/etinput" android:layout_width="match_parent" android:layout_height="100dp" android:layout_below="@+id/tvgfg" android:layout_marginTop="5dp" android:background="#ffffff" android:gravity="start" /> <!--edit text to accept the input from the user--> <LinearLayout android:id="@+id/llout" android:layout_width="match_parent" android:layout_height="50dp" android:layout_below="@+id/etinput" android:layout_marginTop="5dp" android:gravity="center" android:orientation="horizontal"> <Button android:id="@+id/btnencode" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_marginRight="5dp" android:background="@drawable/mybutton" android:padding="13dp" android:text="EnCode" android:textColor="#fff" android:textSize="20sp" android:textStyle="bold" /> <Button android:id="@+id/btnclear" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_marginRight="5dp" android:background="@drawable/mybutton" android:padding="13dp" android:text="clear" android:textColor="#fff" android:textSize="20sp" android:textStyle="bold" /> <Button android:id="@+id/btndecode" android:layout_width="wrap_content" android:layout_height="match_parent" android:background="@drawable/mybutton" android:padding="13dp" android:text="decode" android:textColor="#fff" android:textSize="20sp" android:textStyle="bold" /> </LinearLayout> <!--edit text to display output to the user. Edit text is used since the user can copy the text easily if he wants to--> <EditText android:id="@+id/etoutput" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@+id/llout" android:layout_marginTop="10dp" android:background="#ffffff" android:gravity="start" android:textSize="20sp" android:textStyle="bold" /> </RelativeLayout> Step 4: Working with MainActivity.java file Open the MainActivity.java file. Initialize the variables just under the MainActivity class (Syntax:- Edit Text etinput, etoutput;Button btnEncode, btnDecode, btnclear;) Assign the variables under the OnCreate method. Make an array and store all the alphabets and digits in it. Make another array and store the morse code of each alphahbets and digits in the indices corresponding to it’s alphabets and digits in the first array. Use the logic in the code below to complete the morse code converter app. Below is the complete code for MainActivity.java file. MainActivity.java package com.example.morseconverter; import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { // initialize variables EditText etinput, etoutput; Button btnEncode, btnDecode, btnclear; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Assign variables etinput = findViewById(R.id.etinput); etoutput = findViewById(R.id.etoutput); btnDecode = findViewById(R.id.btndecode); btnEncode = findViewById(R.id.btnencode); btnclear = findViewById(R.id.btnclear); // initializing string arrays final String[] AlphaNumeric = new String[37]; // string array for storing alphabets and numbers final String[] AlphaNumeric1 = new String[37]; // string array for storing corresponding morse code // assigning alphabets to the string array Alphanumeric[] AlphaNumeric[0] = "A"; AlphaNumeric[1] = "B"; AlphaNumeric[2] = "C"; AlphaNumeric[3] = "D"; AlphaNumeric[4] = "E"; AlphaNumeric[5] = "F"; AlphaNumeric[6] = "G"; AlphaNumeric[7] = "H"; AlphaNumeric[8] = "I"; AlphaNumeric[9] = "J"; AlphaNumeric[10] = "K"; AlphaNumeric[11] = "L"; AlphaNumeric[12] = "M"; AlphaNumeric[13] = "N"; AlphaNumeric[14] = "O"; AlphaNumeric[15] = "P"; AlphaNumeric[16] = "Q"; AlphaNumeric[17] = "R"; AlphaNumeric[18] = "S"; AlphaNumeric[19] = "T"; AlphaNumeric[20] = "U"; AlphaNumeric[21] = "V"; AlphaNumeric[22] = "W"; AlphaNumeric[23] = "X"; AlphaNumeric[24] = "Y"; AlphaNumeric[25] = "Z"; AlphaNumeric[26] = "0"; AlphaNumeric[27] = "1"; AlphaNumeric[28] = "2"; AlphaNumeric[29] = "3"; AlphaNumeric[30] = "4"; AlphaNumeric[31] = "5"; AlphaNumeric[32] = "6"; AlphaNumeric[33] = "7"; AlphaNumeric[34] = "8"; AlphaNumeric[35] = "9"; AlphaNumeric[36] = " "; // assigning the corresponding morse code // for each letter and number to // Alphanumeric1[] array AlphaNumeric1[0] = ".-"; AlphaNumeric1[1] = "-..."; AlphaNumeric1[2] = "-.-."; AlphaNumeric1[3] = "-.."; AlphaNumeric1[4] = "."; AlphaNumeric1[5] = "..-."; AlphaNumeric1[6] = "--."; AlphaNumeric1[7] = "...."; AlphaNumeric1[8] = ".."; AlphaNumeric1[9] = ".---"; AlphaNumeric1[10] = "-.-"; AlphaNumeric1[11] = ".-.."; AlphaNumeric1[12] = "--"; AlphaNumeric1[13] = "-."; AlphaNumeric1[14] = "---"; AlphaNumeric1[15] = ".--."; AlphaNumeric1[16] = "--.-"; AlphaNumeric1[17] = ".-."; AlphaNumeric1[18] = "..."; AlphaNumeric1[19] = "-"; AlphaNumeric1[20] = "..-"; AlphaNumeric1[21] = "...-"; AlphaNumeric1[22] = ".--"; AlphaNumeric1[23] = "-..-"; AlphaNumeric1[24] = "-.--"; AlphaNumeric1[25] = "--.."; AlphaNumeric1[26] = "-----"; AlphaNumeric1[27] = ".----"; AlphaNumeric1[28] = "..---"; AlphaNumeric1[29] = "...--"; AlphaNumeric1[30] = "....-"; AlphaNumeric1[31] = "....."; AlphaNumeric1[32] = "-...."; AlphaNumeric1[33] = "--..."; AlphaNumeric1[34] = "---.."; AlphaNumeric1[35] = "----."; AlphaNumeric1[36] = "/"; btnEncode.setOnClickListener(new View.OnClickListener() {@Override public void onClick(View v) { // When button encode is clicked then the // following lines inside this curly // braces will be executed // to get the input as string which the user wants to encode String input = etinput.getText().toString(); String output = ""; // variable used to compute the output // to get the length of the input string int l = input.length(); // variables used in loops int i, j; for (i = 0; i < l; i++) { // to extract each Token of the string at a time String ch = input.substring(i, i + 1); // the loop to check the extracted token with // each letter and store the morse code in // the output variable accordingly for (j = 0; j < 37; j++) { if (ch.equalsIgnoreCase(AlphaNumeric[j])) { // concat space is used to separate // the morse code of each token output = output.concat(AlphaNumeric1[j]).concat(" "); } } } // to display the output etoutput.setText(output); } }); btnclear.setOnClickListener(new View.OnClickListener() {@Override public void onClick(View v) { // When button clear is clicked then the // following lines inside this curly // braces will be executed // to clear the etinput etinput.setText(""); // to clear etoutput etoutput.setText(""); } }); btnDecode.setOnClickListener(new View.OnClickListener() {@Override public void onClick(View v) { // When button decode is clicked then the // following lines inside this curly // braces will be executed // to get the input given by the user as string String input1 = etinput.getText().toString(); // to add space to the end of the string // because of the logic used in decoding String input = input1.concat(" "); // to get the length of the input string int l = input.length(); // i and j are integer variables used in loops. // Variable p is used as the end index of // substring() function int i, j, p = 0; // variable used as a starting // index of substring() function int pos = 0; // to store the extracted morse code // for each Alphabet,number or space String letter = ""; // a to store the output in it String output = ""; for (i = 0; i < l; i++) { // a variable used to trigger the j loop only // when the complete morse code of a letter // or number is extracted int flag = 0; // to extract each token at a time String ch = input.substring(i, i + 1); // if the extracted token is a space if (ch.equalsIgnoreCase(" ")) { // to store the value of i in p p = i; // to extract the morse code for each letter or number letter = input.substring(pos, p); // to update the value of pos so that next // time the morse code for the next letter // or digit is extracted pos = p + 1; flag = 1; } String letter1 = letter.trim(); // to delete extra whitespaces at // both ends in case there are any if (flag == 1) { for (j = 0; j <= 36; j++) { if (letter1.equalsIgnoreCase(AlphaNumeric1[j])) { output = output.concat(AlphaNumeric[j]); break; } } } } // to display the output etoutput.setText(output); } }); }} Github link: Click here android Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Resource Raw Folder in Android Studio Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? Flexbox-Layout in Android Retrofit with Kotlin Coroutine in Android Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java Stream In Java
[ { "code": null, "e": 26491, "s": 26463, "text": "\n01 Sep, 2020" }, { "code": null, "e": 27055, "s": 26491, "text": "Morse code is a way in which one can encode characters and text using dots and dashes. The international Morse codes contain 26 letters of the alphabets and some non-English letters that are Arabic numerals as well as some punctuation. In Morse code, there is no difference between the upper and lower case letters. The transmission of the Morse Code is measured in dot durations. The Morse Code Converter App is an app that is used to convert the given statements to Morse Code. This is done by using Android Studio. The Languages that are used are Java and XML." }, { "code": null, "e": 27304, "s": 27055, "text": "So in this article lets create a Morse Code Converter Android App using the Java language. This project also involves the conversion of the Morse Code into relevant Statements. It means both encoding and decoding can be done using this Android app." }, { "code": null, "e": 27353, "s": 27304, "text": "The software tools required in this project are:" }, { "code": null, "e": 27527, "s": 27353, "text": "ANDROID-STUDIO IDE (1.0.2)SDK having API level-21(minimum version)JAVA 7 and aboveAn android smartphone – version 4.2.2(Jelly bean and above) (only for testing the software)" }, { "code": null, "e": 27554, "s": 27527, "text": "ANDROID-STUDIO IDE (1.0.2)" }, { "code": null, "e": 27595, "s": 27554, "text": "SDK having API level-21(minimum version)" }, { "code": null, "e": 27612, "s": 27595, "text": "JAVA 7 and above" }, { "code": null, "e": 27704, "s": 27612, "text": "An android smartphone – version 4.2.2(Jelly bean and above) (only for testing the software)" }, { "code": null, "e": 27733, "s": 27704, "text": "Step 1: Create a New Project" }, { "code": null, "e": 27892, "s": 27733, "text": "To create a new project in Android Studio please refer How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 27922, "s": 27892, "text": "Step 2: Create a Round Button" }, { "code": null, "e": 28507, "s": 27922, "text": "This step is optional (only if you want a black button with round corners). In the project tab, in the left-hand corner of the screen, click on the app folder. Then, click on the res folder. Then, right-click on the drawable folder and select New then select Drawable Resource file. Give this resource file a name. Remember one can use only lower case letters for the name of the resource file. Write the code below to create a resource file for black buttons with round corners. Use this resource file as background in the XML code of buttons to get black buttons with round corners." }, { "code": null, "e": 28520, "s": 28507, "text": "mybutton.xml" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><selector xmlns:android=\"http://schemas.android.com/apk/res/android\"> <item> <shape android:shape=\"rectangle\"> <corners android:radius=\"15dip\" /> <stroke android:width=\"1dip\" android:color=\"#5e7974\" /> <gradient android:angle=\"-90\" android:endColor=\"#091037\" android:startColor=\"#0C000E\" /> </shape> </item></selector> ", "e": 28968, "s": 28520, "text": null }, { "code": null, "e": 29132, "s": 28968, "text": "In case one wants to use the default button or some other button then skip this optional step and don’t include the resource file in the background of the buttons." }, { "code": null, "e": 29176, "s": 29132, "text": "Step 3: Working with activity_main.xml file" }, { "code": null, "e": 29240, "s": 29176, "text": "Open the activity_main.xml file and start writing the xml code." }, { "code": null, "e": 29545, "s": 29240, "text": "Create 2 EditTexts in the xml file. One for writing the input and the other one for displaying the output. EditTexts are used because on clicking on the EditTexts the text can be selected and copied which will be very useful in sending the coded/uncoded message some other person using any messaging app." }, { "code": null, "e": 29949, "s": 29545, "text": "Make 3 Buttons: Encode, Decode and Clear.The Encode Button will take the input as text from the input EditText and then encode it into morse code and display it in the output EditText.The Decode Button will take the morse code as input from the input EditText and then decode it into alphabets and numbers and display it in the output EditText.The Clear Button will clear the input and output EditTexts." }, { "code": null, "e": 30093, "s": 29949, "text": "The Encode Button will take the input as text from the input EditText and then encode it into morse code and display it in the output EditText." }, { "code": null, "e": 30254, "s": 30093, "text": "The Decode Button will take the morse code as input from the input EditText and then decode it into alphabets and numbers and display it in the output EditText." }, { "code": null, "e": 30314, "s": 30254, "text": "The Clear Button will clear the input and output EditTexts." }, { "code": null, "e": 30358, "s": 30314, "text": "Give id’s to all the EditTexts and Buttons." }, { "code": null, "e": 30396, "s": 30358, "text": "The complete xml code is given below:" }, { "code": null, "e": 30414, "s": 30396, "text": "activity_main.xml" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"#006600\" android:padding=\"25dp\" tools:context=\".MainActivity\"> <TextView android:id=\"@+id/tvgfg\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"-8dp\" android:gravity=\"center\" android:text=\"GfG\" android:textAlignment=\"center\" android:textColor=\"#000\" android:textSize=\"25sp\" android:textStyle=\"italic\" /> <EditText android:id=\"@+id/etinput\" android:layout_width=\"match_parent\" android:layout_height=\"100dp\" android:layout_below=\"@+id/tvgfg\" android:layout_marginTop=\"5dp\" android:background=\"#ffffff\" android:gravity=\"start\" /> <!--edit text to accept the input from the user--> <LinearLayout android:id=\"@+id/llout\" android:layout_width=\"match_parent\" android:layout_height=\"50dp\" android:layout_below=\"@+id/etinput\" android:layout_marginTop=\"5dp\" android:gravity=\"center\" android:orientation=\"horizontal\"> <Button android:id=\"@+id/btnencode\" android:layout_width=\"wrap_content\" android:layout_height=\"match_parent\" android:layout_marginRight=\"5dp\" android:background=\"@drawable/mybutton\" android:padding=\"13dp\" android:text=\"EnCode\" android:textColor=\"#fff\" android:textSize=\"20sp\" android:textStyle=\"bold\" /> <Button android:id=\"@+id/btnclear\" android:layout_width=\"wrap_content\" android:layout_height=\"match_parent\" android:layout_marginRight=\"5dp\" android:background=\"@drawable/mybutton\" android:padding=\"13dp\" android:text=\"clear\" android:textColor=\"#fff\" android:textSize=\"20sp\" android:textStyle=\"bold\" /> <Button android:id=\"@+id/btndecode\" android:layout_width=\"wrap_content\" android:layout_height=\"match_parent\" android:background=\"@drawable/mybutton\" android:padding=\"13dp\" android:text=\"decode\" android:textColor=\"#fff\" android:textSize=\"20sp\" android:textStyle=\"bold\" /> </LinearLayout> <!--edit text to display output to the user. Edit text is used since the user can copy the text easily if he wants to--> <EditText android:id=\"@+id/etoutput\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_below=\"@+id/llout\" android:layout_marginTop=\"10dp\" android:background=\"#ffffff\" android:gravity=\"start\" android:textSize=\"20sp\" android:textStyle=\"bold\" /> </RelativeLayout>", "e": 33486, "s": 30414, "text": null }, { "code": null, "e": 33530, "s": 33486, "text": "Step 4: Working with MainActivity.java file" }, { "code": null, "e": 33563, "s": 33530, "text": "Open the MainActivity.java file." }, { "code": null, "e": 33700, "s": 33563, "text": "Initialize the variables just under the MainActivity class (Syntax:- Edit Text etinput, etoutput;Button btnEncode, btnDecode, btnclear;)" }, { "code": null, "e": 33748, "s": 33700, "text": "Assign the variables under the OnCreate method." }, { "code": null, "e": 33808, "s": 33748, "text": "Make an array and store all the alphabets and digits in it." }, { "code": null, "e": 33960, "s": 33808, "text": "Make another array and store the morse code of each alphahbets and digits in the indices corresponding to it’s alphabets and digits in the first array." }, { "code": null, "e": 34034, "s": 33960, "text": "Use the logic in the code below to complete the morse code converter app." }, { "code": null, "e": 34089, "s": 34034, "text": "Below is the complete code for MainActivity.java file." }, { "code": null, "e": 34107, "s": 34089, "text": "MainActivity.java" }, { "code": "package com.example.morseconverter; import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { // initialize variables EditText etinput, etoutput; Button btnEncode, btnDecode, btnclear; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Assign variables etinput = findViewById(R.id.etinput); etoutput = findViewById(R.id.etoutput); btnDecode = findViewById(R.id.btndecode); btnEncode = findViewById(R.id.btnencode); btnclear = findViewById(R.id.btnclear); // initializing string arrays final String[] AlphaNumeric = new String[37]; // string array for storing alphabets and numbers final String[] AlphaNumeric1 = new String[37]; // string array for storing corresponding morse code // assigning alphabets to the string array Alphanumeric[] AlphaNumeric[0] = \"A\"; AlphaNumeric[1] = \"B\"; AlphaNumeric[2] = \"C\"; AlphaNumeric[3] = \"D\"; AlphaNumeric[4] = \"E\"; AlphaNumeric[5] = \"F\"; AlphaNumeric[6] = \"G\"; AlphaNumeric[7] = \"H\"; AlphaNumeric[8] = \"I\"; AlphaNumeric[9] = \"J\"; AlphaNumeric[10] = \"K\"; AlphaNumeric[11] = \"L\"; AlphaNumeric[12] = \"M\"; AlphaNumeric[13] = \"N\"; AlphaNumeric[14] = \"O\"; AlphaNumeric[15] = \"P\"; AlphaNumeric[16] = \"Q\"; AlphaNumeric[17] = \"R\"; AlphaNumeric[18] = \"S\"; AlphaNumeric[19] = \"T\"; AlphaNumeric[20] = \"U\"; AlphaNumeric[21] = \"V\"; AlphaNumeric[22] = \"W\"; AlphaNumeric[23] = \"X\"; AlphaNumeric[24] = \"Y\"; AlphaNumeric[25] = \"Z\"; AlphaNumeric[26] = \"0\"; AlphaNumeric[27] = \"1\"; AlphaNumeric[28] = \"2\"; AlphaNumeric[29] = \"3\"; AlphaNumeric[30] = \"4\"; AlphaNumeric[31] = \"5\"; AlphaNumeric[32] = \"6\"; AlphaNumeric[33] = \"7\"; AlphaNumeric[34] = \"8\"; AlphaNumeric[35] = \"9\"; AlphaNumeric[36] = \" \"; // assigning the corresponding morse code // for each letter and number to // Alphanumeric1[] array AlphaNumeric1[0] = \".-\"; AlphaNumeric1[1] = \"-...\"; AlphaNumeric1[2] = \"-.-.\"; AlphaNumeric1[3] = \"-..\"; AlphaNumeric1[4] = \".\"; AlphaNumeric1[5] = \"..-.\"; AlphaNumeric1[6] = \"--.\"; AlphaNumeric1[7] = \"....\"; AlphaNumeric1[8] = \"..\"; AlphaNumeric1[9] = \".---\"; AlphaNumeric1[10] = \"-.-\"; AlphaNumeric1[11] = \".-..\"; AlphaNumeric1[12] = \"--\"; AlphaNumeric1[13] = \"-.\"; AlphaNumeric1[14] = \"---\"; AlphaNumeric1[15] = \".--.\"; AlphaNumeric1[16] = \"--.-\"; AlphaNumeric1[17] = \".-.\"; AlphaNumeric1[18] = \"...\"; AlphaNumeric1[19] = \"-\"; AlphaNumeric1[20] = \"..-\"; AlphaNumeric1[21] = \"...-\"; AlphaNumeric1[22] = \".--\"; AlphaNumeric1[23] = \"-..-\"; AlphaNumeric1[24] = \"-.--\"; AlphaNumeric1[25] = \"--..\"; AlphaNumeric1[26] = \"-----\"; AlphaNumeric1[27] = \".----\"; AlphaNumeric1[28] = \"..---\"; AlphaNumeric1[29] = \"...--\"; AlphaNumeric1[30] = \"....-\"; AlphaNumeric1[31] = \".....\"; AlphaNumeric1[32] = \"-....\"; AlphaNumeric1[33] = \"--...\"; AlphaNumeric1[34] = \"---..\"; AlphaNumeric1[35] = \"----.\"; AlphaNumeric1[36] = \"/\"; btnEncode.setOnClickListener(new View.OnClickListener() {@Override public void onClick(View v) { // When button encode is clicked then the // following lines inside this curly // braces will be executed // to get the input as string which the user wants to encode String input = etinput.getText().toString(); String output = \"\"; // variable used to compute the output // to get the length of the input string int l = input.length(); // variables used in loops int i, j; for (i = 0; i < l; i++) { // to extract each Token of the string at a time String ch = input.substring(i, i + 1); // the loop to check the extracted token with // each letter and store the morse code in // the output variable accordingly for (j = 0; j < 37; j++) { if (ch.equalsIgnoreCase(AlphaNumeric[j])) { // concat space is used to separate // the morse code of each token output = output.concat(AlphaNumeric1[j]).concat(\" \"); } } } // to display the output etoutput.setText(output); } }); btnclear.setOnClickListener(new View.OnClickListener() {@Override public void onClick(View v) { // When button clear is clicked then the // following lines inside this curly // braces will be executed // to clear the etinput etinput.setText(\"\"); // to clear etoutput etoutput.setText(\"\"); } }); btnDecode.setOnClickListener(new View.OnClickListener() {@Override public void onClick(View v) { // When button decode is clicked then the // following lines inside this curly // braces will be executed // to get the input given by the user as string String input1 = etinput.getText().toString(); // to add space to the end of the string // because of the logic used in decoding String input = input1.concat(\" \"); // to get the length of the input string int l = input.length(); // i and j are integer variables used in loops. // Variable p is used as the end index of // substring() function int i, j, p = 0; // variable used as a starting // index of substring() function int pos = 0; // to store the extracted morse code // for each Alphabet,number or space String letter = \"\"; // a to store the output in it String output = \"\"; for (i = 0; i < l; i++) { // a variable used to trigger the j loop only // when the complete morse code of a letter // or number is extracted int flag = 0; // to extract each token at a time String ch = input.substring(i, i + 1); // if the extracted token is a space if (ch.equalsIgnoreCase(\" \")) { // to store the value of i in p p = i; // to extract the morse code for each letter or number letter = input.substring(pos, p); // to update the value of pos so that next // time the morse code for the next letter // or digit is extracted pos = p + 1; flag = 1; } String letter1 = letter.trim(); // to delete extra whitespaces at // both ends in case there are any if (flag == 1) { for (j = 0; j <= 36; j++) { if (letter1.equalsIgnoreCase(AlphaNumeric1[j])) { output = output.concat(AlphaNumeric[j]); break; } } } } // to display the output etoutput.setText(output); } }); }}", "e": 41529, "s": 34107, "text": null }, { "code": null, "e": 41553, "s": 41529, "text": "Github link: Click here" }, { "code": null, "e": 41561, "s": 41553, "text": "android" }, { "code": null, "e": 41569, "s": 41561, "text": "Android" }, { "code": null, "e": 41574, "s": 41569, "text": "Java" }, { "code": null, "e": 41579, "s": 41574, "text": "Java" }, { "code": null, "e": 41587, "s": 41579, "text": "Android" }, { "code": null, "e": 41685, "s": 41587, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41723, "s": 41685, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 41762, "s": 41723, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 41812, "s": 41762, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 41838, "s": 41812, "text": "Flexbox-Layout in Android" }, { "code": null, "e": 41880, "s": 41838, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 41895, "s": 41880, "text": "Arrays in Java" }, { "code": null, "e": 41939, "s": 41895, "text": "Split() String method in Java with examples" }, { "code": null, "e": 41961, "s": 41939, "text": "For-each loop in Java" }, { "code": null, "e": 42012, "s": 41961, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
Bootstrap 4 | Custom Forms - GeeksforGeeks
29 Nov, 2021 Bootstrap 4 enables to customize the browser’s default form and control layouts. The customized form can be created by using Bootstrap 4 like checkbox, radio buttons, file inputs and more. Bootstrap simplifies the process of alignment and styling of web pages in many forms like label, input, field, textarea, button, checkbox, etc.Custom Checkbox: The .custom-control and .custom-checkbox classes are used in <div> element to wrap the container element. The .custom-control-input class is used with input type=”checkbox” to create custom input textbox.Example: html <!DOCTYPE html><html lang="en"> <head> <title> Bootstrap Custom forms </title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head> <body> <div class="container"> <h1 class="text-center text-success">GeeksforGeeks</h1> <h2 class="text-center">Custom Checkbox</h2> <form action="#"> <div class="custom-control custom-checkbox mb-3"> <input type="checkbox" class="custom-control-input" id="customCheckBox" name="checkbox1"> <label class="custom-control-label" for="customCheckBox"> Custom checkbox </label> </div> <div class="custom-control custom-checkbox mb-3"> <input type="checkbox" class="custom-control-input" id="customCheckBox" name="checkbox1" checked> <label class="custom-control-label" for="customCheckBox"> Custom checkbox </label> </div> <div class="mb-3"> <input type="checkbox" id="defaultCheckBox" name="checkbox2"> <label for="defaultCheckBox">Default checkbox</label> </div> <input type="checkbox" id="defaultCheckBox" name="checkbox2" checked> <label for="defaultCheckBox">Default checkbox</label> <br> <button type="submit" class="btn btn-success">Submit</button> </form> </div></body></html> Output: Custom switch: The .custom-control and .custom-switch classes are used to wrap the input checkbox. The .custom-control-input class is used with label tag. Bootstrap switch/toggle is a simple component used for activating one of two predefined options. Commonly used as an on/off button. A toggle button allows the user to change a setting between two states.Example: html <!DOCTYPE html><html lang="en"> <head> <title> Bootstrap Custom forms </title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head> <body> <div class="container"> <h1 class="text-center text-success">GeeksforGeeks</h1> <h2 class="text-center">Custom Switch Buttons</h2> <form action="#"> <div class="custom-control custom-switch"> <input type="checkbox" class="custom-control-input" id="customSwitch" name="switch" checked> <label class="custom-control-label" for="customSwitch"> Toggle On </label> </div> <br> <div class="custom-control custom-switch"> <input type="checkbox" class="custom-control-input" id="customSwitch" name="switch"> <label class="custom-control-label" for="customSwitch"> Toggle Off </label> </div> <br> <button type="submit" class="btn btn-success">Submit</button> </form> </div></body></html> Output: Custom Radio button: It is same as checkbox. It uses .custom-radio instead of .custom-input on label tag. Checkbox and radio buttond are made to support HTML-based form validation and give a brief, friendly labels.Example: html <!DOCTYPE html><html lang="en"> <head> <title> Bootstrap Custom forms </title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head> <body> <div class="container"> <h1 class="text-center text-success">GeeksforGeeks</h1> <h2 class="text-center">Custom Radio Buttons</h2> <form action="#"> <div class="custom-control custom-radio"> <input type="radio" class="custom-control-input" id="customRadio" name="radioButton" checked> <label class="custom-control-label" for="customRadio"> Radio Button On </label> </div> <br> <div class="custom-control custom-radio"> <input type="radio" class="custom-control-input" id="customRadio" name="radioButton"> <label class="custom-control-label" for="customRadio"> Radio Button Off </label> </div> <br> <button type="submit" class="btn btn-success">Submit</button> </form> </div></body></html> Output: Custom Inline form control: Custom checkbox and radio buttons are used as a default to use inline control to display them inline by using .custom-control-inline class. The group checkboxes or radio buttons on the same horizontal row by adding .form-check-inline to .form-check class.Example: html <!DOCTYPE html><html lang="en"> <head> <title> Bootstrap Custom forms </title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head> <body> <div class="container"> <h1 class="text-center text-success">GeeksforGeeks</h1> <h2 class="text-center">Inline Custom Form Controls</h2> <form action="#"> <div class="custom-control custom-radio custom-control-inline"> <input type="radio" class="custom-control-input" id="customRadio" name="radioButton" checked> <label class="custom-control-label" for="customRadio"> Radio Button </label> </div> <div class="custom-control custom-radio custom-control-inline"> <input type="radio" class="custom-control-input" id="customRadio" name="radioButton"> <label class="custom-control-label" for="customRadio"> Radio Button </label> </div> <br><br> <div class="custom-control custom-checkbox custom-control-inline"> <input type="checkbox" class="custom-control-input" id="customCheckBox" name="checkbox1"> <label class="custom-control-label" for="customCheckBox"> Custom checkbox </label> </div> <div class="custom-control custom-checkbox custom-control-inline"> <input type="checkbox" class="custom-control-input" id="customCheckBox" name="checkbox1" checked> <label class="custom-control-label" for="customCheckBox"> Custom checkbox </label> </div> <br><br> <button type="submit" class="btn btn-success">Submit</button> </form> </div></body></html> Output: Custom select menu: It is used to select any particular attribute value and customized according to users need. The .custom-select class is used within <select> element to create custom menu. It uses <select> and <option> tag for customization. Inside option tag, it puts value and show in the dropdown when you will run the program. Example: html <!DOCTYPE html><html lang="en"> <head> <title> Bootstrap Custom forms </title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head> <body> <div class="container"> <h1 class="text-center text-success">GeeksforGeeks</h1> <h2 class="text-center">Custom Select Menu</h2> <form action="#"> <select name="sub" class="custom-select mb-3"> <option selected>Select Computer science Subject</option> <option value="DS">Data Structure</option> <option value="Algo">Algorithm</option> <option value="CN">Computer Networks</option> <option value="OS">Operating System</option> </select> <button type="submit" class="btn btn-success">Submit</button> </form> </div></body></html> Output: Custom Select Menu Size: The .custom-select-sm class is used to create small and .custom-select-lg class is used to create large select menu.Example: html <!DOCTYPE html><html lang="en"> <head> <title> Bootstrap Custom forms </title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head> <body> <div class="container"> <h1 class="text-center text-success">GeeksforGeeks</h1> <h2 class="text-center">Custom Select Menu Size</h2> <form action="#"> <select name="sub" class="custom-select custom-select-lg mb-3"> <option selected>Select Computer science Subject</option> <option value="DS">Data Structure</option> <option value="Algo">Algorithm</option> <option value="CN">Computer Networks</option> <option value="OS">Operating System</option> </select> <select name="sub" class="custom-select custom-select mb-3"> <option selected>Select Computer science Subject</option> <option value="DS">Data Structure</option> <option value="Algo">Algorithm</option> <option value="CN">Computer Networks</option> <option value="OS">Operating System</option> </select> <select name="sub" class="custom-select custom-select-sm mb-3"> <option selected>Select Computer science Subject</option> <option value="DS">Data Structure</option> <option value="Algo">Algorithm</option> <option value="CN">Computer Networks</option> <option value="OS">Operating System</option> </select> </form> </div></body></html> Custom File Upload: for make a custom file control, wrap the tag inside div tag that uses .custom-file class .The file uploader component has always been part of the HTML specification since the very early days. Lately, though, it is often hidden behind nicer user interfaces that support the drag-and-drop of files and preview of images. Some basic restyling of the classic input box with a push button that unifies the rendering across all browsers is possible. for label tag it uses .custom-control-label class. for input tag it uses .custom-control-input class .Example: HTML <!DOCTYPE html><html lang="en"> <head> <title> Bootstrap Custom forms </title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head> <body> <div class="container"> <h1 class="text-center text-success">GeeksforGeeks</h1> <h2 class="text-center">Custom File Upload</h2> <form action="#"> <p>Custom file upload:</p> <div class="custom-file"> <input type="file" class="custom-file-input" id="fileUpload" name="file_name"> <label class="custom-file-label" for="fileUpload"> Choose file from computer </label> </div> </form> </div> <!-- Script to appear file name in select box --> <script> $(".custom-file-input").on("change", function() { var file_name = $(this).val().split("\\").pop(); $(this).siblings(".custom-file-label") .addClass("selected").html(file_name); });</script> </body></html> Output: Custom Range: The .custom-range class is used within <range> element to create custom_range menu.Example: html <!DOCTYPE html><html lang="en"> <head> <title> Bootstrap Custom forms </title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head> <body> <div class="container"> <h1 class="text-center text-success">GeeksforGeeks</h1> <h2 class="text-center">Custom Range</h2> <form action="#"> <label for="cus_range">Custom range</label> <input type="range" class="custom-range" id="cus_range" name="range"> </form> </div></body></html> Supported Browser: Google Chrome Internet Explorer Firefox Opera Safari ysachin2314 rs1686740 Bootstrap-4 Picked Bootstrap Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to change navigation bar color in Bootstrap ? Form validation using jQuery How to align navbar items to the right in Bootstrap 4 ? How to pass data into a bootstrap modal? How to Show Images on Click using HTML ? 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": 28440, "s": 28412, "text": "\n29 Nov, 2021" }, { "code": null, "e": 29004, "s": 28440, "text": "Bootstrap 4 enables to customize the browser’s default form and control layouts. The customized form can be created by using Bootstrap 4 like checkbox, radio buttons, file inputs and more. Bootstrap simplifies the process of alignment and styling of web pages in many forms like label, input, field, textarea, button, checkbox, etc.Custom Checkbox: The .custom-control and .custom-checkbox classes are used in <div> element to wrap the container element. The .custom-control-input class is used with input type=”checkbox” to create custom input textbox.Example: " }, { "code": null, "e": 29009, "s": 29004, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title> Bootstrap Custom forms </title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head> <body> <div class=\"container\"> <h1 class=\"text-center text-success\">GeeksforGeeks</h1> <h2 class=\"text-center\">Custom Checkbox</h2> <form action=\"#\"> <div class=\"custom-control custom-checkbox mb-3\"> <input type=\"checkbox\" class=\"custom-control-input\" id=\"customCheckBox\" name=\"checkbox1\"> <label class=\"custom-control-label\" for=\"customCheckBox\"> Custom checkbox </label> </div> <div class=\"custom-control custom-checkbox mb-3\"> <input type=\"checkbox\" class=\"custom-control-input\" id=\"customCheckBox\" name=\"checkbox1\" checked> <label class=\"custom-control-label\" for=\"customCheckBox\"> Custom checkbox </label> </div> <div class=\"mb-3\"> <input type=\"checkbox\" id=\"defaultCheckBox\" name=\"checkbox2\"> <label for=\"defaultCheckBox\">Default checkbox</label> </div> <input type=\"checkbox\" id=\"defaultCheckBox\" name=\"checkbox2\" checked> <label for=\"defaultCheckBox\">Default checkbox</label> <br> <button type=\"submit\" class=\"btn btn-success\">Submit</button> </form> </div></body></html>", "e": 31015, "s": 29009, "text": null }, { "code": null, "e": 31025, "s": 31015, "text": "Output: " }, { "code": null, "e": 31394, "s": 31025, "text": "Custom switch: The .custom-control and .custom-switch classes are used to wrap the input checkbox. The .custom-control-input class is used with label tag. Bootstrap switch/toggle is a simple component used for activating one of two predefined options. Commonly used as an on/off button. A toggle button allows the user to change a setting between two states.Example: " }, { "code": null, "e": 31399, "s": 31394, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title> Bootstrap Custom forms </title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head> <body> <div class=\"container\"> <h1 class=\"text-center text-success\">GeeksforGeeks</h1> <h2 class=\"text-center\">Custom Switch Buttons</h2> <form action=\"#\"> <div class=\"custom-control custom-switch\"> <input type=\"checkbox\" class=\"custom-control-input\" id=\"customSwitch\" name=\"switch\" checked> <label class=\"custom-control-label\" for=\"customSwitch\"> Toggle On </label> </div> <br> <div class=\"custom-control custom-switch\"> <input type=\"checkbox\" class=\"custom-control-input\" id=\"customSwitch\" name=\"switch\"> <label class=\"custom-control-label\" for=\"customSwitch\"> Toggle Off </label> </div> <br> <button type=\"submit\" class=\"btn btn-success\">Submit</button> </form> </div></body></html>", "e": 32990, "s": 31399, "text": null }, { "code": null, "e": 33000, "s": 32990, "text": "Output: " }, { "code": null, "e": 33225, "s": 33000, "text": "Custom Radio button: It is same as checkbox. It uses .custom-radio instead of .custom-input on label tag. Checkbox and radio buttond are made to support HTML-based form validation and give a brief, friendly labels.Example: " }, { "code": null, "e": 33230, "s": 33225, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title> Bootstrap Custom forms </title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head> <body> <div class=\"container\"> <h1 class=\"text-center text-success\">GeeksforGeeks</h1> <h2 class=\"text-center\">Custom Radio Buttons</h2> <form action=\"#\"> <div class=\"custom-control custom-radio\"> <input type=\"radio\" class=\"custom-control-input\" id=\"customRadio\" name=\"radioButton\" checked> <label class=\"custom-control-label\" for=\"customRadio\"> Radio Button On </label> </div> <br> <div class=\"custom-control custom-radio\"> <input type=\"radio\" class=\"custom-control-input\" id=\"customRadio\" name=\"radioButton\"> <label class=\"custom-control-label\" for=\"customRadio\"> Radio Button Off </label> </div> <br> <button type=\"submit\" class=\"btn btn-success\">Submit</button> </form> </div></body></html>", "e": 34830, "s": 33230, "text": null }, { "code": null, "e": 34840, "s": 34830, "text": "Output: " }, { "code": null, "e": 35134, "s": 34840, "text": "Custom Inline form control: Custom checkbox and radio buttons are used as a default to use inline control to display them inline by using .custom-control-inline class. The group checkboxes or radio buttons on the same horizontal row by adding .form-check-inline to .form-check class.Example: " }, { "code": null, "e": 35139, "s": 35134, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title> Bootstrap Custom forms </title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head> <body> <div class=\"container\"> <h1 class=\"text-center text-success\">GeeksforGeeks</h1> <h2 class=\"text-center\">Inline Custom Form Controls</h2> <form action=\"#\"> <div class=\"custom-control custom-radio custom-control-inline\"> <input type=\"radio\" class=\"custom-control-input\" id=\"customRadio\" name=\"radioButton\" checked> <label class=\"custom-control-label\" for=\"customRadio\"> Radio Button </label> </div> <div class=\"custom-control custom-radio custom-control-inline\"> <input type=\"radio\" class=\"custom-control-input\" id=\"customRadio\" name=\"radioButton\"> <label class=\"custom-control-label\" for=\"customRadio\"> Radio Button </label> </div> <br><br> <div class=\"custom-control custom-checkbox custom-control-inline\"> <input type=\"checkbox\" class=\"custom-control-input\" id=\"customCheckBox\" name=\"checkbox1\"> <label class=\"custom-control-label\" for=\"customCheckBox\"> Custom checkbox </label> </div> <div class=\"custom-control custom-checkbox custom-control-inline\"> <input type=\"checkbox\" class=\"custom-control-input\" id=\"customCheckBox\" name=\"checkbox1\" checked> <label class=\"custom-control-label\" for=\"customCheckBox\"> Custom checkbox </label> </div> <br><br> <button type=\"submit\" class=\"btn btn-success\">Submit</button> </form> </div></body></html>", "e": 37503, "s": 35139, "text": null }, { "code": null, "e": 37513, "s": 37503, "text": "Output: " }, { "code": null, "e": 37858, "s": 37513, "text": "Custom select menu: It is used to select any particular attribute value and customized according to users need. The .custom-select class is used within <select> element to create custom menu. It uses <select> and <option> tag for customization. Inside option tag, it puts value and show in the dropdown when you will run the program. Example: " }, { "code": null, "e": 37863, "s": 37858, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title> Bootstrap Custom forms </title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head> <body> <div class=\"container\"> <h1 class=\"text-center text-success\">GeeksforGeeks</h1> <h2 class=\"text-center\">Custom Select Menu</h2> <form action=\"#\"> <select name=\"sub\" class=\"custom-select mb-3\"> <option selected>Select Computer science Subject</option> <option value=\"DS\">Data Structure</option> <option value=\"Algo\">Algorithm</option> <option value=\"CN\">Computer Networks</option> <option value=\"OS\">Operating System</option> </select> <button type=\"submit\" class=\"btn btn-success\">Submit</button> </form> </div></body></html>", "e": 39175, "s": 37863, "text": null }, { "code": null, "e": 39185, "s": 39175, "text": "Output: " }, { "code": null, "e": 39337, "s": 39185, "text": "Custom Select Menu Size: The .custom-select-sm class is used to create small and .custom-select-lg class is used to create large select menu.Example: " }, { "code": null, "e": 39342, "s": 39337, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title> Bootstrap Custom forms </title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head> <body> <div class=\"container\"> <h1 class=\"text-center text-success\">GeeksforGeeks</h1> <h2 class=\"text-center\">Custom Select Menu Size</h2> <form action=\"#\"> <select name=\"sub\" class=\"custom-select custom-select-lg mb-3\"> <option selected>Select Computer science Subject</option> <option value=\"DS\">Data Structure</option> <option value=\"Algo\">Algorithm</option> <option value=\"CN\">Computer Networks</option> <option value=\"OS\">Operating System</option> </select> <select name=\"sub\" class=\"custom-select custom-select mb-3\"> <option selected>Select Computer science Subject</option> <option value=\"DS\">Data Structure</option> <option value=\"Algo\">Algorithm</option> <option value=\"CN\">Computer Networks</option> <option value=\"OS\">Operating System</option> </select> <select name=\"sub\" class=\"custom-select custom-select-sm mb-3\"> <option selected>Select Computer science Subject</option> <option value=\"DS\">Data Structure</option> <option value=\"Algo\">Algorithm</option> <option value=\"CN\">Computer Networks</option> <option value=\"OS\">Operating System</option> </select> </form> </div></body></html>", "e": 41423, "s": 39342, "text": null }, { "code": null, "e": 42000, "s": 41423, "text": "Custom File Upload: for make a custom file control, wrap the tag inside div tag that uses .custom-file class .The file uploader component has always been part of the HTML specification since the very early days. Lately, though, it is often hidden behind nicer user interfaces that support the drag-and-drop of files and preview of images. Some basic restyling of the classic input box with a push button that unifies the rendering across all browsers is possible. for label tag it uses .custom-control-label class. for input tag it uses .custom-control-input class .Example: " }, { "code": null, "e": 42005, "s": 42000, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title> Bootstrap Custom forms </title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head> <body> <div class=\"container\"> <h1 class=\"text-center text-success\">GeeksforGeeks</h1> <h2 class=\"text-center\">Custom File Upload</h2> <form action=\"#\"> <p>Custom file upload:</p> <div class=\"custom-file\"> <input type=\"file\" class=\"custom-file-input\" id=\"fileUpload\" name=\"file_name\"> <label class=\"custom-file-label\" for=\"fileUpload\"> Choose file from computer </label> </div> </form> </div> <!-- Script to appear file name in select box --> <script> $(\".custom-file-input\").on(\"change\", function() { var file_name = $(this).val().split(\"\\\\\").pop(); $(this).siblings(\".custom-file-label\") .addClass(\"selected\").html(file_name); });</script> </body></html>", "e": 43514, "s": 42005, "text": null }, { "code": null, "e": 43524, "s": 43514, "text": "Output: " }, { "code": null, "e": 43632, "s": 43524, "text": "Custom Range: The .custom-range class is used within <range> element to create custom_range menu.Example: " }, { "code": null, "e": 43637, "s": 43632, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title> Bootstrap Custom forms </title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head> <body> <div class=\"container\"> <h1 class=\"text-center text-success\">GeeksforGeeks</h1> <h2 class=\"text-center\">Custom Range</h2> <form action=\"#\"> <label for=\"cus_range\">Custom range</label> <input type=\"range\" class=\"custom-range\" id=\"cus_range\" name=\"range\"> </form> </div></body></html>", "e": 44643, "s": 43637, "text": null }, { "code": null, "e": 44662, "s": 44643, "text": "Supported Browser:" }, { "code": null, "e": 44676, "s": 44662, "text": "Google Chrome" }, { "code": null, "e": 44694, "s": 44676, "text": "Internet Explorer" }, { "code": null, "e": 44702, "s": 44694, "text": "Firefox" }, { "code": null, "e": 44708, "s": 44702, "text": "Opera" }, { "code": null, "e": 44715, "s": 44708, "text": "Safari" }, { "code": null, "e": 44727, "s": 44715, "text": "ysachin2314" }, { "code": null, "e": 44737, "s": 44727, "text": "rs1686740" }, { "code": null, "e": 44749, "s": 44737, "text": "Bootstrap-4" }, { "code": null, "e": 44756, "s": 44749, "text": "Picked" }, { "code": null, "e": 44766, "s": 44756, "text": "Bootstrap" }, { "code": null, "e": 44783, "s": 44766, "text": "Web Technologies" }, { "code": null, "e": 44881, "s": 44783, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 44931, "s": 44881, "text": "How to change navigation bar color in Bootstrap ?" }, { "code": null, "e": 44960, "s": 44931, "text": "Form validation using jQuery" }, { "code": null, "e": 45016, "s": 44960, "text": "How to align navbar items to the right in Bootstrap 4 ?" }, { "code": null, "e": 45057, "s": 45016, "text": "How to pass data into a bootstrap modal?" }, { "code": null, "e": 45098, "s": 45057, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 45140, "s": 45098, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 45173, "s": 45140, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 45216, "s": 45173, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 45266, "s": 45216, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
PHP date_add() Function
The date_add() function is an alias of DateTime::add(). It accepts a DateTime object as parameters and a DateInterval object, adds the specified interval to the given DateTime. date_add($object, $interval) object(Optional) This is a DateTime object specifying/representing the date to which you need to add the time interval. interval (Optional) This is a DateInterval object specifying the interval to be added. PHP date_add() function returns a DateTime object with added interval. In case of failure, this function returns the boolean value false. This function was first introduced in PHP Version 5.3.0 and, works with all the later versions. Following example demonstrates the usage of the date_add() function − <?php //Creating a DateTime object $date = date_create("25-09-1989"); //Adding interval to the date $res = date_add($date, new DateInterval('PT10H30S')); //formatting the date to print it $format = date_format( $res, "d-m-Y H:i:s"); print($format); ?> This will produce following result − 25-09-1989 10:00:30 You can create an interval using the date_interval_create_from_date_string() function. Following example creates an interval using this function, adds it to a date − <?php $date = date_create("25-09-1989"); $interval = date_interval_create_from_date_string('1025 days'); $res = date_add($date, $interval); $format = date_format( $res, "d-m-Y H:i:s"); print($format); ?> This will produce following result − 16-07-1992 00:00:00 Now, let us try to add interval with years, months and days − <?php //Creating a DateTime object $date = date_create("25-09-1989"); //Adding interval to the date $res = date_add($date, new DateInterval('P29Y2M5D')); //formatting the date to print it $format = date_format( $res, "d-m-Y"); print($format); ?> This will produce following result − 30-11-2018 <?php $date = date_create('1995-05-07'); $interval = date_interval_create_from_date_string('150 days'); $date->add($interval); print($date -> format('d-m-Y')); ?> This produces the following result − 04-10-1995 45 Lectures 9 hours Malhar Lathkar 34 Lectures 4 hours Syed Raza 84 Lectures 5.5 hours Frahaan Hussain 17 Lectures 1 hours Nivedita Jain 100 Lectures 34 hours Azaz Patel 43 Lectures 5.5 hours Vijay Kumar Parvatha Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 2934, "s": 2757, "text": "The date_add() function is an alias of DateTime::add(). It accepts a DateTime object as parameters and a DateInterval object, adds the specified interval to the given DateTime." }, { "code": null, "e": 2964, "s": 2934, "text": "date_add($object, $interval)\n" }, { "code": null, "e": 2981, "s": 2964, "text": "object(Optional)" }, { "code": null, "e": 3084, "s": 2981, "text": "This is a DateTime object specifying/representing the date to which you need to add the time interval." }, { "code": null, "e": 3104, "s": 3084, "text": "interval (Optional)" }, { "code": null, "e": 3171, "s": 3104, "text": "This is a DateInterval object specifying the interval to be added." }, { "code": null, "e": 3309, "s": 3171, "text": "PHP date_add() function returns a DateTime object with added interval. In case of failure, this function returns the boolean value false." }, { "code": null, "e": 3405, "s": 3309, "text": "This function was first introduced in PHP Version 5.3.0 and, works with all the later versions." }, { "code": null, "e": 3475, "s": 3405, "text": "Following example demonstrates the usage of the date_add() function −" }, { "code": null, "e": 3751, "s": 3475, "text": "<?php\n //Creating a DateTime object\n $date = date_create(\"25-09-1989\");\n //Adding interval to the date\n $res = date_add($date, new DateInterval('PT10H30S')); \n //formatting the date to print it\n $format = date_format( $res, \"d-m-Y H:i:s\");\n print($format);\n?>" }, { "code": null, "e": 3788, "s": 3751, "text": "This will produce following result −" }, { "code": null, "e": 3809, "s": 3788, "text": "25-09-1989 10:00:30\n" }, { "code": null, "e": 3975, "s": 3809, "text": "You can create an interval using the date_interval_create_from_date_string() function. Following example creates an interval using this function, adds it to a date −" }, { "code": null, "e": 4200, "s": 3975, "text": "<?php\n $date = date_create(\"25-09-1989\");\n $interval = date_interval_create_from_date_string('1025 days');\n $res = date_add($date, $interval); \n $format = date_format( $res, \"d-m-Y H:i:s\");\n print($format); \n?>" }, { "code": null, "e": 4237, "s": 4200, "text": "This will produce following result −" }, { "code": null, "e": 4258, "s": 4237, "text": "16-07-1992 00:00:00\n" }, { "code": null, "e": 4320, "s": 4258, "text": "Now, let us try to add interval with years, months and days −" }, { "code": null, "e": 4590, "s": 4320, "text": "<?php\n //Creating a DateTime object\n $date = date_create(\"25-09-1989\");\n //Adding interval to the date\n $res = date_add($date, new DateInterval('P29Y2M5D')); \n //formatting the date to print it\n $format = date_format( $res, \"d-m-Y\");\n print($format);\n?>" }, { "code": null, "e": 4627, "s": 4590, "text": "This will produce following result −" }, { "code": null, "e": 4639, "s": 4627, "text": "30-11-2018\n" }, { "code": null, "e": 4814, "s": 4639, "text": "<?php\n $date = date_create('1995-05-07');\n $interval = date_interval_create_from_date_string('150 days');\n $date->add($interval);\n print($date -> format('d-m-Y'));\n?>" }, { "code": null, "e": 4851, "s": 4814, "text": "This produces the following result −" }, { "code": null, "e": 4863, "s": 4851, "text": "04-10-1995\n" }, { "code": null, "e": 4896, "s": 4863, "text": "\n 45 Lectures \n 9 hours \n" }, { "code": null, "e": 4912, "s": 4896, "text": " Malhar Lathkar" }, { "code": null, "e": 4945, "s": 4912, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 4956, "s": 4945, "text": " Syed Raza" }, { "code": null, "e": 4991, "s": 4956, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5008, "s": 4991, "text": " Frahaan Hussain" }, { "code": null, "e": 5041, "s": 5008, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 5056, "s": 5041, "text": " Nivedita Jain" }, { "code": null, "e": 5091, "s": 5056, "text": "\n 100 Lectures \n 34 hours \n" }, { "code": null, "e": 5103, "s": 5091, "text": " Azaz Patel" }, { "code": null, "e": 5138, "s": 5103, "text": "\n 43 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5166, "s": 5138, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 5173, "s": 5166, "text": " Print" }, { "code": null, "e": 5184, "s": 5173, "text": " Add Notes" } ]
Using Gradient Boosting for Time Series prediction tasks | by Rahul Agarwal | Towards Data Science
Time series prediction problems are pretty frequent in the retail domain. Companies like Walmart and Target need to keep track of how much product should be shipped from Distribution Centres to stores. Even a small improvement in such a demand forecasting system can help save a lot of dollars in term of workforce management, inventory cost and out of stock loss. While there are many techniques to solve this particular problem like ARIMA, Prophet, and LSTMs, we can also treat such a problem as a regression problem too and use trees to solve it. In this post, we will try to solve the time series problem using XGBoost. The main things I am going to focus on are the sort of features such a setup takes and how to create such features. Kaggle master Kazanova along with some of his friends released a “How to win a data science competition” Coursera course. The Course involved a final project which itself was a time series prediction problem. In this competition, we are given a challenging time-series dataset consisting of daily sales data, provided by one of the largest Russian software firms — 1C Company. We have to predict total sales for every product and store in the next month. Here is how the data looks like: We are given the data at a daily level, and we want to build a model which predicts total sales for every product and store in the next month. The variable date_block_num is a consecutive month number, used for convenience. January 2013 is 0, and October 2015 is 33. You can think of it as a proxy to month variable. I think all the other variables are self-explanatory. So how do we approach this sort of a problem? The main thing that I noticed is that the data preparation and feature generation aspect is by far the most important thing when we attempt to solve the time series problem using regression. sales = sales[sales['item_price']<100000]sales = sales[sales['item_cnt_day']<=1000] We start with creating a dataframe of distinct date_block_num, store and item combinations. This is important because in the months we don’t have a data for an item store combination, the machine learning algorithm needs to be told explicitly that the sales are zero. The grid dataFrame contains all the shop, items and month combinations. We then merge the Grid with Sales to get the monthly sales DataFrame. We also replace all the NA’s with zero for months that didn’t have any sales. To create target encodings, we group by a particular column and take the mean/min/sum etc. of the target column on it. These features are the first features we create in our model. Please note that these features may induce a lot of leakage/overfitting in our system and thus we don’t use them directly in our models. We will use the lag based version of these features in our models which we will create next. We group by item_id, shop_id, and item_category_id and aggregate on the item_price and item_cnt_day column to create the following new features: We could also have used featuretools for this. Featuretools is a framework to perform automated feature engineering. It excels at transforming temporal and relational datasets into feature matrices for machine learning. The next set of features our model needs are the lag based Features. When we create regular classification models, we treat training examples as fairly independent of each other. But in case of time series problems, at any point in time, the model needs information on what happened in the past. We can’t do this for all the past days, but we can provide the models with the most recent information nonetheless using our target encoded features. So we aim to add past information for a few features in our data. We do it for all the new features we created and the item_cnt_day feature. We fill the NA’s with zeros once we have the lag features. We end up creating a lot of lag features with different lags: 'item_id_avg_item_price_lag_1','item_id_sum_item_cnt_day_lag_1', 'item_id_avg_item_cnt_day_lag_1','shop_id_avg_item_price_lag_1', 'shop_id_sum_item_cnt_day_lag_1','shop_id_avg_item_cnt_day_lag_1','item_category_id_avg_item_price_lag_1','item_category_id_sum_item_cnt_day_lag_1','item_category_id_avg_item_cnt_day_lag_1', 'item_cnt_day_lag_1','item_id_avg_item_price_lag_2', 'item_id_sum_item_cnt_day_lag_2','item_id_avg_item_cnt_day_lag_2', 'shop_id_avg_item_price_lag_2','shop_id_sum_item_cnt_day_lag_2', 'shop_id_avg_item_cnt_day_lag_2','item_category_id_avg_item_price_lag_2','item_category_id_sum_item_cnt_day_lag_2','item_category_id_avg_item_cnt_day_lag_2', 'item_cnt_day_lag_2',... As previously said, we are going to drop the target encoded features as they might induce a lot of overfitting in the model. We also lose the item_name and item_price feature. When we created the lag variables, we induced a lot of zeroes in the system. We used the maximum lag as 12. To counter that we remove the first 12 months indexes. sales_means = sales_means[sales_means['date_block_num']>11] When we do a time series split, we usually don’t take a cross-sectional split as the data is time-dependent. We want to create a model that sees till now and can predict the next month well. X_train = sales_means[sales_means['date_block_num']<33]X_cv = sales_means[sales_means['date_block_num']==33]Y_train = X_train['item_cnt_day']Y_cv = X_cv['item_cnt_day']del X_train['item_cnt_day']del X_cv['item_cnt_day'] Before we proceed with modelling steps, lets check the RMSE of a naive model, as we want to have an RMSE to compare to. We assume that we are going to predict the last month sales as current month sale for our baseline model. We can quantify the performance of our model using this baseline RMSE. 1.1358170090812756 We use the XGBRegressor object from the xgboost scikit API to build our model. Parameters are taken from this kaggle kernel. If you have time, you can use hyperopt to automatically find out the hyperparameters yourself. from xgboost import XGBRegressormodel = XGBRegressor( max_depth=8, n_estimators=1000, min_child_weight=300, colsample_bytree=0.8, subsample=0.8, eta=0.3, seed=42)model.fit( X_train, Y_train, eval_metric="rmse", eval_set=[(X_train, Y_train), (X_cv, Y_cv)], verbose=True, early_stopping_rounds = 10) After running this, we can see RMSE in ranges of 0.93 on the CV set. And that is pretty impressive based on our baseline validation RMSE of 1.13. And so we work on deploying this model as part of our continuous integration effort. We can also see the important features that come from XGB. In this post, we talked about how we can use trees for even time series modelling. The purpose was not to get perfect scores on the kaggle leaderboard but to gain an understanding of how such models work. When I took part in this competition as part of the course, a couple of years back, using trees I reached near the top of the leaderboard. Over time people have worked a lot on tweaking the model, hyperparameter tuning and creating even more informative features. But the basic approach has remained the same. You can find the whole running code on GitHub. Take a look at the Advanced Machine Learning on Google Cloud Specialization. This course talks about deploy and productionizing your models. Definitely recommended. I am going to be writing more beginner-friendly posts in the future too. Let me know what you think about the series. Follow me up at Medium or Subscribe to my blog to be informed about them. As always, I welcome feedback and constructive criticism and can be reached on Twitter @mlwhiz. Also, a small disclaimer — There might be some affiliate links in this post to relevant resources, as sharing knowledge is never a bad idea.
[ { "code": null, "e": 246, "s": 172, "text": "Time series prediction problems are pretty frequent in the retail domain." }, { "code": null, "e": 537, "s": 246, "text": "Companies like Walmart and Target need to keep track of how much product should be shipped from Distribution Centres to stores. Even a small improvement in such a demand forecasting system can help save a lot of dollars in term of workforce management, inventory cost and out of stock loss." }, { "code": null, "e": 722, "s": 537, "text": "While there are many techniques to solve this particular problem like ARIMA, Prophet, and LSTMs, we can also treat such a problem as a regression problem too and use trees to solve it." }, { "code": null, "e": 796, "s": 722, "text": "In this post, we will try to solve the time series problem using XGBoost." }, { "code": null, "e": 912, "s": 796, "text": "The main things I am going to focus on are the sort of features such a setup takes and how to create such features." }, { "code": null, "e": 1121, "s": 912, "text": "Kaggle master Kazanova along with some of his friends released a “How to win a data science competition” Coursera course. The Course involved a final project which itself was a time series prediction problem." }, { "code": null, "e": 1289, "s": 1121, "text": "In this competition, we are given a challenging time-series dataset consisting of daily sales data, provided by one of the largest Russian software firms — 1C Company." }, { "code": null, "e": 1367, "s": 1289, "text": "We have to predict total sales for every product and store in the next month." }, { "code": null, "e": 1400, "s": 1367, "text": "Here is how the data looks like:" }, { "code": null, "e": 1543, "s": 1400, "text": "We are given the data at a daily level, and we want to build a model which predicts total sales for every product and store in the next month." }, { "code": null, "e": 1771, "s": 1543, "text": "The variable date_block_num is a consecutive month number, used for convenience. January 2013 is 0, and October 2015 is 33. You can think of it as a proxy to month variable. I think all the other variables are self-explanatory." }, { "code": null, "e": 1817, "s": 1771, "text": "So how do we approach this sort of a problem?" }, { "code": null, "e": 2008, "s": 1817, "text": "The main thing that I noticed is that the data preparation and feature generation aspect is by far the most important thing when we attempt to solve the time series problem using regression." }, { "code": null, "e": 2092, "s": 2008, "text": "sales = sales[sales['item_price']<100000]sales = sales[sales['item_cnt_day']<=1000]" }, { "code": null, "e": 2184, "s": 2092, "text": "We start with creating a dataframe of distinct date_block_num, store and item combinations." }, { "code": null, "e": 2360, "s": 2184, "text": "This is important because in the months we don’t have a data for an item store combination, the machine learning algorithm needs to be told explicitly that the sales are zero." }, { "code": null, "e": 2432, "s": 2360, "text": "The grid dataFrame contains all the shop, items and month combinations." }, { "code": null, "e": 2580, "s": 2432, "text": "We then merge the Grid with Sales to get the monthly sales DataFrame. We also replace all the NA’s with zero for months that didn’t have any sales." }, { "code": null, "e": 2761, "s": 2580, "text": "To create target encodings, we group by a particular column and take the mean/min/sum etc. of the target column on it. These features are the first features we create in our model." }, { "code": null, "e": 2991, "s": 2761, "text": "Please note that these features may induce a lot of leakage/overfitting in our system and thus we don’t use them directly in our models. We will use the lag based version of these features in our models which we will create next." }, { "code": null, "e": 3136, "s": 2991, "text": "We group by item_id, shop_id, and item_category_id and aggregate on the item_price and item_cnt_day column to create the following new features:" }, { "code": null, "e": 3356, "s": 3136, "text": "We could also have used featuretools for this. Featuretools is a framework to perform automated feature engineering. It excels at transforming temporal and relational datasets into feature matrices for machine learning." }, { "code": null, "e": 3425, "s": 3356, "text": "The next set of features our model needs are the lag based Features." }, { "code": null, "e": 3652, "s": 3425, "text": "When we create regular classification models, we treat training examples as fairly independent of each other. But in case of time series problems, at any point in time, the model needs information on what happened in the past." }, { "code": null, "e": 3802, "s": 3652, "text": "We can’t do this for all the past days, but we can provide the models with the most recent information nonetheless using our target encoded features." }, { "code": null, "e": 3943, "s": 3802, "text": "So we aim to add past information for a few features in our data. We do it for all the new features we created and the item_cnt_day feature." }, { "code": null, "e": 4002, "s": 3943, "text": "We fill the NA’s with zeros once we have the lag features." }, { "code": null, "e": 4064, "s": 4002, "text": "We end up creating a lot of lag features with different lags:" }, { "code": null, "e": 4753, "s": 4064, "text": "'item_id_avg_item_price_lag_1','item_id_sum_item_cnt_day_lag_1', 'item_id_avg_item_cnt_day_lag_1','shop_id_avg_item_price_lag_1', 'shop_id_sum_item_cnt_day_lag_1','shop_id_avg_item_cnt_day_lag_1','item_category_id_avg_item_price_lag_1','item_category_id_sum_item_cnt_day_lag_1','item_category_id_avg_item_cnt_day_lag_1', 'item_cnt_day_lag_1','item_id_avg_item_price_lag_2', 'item_id_sum_item_cnt_day_lag_2','item_id_avg_item_cnt_day_lag_2', 'shop_id_avg_item_price_lag_2','shop_id_sum_item_cnt_day_lag_2', 'shop_id_avg_item_cnt_day_lag_2','item_category_id_avg_item_price_lag_2','item_category_id_sum_item_cnt_day_lag_2','item_category_id_avg_item_cnt_day_lag_2', 'item_cnt_day_lag_2',..." }, { "code": null, "e": 4929, "s": 4753, "text": "As previously said, we are going to drop the target encoded features as they might induce a lot of overfitting in the model. We also lose the item_name and item_price feature." }, { "code": null, "e": 5092, "s": 4929, "text": "When we created the lag variables, we induced a lot of zeroes in the system. We used the maximum lag as 12. To counter that we remove the first 12 months indexes." }, { "code": null, "e": 5152, "s": 5092, "text": "sales_means = sales_means[sales_means['date_block_num']>11]" }, { "code": null, "e": 5343, "s": 5152, "text": "When we do a time series split, we usually don’t take a cross-sectional split as the data is time-dependent. We want to create a model that sees till now and can predict the next month well." }, { "code": null, "e": 5564, "s": 5343, "text": "X_train = sales_means[sales_means['date_block_num']<33]X_cv = sales_means[sales_means['date_block_num']==33]Y_train = X_train['item_cnt_day']Y_cv = X_cv['item_cnt_day']del X_train['item_cnt_day']del X_cv['item_cnt_day']" }, { "code": null, "e": 5861, "s": 5564, "text": "Before we proceed with modelling steps, lets check the RMSE of a naive model, as we want to have an RMSE to compare to. We assume that we are going to predict the last month sales as current month sale for our baseline model. We can quantify the performance of our model using this baseline RMSE." }, { "code": null, "e": 5880, "s": 5861, "text": "1.1358170090812756" }, { "code": null, "e": 6100, "s": 5880, "text": "We use the XGBRegressor object from the xgboost scikit API to build our model. Parameters are taken from this kaggle kernel. If you have time, you can use hyperopt to automatically find out the hyperparameters yourself." }, { "code": null, "e": 6449, "s": 6100, "text": "from xgboost import XGBRegressormodel = XGBRegressor( max_depth=8, n_estimators=1000, min_child_weight=300, colsample_bytree=0.8, subsample=0.8, eta=0.3, seed=42)model.fit( X_train, Y_train, eval_metric=\"rmse\", eval_set=[(X_train, Y_train), (X_cv, Y_cv)], verbose=True, early_stopping_rounds = 10)" }, { "code": null, "e": 6680, "s": 6449, "text": "After running this, we can see RMSE in ranges of 0.93 on the CV set. And that is pretty impressive based on our baseline validation RMSE of 1.13. And so we work on deploying this model as part of our continuous integration effort." }, { "code": null, "e": 6739, "s": 6680, "text": "We can also see the important features that come from XGB." }, { "code": null, "e": 6944, "s": 6739, "text": "In this post, we talked about how we can use trees for even time series modelling. The purpose was not to get perfect scores on the kaggle leaderboard but to gain an understanding of how such models work." }, { "code": null, "e": 7083, "s": 6944, "text": "When I took part in this competition as part of the course, a couple of years back, using trees I reached near the top of the leaderboard." }, { "code": null, "e": 7254, "s": 7083, "text": "Over time people have worked a lot on tweaking the model, hyperparameter tuning and creating even more informative features. But the basic approach has remained the same." }, { "code": null, "e": 7301, "s": 7254, "text": "You can find the whole running code on GitHub." }, { "code": null, "e": 7466, "s": 7301, "text": "Take a look at the Advanced Machine Learning on Google Cloud Specialization. This course talks about deploy and productionizing your models. Definitely recommended." }, { "code": null, "e": 7754, "s": 7466, "text": "I am going to be writing more beginner-friendly posts in the future too. Let me know what you think about the series. Follow me up at Medium or Subscribe to my blog to be informed about them. As always, I welcome feedback and constructive criticism and can be reached on Twitter @mlwhiz." } ]
p5.js | jump() Function - GeeksforGeeks
01 Sep, 2021 The jump() function is an inbuilt function in the p5.js library. This function is used to jump at some specific point of playing audio, just required the time position of that audio. which is playing that time on the web. Syntax: jump( cueTime, duration ) Note: All the sound-related functions only work when the sound library is included in the head section of the index.html file. Parameter: This function accepts two parameter as mentioned above and described below. cueTime: This parameter holds an integer number as seconds that define the cue time in seconds. duration: This parameter holds an integer number that defines the duration of playback in seconds. Below examples illustrates the p5.js jump() function in JavaScript: Example 1: In this example the song will jump at second 7 position of the song. Javascript var sound; function preload() { // Initialize sound sound = loadSound("pfivesound.mp3");} function setup() { // Playing the preloaded sound sound.play(); //sound will jump at that point sound.jump( 7 ); } Example 2: In this example, the song will jump at middle position of the song if you press the button. Javascript var sound;var jmp; function preload() { // Initialize sound sound = loadSound("song.mp3");} function setup() { // Playing the preloaded sound sound.play(); //Creating button jmp = createButton("Jump"); jmp.mousePressed(jumpAudio);} function jumpAudio() { //sound will jump at that point var len = sound.duration(); sound.jump( len/2);} Note: May after crossing the middle position if you press the button again another time song will be played from middle position. Online editor: https://editor.p5js.org/ Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/ Supported Browsers: The browsers supported by p5.js jump() function are listed below: Google Chrome Internet Explorer Firefox Safari Opera adnanirshad158 JavaScript-p5.js 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 How to create a link in JavaScript ? How to Show Images on Click using HTML ? How to remove an HTML element using JavaScript ? Remove elements from a JavaScript Array Express.js express.Router() Function How to set input type date in dd-mm-yyyy format using HTML ? Installation of Node.js on Linux How to create footer to stay at the bottom of a Web page? How to float three div side by side using CSS?
[ { "code": null, "e": 24991, "s": 24963, "text": "\n01 Sep, 2021" }, { "code": null, "e": 25214, "s": 24991, "text": "The jump() function is an inbuilt function in the p5.js library. This function is used to jump at some specific point of playing audio, just required the time position of that audio. which is playing that time on the web. " }, { "code": null, "e": 25223, "s": 25214, "text": "Syntax: " }, { "code": null, "e": 25249, "s": 25223, "text": "jump( cueTime, duration )" }, { "code": null, "e": 25376, "s": 25249, "text": "Note: All the sound-related functions only work when the sound library is included in the head section of the index.html file." }, { "code": null, "e": 25465, "s": 25376, "text": "Parameter: This function accepts two parameter as mentioned above and described below. " }, { "code": null, "e": 25561, "s": 25465, "text": "cueTime: This parameter holds an integer number as seconds that define the cue time in seconds." }, { "code": null, "e": 25660, "s": 25561, "text": "duration: This parameter holds an integer number that defines the duration of playback in seconds." }, { "code": null, "e": 25729, "s": 25660, "text": "Below examples illustrates the p5.js jump() function in JavaScript: " }, { "code": null, "e": 25811, "s": 25729, "text": "Example 1: In this example the song will jump at second 7 position of the song. " }, { "code": null, "e": 25822, "s": 25811, "text": "Javascript" }, { "code": "var sound; function preload() { // Initialize sound sound = loadSound(\"pfivesound.mp3\");} function setup() { // Playing the preloaded sound sound.play(); //sound will jump at that point sound.jump( 7 ); }", "e": 26060, "s": 25822, "text": null }, { "code": null, "e": 26164, "s": 26060, "text": "Example 2: In this example, the song will jump at middle position of the song if you press the button. " }, { "code": null, "e": 26175, "s": 26164, "text": "Javascript" }, { "code": "var sound;var jmp; function preload() { // Initialize sound sound = loadSound(\"song.mp3\");} function setup() { // Playing the preloaded sound sound.play(); //Creating button jmp = createButton(\"Jump\"); jmp.mousePressed(jumpAudio);} function jumpAudio() { //sound will jump at that point var len = sound.duration(); sound.jump( len/2);}", "e": 26562, "s": 26175, "text": null }, { "code": null, "e": 26692, "s": 26562, "text": "Note: May after crossing the middle position if you press the button again another time song will be played from middle position." }, { "code": null, "e": 26830, "s": 26692, "text": "Online editor: https://editor.p5js.org/ Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/" }, { "code": null, "e": 26917, "s": 26830, "text": "Supported Browsers: The browsers supported by p5.js jump() function are listed below: " }, { "code": null, "e": 26931, "s": 26917, "text": "Google Chrome" }, { "code": null, "e": 26949, "s": 26931, "text": "Internet Explorer" }, { "code": null, "e": 26957, "s": 26949, "text": "Firefox" }, { "code": null, "e": 26964, "s": 26957, "text": "Safari" }, { "code": null, "e": 26970, "s": 26964, "text": "Opera" }, { "code": null, "e": 26987, "s": 26972, "text": "adnanirshad158" }, { "code": null, "e": 27004, "s": 26987, "text": "JavaScript-p5.js" }, { "code": null, "e": 27015, "s": 27004, "text": "JavaScript" }, { "code": null, "e": 27032, "s": 27015, "text": "Web Technologies" }, { "code": null, "e": 27130, "s": 27032, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27139, "s": 27130, "text": "Comments" }, { "code": null, "e": 27152, "s": 27139, "text": "Old Comments" }, { "code": null, "e": 27213, "s": 27152, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27250, "s": 27213, "text": "How to create a link in JavaScript ?" }, { "code": null, "e": 27291, "s": 27250, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 27340, "s": 27291, "text": "How to remove an HTML element using JavaScript ?" }, { "code": null, "e": 27380, "s": 27340, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27417, "s": 27380, "text": "Express.js express.Router() Function" }, { "code": null, "e": 27478, "s": 27417, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 27511, "s": 27478, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27569, "s": 27511, "text": "How to create footer to stay at the bottom of a Web page?" } ]
Median in a stream of integers (running integers) in C++
Given that integers are read from a data stream. Find median of elements read so for in an efficient way After reading 1st element of stream - 10 -> median - 10 After reading 2nd element of stream - 10, 20 -> median - 15 After reading 3rd element of stream - 10, 20, 30 -> median - 20, so on... 1. Use a max heap on left side to represent elements that are less than effective median, and a min heap on right side to represent elements that are greater than effective median 2. After processing an incoming element, the number of elements in heaps differ utmost by 1 element 3. When both heaps contain same number of elements, we pick average of heaps root data as effective median 4. When the heaps are not balanced, we select effective median from the root of heap containing more elements #include <iostream> using namespace std; #define MAX_HEAP_SIZE (128) #define ARRAY_SIZE(a) sizeof(a)/sizeof(a[0]) inline void Exch(int &a, int &b){ int aux = a; a = b; b = aux; } bool Greater(int a, int b){ return a > b; } bool Smaller(int a, int b){ return a < b; } int Average(int a, int b){ return (a + b) / 2; } int Signum(int a, int b){ if( a == b ) { return 0; } return a < b ? -1 : 1; } class Heap{ public: Heap(int *b, bool (*c)(int, int)) : A(b), comp(c){ heapSize = -1; } virtual ~Heap(){ if( A ) { delete[] A; } } virtual bool Insert(int e) = 0; virtual int GetTop() = 0; virtual int ExtractTop() = 0; virtual int GetCount() = 0; protected: int left(int i){ return 2 * i + 1; } int right(int i){ return 2 * (i + 1); } int parent(int i){ if( i <= 0 ) { return -1; } return (i - 1)/2; } int *A; bool (*comp)(int, int); int heapSize; int top(void){ int max = -1; if( heapSize >= 0 ) { max = A[0]; } return max; } int count(){ return heapSize + 1; } void heapify(int i){ int p = parent(i); if( p >= 0 && comp(A[i], A[p]) ) { Exch(A[i], A[p]); heapify(p); } } int deleteTop(){ int del = -1; if( heapSize > -1) { del = A[0]; Exch(A[0], A[heapSize]); heapSize--; heapify(parent(heapSize+1)); } return del; } bool insertHelper(int key){ bool ret = false; if( heapSize < MAX_HEAP_SIZE ) { ret = true; heapSize++; A[heapSize] = key; heapify(heapSize); } return ret; } }; class MaxHeap : public Heap{ private: public: MaxHeap() : Heap(new int[MAX_HEAP_SIZE], &Greater) { } ~MaxHeap() { } int GetTop(){ return top(); } int ExtractTop(){ return deleteTop(); } int GetCount(){ return count(); } bool Insert(int key){ return insertHelper(key); } }; class MinHeap : public Heap{ private: public: MinHeap() : Heap(new int[MAX_HEAP_SIZE], &Smaller) { } ~MinHeap() { } int GetTop(){ return top(); } int ExtractTop(){ return deleteTop(); } int GetCount(){ return count(); } bool Insert(int key){ return insertHelper(key); } }; int getMedian(int e, int &m, Heap &l, Heap &r){ int sig = Signum(l.GetCount(), r.GetCount()); switch(sig){ case 1: if( e < m ) { r.Insert(l.ExtractTop()); l.Insert(e); } else { r.Insert(e); } m = Average(l.GetTop(), r.GetTop()); break; case 0: if( e < m ) { l.Insert(e); m = l.GetTop(); } else { r.Insert(e); m = r.GetTop(); } break; case -1: if( e < m ) { l.Insert(e); } else { l.Insert(r.ExtractTop()); r.Insert(e); } m = Average(l.GetTop(), r.GetTop()); break; } return m; } void printMedian(int A[], int size){ int m = 0; Heap *left = new MaxHeap(); Heap *right = new MinHeap(); for(int i = 0; i < size; ++i) { m = getMedian(A[i], m, *left, *right); cout << m << endl; } delete left; delete right; } // Driver code int main(){ int A[] = {10, 20, 30}; int size = ARRAY_SIZE(A); cout "Result:\n"; printMedian(A, size); return 0; } When you compile and execute the above program. It generates the following output − Result: 10 15 20
[ { "code": null, "e": 1167, "s": 1062, "text": "Given that integers are read from a data stream. Find median of elements read so for in an efficient way" }, { "code": null, "e": 1223, "s": 1167, "text": "After reading 1st element of stream - 10 -> median - 10" }, { "code": null, "e": 1283, "s": 1223, "text": "After reading 2nd element of stream - 10, 20 -> median - 15" }, { "code": null, "e": 1357, "s": 1283, "text": "After reading 3rd element of stream - 10, 20, 30 -> median - 20, so on..." }, { "code": null, "e": 1857, "s": 1357, "text": "1. Use a max heap on left side to represent elements that are less than effective median,\n and a min heap on right side to represent elements that are greater than effective median\n2. After processing an incoming element, the number of elements in heaps differ utmost by 1 element\n3. When both heaps contain same number of elements, we pick average of heaps root data as effective median\n4. When the heaps are not balanced, we select effective median from the root of heap containing more elements" }, { "code": null, "e": 5626, "s": 1857, "text": "#include <iostream>\nusing namespace std;\n#define MAX_HEAP_SIZE (128)\n#define ARRAY_SIZE(a) sizeof(a)/sizeof(a[0])\ninline void Exch(int &a, int &b){\n int aux = a;\n a = b;\n b = aux;\n}\nbool Greater(int a, int b){\n return a > b;\n}\nbool Smaller(int a, int b){\n return a < b;\n}\nint Average(int a, int b){\n return (a + b) / 2;\n}\nint Signum(int a, int b){\n if( a == b ) {\n return 0;\n }\n return a < b ? -1 : 1;\n}\nclass Heap{\n public:\n Heap(int *b, bool (*c)(int, int)) : A(b), comp(c){\n heapSize = -1;\n }\n virtual ~Heap(){\n if( A ) {\n delete[] A;\n }\n }\n virtual bool Insert(int e) = 0;\n virtual int GetTop() = 0;\n virtual int ExtractTop() = 0;\n virtual int GetCount() = 0;\n protected:\n int left(int i){\n return 2 * i + 1;\n }\n int right(int i){\n return 2 * (i + 1);\n }\n int parent(int i){\n if( i <= 0 ) {\n return -1;\n }\n return (i - 1)/2;\n }\n int *A;\n bool (*comp)(int, int);\n int heapSize;\n int top(void){\n int max = -1;\n if( heapSize >= 0 ) {\n max = A[0];\n }\n return max;\n }\n int count(){\n return heapSize + 1;\n }\n void heapify(int i){\n int p = parent(i);\n if( p >= 0 && comp(A[i], A[p]) ) {\n Exch(A[i], A[p]);\n heapify(p);\n }\n }\n int deleteTop(){\n int del = -1;\n if( heapSize > -1) {\n del = A[0];\n Exch(A[0], A[heapSize]);\n heapSize--;\n heapify(parent(heapSize+1));\n }\n return del;\n }\n bool insertHelper(int key){\n bool ret = false;\n if( heapSize < MAX_HEAP_SIZE ) {\n ret = true;\n heapSize++;\n A[heapSize] = key;\n heapify(heapSize);\n }\n return ret;\n }\n};\nclass MaxHeap : public Heap{\nprivate:\npublic:\n MaxHeap() : Heap(new int[MAX_HEAP_SIZE], &Greater) { }\n ~MaxHeap() { }\n int GetTop(){\n return top();\n }\n int ExtractTop(){\n return deleteTop();\n }\n int GetCount(){\n return count();\n }\n bool Insert(int key){\n return insertHelper(key);\n }\n};\nclass MinHeap : public Heap{\nprivate:\npublic:\n MinHeap() : Heap(new int[MAX_HEAP_SIZE], &Smaller) { }\n ~MinHeap() { }\n int GetTop(){\n return top();\n }\n int ExtractTop(){\n return deleteTop();\n }\n int GetCount(){\n return count();\n }\n bool Insert(int key){\n return insertHelper(key);\n }\n};\nint getMedian(int e, int &m, Heap &l, Heap &r){\n int sig = Signum(l.GetCount(), r.GetCount());\n switch(sig){\n case 1:\n if( e < m ) {\n r.Insert(l.ExtractTop());\n l.Insert(e);\n } else {\n r.Insert(e);\n }\n m = Average(l.GetTop(), r.GetTop());\n break;\n case 0:\n if( e < m ) {\n l.Insert(e);\n m = l.GetTop();\n } else {\n r.Insert(e);\n m = r.GetTop();\n }\n break;\n case -1:\n if( e < m ) {\n l.Insert(e);\n } else { \n l.Insert(r.ExtractTop());\n r.Insert(e);\n }\n m = Average(l.GetTop(), r.GetTop());\n break;\n }\n return m;\n}\nvoid printMedian(int A[], int size){\n int m = 0;\n Heap *left = new MaxHeap();\n Heap *right = new MinHeap();\n for(int i = 0; i < size; ++i) {\n m = getMedian(A[i], m, *left, *right);\n cout << m << endl;\n }\n delete left;\n delete right;\n}\n// Driver code\nint main(){\n int A[] = {10, 20, 30};\n int size = ARRAY_SIZE(A);\n cout \"Result:\\n\";\n printMedian(A, size);\n return 0;\n}" }, { "code": null, "e": 5710, "s": 5626, "text": "When you compile and execute the above program. It generates the following output −" }, { "code": null, "e": 5727, "s": 5710, "text": "Result:\n10\n15\n20" } ]
Create pong game using Python – Turtle
11 Jun, 2021 Pong is one of the most famous arcade games, simulating table tennis. Each player controls a paddle in the game by dragging it vertically across the screen’s left or right side. Players use their paddles to strike back and forth on the ball. Turtle is an inbuilt graphic module in Python. It uses a panel and pen to depict illustrations. Below are the steps used: Step 1) Create two paddles A and B on the left and right side of the screen. Step 2) Create a ball. Step 3) Create an event to move the paddle vertically on pressing a certain key. Step 4) Create the function to update the score after each player misses a collision. Below is the program to create Paddle and Ball: Python3 # Import required libraryimport turtle # Create screensc = turtle.Screen()sc.title("Pong game")sc.bgcolor("white")sc.setup(width=1000, height=600) # Left paddleleft_pad = turtle.Turtle()left_pad.speed(0)left_pad.shape("square")left_pad.color("black")left_pad.shapesize(stretch_wid=6, stretch_len=2)left_pad.penup()left_pad.goto(-400, 0) # Right paddleright_pad = turtle.Turtle()right_pad.speed(0)right_pad.shape("square")right_pad.color("black")right_pad.shapesize(stretch_wid=6, stretch_len=2)right_pad.penup()right_pad.goto(400, 0) # Ball of circle shapehit_ball = turtle.Turtle()hit_ball.speed(40)hit_ball.shape("circle")hit_ball.color("blue")hit_ball.penup()hit_ball.goto(0, 0)hit_ball.dx = 5hit_ball.dy = -5 Output: Below is the complete python program to create pong game using turtle library. Python # Import required libraryimport turtle # Create screensc = turtle.Screen()sc.title("Pong game")sc.bgcolor("white")sc.setup(width=1000, height=600) # Left paddleleft_pad = turtle.Turtle()left_pad.speed(0)left_pad.shape("square")left_pad.color("black")left_pad.shapesize(stretch_wid=6, stretch_len=2)left_pad.penup()left_pad.goto(-400, 0) # Right paddleright_pad = turtle.Turtle()right_pad.speed(0)right_pad.shape("square")right_pad.color("black")right_pad.shapesize(stretch_wid=6, stretch_len=2)right_pad.penup()right_pad.goto(400, 0) # Ball of circle shapehit_ball = turtle.Turtle()hit_ball.speed(40)hit_ball.shape("circle")hit_ball.color("blue")hit_ball.penup()hit_ball.goto(0, 0)hit_ball.dx = 5hit_ball.dy = -5 # Initialize the scoreleft_player = 0right_player = 0 # Displays the scoresketch = turtle.Turtle()sketch.speed(0)sketch.color("blue")sketch.penup()sketch.hideturtle()sketch.goto(0, 260)sketch.write("Left_player : 0 Right_player: 0", align="center", font=("Courier", 24, "normal")) # Functions to move paddle verticallydef paddleaup(): y = left_pad.ycor() y += 20 left_pad.sety(y) def paddleadown(): y = left_pad.ycor() y -= 20 left_pad.sety(y) def paddlebup(): y = right_pad.ycor() y += 20 right_pad.sety(y) def paddlebdown(): y = right_pad.ycor() y -= 20 right_pad.sety(y) # Keyboard bindingssc.listen()sc.onkeypress(paddleaup, "e")sc.onkeypress(paddleadown, "x")sc.onkeypress(paddlebup, "Up")sc.onkeypress(paddlebdown, "Down") while True: sc.update() hit_ball.setx(hit_ball.xcor()+hit_ball.dx) hit_ball.sety(hit_ball.ycor()+hit_ball.dy) # Checking borders if hit_ball.ycor() > 280: hit_ball.sety(280) hit_ball.dy *= -1 if hit_ball.ycor() < -280: hit_ball.sety(-280) hit_ball.dy *= -1 if hit_ball.xcor() > 500: hit_ball.goto(0, 0) hit_ball.dy *= -1 left_player += 1 sketch.clear() sketch.write("Left_player : {} Right_player: {}".format( left_player, right_player), align="center", font=("Courier", 24, "normal")) if hit_ball.xcor() < -500: hit_ball.goto(0, 0) hit_ball.dy *= -1 right_player += 1 sketch.clear() sketch.write("Left_player : {} Right_player: {}".format( left_player, right_player), align="center", font=("Courier", 24, "normal")) # Paddle ball collision if (hit_ball.xcor() > 360 and hit_ball.xcor() < 370) and (hit_ball.ycor() < right_pad.ycor()+40 and hit_ball.ycor() > right_pad.ycor()-40): hit_ball.setx(360) hit_ball.dx*=-1 if (hit_ball.xcor()<-360 and hit_ball.xcor()>-370) and (hit_ball.ycor()<left_pad.ycor()+40 and hit_ball.ycor()>left_pad.ycor()-40): hit_ball.setx(-360) hit_ball.dx*=-1 Output: varshagumber28 Python-projects Python-turtle Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 54, "s": 26, "text": "\n11 Jun, 2021" }, { "code": null, "e": 296, "s": 54, "text": "Pong is one of the most famous arcade games, simulating table tennis. Each player controls a paddle in the game by dragging it vertically across the screen’s left or right side. Players use their paddles to strike back and forth on the ball." }, { "code": null, "e": 393, "s": 296, "text": "Turtle is an inbuilt graphic module in Python. It uses a panel and pen to depict illustrations. " }, { "code": null, "e": 419, "s": 393, "text": "Below are the steps used:" }, { "code": null, "e": 496, "s": 419, "text": "Step 1) Create two paddles A and B on the left and right side of the screen." }, { "code": null, "e": 519, "s": 496, "text": "Step 2) Create a ball." }, { "code": null, "e": 600, "s": 519, "text": "Step 3) Create an event to move the paddle vertically on pressing a certain key." }, { "code": null, "e": 686, "s": 600, "text": "Step 4) Create the function to update the score after each player misses a collision." }, { "code": null, "e": 734, "s": 686, "text": "Below is the program to create Paddle and Ball:" }, { "code": null, "e": 742, "s": 734, "text": "Python3" }, { "code": "# Import required libraryimport turtle # Create screensc = turtle.Screen()sc.title(\"Pong game\")sc.bgcolor(\"white\")sc.setup(width=1000, height=600) # Left paddleleft_pad = turtle.Turtle()left_pad.speed(0)left_pad.shape(\"square\")left_pad.color(\"black\")left_pad.shapesize(stretch_wid=6, stretch_len=2)left_pad.penup()left_pad.goto(-400, 0) # Right paddleright_pad = turtle.Turtle()right_pad.speed(0)right_pad.shape(\"square\")right_pad.color(\"black\")right_pad.shapesize(stretch_wid=6, stretch_len=2)right_pad.penup()right_pad.goto(400, 0) # Ball of circle shapehit_ball = turtle.Turtle()hit_ball.speed(40)hit_ball.shape(\"circle\")hit_ball.color(\"blue\")hit_ball.penup()hit_ball.goto(0, 0)hit_ball.dx = 5hit_ball.dy = -5", "e": 1458, "s": 742, "text": null }, { "code": null, "e": 1466, "s": 1458, "text": "Output:" }, { "code": null, "e": 1545, "s": 1466, "text": "Below is the complete python program to create pong game using turtle library." }, { "code": null, "e": 1552, "s": 1545, "text": "Python" }, { "code": "# Import required libraryimport turtle # Create screensc = turtle.Screen()sc.title(\"Pong game\")sc.bgcolor(\"white\")sc.setup(width=1000, height=600) # Left paddleleft_pad = turtle.Turtle()left_pad.speed(0)left_pad.shape(\"square\")left_pad.color(\"black\")left_pad.shapesize(stretch_wid=6, stretch_len=2)left_pad.penup()left_pad.goto(-400, 0) # Right paddleright_pad = turtle.Turtle()right_pad.speed(0)right_pad.shape(\"square\")right_pad.color(\"black\")right_pad.shapesize(stretch_wid=6, stretch_len=2)right_pad.penup()right_pad.goto(400, 0) # Ball of circle shapehit_ball = turtle.Turtle()hit_ball.speed(40)hit_ball.shape(\"circle\")hit_ball.color(\"blue\")hit_ball.penup()hit_ball.goto(0, 0)hit_ball.dx = 5hit_ball.dy = -5 # Initialize the scoreleft_player = 0right_player = 0 # Displays the scoresketch = turtle.Turtle()sketch.speed(0)sketch.color(\"blue\")sketch.penup()sketch.hideturtle()sketch.goto(0, 260)sketch.write(\"Left_player : 0 Right_player: 0\", align=\"center\", font=(\"Courier\", 24, \"normal\")) # Functions to move paddle verticallydef paddleaup(): y = left_pad.ycor() y += 20 left_pad.sety(y) def paddleadown(): y = left_pad.ycor() y -= 20 left_pad.sety(y) def paddlebup(): y = right_pad.ycor() y += 20 right_pad.sety(y) def paddlebdown(): y = right_pad.ycor() y -= 20 right_pad.sety(y) # Keyboard bindingssc.listen()sc.onkeypress(paddleaup, \"e\")sc.onkeypress(paddleadown, \"x\")sc.onkeypress(paddlebup, \"Up\")sc.onkeypress(paddlebdown, \"Down\") while True: sc.update() hit_ball.setx(hit_ball.xcor()+hit_ball.dx) hit_ball.sety(hit_ball.ycor()+hit_ball.dy) # Checking borders if hit_ball.ycor() > 280: hit_ball.sety(280) hit_ball.dy *= -1 if hit_ball.ycor() < -280: hit_ball.sety(-280) hit_ball.dy *= -1 if hit_ball.xcor() > 500: hit_ball.goto(0, 0) hit_ball.dy *= -1 left_player += 1 sketch.clear() sketch.write(\"Left_player : {} Right_player: {}\".format( left_player, right_player), align=\"center\", font=(\"Courier\", 24, \"normal\")) if hit_ball.xcor() < -500: hit_ball.goto(0, 0) hit_ball.dy *= -1 right_player += 1 sketch.clear() sketch.write(\"Left_player : {} Right_player: {}\".format( left_player, right_player), align=\"center\", font=(\"Courier\", 24, \"normal\")) # Paddle ball collision if (hit_ball.xcor() > 360 and hit_ball.xcor() < 370) and (hit_ball.ycor() < right_pad.ycor()+40 and hit_ball.ycor() > right_pad.ycor()-40): hit_ball.setx(360) hit_ball.dx*=-1 if (hit_ball.xcor()<-360 and hit_ball.xcor()>-370) and (hit_ball.ycor()<left_pad.ycor()+40 and hit_ball.ycor()>left_pad.ycor()-40): hit_ball.setx(-360) hit_ball.dx*=-1", "e": 4562, "s": 1552, "text": null }, { "code": null, "e": 4570, "s": 4562, "text": "Output:" }, { "code": null, "e": 4585, "s": 4570, "text": "varshagumber28" }, { "code": null, "e": 4601, "s": 4585, "text": "Python-projects" }, { "code": null, "e": 4615, "s": 4601, "text": "Python-turtle" }, { "code": null, "e": 4622, "s": 4615, "text": "Python" }, { "code": null, "e": 4720, "s": 4622, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4738, "s": 4720, "text": "Python Dictionary" }, { "code": null, "e": 4780, "s": 4738, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 4802, "s": 4780, "text": "Enumerate() in Python" }, { "code": null, "e": 4837, "s": 4802, "text": "Read a file line by line in Python" }, { "code": null, "e": 4863, "s": 4837, "text": "Python String | replace()" }, { "code": null, "e": 4895, "s": 4863, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4924, "s": 4895, "text": "*args and **kwargs in Python" }, { "code": null, "e": 4951, "s": 4924, "text": "Python Classes and Objects" }, { "code": null, "e": 4981, "s": 4951, "text": "Iterate over a list in Python" } ]
JavaScript escape() Function
22 Nov, 2021 Below is the example of the escape() function. Example:<script> // Special character encoded with // escape function document.write(escape("Geeks for Geeks!!!")); document.write("<br>"); // Print encoded string using escape() function // Also include exceptions i.e. @ and . document.write(escape("To contribute articles contact"+ " us at review-team@geeksforgeeks.org"));</script> <script> // Special character encoded with // escape function document.write(escape("Geeks for Geeks!!!")); document.write("<br>"); // Print encoded string using escape() function // Also include exceptions i.e. @ and . document.write(escape("To contribute articles contact"+ " us at review-team@geeksforgeeks.org"));</script> Output:Geeks%20for%20Geeks%21%21%21 To%20contribute%20articles%20contact%20us%20atcontribute @geeksforgeeks.org Geeks%20for%20Geeks%21%21%21 To%20contribute%20articles%20contact%20us%20atcontribute @geeksforgeeks.org The escape() function takes a string as a parameter and encodes it so that it can be transmitted to any computer in any network which supports ASCII characters. Syntax: escape(string) Parameters: This function accepts a single parameter as mentioned above and described below: string: This parameters holds the string that will be encoded. Return value: This function returns a encoded string. Note: This function only encodes the special characters, this function is depricated.Exceptions: @ – + . / * _ More example codes for the above function are as follows: Program 1: <script> // Special character encoded with // escape function document.write(escape("Geeks for Geeks!!!")); document.write("<br>"); // Print encoded string using escape() function // Also include exceptions i.e. @ and . document.write(escape("A Computer Science Portal"));</script> Output: Geeks%20for%20Geeks%21%21%21 A%20Computer%20Science%20Portal Program 2: <script> // Special character encoded with // escape function document.write(escape("GeeksforGeeks")); document.write("<br>"); // Print encoded string using escape() function // Also include exceptions i.e. @ and . document.write(escape("A#Computer-Science"+ "%Portal@for*Geeks"));</script> Output: GeeksforGeeks A%23Computer-Science%25Portal@for*Geeks Supported Browsers: Google Chrome 1 and above Internet Explorer 3 and above Edge 12 and above Mozilla Firefox 1 and above Safari 1 and above Opera 3 and above javascript-functions JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Nov, 2021" }, { "code": null, "e": 75, "s": 28, "text": "Below is the example of the escape() function." }, { "code": null, "e": 467, "s": 75, "text": "Example:<script> // Special character encoded with // escape function document.write(escape(\"Geeks for Geeks!!!\")); document.write(\"<br>\"); // Print encoded string using escape() function // Also include exceptions i.e. @ and . document.write(escape(\"To contribute articles contact\"+ \" us at review-team@geeksforgeeks.org\"));</script> " }, { "code": "<script> // Special character encoded with // escape function document.write(escape(\"Geeks for Geeks!!!\")); document.write(\"<br>\"); // Print encoded string using escape() function // Also include exceptions i.e. @ and . document.write(escape(\"To contribute articles contact\"+ \" us at review-team@geeksforgeeks.org\"));</script> ", "e": 851, "s": 467, "text": null }, { "code": null, "e": 964, "s": 851, "text": "Output:Geeks%20for%20Geeks%21%21%21\nTo%20contribute%20articles%20contact%20us%20atcontribute\n@geeksforgeeks.org " }, { "code": null, "e": 1070, "s": 964, "text": "Geeks%20for%20Geeks%21%21%21\nTo%20contribute%20articles%20contact%20us%20atcontribute\n@geeksforgeeks.org " }, { "code": null, "e": 1231, "s": 1070, "text": "The escape() function takes a string as a parameter and encodes it so that it can be transmitted to any computer in any network which supports ASCII characters." }, { "code": null, "e": 1239, "s": 1231, "text": "Syntax:" }, { "code": null, "e": 1254, "s": 1239, "text": "escape(string)" }, { "code": null, "e": 1347, "s": 1254, "text": "Parameters: This function accepts a single parameter as mentioned above and described below:" }, { "code": null, "e": 1410, "s": 1347, "text": "string: This parameters holds the string that will be encoded." }, { "code": null, "e": 1464, "s": 1410, "text": "Return value: This function returns a encoded string." }, { "code": null, "e": 1575, "s": 1464, "text": "Note: This function only encodes the special characters, this function is depricated.Exceptions: @ – + . / * _" }, { "code": null, "e": 1633, "s": 1575, "text": "More example codes for the above function are as follows:" }, { "code": null, "e": 1644, "s": 1633, "text": "Program 1:" }, { "code": "<script> // Special character encoded with // escape function document.write(escape(\"Geeks for Geeks!!!\")); document.write(\"<br>\"); // Print encoded string using escape() function // Also include exceptions i.e. @ and . document.write(escape(\"A Computer Science Portal\"));</script> ", "e": 1964, "s": 1644, "text": null }, { "code": null, "e": 1972, "s": 1964, "text": "Output:" }, { "code": null, "e": 2033, "s": 1972, "text": "Geeks%20for%20Geeks%21%21%21\nA%20Computer%20Science%20Portal" }, { "code": null, "e": 2044, "s": 2033, "text": "Program 2:" }, { "code": "<script> // Special character encoded with // escape function document.write(escape(\"GeeksforGeeks\")); document.write(\"<br>\"); // Print encoded string using escape() function // Also include exceptions i.e. @ and . document.write(escape(\"A#Computer-Science\"+ \"%Portal@for*Geeks\"));</script> ", "e": 2403, "s": 2044, "text": null }, { "code": null, "e": 2411, "s": 2403, "text": "Output:" }, { "code": null, "e": 2465, "s": 2411, "text": "GeeksforGeeks\nA%23Computer-Science%25Portal@for*Geeks" }, { "code": null, "e": 2485, "s": 2465, "text": "Supported Browsers:" }, { "code": null, "e": 2511, "s": 2485, "text": "Google Chrome 1 and above" }, { "code": null, "e": 2541, "s": 2511, "text": "Internet Explorer 3 and above" }, { "code": null, "e": 2559, "s": 2541, "text": "Edge 12 and above" }, { "code": null, "e": 2587, "s": 2559, "text": "Mozilla Firefox 1 and above" }, { "code": null, "e": 2606, "s": 2587, "text": "Safari 1 and above" }, { "code": null, "e": 2624, "s": 2606, "text": "Opera 3 and above" }, { "code": null, "e": 2645, "s": 2624, "text": "javascript-functions" }, { "code": null, "e": 2656, "s": 2645, "text": "JavaScript" }, { "code": null, "e": 2673, "s": 2656, "text": "Web Technologies" } ]
Natural Language Processing – Overview
18 Jul, 2021 Natural language processing (NLP) is a subfield of Artificial Intelligence (AI). This is a widely used technology for personal assistants that are used in various business fields/areas. This technology works on the speech provided by the user, breaks it down for proper understanding and processes accordingly. This is a very recent and effective approach due to which it has a really high demand in today’s market. Natural Language Processing is an upcoming field where already many transitions such as compatibility with smart devices, interactive talks with a human have been made possible. Knowledge representation, logical reasoning, and constraint satisfaction were the emphasis of AI applications in NLP. Here first it was applied to semantics and later to the grammar. In the last decade, a significant change in NLP research has resulted in the widespread use of statistical approaches such as machine learning and data mining on a massive scale. The need for automation is never ending courtesy of the amount of work required to be done these days. NLP is a very favourable, but aspect when it comes to automated applications. The applications of NLP have led it to be one of the most sought-after methods of implementing machine learning. Natural Language Processing (NLP) is a field that combines computer science, linguistics, and machine learning to study how computers and humans communicate in natural language. The goal of NLP is for computers to be able to interpret and generate human language. This not only improves the efficiency of work done by humans but also helps in interacting with the machine. NLP bridges the gap of interaction between humans and electronic devices. The field is divided into three different parts: Speech Recognition — The translation of spoken language into text.Natural Language Understanding (NLU) — The computer’s ability to understand what we say.Natural Language Generation (NLG) — The generation of natural language by a computer. Speech Recognition — The translation of spoken language into text. Natural Language Understanding (NLU) — The computer’s ability to understand what we say. Natural Language Generation (NLG) — The generation of natural language by a computer. NLU and NLG are the key aspects depicting the working of NLP devices. These 2 aspects are very different from each other and are achieved using different methods. First, the computer must take natural language and convert it into artificial language. This is what speech recognition, or speech-to-text, does. This is the first step of NLU. Hidden Markov Models (HMMs) are used in the majority of voice recognition systems nowadays. These are statistical models that use mathematical calculations to determine what you said in order to convert your speech to text. HMMs do this by listening to you talk, breaking it down into small units (typically 10-20 milliseconds), and comparing it to pre-recorded speech to figure out which phoneme you uttered in each unit (a phoneme is the smallest unit of speech).The program then examines the sequence of phonemes and uses statistical analysis to determine the most likely words and sentences you were speaking. The next and hardest step of NLP, is the understanding part. First, the computer must comprehend the meaning of each word. It tries to figure out whether the word is a noun or a verb, whether it’s in the past or present tense, and so on. This is called Part-of-Speech tagging (POS). A lexicon (a vocabulary) and a set of grammatical rules are also built into NLP systems. The most difficult part of NLP is understanding. The machine should be able to grasp what you said by the conclusion of the process. There are several challenges in accomplishing this when considering problems such as words having several meanings (polysemy) or different words having similar meanings (synonymy), but developers encode rules into their NLU systems and train them to learn to apply the rules correctly. NLG is much simpler to accomplish. NLG converts a computer’s artificial language into text and can also convert that text into audible speech using text-to-speech technology. First, the NLP system identifies what data should be converted to text. If you asked the computer a question about the weather, it most likely did an online search to find your answer, and from there it decides that the temperature, wind, and humidity are the factors that should be read aloud to you. Then, it organizes the structure of how it’s going to say it. This is similar to NLU except backwards. NLG system can construct full sentences using a lexicon and a set of grammar rules. Finally, text-to-speech takes over. The text-to-speech engine uses a prosody model to evaluate the text and identify breaks, duration, and pitch. The engine then combines all the recorded phonemes into one cohesive string of speech using a speech database. Machine Translation: NLP is used for language translation from one language to another through a computer. Chatterbots: NLP is used for chatter bots that communicate with other chat bots or humans through auditory or textual methods. AI Software: NLP is used in question-answering software for knowledge representation, analytical reasoning as well as information retrieval. Spam Filters: One of the most irritating things about email is spam. Gmail uses natural language processing (NLP) to discern which emails are legitimate and which are spam. These spam filters look at the text in all the emails you receive and try to figure out what it means to see if it’s spam or not. Algorithmic Trading: Algorithmic trading is used for predicting stock market conditions. Using NLP, this technology examines news headlines about companies and stocks and attempts to comprehend their meaning in order to determine if you should buy, sell, or hold certain stocks. Answering Questions: NLP can be seen in action by using Google Search or Siri Services. A major use of NLP is to make search engines understand the meaning of what we are asking and generating natural language in return to give us the answers. Summarizing Information: On the internet, there is a lot of information, and a lot of it comes in the form of long documents or articles. NLP is used to decipher the meaning of the data and then provides shorter summaries of the data so that humans can comprehend it more quickly. Bots: Chatbots assist clients get to the point quickly by answering inquiries and referring them to relevant resources and products at any time of day or night. To be effective, chatbots must be fast, smart and easy to use, To accomplish this, chatbots employ NLP to understand language, usually over text or voice-recognition interactions Supporting Invisible UI: Almost every connection we have with machines involves human communication, both spoken and written. Amazon’s Echo is only one illustration of the trend toward putting humans in closer contact with technology in the future. The concept of an invisible or zero user interface will rely on direct communication between the user and the machine, whether by voice, text, or a combination of the two. NLP helps to make this concept a real-world thing. Smarter Search: NLP’s future also includes improved search, something we’ve been discussing at Expert System for a long time. Smarter search allows a chatbot to understand a customer’s request can enable “search like you talk” functionality (much like you could query Siri) rather than focusing on keywords or topics. Google recently announced that NLP capabilities have been added to Google Drive, allowing users to search for documents and content using natural language. Companies like Google are experimenting with Deep Neural Networks (DNNs) to push the limits of NLP and make it possible for human-to-machine interactions to feel just like human-to-human interactions. Basic words can be further subdivided into proper semantics and used in NLP algorithms. The NLP algorithms can be used in various languages that are currently unavailable such as regional languages or languages is spoken in rural areas etc. Translation of a sentence in one language to the same sentence in another Language at a broader scope. Natural-language-processing Machine Learning Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Monte Carlo Tree Search (MCTS) Introduction to Recurrent Neural Network Markov Decision Process Support Vector Machine Algorithm DBSCAN Clustering in ML | Density based clustering Normalization vs Standardization Types of Environments in AI Bagging vs Boosting in Machine Learning Principal Component Analysis with Python Difference between Informed and Uninformed Search in AI
[ { "code": null, "e": 52, "s": 24, "text": "\n18 Jul, 2021" }, { "code": null, "e": 1749, "s": 52, "text": "Natural language processing (NLP) is a subfield of Artificial Intelligence (AI). This is a widely used technology for personal assistants that are used in various business fields/areas. This technology works on the speech provided by the user, breaks it down for proper understanding and processes accordingly. This is a very recent and effective approach due to which it has a really high demand in today’s market. Natural Language Processing is an upcoming field where already many transitions such as compatibility with smart devices, interactive talks with a human have been made possible. Knowledge representation, logical reasoning, and constraint satisfaction were the emphasis of AI applications in NLP. Here first it was applied to semantics and later to the grammar. In the last decade, a significant change in NLP research has resulted in the widespread use of statistical approaches such as machine learning and data mining on a massive scale. The need for automation is never ending courtesy of the amount of work required to be done these days. NLP is a very favourable, but aspect when it comes to automated applications. The applications of NLP have led it to be one of the most sought-after methods of implementing machine learning. Natural Language Processing (NLP) is a field that combines computer science, linguistics, and machine learning to study how computers and humans communicate in natural language. The goal of NLP is for computers to be able to interpret and generate human language. This not only improves the efficiency of work done by humans but also helps in interacting with the machine. NLP bridges the gap of interaction between humans and electronic devices." }, { "code": null, "e": 1799, "s": 1749, "text": "The field is divided into three different parts:" }, { "code": null, "e": 2041, "s": 1799, "text": "Speech Recognition — The translation of spoken language into text.Natural Language Understanding (NLU) — The computer’s ability to understand what we say.Natural Language Generation (NLG) — The generation of natural language by a computer." }, { "code": null, "e": 2108, "s": 2041, "text": "Speech Recognition — The translation of spoken language into text." }, { "code": null, "e": 2198, "s": 2108, "text": "Natural Language Understanding (NLU) — The computer’s ability to understand what we say." }, { "code": null, "e": 2285, "s": 2198, "text": "Natural Language Generation (NLG) — The generation of natural language by a computer." }, { "code": null, "e": 2448, "s": 2285, "text": "NLU and NLG are the key aspects depicting the working of NLP devices. These 2 aspects are very different from each other and are achieved using different methods." }, { "code": null, "e": 2625, "s": 2448, "text": "First, the computer must take natural language and convert it into artificial language. This is what speech recognition, or speech-to-text, does. This is the first step of NLU." }, { "code": null, "e": 2849, "s": 2625, "text": "Hidden Markov Models (HMMs) are used in the majority of voice recognition systems nowadays. These are statistical models that use mathematical calculations to determine what you said in order to convert your speech to text." }, { "code": null, "e": 3239, "s": 2849, "text": "HMMs do this by listening to you talk, breaking it down into small units (typically 10-20 milliseconds), and comparing it to pre-recorded speech to figure out which phoneme you uttered in each unit (a phoneme is the smallest unit of speech).The program then examines the sequence of phonemes and uses statistical analysis to determine the most likely words and sentences you were speaking." }, { "code": null, "e": 3300, "s": 3239, "text": "The next and hardest step of NLP, is the understanding part." }, { "code": null, "e": 3522, "s": 3300, "text": "First, the computer must comprehend the meaning of each word. It tries to figure out whether the word is a noun or a verb, whether it’s in the past or present tense, and so on. This is called Part-of-Speech tagging (POS)." }, { "code": null, "e": 3660, "s": 3522, "text": "A lexicon (a vocabulary) and a set of grammatical rules are also built into NLP systems. The most difficult part of NLP is understanding." }, { "code": null, "e": 4030, "s": 3660, "text": "The machine should be able to grasp what you said by the conclusion of the process. There are several challenges in accomplishing this when considering problems such as words having several meanings (polysemy) or different words having similar meanings (synonymy), but developers encode rules into their NLU systems and train them to learn to apply the rules correctly." }, { "code": null, "e": 4205, "s": 4030, "text": "NLG is much simpler to accomplish. NLG converts a computer’s artificial language into text and can also convert that text into audible speech using text-to-speech technology." }, { "code": null, "e": 4507, "s": 4205, "text": "First, the NLP system identifies what data should be converted to text. If you asked the computer a question about the weather, it most likely did an online search to find your answer, and from there it decides that the temperature, wind, and humidity are the factors that should be read aloud to you." }, { "code": null, "e": 4694, "s": 4507, "text": "Then, it organizes the structure of how it’s going to say it. This is similar to NLU except backwards. NLG system can construct full sentences using a lexicon and a set of grammar rules." }, { "code": null, "e": 4951, "s": 4694, "text": "Finally, text-to-speech takes over. The text-to-speech engine uses a prosody model to evaluate the text and identify breaks, duration, and pitch. The engine then combines all the recorded phonemes into one cohesive string of speech using a speech database." }, { "code": null, "e": 5058, "s": 4951, "text": "Machine Translation: NLP is used for language translation from one language to another through a computer." }, { "code": null, "e": 5185, "s": 5058, "text": "Chatterbots: NLP is used for chatter bots that communicate with other chat bots or humans through auditory or textual methods." }, { "code": null, "e": 5326, "s": 5185, "text": "AI Software: NLP is used in question-answering software for knowledge representation, analytical reasoning as well as information retrieval." }, { "code": null, "e": 5629, "s": 5326, "text": "Spam Filters: One of the most irritating things about email is spam. Gmail uses natural language processing (NLP) to discern which emails are legitimate and which are spam. These spam filters look at the text in all the emails you receive and try to figure out what it means to see if it’s spam or not." }, { "code": null, "e": 5908, "s": 5629, "text": "Algorithmic Trading: Algorithmic trading is used for predicting stock market conditions. Using NLP, this technology examines news headlines about companies and stocks and attempts to comprehend their meaning in order to determine if you should buy, sell, or hold certain stocks." }, { "code": null, "e": 6153, "s": 5908, "text": " Answering Questions: NLP can be seen in action by using Google Search or Siri Services. A major use of NLP is to make search engines understand the meaning of what we are asking and generating natural language in return to give us the answers." }, { "code": null, "e": 6434, "s": 6153, "text": "Summarizing Information: On the internet, there is a lot of information, and a lot of it comes in the form of long documents or articles. NLP is used to decipher the meaning of the data and then provides shorter summaries of the data so that humans can comprehend it more quickly." }, { "code": null, "e": 6774, "s": 6434, "text": "Bots: Chatbots assist clients get to the point quickly by answering inquiries and referring them to relevant resources and products at any time of day or night. To be effective, chatbots must be fast, smart and easy to use, To accomplish this, chatbots employ NLP to understand language, usually over text or voice-recognition interactions" }, { "code": null, "e": 7246, "s": 6774, "text": "Supporting Invisible UI: Almost every connection we have with machines involves human communication, both spoken and written. Amazon’s Echo is only one illustration of the trend toward putting humans in closer contact with technology in the future. The concept of an invisible or zero user interface will rely on direct communication between the user and the machine, whether by voice, text, or a combination of the two. NLP helps to make this concept a real-world thing." }, { "code": null, "e": 7720, "s": 7246, "text": "Smarter Search: NLP’s future also includes improved search, something we’ve been discussing at Expert System for a long time. Smarter search allows a chatbot to understand a customer’s request can enable “search like you talk” functionality (much like you could query Siri) rather than focusing on keywords or topics. Google recently announced that NLP capabilities have been added to Google Drive, allowing users to search for documents and content using natural language." }, { "code": null, "e": 7921, "s": 7720, "text": "Companies like Google are experimenting with Deep Neural Networks (DNNs) to push the limits of NLP and make it possible for human-to-machine interactions to feel just like human-to-human interactions." }, { "code": null, "e": 8009, "s": 7921, "text": "Basic words can be further subdivided into proper semantics and used in NLP algorithms." }, { "code": null, "e": 8162, "s": 8009, "text": "The NLP algorithms can be used in various languages that are currently unavailable such as regional languages or languages is spoken in rural areas etc." }, { "code": null, "e": 8265, "s": 8162, "text": "Translation of a sentence in one language to the same sentence in another Language at a broader scope." }, { "code": null, "e": 8293, "s": 8265, "text": "Natural-language-processing" }, { "code": null, "e": 8310, "s": 8293, "text": "Machine Learning" }, { "code": null, "e": 8327, "s": 8310, "text": "Machine Learning" }, { "code": null, "e": 8425, "s": 8327, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8461, "s": 8425, "text": "ML | Monte Carlo Tree Search (MCTS)" }, { "code": null, "e": 8502, "s": 8461, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 8526, "s": 8502, "text": "Markov Decision Process" }, { "code": null, "e": 8559, "s": 8526, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 8610, "s": 8559, "text": "DBSCAN Clustering in ML | Density based clustering" }, { "code": null, "e": 8643, "s": 8610, "text": "Normalization vs Standardization" }, { "code": null, "e": 8671, "s": 8643, "text": "Types of Environments in AI" }, { "code": null, "e": 8711, "s": 8671, "text": "Bagging vs Boosting in Machine Learning" }, { "code": null, "e": 8752, "s": 8711, "text": "Principal Component Analysis with Python" } ]
Python program to get Current Time
26 Mar, 2020 In this article, we will know the approaches to get the current time in Python. There are multiple ways to get it. The most preferably date-time module is used in Python to create the object containing date and time.1: Current time of a timezone – Using pytZ module from datetime import *import pytz tz_INDIA = pytz.timezone('Asia/Kolkata') datetime_INDIA = datetime.now(tz_INDIA)print("INDIA time:", datetime_INDIA.strftime("%H:%M:%S")) Output: INDIA time: 19:29:53 2 : Current time – Using date time object Example 1: from datetime import datetime # now() method is used to# get object containing # current date & time.now_method = datetime.now() # strftime() method used to# create a string representing# the current time.currentTime = now_method.strftime("%H:%M:%S")print("Current Time =", currentTime) Output: Current Time = 19:31:51 Example 2: from datetime import datetime # Time object containing # the current time.time = datetime.now().time() print("Current Time =", time) Output: Current Time = 19:33:29.087840 3. Getting Time – using Time module. import time # localtime() method used to# get the object containing# the local time.Time = time.localtime() # strftime() method used to# create a string representing# the current time.currentTime = time.strftime("%H:%M:%S", Time)print(currentTime) Output: 19:35:17 Python datetime-program Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary
[ { "code": null, "e": 52, "s": 24, "text": "\n26 Mar, 2020" }, { "code": null, "e": 318, "s": 52, "text": "In this article, we will know the approaches to get the current time in Python. There are multiple ways to get it. The most preferably date-time module is used in Python to create the object containing date and time.1: Current time of a timezone – Using pytZ module" }, { "code": "from datetime import *import pytz tz_INDIA = pytz.timezone('Asia/Kolkata') datetime_INDIA = datetime.now(tz_INDIA)print(\"INDIA time:\", datetime_INDIA.strftime(\"%H:%M:%S\"))", "e": 493, "s": 318, "text": null }, { "code": null, "e": 501, "s": 493, "text": "Output:" }, { "code": null, "e": 522, "s": 501, "text": "INDIA time: 19:29:53" }, { "code": null, "e": 564, "s": 522, "text": "2 : Current time – Using date time object" }, { "code": null, "e": 575, "s": 564, "text": "Example 1:" }, { "code": "from datetime import datetime # now() method is used to# get object containing # current date & time.now_method = datetime.now() # strftime() method used to# create a string representing# the current time.currentTime = now_method.strftime(\"%H:%M:%S\")print(\"Current Time =\", currentTime)", "e": 864, "s": 575, "text": null }, { "code": null, "e": 872, "s": 864, "text": "Output:" }, { "code": null, "e": 897, "s": 872, "text": "Current Time = 19:31:51\n" }, { "code": null, "e": 908, "s": 897, "text": "Example 2:" }, { "code": "from datetime import datetime # Time object containing # the current time.time = datetime.now().time() print(\"Current Time =\", time)", "e": 1044, "s": 908, "text": null }, { "code": null, "e": 1052, "s": 1044, "text": "Output:" }, { "code": null, "e": 1083, "s": 1052, "text": "Current Time = 19:33:29.087840" }, { "code": null, "e": 1120, "s": 1083, "text": "3. Getting Time – using Time module." }, { "code": "import time # localtime() method used to# get the object containing# the local time.Time = time.localtime() # strftime() method used to# create a string representing# the current time.currentTime = time.strftime(\"%H:%M:%S\", Time)print(currentTime)", "e": 1372, "s": 1120, "text": null }, { "code": null, "e": 1380, "s": 1372, "text": "Output:" }, { "code": null, "e": 1389, "s": 1380, "text": "19:35:17" }, { "code": null, "e": 1413, "s": 1389, "text": "Python datetime-program" }, { "code": null, "e": 1420, "s": 1413, "text": "Python" }, { "code": null, "e": 1436, "s": 1420, "text": "Python Programs" }, { "code": null, "e": 1534, "s": 1436, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1552, "s": 1534, "text": "Python Dictionary" }, { "code": null, "e": 1594, "s": 1552, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1616, "s": 1594, "text": "Enumerate() in Python" }, { "code": null, "e": 1651, "s": 1616, "text": "Read a file line by line in Python" }, { "code": null, "e": 1677, "s": 1651, "text": "Python String | replace()" }, { "code": null, "e": 1720, "s": 1677, "text": "Python program to convert a list to string" }, { "code": null, "e": 1742, "s": 1720, "text": "Defaultdict in Python" }, { "code": null, "e": 1781, "s": 1742, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 1819, "s": 1781, "text": "Python | Convert a list to dictionary" } ]
Find the Largest number with given number of digits and sum of digits
23 Jun, 2022 How to find the largest number with given digit sum s and number of digits d?Examples: Input : s = 9, d = 2 Output : 90 Input : s = 20, d = 3 Output : 992 A Simple Solution is to consider all m digit numbers and keep track of maximum number with digit sum as s. A close upper bound on time complexity of this solution is O(10m).There is a Greedy approach to solve the problem. The idea is to one by one fill all digits from leftmost to rightmost (or from most significant digit to least significant). We compare the remaining sum with 9 if the remaining sum is more than 9, we put 9 at the current position, else we put the remaining sum. Since we fill digits from left to right, we put the highest digits on the left side, hence get the largest number. Below image is an illustration of the above approach: Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ program to find the largest number that can be// formed from given sum of digits and number of digits.#include <iostream>using namespace std; // Prints the smallest possible number with digit sum 's'// and 'm' number of digits.void findLargest(int m, int s){ // If sum of digits is 0, then a number is possible // only if number of digits is 1. if (s == 0) { (m == 1)? cout << "Largest number is " << 0 : cout << "Not possible"; return ; } // Sum greater than the maximum possible sum. if (s > 9*m) { cout << "Not possible"; return ; } // Create an array to store digits of result int res[m]; // Fill from most significant digit to least // significant digit. for (int i=0; i<m; i++) { // Fill 9 first to make the number largest if (s >= 9) { res[i] = 9; s -= 9; } // If remaining sum becomes less than 9, then // fill the remaining sum else { res[i] = s; s = 0; } } cout << "Largest number is "; for (int i=0; i<m; i++) cout << res[i];} // Driver codeint main(){ int s = 9, m = 2; findLargest(m, s); return 0;} // Java program to find the largest number that can be// formed from given sum of digits and number of digits class GFG{ // Function to print the largest possible number with digit sum 's' // and 'm' number of digits static void findLargest(int m, int s) { // If sum of digits is 0, then a number is possible // only if number of digits is 1 if (s == 0) { System.out.print(m == 1 ? "Largest number is 0" : "Not possible"); return ; } // Sum greater than the maximum possible sum if (s > 9*m) { System.out.println("Not possible"); return ; } // Create an array to store digits of result int[] res = new int[m]; // Fill from most significant digit to least // significant digit for (int i=0; i<m; i++) { // Fill 9 first to make the number largest if (s >= 9) { res[i] = 9; s -= 9; } // If remaining sum becomes less than 9, then // fill the remaining sum else { res[i] = s; s = 0; } } System.out.print("Largest number is "); for (int i=0; i<m; i++) System.out.print(res[i]); } // driver program public static void main (String[] args) { int s = 9, m = 2; findLargest(m, s); }} // Contributed by Pramod Kumar # Python 3 program to find# the largest number that# can be formed from given# sum of digits and number# of digits. # Prints the smallest# possible number with digit# sum 's' and 'm' number of# digits.def findLargest( m, s) : # If sum of digits is 0, # then a number is possible # only if number of digits # is 1. if (s == 0) : if(m == 1) : print("Largest number is " , "0",end = "") else : print("Not possible",end = "") return # Sum greater than the # maximum possible sum. if (s > 9 * m) : print("Not possible",end = "") return # Create an array to # store digits of # result res = [0] * m # Fill from most significant # digit to least significant # digit. for i in range(0, m) : # Fill 9 first to make # the number largest if (s >= 9) : res[i] = 9 s = s - 9 # If remaining sum # becomes less than # 9, then fill the # remaining sum else : res[i] = s s = 0 print( "Largest number is ",end = "") for i in range(0, m) : print(res[i],end = "") # Driver codes = 9m = 2findLargest(m, s) # This code is contributed by Nikita Tiwari. // C# program to find the// largest number that can// be formed from given sum// of digits and number of digitsusing System; class GFG{ // Function to print the // largest possible number // with digit sum 's' and // 'm' number of digits static void findLargest(int m, int s) { // If sum of digits is 0, // then a number is possible // only if number of digits is 1 if (s == 0) { Console.Write(m == 1 ? "Largest number is 0" : "Not possible"); return ; } // Sum greater than the // maximum possible sum if (s > 9 * m) { Console.WriteLine("Not possible"); return ; } // Create an array to // store digits of result int []res = new int[m]; // Fill from most significant // digit to least significant digit for (int i = 0; i < m; i++) { // Fill 9 first to make // the number largest if (s >= 9) { res[i] = 9; s -= 9; } // If remaining sum becomes // less than 9, then // fill the remaining sum else { res[i] = s; s = 0; } } Console.Write("Largest number is "); for (int i = 0; i < m; i++) Console.Write(res[i]); } // Driver Code static public void Main () { int s = 9, m = 2; findLargest(m, s); }} // This code is Contributed by ajit <?php// PHP program to find the largest// number that can be formed from// given sum of digits and number// of digits. // Prints the smallest possible// number with digit sum 's'// and 'm' number of digits.function findLargest($m, $s){ // If sum of digits is 0, then // a number is possible only if // number of digits is 1. if ($s == 0) { if(($m == 1) == true) echo "Largest number is " , 0; else echo "Not possible"; return ; } // Sum greater than the // maximum possible sum. if ($s > 9 * $m) { echo "Not possible"; return ; } // Create an array to store // digits of result Fill from // most significant digit to // least significant digit. for ($i = 0; $i < $m; $i++) { // Fill 9 first to make // the number largest if ($s >= 9) { $res[$i] = 9; $s -= 9; } // If remaining sum becomes // less than 9, then fill // the remaining sum else { $res[$i] = $s; $s = 0; } } echo "Largest number is "; for ($i = 0; $i < $m; $i++) echo $res[$i];} // Driver code$s = 9; $m = 2;findLargest($m, $s); // This code is contributed by m_kit?> <script>// Javascript program to find the largest number that can be// formed from given sum of digits and number of digits. // Prints the smallest possible number with digit sum 's'// and 'm' number of digits.function findLargest(m, s){ // If sum of digits is 0, then a number is possible // only if number of digits is 1. if (s == 0) { (m == 1)? document.write("Largest number is " + 0) : document.write("Not possible"); return ; } // Sum greater than the maximum possible sum. if (s > 9*m) { document.write("Not possible"); return ; } // Create an array to store digits of result let res = new Array(m); // Fill from most significant digit to least // significant digit. for (let i=0; i<m; i++) { // Fill 9 first to make the number largest if (s >= 9) { res[i] = 9; s -= 9; } // If remaining sum becomes less than 9, then // fill the remaining sum else { res[i] = s; s = 0; } } document.write("Largest number is "); for (let i=0; i<m; i++) document.write(res[i]);} // Driver code let s = 9, m = 2; findLargest(m, s); // This code is contributed by Mayank Tyagi </script> Output : Largest number is 90 Time Complexity of this solution is O(m). Auxiliary Space : O(m), where m is the given integer. This article is contributed by Vaibhav Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above jit_t mayanktyagi1709 AshokJaiswal simmytarika5 tamanna17122007 number-digits Greedy Mathematical Greedy Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Huffman Coding | Greedy Algo-3 Activity Selection Problem | Greedy Algo-1 Fractional Knapsack Problem Job Sequencing Problem Policemen catch thieves Set in C++ Standard Template Library (STL) C++ Data Types Merge two sorted arrays Operators in C / C++ Sieve of Eratosthenes
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Jun, 2022" }, { "code": null, "e": 141, "s": 52, "text": "How to find the largest number with given digit sum s and number of digits d?Examples: " }, { "code": null, "e": 212, "s": 141, "text": "Input : s = 9, d = 2\nOutput : 90\n\nInput : s = 20, d = 3\nOutput : 992" }, { "code": null, "e": 869, "s": 214, "text": "A Simple Solution is to consider all m digit numbers and keep track of maximum number with digit sum as s. A close upper bound on time complexity of this solution is O(10m).There is a Greedy approach to solve the problem. The idea is to one by one fill all digits from leftmost to rightmost (or from most significant digit to least significant). We compare the remaining sum with 9 if the remaining sum is more than 9, we put 9 at the current position, else we put the remaining sum. Since we fill digits from left to right, we put the highest digits on the left side, hence get the largest number. Below image is an illustration of the above approach: " }, { "code": null, "e": 922, "s": 869, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 926, "s": 922, "text": "C++" }, { "code": null, "e": 931, "s": 926, "text": "Java" }, { "code": null, "e": 939, "s": 931, "text": "Python3" }, { "code": null, "e": 942, "s": 939, "text": "C#" }, { "code": null, "e": 946, "s": 942, "text": "PHP" }, { "code": null, "e": 957, "s": 946, "text": "Javascript" }, { "code": "// C++ program to find the largest number that can be// formed from given sum of digits and number of digits.#include <iostream>using namespace std; // Prints the smallest possible number with digit sum 's'// and 'm' number of digits.void findLargest(int m, int s){ // If sum of digits is 0, then a number is possible // only if number of digits is 1. if (s == 0) { (m == 1)? cout << \"Largest number is \" << 0 : cout << \"Not possible\"; return ; } // Sum greater than the maximum possible sum. if (s > 9*m) { cout << \"Not possible\"; return ; } // Create an array to store digits of result int res[m]; // Fill from most significant digit to least // significant digit. for (int i=0; i<m; i++) { // Fill 9 first to make the number largest if (s >= 9) { res[i] = 9; s -= 9; } // If remaining sum becomes less than 9, then // fill the remaining sum else { res[i] = s; s = 0; } } cout << \"Largest number is \"; for (int i=0; i<m; i++) cout << res[i];} // Driver codeint main(){ int s = 9, m = 2; findLargest(m, s); return 0;}", "e": 2208, "s": 957, "text": null }, { "code": "// Java program to find the largest number that can be// formed from given sum of digits and number of digits class GFG{ // Function to print the largest possible number with digit sum 's' // and 'm' number of digits static void findLargest(int m, int s) { // If sum of digits is 0, then a number is possible // only if number of digits is 1 if (s == 0) { System.out.print(m == 1 ? \"Largest number is 0\" : \"Not possible\"); return ; } // Sum greater than the maximum possible sum if (s > 9*m) { System.out.println(\"Not possible\"); return ; } // Create an array to store digits of result int[] res = new int[m]; // Fill from most significant digit to least // significant digit for (int i=0; i<m; i++) { // Fill 9 first to make the number largest if (s >= 9) { res[i] = 9; s -= 9; } // If remaining sum becomes less than 9, then // fill the remaining sum else { res[i] = s; s = 0; } } System.out.print(\"Largest number is \"); for (int i=0; i<m; i++) System.out.print(res[i]); } // driver program public static void main (String[] args) { int s = 9, m = 2; findLargest(m, s); }} // Contributed by Pramod Kumar", "e": 3723, "s": 2208, "text": null }, { "code": "# Python 3 program to find# the largest number that# can be formed from given# sum of digits and number# of digits. # Prints the smallest# possible number with digit# sum 's' and 'm' number of# digits.def findLargest( m, s) : # If sum of digits is 0, # then a number is possible # only if number of digits # is 1. if (s == 0) : if(m == 1) : print(\"Largest number is \" , \"0\",end = \"\") else : print(\"Not possible\",end = \"\") return # Sum greater than the # maximum possible sum. if (s > 9 * m) : print(\"Not possible\",end = \"\") return # Create an array to # store digits of # result res = [0] * m # Fill from most significant # digit to least significant # digit. for i in range(0, m) : # Fill 9 first to make # the number largest if (s >= 9) : res[i] = 9 s = s - 9 # If remaining sum # becomes less than # 9, then fill the # remaining sum else : res[i] = s s = 0 print( \"Largest number is \",end = \"\") for i in range(0, m) : print(res[i],end = \"\") # Driver codes = 9m = 2findLargest(m, s) # This code is contributed by Nikita Tiwari.", "e": 5031, "s": 3723, "text": null }, { "code": "// C# program to find the// largest number that can// be formed from given sum// of digits and number of digitsusing System; class GFG{ // Function to print the // largest possible number // with digit sum 's' and // 'm' number of digits static void findLargest(int m, int s) { // If sum of digits is 0, // then a number is possible // only if number of digits is 1 if (s == 0) { Console.Write(m == 1 ? \"Largest number is 0\" : \"Not possible\"); return ; } // Sum greater than the // maximum possible sum if (s > 9 * m) { Console.WriteLine(\"Not possible\"); return ; } // Create an array to // store digits of result int []res = new int[m]; // Fill from most significant // digit to least significant digit for (int i = 0; i < m; i++) { // Fill 9 first to make // the number largest if (s >= 9) { res[i] = 9; s -= 9; } // If remaining sum becomes // less than 9, then // fill the remaining sum else { res[i] = s; s = 0; } } Console.Write(\"Largest number is \"); for (int i = 0; i < m; i++) Console.Write(res[i]); } // Driver Code static public void Main () { int s = 9, m = 2; findLargest(m, s); }} // This code is Contributed by ajit", "e": 6664, "s": 5031, "text": null }, { "code": "<?php// PHP program to find the largest// number that can be formed from// given sum of digits and number// of digits. // Prints the smallest possible// number with digit sum 's'// and 'm' number of digits.function findLargest($m, $s){ // If sum of digits is 0, then // a number is possible only if // number of digits is 1. if ($s == 0) { if(($m == 1) == true) echo \"Largest number is \" , 0; else echo \"Not possible\"; return ; } // Sum greater than the // maximum possible sum. if ($s > 9 * $m) { echo \"Not possible\"; return ; } // Create an array to store // digits of result Fill from // most significant digit to // least significant digit. for ($i = 0; $i < $m; $i++) { // Fill 9 first to make // the number largest if ($s >= 9) { $res[$i] = 9; $s -= 9; } // If remaining sum becomes // less than 9, then fill // the remaining sum else { $res[$i] = $s; $s = 0; } } echo \"Largest number is \"; for ($i = 0; $i < $m; $i++) echo $res[$i];} // Driver code$s = 9; $m = 2;findLargest($m, $s); // This code is contributed by m_kit?>", "e": 7943, "s": 6664, "text": null }, { "code": "<script>// Javascript program to find the largest number that can be// formed from given sum of digits and number of digits. // Prints the smallest possible number with digit sum 's'// and 'm' number of digits.function findLargest(m, s){ // If sum of digits is 0, then a number is possible // only if number of digits is 1. if (s == 0) { (m == 1)? document.write(\"Largest number is \" + 0) : document.write(\"Not possible\"); return ; } // Sum greater than the maximum possible sum. if (s > 9*m) { document.write(\"Not possible\"); return ; } // Create an array to store digits of result let res = new Array(m); // Fill from most significant digit to least // significant digit. for (let i=0; i<m; i++) { // Fill 9 first to make the number largest if (s >= 9) { res[i] = 9; s -= 9; } // If remaining sum becomes less than 9, then // fill the remaining sum else { res[i] = s; s = 0; } } document.write(\"Largest number is \"); for (let i=0; i<m; i++) document.write(res[i]);} // Driver code let s = 9, m = 2; findLargest(m, s); // This code is contributed by Mayank Tyagi </script>", "e": 9243, "s": 7943, "text": null }, { "code": null, "e": 9253, "s": 9243, "text": "Output : " }, { "code": null, "e": 9274, "s": 9253, "text": "Largest number is 90" }, { "code": null, "e": 9316, "s": 9274, "text": "Time Complexity of this solution is O(m)." }, { "code": null, "e": 9370, "s": 9316, "text": "Auxiliary Space : O(m), where m is the given integer." }, { "code": null, "e": 9764, "s": 9370, "text": "This article is contributed by Vaibhav Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 9770, "s": 9764, "text": "jit_t" }, { "code": null, "e": 9786, "s": 9770, "text": "mayanktyagi1709" }, { "code": null, "e": 9799, "s": 9786, "text": "AshokJaiswal" }, { "code": null, "e": 9812, "s": 9799, "text": "simmytarika5" }, { "code": null, "e": 9828, "s": 9812, "text": "tamanna17122007" }, { "code": null, "e": 9842, "s": 9828, "text": "number-digits" }, { "code": null, "e": 9849, "s": 9842, "text": "Greedy" }, { "code": null, "e": 9862, "s": 9849, "text": "Mathematical" }, { "code": null, "e": 9869, "s": 9862, "text": "Greedy" }, { "code": null, "e": 9882, "s": 9869, "text": "Mathematical" }, { "code": null, "e": 9980, "s": 9882, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10011, "s": 9980, "text": "Huffman Coding | Greedy Algo-3" }, { "code": null, "e": 10054, "s": 10011, "text": "Activity Selection Problem | Greedy Algo-1" }, { "code": null, "e": 10082, "s": 10054, "text": "Fractional Knapsack Problem" }, { "code": null, "e": 10105, "s": 10082, "text": "Job Sequencing Problem" }, { "code": null, "e": 10129, "s": 10105, "text": "Policemen catch thieves" }, { "code": null, "e": 10172, "s": 10129, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 10187, "s": 10172, "text": "C++ Data Types" }, { "code": null, "e": 10211, "s": 10187, "text": "Merge two sorted arrays" }, { "code": null, "e": 10232, "s": 10211, "text": "Operators in C / C++" } ]
Python Exit handlers (atexit)
29 Jun, 2022 atexit is a module in python which contains two functions register() and unregister(). The main role of this module is to perform clean up upon interpreter termination. Functions that are registered are automatically executed upon interpreter termination. Whenever a program is killed by a signal not handled by Python, when os.exit() is called, or Python fatal internal error is detected, the functions registered via this module are not executed. register(): Register function takes a function as an argument that is to be executed at interpreter termination. If there are multiple functions passed as arguments e.g. (fun1(), fun2()..) then there execution will be in reverse order (...fun2(), fun1()). The execution occurs in last in first out (LIFO) concept. Syntax: atexit.register(fun, *args, **kwargs) Parameters: First the function name is mentioned and then any arguments for that function is passed. The parameters are separated using ‘, ‘. Return: This function returns the called fun and hence the calling can be traced. Note: This function can also be used as a decorator. # Example 1: Python3 # Python program to demonstrate# atexit module import atexit names = ['Geeks', 'for', 'Geeks'] def hello(name): print (name) for name in names: # Using register() atexit.register(hello, name) Output : Geeks for Geeks # Example 2: Using register as a decorator Python3 # Python program to demonstrate# atexit module import atexit # Using register() as a decorator@atexit.registerdef goodbye(): print("GoodBye.") Output : GoodBye. unregister(): The unregister() function removes the specified fun from the functions defined in the program. It provides a surety that the fun will not be called when the interpreter terminates. Syntax: atexit.unregister(fun) Parameters: The function may or may not contain any parameter. If any present then the fun name is to be specified. Return: No return. Example: Python3 # Python program to demonstrate# atexit module import atexit names = ['Geeks', 'for', 'Geeks'] def hello(name): print (name) for name in names: # Using unregister() atexit.unregister(hello) Output : No Output jjlopezb4e40 python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Jun, 2022" }, { "code": null, "e": 477, "s": 28, "text": "atexit is a module in python which contains two functions register() and unregister(). The main role of this module is to perform clean up upon interpreter termination. Functions that are registered are automatically executed upon interpreter termination. Whenever a program is killed by a signal not handled by Python, when os.exit() is called, or Python fatal internal error is detected, the functions registered via this module are not executed." }, { "code": null, "e": 791, "s": 477, "text": "register(): Register function takes a function as an argument that is to be executed at interpreter termination. If there are multiple functions passed as arguments e.g. (fun1(), fun2()..) then there execution will be in reverse order (...fun2(), fun1()). The execution occurs in last in first out (LIFO) concept." }, { "code": null, "e": 838, "s": 791, "text": "Syntax: atexit.register(fun, *args, **kwargs) " }, { "code": null, "e": 981, "s": 838, "text": "Parameters: First the function name is mentioned and then any arguments for that function is passed. The parameters are separated using ‘, ‘. " }, { "code": null, "e": 1063, "s": 981, "text": "Return: This function returns the called fun and hence the calling can be traced." }, { "code": null, "e": 1117, "s": 1063, "text": "Note: This function can also be used as a decorator. " }, { "code": null, "e": 1131, "s": 1117, "text": "# Example 1: " }, { "code": null, "e": 1139, "s": 1131, "text": "Python3" }, { "code": "# Python program to demonstrate# atexit module import atexit names = ['Geeks', 'for', 'Geeks'] def hello(name): print (name) for name in names: # Using register() atexit.register(hello, name)", "e": 1342, "s": 1139, "text": null }, { "code": null, "e": 1351, "s": 1342, "text": "Output :" }, { "code": null, "e": 1367, "s": 1351, "text": "Geeks\nfor\nGeeks" }, { "code": null, "e": 1411, "s": 1367, "text": "# Example 2: Using register as a decorator " }, { "code": null, "e": 1419, "s": 1411, "text": "Python3" }, { "code": "# Python program to demonstrate# atexit module import atexit # Using register() as a decorator@atexit.registerdef goodbye(): print(\"GoodBye.\")", "e": 1566, "s": 1419, "text": null }, { "code": null, "e": 1575, "s": 1566, "text": "Output :" }, { "code": null, "e": 1584, "s": 1575, "text": "GoodBye." }, { "code": null, "e": 1779, "s": 1584, "text": "unregister(): The unregister() function removes the specified fun from the functions defined in the program. It provides a surety that the fun will not be called when the interpreter terminates." }, { "code": null, "e": 1811, "s": 1779, "text": "Syntax: atexit.unregister(fun) " }, { "code": null, "e": 1928, "s": 1811, "text": "Parameters: The function may or may not contain any parameter. If any present then the fun name is to be specified. " }, { "code": null, "e": 1947, "s": 1928, "text": "Return: No return." }, { "code": null, "e": 1957, "s": 1947, "text": "Example: " }, { "code": null, "e": 1965, "s": 1957, "text": "Python3" }, { "code": "# Python program to demonstrate# atexit module import atexit names = ['Geeks', 'for', 'Geeks'] def hello(name): print (name) for name in names: # Using unregister() atexit.unregister(hello)", "e": 2166, "s": 1965, "text": null }, { "code": null, "e": 2175, "s": 2166, "text": "Output :" }, { "code": null, "e": 2185, "s": 2175, "text": "No Output" }, { "code": null, "e": 2198, "s": 2185, "text": "jjlopezb4e40" }, { "code": null, "e": 2213, "s": 2198, "text": "python-modules" }, { "code": null, "e": 2220, "s": 2213, "text": "Python" }, { "code": null, "e": 2318, "s": 2220, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2336, "s": 2318, "text": "Python Dictionary" }, { "code": null, "e": 2378, "s": 2336, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2400, "s": 2378, "text": "Enumerate() in Python" }, { "code": null, "e": 2435, "s": 2400, "text": "Read a file line by line in Python" }, { "code": null, "e": 2461, "s": 2435, "text": "Python String | replace()" }, { "code": null, "e": 2493, "s": 2461, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2522, "s": 2493, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2549, "s": 2522, "text": "Python Classes and Objects" }, { "code": null, "e": 2579, "s": 2549, "text": "Iterate over a list in Python" } ]
Sub-string that contains all lowercase alphabets after performing the given operation
23 May, 2022 Given a string str containing lower case alphabets and character ‘?’. The task is to check if it is possible to make str good or not.A string is called good if it contains a sub-string of length 26 which has every character of lower case alphabets in it. The task is to check if it is possible to make the string good by replacing ‘?’ characters with any lower case alphabet. If it is possible then print the modified string otherwise print -1.Examples: Input: str = “abcdefghijkl?nopqrstuvwxy?” Output: abcdefghijklmnopqrstuvwxyz Replace first ‘?’ with ‘m’ and second with ‘z’.Input: str = “abcdefghijklmnopqrstuvwxyz??????” Output: abcdefghijklmnopqrstuvwxyzaaaaaa Given string already has a sub-string which contains all the 26 lower case alphabets. Approach: If the length of the string is less than 26 then print -1. The Task is to make a sub-string of length 26 that has all the lowercase characters. Thus, the simplest way is to iterate through all sub-strings of length 26 then for each sub-string count the number of occurrences of each alphabet, ignoring the question marks. After that, if there exists a character that occurs twice or more then this sub-string cannot contain all letters of the alphabet, and we process the next sub-string. Otherwise, we can fill in the question marks with the letters that have not appeared in the sub-string and obtain a sub-string of length 26 which contains all letters of the alphabet.Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that returns true if every// lowercase character appears atmost oncebool valid(int cnt[]){ // every character frequency must be not // greater than one for (int i = 0; i < 26; i++) { if (cnt[i] >= 2) return false; } return true;} // Function that returns the modified// good string if possiblestring getGoodString(string s, int n){ // If the length of the string is less than n if (n < 26) return "-1"; // Sub-strings of length 26 for (int i = 25; i < n; i++) { // To store frequency of each character int cnt[26] = { 0 }; // Get the frequency of each character // in the current sub-string for (int j = i; j >= i - 25; j--) { cnt[s[j] - 'a']++; } // Check if we can get sub-string containing all // the 26 characters if (valid(cnt)) { // Find which character is missing int cur = 0; while (cnt[cur] > 0) cur++; for (int j = i - 25; j <= i; j++) { // Fill with missing characters if (s[j] == '?') { s[j] = cur + 'a'; cur++; // Find the next missing character while (cnt[cur] > 0) cur++; } } // Return the modified good string return s; } } return "-1";} // Driver codeint main(){ string s = "abcdefghijkl?nopqrstuvwxy?"; int n = s.length(); cout << getGoodString(s, n); return 0;} // Java implementation of the approachimport java.util.*; class GFG{ // Function that returns true if every// lowercase character appears atmost oncestatic boolean valid(int []cnt){ // every character frequency must be not // greater than one for (int i = 0; i < 26; i++) { if (cnt[i] >= 2) return false; } return true;} // Function that returns the modified// good string if possiblestatic String getGoodString(String ss, int n){ char[] s=ss.toCharArray(); // If the length of the string is less than n if (n < 26) return "-1"; // To store frequency of each character int[] cnt = new int[27]; // Sub-strings of length 26 for (int i = 25; i < n; i++) { // Get the frequency of each character // in the current sub-string for (int j = i; j >= i - 25; j--) { if (s[j] != '?') cnt[((int)s[j] - (int)'a')]++; } // Check if we can get sub-string containing all // the 26 characters if (valid(cnt)) { // Find which character is missing int cur = 0; while (cnt[cur] > 0) cur++; for (int j = i - 25; j <= i; j++) { // Fill with missing characters if (s[j] == '?') { s[j] = (char)(cur + (int)('a')); cur++; // Find the next missing character while (cnt[cur] > 0) cur++; } } // Return the modified good string return new String(s); } } return "-1";} // Driver codepublic static void main (String[] args){ String s = "abcdefghijkl?nopqrstuvwxy?"; int n = s.length(); System.out.println(getGoodString(s, n));}} // This code is contributed by chandan_jnu # Python3 implementation of the approach # Function that returns true if every# lowercase character appears atmost oncedef valid(cnt): # Every character frequency must # be not greater than one for i in range(0, 26): if cnt[i] >= 2: return False return True # Function that returns the modified# good string if possibledef getGoodString(s, n): # If the length of the string is # less than n if n < 26: return "-1" # Sub-strings of length 26 for i in range(25, n): # To store frequency of each character cnt = [0] * 26 # Get the frequency of each character # in the current sub-string for j in range(i, i - 26, -1): if s[j] != '?': cnt[ord(s[j]) - ord('a')] += 1 # Check if we can get sub-string # containing the 26 characters all if valid(cnt): # Find which character is missing cur = 0 while cur < 26 and cnt[cur] > 0: cur += 1 for j in range(i - 25, i + 1): # Fill with missing characters if s[j] == '?': s[j] = chr(cur + ord('a')) cur += 1 # Find the next missing character while cur < 26 and cnt[cur] > 0: cur += 1 # Return the modified good string return ''.join(s) return "-1" # Driver codeif __name__ == "__main__": s = "abcdefghijkl?nopqrstuvwxy?" n = len(s) print(getGoodString(list(s), n)) # This code is contributed by Rituraj Jain // C# implementation of the approachusing System; class GFG{ // Function that returns true if every// lowercase character appears atmost oncestatic bool valid(int []cnt){ // every character frequency must be not // greater than one for (int i = 0; i < 26; i++) { if (cnt[i] >= 2) return false; } return true;} // Function that returns the modified// good string if possiblestatic string getGoodString(string ss, int n){ char[] s = ss.ToCharArray(); // If the length of the string is less than n if (n < 26) return "-1"; // To store frequency of each character int[] cnt = new int[27]; // Sub-strings of length 26 for (int i = 25; i < n; i++) { // Get the frequency of each character // in the current sub-string for (int j = i; j >= i - 25; j--) { if (s[j] != '?') cnt[((int)s[j] - (int)'a')]++; } // Check if we can get sub-string containing all // the 26 characters if (valid(cnt)) { // Find which character is missing int cur = 0; while (cnt[cur] > 0) cur++; for (int j = i - 25; j <= i; j++) { // Fill with missing characters if (s[j] == '?') { s[j] = (char)(cur + (int)('a')); cur++; // Find the next missing character while (cnt[cur] > 0) cur++; } } // Return the modified good string return new String(s); } } return "-1";} // Driver codestatic void Main(){ string s = "abcdefghijkl?nopqrstuvwxy?"; int n = s.Length; Console.WriteLine(getGoodString(s, n));}} // This code is contributed by chandan_jnu <?php// PHP implementation of the approach // Function that returns true if every// lowercase character appears atmost oncefunction valid(&$cnt){ // every character frequency must // be not greater than one for ($i = 0; $i < 26; $i++) { if ($cnt[$i] >= 2) return false; } return true;} // Function that returns the modified// good string if possiblefunction getGoodString($s, $n){ // If the length of the string is // less than n if ($n < 26) return "-1"; // Sub-strings of length 26 for ($i = 25; $i < $n; $i++) { // To store frequency of each character $cnt = array_fill(0, 26, NULL); // Get the frequency of each character // in the current sub-string for ($j = $i; $j >= $i - 25; $j--) { if ($s[$j] != '?') $cnt[ord($s[$j]) - ord('a')]++; } // Check if we can get sub-string // containing all the 26 characters if (valid($cnt)) { // Find which character is missing $cur = 0; while ($cur < 26 && $cnt[$cur] > 0) $cur++; for ($j = $i - 25; $j <= $i; $j++) { // Fill with missing characters if ($s[$j] == '?') { $s[$j] = chr($cur + ord('a')); $cur++; // Find the next missing character while ($cur < 26 && $cnt[$cur] > 0) $cur++; } } // Return the modified good string return $s; } } return "-1";} // Driver code$s = "abcdefghijkl?nopqrstuvwxy?";$n = strlen($s);echo getGoodString($s, $n); // This code is contributed by ita_c?> <script> // JavaScript implementation of the approach // Function that returns true if every // lowercase character appears atmost once function valid(cnt) { // every character frequency must be not // greater than one for (var i = 0; i < 26; i++) { if (cnt[i] >= 2) return false; } return true; } // Function that returns the modified // good string if possible function getGoodString(ss, n) { var s = ss.split(""); // If the length of the string is less than n if (n < 26) return "-1"; // Sub-strings of length 26 for (var i = 25; i < n; i++) { // To store frequency of each character var cnt = new Array(26).fill(0); // Get the frequency of each character // in the current sub-string for (var j = i; j >= i - 25; j--) { cnt[s[j].charCodeAt(0) - "a".charCodeAt(0)]++; } // Check if we can get sub-string containing all // the 26 characters if (valid(cnt)) { // Find which character is missing var cur = 0; while (cnt[cur] > 0) cur++; for (var j = i - 25; j <= i; j++) { // Fill with missing characters if (s[j] === "?") { s[j] = String.fromCharCode(cur + "a".charCodeAt(0)); cur++; // Find the next missing character while (cnt[cur] > 0) cur++; } } // Return the modified good string return s.join(""); } } return "-1"; } // Driver code var s = "abcdefghijkl?nopqrstuvwxy?"; var n = s.length; document.write(getGoodString(s, n)); </script> abcdefghijklmnopqrstuvwxyz Time Complexity: O(N2), where N is the size of the given string. Auxiliary Space: O(26) rituraj_jain ukasp Chandan_Kumar rdtank samim2000 cpp-strings Competitive Programming Mathematical Strings cpp-strings Strings Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Modulo 10^9+7 (1000000007) Prefix Sum Array - Implementation and Applications in Competitive Programming Bits manipulation (Important tactics) What is Competitive Programming and How to Prepare for It? Bitwise Hacks for Competitive Programming Program for Fibonacci numbers Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays
[ { "code": null, "e": 52, "s": 24, "text": "\n23 May, 2022" }, { "code": null, "e": 508, "s": 52, "text": "Given a string str containing lower case alphabets and character ‘?’. The task is to check if it is possible to make str good or not.A string is called good if it contains a sub-string of length 26 which has every character of lower case alphabets in it. The task is to check if it is possible to make the string good by replacing ‘?’ characters with any lower case alphabet. If it is possible then print the modified string otherwise print -1.Examples: " }, { "code": null, "e": 809, "s": 508, "text": "Input: str = “abcdefghijkl?nopqrstuvwxy?” Output: abcdefghijklmnopqrstuvwxyz Replace first ‘?’ with ‘m’ and second with ‘z’.Input: str = “abcdefghijklmnopqrstuvwxyz??????” Output: abcdefghijklmnopqrstuvwxyzaaaaaa Given string already has a sub-string which contains all the 26 lower case alphabets. " }, { "code": null, "e": 1545, "s": 811, "text": "Approach: If the length of the string is less than 26 then print -1. The Task is to make a sub-string of length 26 that has all the lowercase characters. Thus, the simplest way is to iterate through all sub-strings of length 26 then for each sub-string count the number of occurrences of each alphabet, ignoring the question marks. After that, if there exists a character that occurs twice or more then this sub-string cannot contain all letters of the alphabet, and we process the next sub-string. Otherwise, we can fill in the question marks with the letters that have not appeared in the sub-string and obtain a sub-string of length 26 which contains all letters of the alphabet.Below is the implementation of the above approach: " }, { "code": null, "e": 1549, "s": 1545, "text": "C++" }, { "code": null, "e": 1554, "s": 1549, "text": "Java" }, { "code": null, "e": 1562, "s": 1554, "text": "Python3" }, { "code": null, "e": 1565, "s": 1562, "text": "C#" }, { "code": null, "e": 1569, "s": 1565, "text": "PHP" }, { "code": null, "e": 1580, "s": 1569, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that returns true if every// lowercase character appears atmost oncebool valid(int cnt[]){ // every character frequency must be not // greater than one for (int i = 0; i < 26; i++) { if (cnt[i] >= 2) return false; } return true;} // Function that returns the modified// good string if possiblestring getGoodString(string s, int n){ // If the length of the string is less than n if (n < 26) return \"-1\"; // Sub-strings of length 26 for (int i = 25; i < n; i++) { // To store frequency of each character int cnt[26] = { 0 }; // Get the frequency of each character // in the current sub-string for (int j = i; j >= i - 25; j--) { cnt[s[j] - 'a']++; } // Check if we can get sub-string containing all // the 26 characters if (valid(cnt)) { // Find which character is missing int cur = 0; while (cnt[cur] > 0) cur++; for (int j = i - 25; j <= i; j++) { // Fill with missing characters if (s[j] == '?') { s[j] = cur + 'a'; cur++; // Find the next missing character while (cnt[cur] > 0) cur++; } } // Return the modified good string return s; } } return \"-1\";} // Driver codeint main(){ string s = \"abcdefghijkl?nopqrstuvwxy?\"; int n = s.length(); cout << getGoodString(s, n); return 0;}", "e": 3255, "s": 1580, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG{ // Function that returns true if every// lowercase character appears atmost oncestatic boolean valid(int []cnt){ // every character frequency must be not // greater than one for (int i = 0; i < 26; i++) { if (cnt[i] >= 2) return false; } return true;} // Function that returns the modified// good string if possiblestatic String getGoodString(String ss, int n){ char[] s=ss.toCharArray(); // If the length of the string is less than n if (n < 26) return \"-1\"; // To store frequency of each character int[] cnt = new int[27]; // Sub-strings of length 26 for (int i = 25; i < n; i++) { // Get the frequency of each character // in the current sub-string for (int j = i; j >= i - 25; j--) { if (s[j] != '?') cnt[((int)s[j] - (int)'a')]++; } // Check if we can get sub-string containing all // the 26 characters if (valid(cnt)) { // Find which character is missing int cur = 0; while (cnt[cur] > 0) cur++; for (int j = i - 25; j <= i; j++) { // Fill with missing characters if (s[j] == '?') { s[j] = (char)(cur + (int)('a')); cur++; // Find the next missing character while (cnt[cur] > 0) cur++; } } // Return the modified good string return new String(s); } } return \"-1\";} // Driver codepublic static void main (String[] args){ String s = \"abcdefghijkl?nopqrstuvwxy?\"; int n = s.length(); System.out.println(getGoodString(s, n));}} // This code is contributed by chandan_jnu", "e": 5184, "s": 3255, "text": null }, { "code": "# Python3 implementation of the approach # Function that returns true if every# lowercase character appears atmost oncedef valid(cnt): # Every character frequency must # be not greater than one for i in range(0, 26): if cnt[i] >= 2: return False return True # Function that returns the modified# good string if possibledef getGoodString(s, n): # If the length of the string is # less than n if n < 26: return \"-1\" # Sub-strings of length 26 for i in range(25, n): # To store frequency of each character cnt = [0] * 26 # Get the frequency of each character # in the current sub-string for j in range(i, i - 26, -1): if s[j] != '?': cnt[ord(s[j]) - ord('a')] += 1 # Check if we can get sub-string # containing the 26 characters all if valid(cnt): # Find which character is missing cur = 0 while cur < 26 and cnt[cur] > 0: cur += 1 for j in range(i - 25, i + 1): # Fill with missing characters if s[j] == '?': s[j] = chr(cur + ord('a')) cur += 1 # Find the next missing character while cur < 26 and cnt[cur] > 0: cur += 1 # Return the modified good string return ''.join(s) return \"-1\" # Driver codeif __name__ == \"__main__\": s = \"abcdefghijkl?nopqrstuvwxy?\" n = len(s) print(getGoodString(list(s), n)) # This code is contributed by Rituraj Jain", "e": 6798, "s": 5184, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function that returns true if every// lowercase character appears atmost oncestatic bool valid(int []cnt){ // every character frequency must be not // greater than one for (int i = 0; i < 26; i++) { if (cnt[i] >= 2) return false; } return true;} // Function that returns the modified// good string if possiblestatic string getGoodString(string ss, int n){ char[] s = ss.ToCharArray(); // If the length of the string is less than n if (n < 26) return \"-1\"; // To store frequency of each character int[] cnt = new int[27]; // Sub-strings of length 26 for (int i = 25; i < n; i++) { // Get the frequency of each character // in the current sub-string for (int j = i; j >= i - 25; j--) { if (s[j] != '?') cnt[((int)s[j] - (int)'a')]++; } // Check if we can get sub-string containing all // the 26 characters if (valid(cnt)) { // Find which character is missing int cur = 0; while (cnt[cur] > 0) cur++; for (int j = i - 25; j <= i; j++) { // Fill with missing characters if (s[j] == '?') { s[j] = (char)(cur + (int)('a')); cur++; // Find the next missing character while (cnt[cur] > 0) cur++; } } // Return the modified good string return new String(s); } } return \"-1\";} // Driver codestatic void Main(){ string s = \"abcdefghijkl?nopqrstuvwxy?\"; int n = s.Length; Console.WriteLine(getGoodString(s, n));}} // This code is contributed by chandan_jnu", "e": 8694, "s": 6798, "text": null }, { "code": "<?php// PHP implementation of the approach // Function that returns true if every// lowercase character appears atmost oncefunction valid(&$cnt){ // every character frequency must // be not greater than one for ($i = 0; $i < 26; $i++) { if ($cnt[$i] >= 2) return false; } return true;} // Function that returns the modified// good string if possiblefunction getGoodString($s, $n){ // If the length of the string is // less than n if ($n < 26) return \"-1\"; // Sub-strings of length 26 for ($i = 25; $i < $n; $i++) { // To store frequency of each character $cnt = array_fill(0, 26, NULL); // Get the frequency of each character // in the current sub-string for ($j = $i; $j >= $i - 25; $j--) { if ($s[$j] != '?') $cnt[ord($s[$j]) - ord('a')]++; } // Check if we can get sub-string // containing all the 26 characters if (valid($cnt)) { // Find which character is missing $cur = 0; while ($cur < 26 && $cnt[$cur] > 0) $cur++; for ($j = $i - 25; $j <= $i; $j++) { // Fill with missing characters if ($s[$j] == '?') { $s[$j] = chr($cur + ord('a')); $cur++; // Find the next missing character while ($cur < 26 && $cnt[$cur] > 0) $cur++; } } // Return the modified good string return $s; } } return \"-1\";} // Driver code$s = \"abcdefghijkl?nopqrstuvwxy?\";$n = strlen($s);echo getGoodString($s, $n); // This code is contributed by ita_c?>", "e": 10470, "s": 8694, "text": null }, { "code": "<script> // JavaScript implementation of the approach // Function that returns true if every // lowercase character appears atmost once function valid(cnt) { // every character frequency must be not // greater than one for (var i = 0; i < 26; i++) { if (cnt[i] >= 2) return false; } return true; } // Function that returns the modified // good string if possible function getGoodString(ss, n) { var s = ss.split(\"\"); // If the length of the string is less than n if (n < 26) return \"-1\"; // Sub-strings of length 26 for (var i = 25; i < n; i++) { // To store frequency of each character var cnt = new Array(26).fill(0); // Get the frequency of each character // in the current sub-string for (var j = i; j >= i - 25; j--) { cnt[s[j].charCodeAt(0) - \"a\".charCodeAt(0)]++; } // Check if we can get sub-string containing all // the 26 characters if (valid(cnt)) { // Find which character is missing var cur = 0; while (cnt[cur] > 0) cur++; for (var j = i - 25; j <= i; j++) { // Fill with missing characters if (s[j] === \"?\") { s[j] = String.fromCharCode(cur + \"a\".charCodeAt(0)); cur++; // Find the next missing character while (cnt[cur] > 0) cur++; } } // Return the modified good string return s.join(\"\"); } } return \"-1\"; } // Driver code var s = \"abcdefghijkl?nopqrstuvwxy?\"; var n = s.length; document.write(getGoodString(s, n)); </script>", "e": 12261, "s": 10470, "text": null }, { "code": null, "e": 12288, "s": 12261, "text": "abcdefghijklmnopqrstuvwxyz" }, { "code": null, "e": 12355, "s": 12290, "text": "Time Complexity: O(N2), where N is the size of the given string." }, { "code": null, "e": 12378, "s": 12355, "text": "Auxiliary Space: O(26)" }, { "code": null, "e": 12391, "s": 12378, "text": "rituraj_jain" }, { "code": null, "e": 12397, "s": 12391, "text": "ukasp" }, { "code": null, "e": 12411, "s": 12397, "text": "Chandan_Kumar" }, { "code": null, "e": 12418, "s": 12411, "text": "rdtank" }, { "code": null, "e": 12428, "s": 12418, "text": "samim2000" }, { "code": null, "e": 12440, "s": 12428, "text": "cpp-strings" }, { "code": null, "e": 12464, "s": 12440, "text": "Competitive Programming" }, { "code": null, "e": 12477, "s": 12464, "text": "Mathematical" }, { "code": null, "e": 12485, "s": 12477, "text": "Strings" }, { "code": null, "e": 12497, "s": 12485, "text": "cpp-strings" }, { "code": null, "e": 12505, "s": 12497, "text": "Strings" }, { "code": null, "e": 12518, "s": 12505, "text": "Mathematical" }, { "code": null, "e": 12616, "s": 12518, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 12643, "s": 12616, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 12721, "s": 12643, "text": "Prefix Sum Array - Implementation and Applications in Competitive Programming" }, { "code": null, "e": 12759, "s": 12721, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 12818, "s": 12759, "text": "What is Competitive Programming and How to Prepare for It?" }, { "code": null, "e": 12860, "s": 12818, "text": "Bitwise Hacks for Competitive Programming" }, { "code": null, "e": 12890, "s": 12860, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 12933, "s": 12890, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 12993, "s": 12933, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 13008, "s": 12993, "text": "C++ Data Types" } ]
Lodash | _.cloneDeep() Method
18 Jan, 2022 The _.cloneDeep() method is used to create a deep copy of the value i.e. it recursively clones the value. This method is similar to the _.clone() method. Syntax: _.cloneDeep( value ) Parameters: This method accepts single parameter as mentioned above and described below: value: This parameter holds the value that need to be clone recursively. Return Value: This method returns the deep cloned value. Example 1: Cloning Simple Object Javascript const _ = require('lodash'); var obj = { x: 23}; // Deep copyvar deepCopy = _.cloneDeep(obj); console.log('Comparing original with' + ' deep ', obj === deepCopy); obj.x = 10; // Changing original value console.log('After changing original value'); console.log("Original value ", obj); console.log("Deep Copy value ", deepCopy); Output: Comparing original with deep false After changing original value Original value { x: 10 } Deep Copy value { x: 23 } Example 2: Cloning complex object Javascript const _ = require('lodash'); var obj = [{ x: 1 }, {y: 2}]; // Deep copyvar deepCopy = _.cloneDeep(obj); console.log('Comparing original with deep ', obj[0] === deepCopy[0]); // Changing original valueobj[0].x = 10; // Values after changing original valueconsole.log("After changing original value"); console.log("Original value ", obj); console.log("Deep Copy value ", deepCopy); Output: Comparing original with deep false After changing original value Original value [ { x: 10 }, { y: 2 } ] Deep Copy value [ { x: 1 }, { y: 2 } ] So, here we have seen that after changing the original value the deep copy of the values didn’t change because _.cloneDeep() recursively copied the value deeply. Note: This will not work in normal JavaScript because it requires the library lodash to be installed. Reference: https://lodash.com/docs/4.17.15#cloneDeep gulshankumarar231 sagartomar9927 JavaScript-Lodash JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n18 Jan, 2022" }, { "code": null, "e": 208, "s": 54, "text": "The _.cloneDeep() method is used to create a deep copy of the value i.e. it recursively clones the value. This method is similar to the _.clone() method." }, { "code": null, "e": 217, "s": 208, "text": "Syntax: " }, { "code": null, "e": 238, "s": 217, "text": "_.cloneDeep( value )" }, { "code": null, "e": 329, "s": 238, "text": "Parameters: This method accepts single parameter as mentioned above and described below: " }, { "code": null, "e": 402, "s": 329, "text": "value: This parameter holds the value that need to be clone recursively." }, { "code": null, "e": 459, "s": 402, "text": "Return Value: This method returns the deep cloned value." }, { "code": null, "e": 494, "s": 459, "text": "Example 1: Cloning Simple Object " }, { "code": null, "e": 505, "s": 494, "text": "Javascript" }, { "code": "const _ = require('lodash'); var obj = { x: 23}; // Deep copyvar deepCopy = _.cloneDeep(obj); console.log('Comparing original with' + ' deep ', obj === deepCopy); obj.x = 10; // Changing original value console.log('After changing original value'); console.log(\"Original value \", obj); console.log(\"Deep Copy value \", deepCopy);", "e": 853, "s": 505, "text": null }, { "code": null, "e": 862, "s": 853, "text": "Output: " }, { "code": null, "e": 981, "s": 862, "text": "Comparing original with deep false\nAfter changing original value\nOriginal value { x: 10 }\nDeep Copy value { x: 23 }" }, { "code": null, "e": 1017, "s": 981, "text": "Example 2: Cloning complex object " }, { "code": null, "e": 1028, "s": 1017, "text": "Javascript" }, { "code": "const _ = require('lodash'); var obj = [{ x: 1 }, {y: 2}]; // Deep copyvar deepCopy = _.cloneDeep(obj); console.log('Comparing original with deep ', obj[0] === deepCopy[0]); // Changing original valueobj[0].x = 10; // Values after changing original valueconsole.log(\"After changing original value\"); console.log(\"Original value \", obj); console.log(\"Deep Copy value \", deepCopy);", "e": 1440, "s": 1028, "text": null }, { "code": null, "e": 1449, "s": 1440, "text": "Output: " }, { "code": null, "e": 1595, "s": 1449, "text": "Comparing original with deep false\nAfter changing original value\nOriginal value [ { x: 10 }, { y: 2 } ]\nDeep Copy value [ { x: 1 }, { y: 2 } ]" }, { "code": null, "e": 1757, "s": 1595, "text": "So, here we have seen that after changing the original value the deep copy of the values didn’t change because _.cloneDeep() recursively copied the value deeply." }, { "code": null, "e": 1859, "s": 1757, "text": "Note: This will not work in normal JavaScript because it requires the library lodash to be installed." }, { "code": null, "e": 1913, "s": 1859, "text": "Reference: https://lodash.com/docs/4.17.15#cloneDeep " }, { "code": null, "e": 1931, "s": 1913, "text": "gulshankumarar231" }, { "code": null, "e": 1946, "s": 1931, "text": "sagartomar9927" }, { "code": null, "e": 1964, "s": 1946, "text": "JavaScript-Lodash" }, { "code": null, "e": 1975, "s": 1964, "text": "JavaScript" }, { "code": null, "e": 1992, "s": 1975, "text": "Web Technologies" } ]
UnaryOperator Interface in Java
18 Nov, 2019 The UnaryOperator Interface<T> is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in one argument and operates on it. However what distinguishes it from a normal Function is that both its argument and return type are the same. Hence this functional interface which takes in one generic namely:- T: denotes the type of the input argument to the operation Hence the UnaryOperator<T> overloads the Function<T, T> type. So it inherits the following methods from the Function Interface: T apply(T t) default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) default <V> Function<V, R> compose(Function<? super V, ? extends T> before) The lambda expression assigned to an object of UnaryOperator type is used to define its accept() which eventually applies the given operation on its argument. The UnaryOperator interface consists of the following functions: This method returns a UnaryOperator which takes in one value and returns it. The returned UnaryOperator does not perform any operation on its only value. Syntax: static UnaryOperator identity() Parameters: This method does not take in any parameter. Returns: A UnaryOperator which takes in one value and returns it. Below is the code to illustrate accept() method: Program 1: import java.util.function.UnaryOperator; public class GFG { public static void main(String args[]) { // Instantiate the UnaryOperator interface UnaryOperator<Boolean> op = UnaryOperator.identity(); // Apply identify() method System.out.println(op.apply(true)); }} true Below are few examples to demonstrate the methods inherited from Function<T, T>: 1.accept() import java.util.function.Function;import java.util.function.UnaryOperator; public class GFG { public static void main(String args[]) { UnaryOperator<Integer> xor = a -> a ^ 1; System.out.println(xor.apply(2)); }} 3 2.addThen() import java.util.function.Function;import java.util.function.UnaryOperator; public class GFG { public static void main(String args[]) { UnaryOperator<Integer> xor = a -> a ^ 1; UnaryOperator<Integer> and = a -> a & 1; Function<Integer, Integer> compose = xor.andThen(and); System.out.println(compose.apply(2)); }} 1 3.compose() import java.util.function.Function;import java.util.function.UnaryOperator; public class GFG { public static void main(String args[]) { UnaryOperator<Integer> xor = a -> a ^ 1; UnaryOperator<Integer> and = a -> a & 1; Function<Integer, Integer> compose = xor.compose(and); System.out.println(compose.apply(231)); }} 0 psil123 Akanksha_Rai Java - util package Java 8 java-basics Java-Functional Programming java-interfaces Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Nov, 2019" }, { "code": null, "e": 370, "s": 28, "text": "The UnaryOperator Interface<T> is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in one argument and operates on it. However what distinguishes it from a normal Function is that both its argument and return type are the same." }, { "code": null, "e": 438, "s": 370, "text": "Hence this functional interface which takes in one generic namely:-" }, { "code": null, "e": 497, "s": 438, "text": "T: denotes the type of the input argument to the operation" }, { "code": null, "e": 625, "s": 497, "text": "Hence the UnaryOperator<T> overloads the Function<T, T> type. So it inherits the following methods from the Function Interface:" }, { "code": null, "e": 638, "s": 625, "text": "T apply(T t)" }, { "code": null, "e": 713, "s": 638, "text": "default <V> Function<T, V> andThen(Function<? super R, ? extends V> after)" }, { "code": null, "e": 789, "s": 713, "text": "default <V> Function<V, R> compose(Function<? super V, ? extends T> before)" }, { "code": null, "e": 948, "s": 789, "text": "The lambda expression assigned to an object of UnaryOperator type is used to define its accept() which eventually applies the given operation on its argument." }, { "code": null, "e": 1013, "s": 948, "text": "The UnaryOperator interface consists of the following functions:" }, { "code": null, "e": 1167, "s": 1013, "text": "This method returns a UnaryOperator which takes in one value and returns it. The returned UnaryOperator does not perform any operation on its only value." }, { "code": null, "e": 1175, "s": 1167, "text": "Syntax:" }, { "code": null, "e": 1208, "s": 1175, "text": "static UnaryOperator identity()" }, { "code": null, "e": 1264, "s": 1208, "text": "Parameters: This method does not take in any parameter." }, { "code": null, "e": 1330, "s": 1264, "text": "Returns: A UnaryOperator which takes in one value and returns it." }, { "code": null, "e": 1379, "s": 1330, "text": "Below is the code to illustrate accept() method:" }, { "code": null, "e": 1390, "s": 1379, "text": "Program 1:" }, { "code": "import java.util.function.UnaryOperator; public class GFG { public static void main(String args[]) { // Instantiate the UnaryOperator interface UnaryOperator<Boolean> op = UnaryOperator.identity(); // Apply identify() method System.out.println(op.apply(true)); }}", "e": 1707, "s": 1390, "text": null }, { "code": null, "e": 1713, "s": 1707, "text": "true\n" }, { "code": null, "e": 1794, "s": 1713, "text": "Below are few examples to demonstrate the methods inherited from Function<T, T>:" }, { "code": null, "e": 1805, "s": 1794, "text": "1.accept()" }, { "code": "import java.util.function.Function;import java.util.function.UnaryOperator; public class GFG { public static void main(String args[]) { UnaryOperator<Integer> xor = a -> a ^ 1; System.out.println(xor.apply(2)); }}", "e": 2043, "s": 1805, "text": null }, { "code": null, "e": 2046, "s": 2043, "text": "3\n" }, { "code": null, "e": 2058, "s": 2046, "text": "2.addThen()" }, { "code": "import java.util.function.Function;import java.util.function.UnaryOperator; public class GFG { public static void main(String args[]) { UnaryOperator<Integer> xor = a -> a ^ 1; UnaryOperator<Integer> and = a -> a & 1; Function<Integer, Integer> compose = xor.andThen(and); System.out.println(compose.apply(2)); }}", "e": 2410, "s": 2058, "text": null }, { "code": null, "e": 2413, "s": 2410, "text": "1\n" }, { "code": null, "e": 2425, "s": 2413, "text": "3.compose()" }, { "code": "import java.util.function.Function;import java.util.function.UnaryOperator; public class GFG { public static void main(String args[]) { UnaryOperator<Integer> xor = a -> a ^ 1; UnaryOperator<Integer> and = a -> a & 1; Function<Integer, Integer> compose = xor.compose(and); System.out.println(compose.apply(231)); }}", "e": 2779, "s": 2425, "text": null }, { "code": null, "e": 2782, "s": 2779, "text": "0\n" }, { "code": null, "e": 2790, "s": 2782, "text": "psil123" }, { "code": null, "e": 2803, "s": 2790, "text": "Akanksha_Rai" }, { "code": null, "e": 2823, "s": 2803, "text": "Java - util package" }, { "code": null, "e": 2830, "s": 2823, "text": "Java 8" }, { "code": null, "e": 2842, "s": 2830, "text": "java-basics" }, { "code": null, "e": 2870, "s": 2842, "text": "Java-Functional Programming" }, { "code": null, "e": 2886, "s": 2870, "text": "java-interfaces" }, { "code": null, "e": 2891, "s": 2886, "text": "Java" }, { "code": null, "e": 2896, "s": 2891, "text": "Java" } ]
How to set the Password Character for MaskedTextBox in C#?
26 Jul, 2019 In C#, MaskedTextBox control gives a validation procedure for the user input on the form like date, phone numbers, etc. Or in other words, it is used to provide a mask which differentiates between proper and improper user input. In MaskedTextBox control, you are allowed to set the character which displays when we enter sensitive data like password in the MaskedTextBox using PasswordChar Property provided by the MaskedTextBox control.If the value of this property is set to non-null character, then the MaskedTextBox will display this character for all input, and if the value of this property is set to null, then it will not display anything in the MaskedTextBox control. You can set this property in two different ways: 1. Design-Time: It is the easiest way to set the value of PasswordChar property of MaskedTextBox control as shown in the following steps: Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp Step 2: Next, drag and drop the MaskedTextBox control from the toolbox on the form as shown in the below image: Step 3: After drag and drop you will go to the properties of the MaskedTextBox and set the value of PasswordChar property of MaskedTextBox control as shown in the below image:Output: Output: 2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the value of PasswordChar property of the MaskedTextBox control programmatically with the help of given syntax: public char PasswordChar { get; set; } Here, the Char represents the password character value. The following steps show how to set the value of PasswordChar property of the MaskedTextBox control dynamically: Step 1: Create a MaskedTextBox using the MaskedTextBox() constructor is provided by the MaskedTextBox class.// Creating a MaskedTextBox MaskedTextBox m = new MaskedTextBox(); // Creating a MaskedTextBox MaskedTextBox m = new MaskedTextBox(); Step 2: After creating MaskedTextBox, set the PasswordChar property of the MaskedTextBox provided by the MaskedTextBox class.// Setting the PasswordChar property m.PasswordChar = '#'; // Setting the PasswordChar property m.PasswordChar = '#'; Step 3: And last add this MaskedTextBox control to the form using the following statement:// Adding MaskedTextBox control on the form this.Controls.Add(m); Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp39 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the Label Label l1 = new Label(); l1.Location = new Point(413, 98); l1.Size = new Size(176, 20); l1.Text = " Example"; l1.Font = new Font("Bell MT", 12); // Adding label on the form this.Controls.Add(l1); // Creating and setting the // properties of the Label Label l2 = new Label(); l2.Location = new Point(242, 135); l2.Size = new Size(126, 20); l2.Text = "Enter Passcode:"; l2.Font = new Font("Bell MT", 12); // Adding label on the form this.Controls.Add(l2); // Creating and setting the // properties of MaskedTextBox MaskedTextBox m = new MaskedTextBox(); m.Location = new Point(374, 137); m.Mask = "000000000"; m.Size = new Size(176, 20); m.Name = "MyBox"; m.BorderStyle = BorderStyle.Fixed3D; m.PasswordChar = '#'; m.Font = new Font("Bell MT", 18); // Adding MaskedTextBox // control on the form this.Controls.Add(m); }}}Output: // Adding MaskedTextBox control on the form this.Controls.Add(m); Example: using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp39 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the Label Label l1 = new Label(); l1.Location = new Point(413, 98); l1.Size = new Size(176, 20); l1.Text = " Example"; l1.Font = new Font("Bell MT", 12); // Adding label on the form this.Controls.Add(l1); // Creating and setting the // properties of the Label Label l2 = new Label(); l2.Location = new Point(242, 135); l2.Size = new Size(126, 20); l2.Text = "Enter Passcode:"; l2.Font = new Font("Bell MT", 12); // Adding label on the form this.Controls.Add(l2); // Creating and setting the // properties of MaskedTextBox MaskedTextBox m = new MaskedTextBox(); m.Location = new Point(374, 137); m.Mask = "000000000"; m.Size = new Size(176, 20); m.Name = "MyBox"; m.BorderStyle = BorderStyle.Fixed3D; m.PasswordChar = '#'; m.Font = new Font("Bell MT", 18); // Adding MaskedTextBox // control on the form this.Controls.Add(m); }}} Output: CSharp-Windows-Forms-Namespace C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples Introduction to .NET Framework C# | Delegates C# | Multiple inheritance using interfaces Differences Between .NET Core and .NET Framework C# | Method Overriding C# | Data Types C# | Constructors C# | Class and Object Extension Method in C#
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Jul, 2019" }, { "code": null, "e": 754, "s": 28, "text": "In C#, MaskedTextBox control gives a validation procedure for the user input on the form like date, phone numbers, etc. Or in other words, it is used to provide a mask which differentiates between proper and improper user input. In MaskedTextBox control, you are allowed to set the character which displays when we enter sensitive data like password in the MaskedTextBox using PasswordChar Property provided by the MaskedTextBox control.If the value of this property is set to non-null character, then the MaskedTextBox will display this character for all input, and if the value of this property is set to null, then it will not display anything in the MaskedTextBox control. You can set this property in two different ways:" }, { "code": null, "e": 892, "s": 754, "text": "1. Design-Time: It is the easiest way to set the value of PasswordChar property of MaskedTextBox control as shown in the following steps:" }, { "code": null, "e": 1008, "s": 892, "text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp" }, { "code": null, "e": 1120, "s": 1008, "text": "Step 2: Next, drag and drop the MaskedTextBox control from the toolbox on the form as shown in the below image:" }, { "code": null, "e": 1303, "s": 1120, "text": "Step 3: After drag and drop you will go to the properties of the MaskedTextBox and set the value of PasswordChar property of MaskedTextBox control as shown in the below image:Output:" }, { "code": null, "e": 1311, "s": 1303, "text": "Output:" }, { "code": null, "e": 1515, "s": 1311, "text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the value of PasswordChar property of the MaskedTextBox control programmatically with the help of given syntax:" }, { "code": null, "e": 1554, "s": 1515, "text": "public char PasswordChar { get; set; }" }, { "code": null, "e": 1723, "s": 1554, "text": "Here, the Char represents the password character value. The following steps show how to set the value of PasswordChar property of the MaskedTextBox control dynamically:" }, { "code": null, "e": 1899, "s": 1723, "text": "Step 1: Create a MaskedTextBox using the MaskedTextBox() constructor is provided by the MaskedTextBox class.// Creating a MaskedTextBox\nMaskedTextBox m = new MaskedTextBox();\n" }, { "code": null, "e": 1967, "s": 1899, "text": "// Creating a MaskedTextBox\nMaskedTextBox m = new MaskedTextBox();\n" }, { "code": null, "e": 2152, "s": 1967, "text": "Step 2: After creating MaskedTextBox, set the PasswordChar property of the MaskedTextBox provided by the MaskedTextBox class.// Setting the PasswordChar property\nm.PasswordChar = '#';\n" }, { "code": null, "e": 2212, "s": 2152, "text": "// Setting the PasswordChar property\nm.PasswordChar = '#';\n" }, { "code": null, "e": 3887, "s": 2212, "text": "Step 3: And last add this MaskedTextBox control to the form using the following statement:// Adding MaskedTextBox control on the form\nthis.Controls.Add(m);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp39 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the Label Label l1 = new Label(); l1.Location = new Point(413, 98); l1.Size = new Size(176, 20); l1.Text = \" Example\"; l1.Font = new Font(\"Bell MT\", 12); // Adding label on the form this.Controls.Add(l1); // Creating and setting the // properties of the Label Label l2 = new Label(); l2.Location = new Point(242, 135); l2.Size = new Size(126, 20); l2.Text = \"Enter Passcode:\"; l2.Font = new Font(\"Bell MT\", 12); // Adding label on the form this.Controls.Add(l2); // Creating and setting the // properties of MaskedTextBox MaskedTextBox m = new MaskedTextBox(); m.Location = new Point(374, 137); m.Mask = \"000000000\"; m.Size = new Size(176, 20); m.Name = \"MyBox\"; m.BorderStyle = BorderStyle.Fixed3D; m.PasswordChar = '#'; m.Font = new Font(\"Bell MT\", 18); // Adding MaskedTextBox // control on the form this.Controls.Add(m); }}}Output:" }, { "code": null, "e": 3954, "s": 3887, "text": "// Adding MaskedTextBox control on the form\nthis.Controls.Add(m);\n" }, { "code": null, "e": 3963, "s": 3954, "text": "Example:" }, { "code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp39 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the Label Label l1 = new Label(); l1.Location = new Point(413, 98); l1.Size = new Size(176, 20); l1.Text = \" Example\"; l1.Font = new Font(\"Bell MT\", 12); // Adding label on the form this.Controls.Add(l1); // Creating and setting the // properties of the Label Label l2 = new Label(); l2.Location = new Point(242, 135); l2.Size = new Size(126, 20); l2.Text = \"Enter Passcode:\"; l2.Font = new Font(\"Bell MT\", 12); // Adding label on the form this.Controls.Add(l2); // Creating and setting the // properties of MaskedTextBox MaskedTextBox m = new MaskedTextBox(); m.Location = new Point(374, 137); m.Mask = \"000000000\"; m.Size = new Size(176, 20); m.Name = \"MyBox\"; m.BorderStyle = BorderStyle.Fixed3D; m.PasswordChar = '#'; m.Font = new Font(\"Bell MT\", 18); // Adding MaskedTextBox // control on the form this.Controls.Add(m); }}}", "e": 5467, "s": 3963, "text": null }, { "code": null, "e": 5475, "s": 5467, "text": "Output:" }, { "code": null, "e": 5506, "s": 5475, "text": "CSharp-Windows-Forms-Namespace" }, { "code": null, "e": 5509, "s": 5506, "text": "C#" }, { "code": null, "e": 5607, "s": 5509, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5635, "s": 5607, "text": "C# Dictionary with examples" }, { "code": null, "e": 5666, "s": 5635, "text": "Introduction to .NET Framework" }, { "code": null, "e": 5681, "s": 5666, "text": "C# | Delegates" }, { "code": null, "e": 5724, "s": 5681, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 5773, "s": 5724, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 5796, "s": 5773, "text": "C# | Method Overriding" }, { "code": null, "e": 5812, "s": 5796, "text": "C# | Data Types" }, { "code": null, "e": 5830, "s": 5812, "text": "C# | Constructors" }, { "code": null, "e": 5852, "s": 5830, "text": "C# | Class and Object" } ]
Lex program to count the number of lines, spaces and tabs
22 Mar, 2021 Lex is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language.Let’s the how to count the number of lines, spaces and tabs using Lex. Example: Input: Geeks for Geeks gfg gfg Output: No. of lines=2 No. of spaces=3 No. of tabs=1 No. of other characters=19 Input: Hello How are you? Output: No. of lines=2 No. of spaces=4 No. of tabs=1 No. of other characters=15 Below is the implementation: C /*lex code to count the number of lines, tabs and spaces used in the input*/ %{#include<stdio.h>int lc=0, sc=0, tc=0, ch=0; /*Global variables*/%} /*Rule Section*/%%\n lc++; //line counter([ ])+ sc++; //space counter\t tc++; //tab counter. ch++; //characters counter%% int main(){ // The function that starts the analysis yylex(); printf("\nNo. of lines=%d", lc); printf("\nNo. of spaces=%d", sc); printf("\nNo. of tabs=%d", tc); printf("\nNo. of other characters=%d", ch); } Output: ankita_chandra architgwl2000 Lex program C Language Compiler Design Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Function Pointer in C Multidimensional Arrays in C / C++ Different Methods to Reverse a String in C++ Left Shift and Right Shift Operators in C/C++ Issues in the design of a code generator Three address code in Compiler Phases of a Compiler Peephole Optimization in Compiler Design Code Optimization in Compiler Design
[ { "code": null, "e": 53, "s": 25, "text": "\n22 Mar, 2021" }, { "code": null, "e": 376, "s": 53, "text": "Lex is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language.Let’s the how to count the number of lines, spaces and tabs using Lex. Example: " }, { "code": null, "e": 616, "s": 376, "text": "Input:\nGeeks for Geeks \ngfg gfg\n\nOutput:\nNo. of lines=2 \nNo. of spaces=3 \nNo. of tabs=1 \nNo. of other characters=19\n\nInput:\nHello\nHow are you?\n\nOutput:\nNo. of lines=2 \nNo. of spaces=4 \nNo. of tabs=1 \nNo. of other characters=15" }, { "code": null, "e": 648, "s": 616, "text": " Below is the implementation: " }, { "code": null, "e": 650, "s": 648, "text": "C" }, { "code": "/*lex code to count the number of lines, tabs and spaces used in the input*/ %{#include<stdio.h>int lc=0, sc=0, tc=0, ch=0; /*Global variables*/%} /*Rule Section*/%%\\n lc++; //line counter([ ])+ sc++; //space counter\\t tc++; //tab counter. ch++; //characters counter%% int main(){ // The function that starts the analysis yylex(); printf(\"\\nNo. of lines=%d\", lc); printf(\"\\nNo. of spaces=%d\", sc); printf(\"\\nNo. of tabs=%d\", tc); printf(\"\\nNo. of other characters=%d\", ch); }", "e": 1161, "s": 650, "text": null }, { "code": null, "e": 1171, "s": 1161, "text": "Output: " }, { "code": null, "e": 1188, "s": 1173, "text": "ankita_chandra" }, { "code": null, "e": 1202, "s": 1188, "text": "architgwl2000" }, { "code": null, "e": 1214, "s": 1202, "text": "Lex program" }, { "code": null, "e": 1225, "s": 1214, "text": "C Language" }, { "code": null, "e": 1241, "s": 1225, "text": "Compiler Design" }, { "code": null, "e": 1339, "s": 1241, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1356, "s": 1339, "text": "Substring in C++" }, { "code": null, "e": 1378, "s": 1356, "text": "Function Pointer in C" }, { "code": null, "e": 1413, "s": 1378, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 1458, "s": 1413, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 1504, "s": 1458, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 1545, "s": 1504, "text": "Issues in the design of a code generator" }, { "code": null, "e": 1576, "s": 1545, "text": "Three address code in Compiler" }, { "code": null, "e": 1597, "s": 1576, "text": "Phases of a Compiler" }, { "code": null, "e": 1638, "s": 1597, "text": "Peephole Optimization in Compiler Design" } ]
Vigenère Cipher
05 Jul, 2022 Vigenere Cipher is a method of encrypting alphabetic text. It uses a simple form of polyalphabetic substitution. A polyalphabetic cipher is any cipher based on substitution, using multiple substitution alphabets. The encryption of the original text is done using the Vigenère square or Vigenère table. The table consists of the alphabets written out 26 times in different rows, each alphabet shifted cyclically to the left compared to the previous alphabet, corresponding to the 26 possible Caesar Ciphers. At different points in the encryption process, the cipher uses a different alphabet from one of the rows. The alphabet used at each point depends on a repeating keyword. Example: Input : Plaintext : GEEKSFORGEEKS Keyword : AYUSH Output : Ciphertext : GCYCZFMLYLEIM For generating key, the given keyword is repeated in a circular manner until it matches the length of the plain text. The keyword "AYUSH" generates the key "AYUSHAYUSHAYU" The plain text is then encrypted using the process explained below. Encryption: The first letter of the plaintext, G is paired with A, the first letter of the key. So use row G and column A of the Vigenère square, namely G. Similarly, for the second letter of the plaintext, the second letter of the key is used, the letter at row E, and column Y is C. The rest of the plaintext is enciphered in a similar fashion. Table to encrypt – Geeks Decryption:Decryption is performed by going to the row in the table corresponding to the key, finding the position of the ciphertext letter in this row, and then using the column’s label as the plaintext. For example, in row A (from AYUSH), the ciphertext G appears in column G, which is the first plaintext letter. Next, we go to row Y (from AYUSH), locate the ciphertext C which is found in column E, thus E is the second plaintext letter. A more easy implementation could be to visualize Vigenère algebraically by converting [A-Z] into numbers [0–25]. Encryption The plaintext(P) and key(K) are added modulo 26. Ei = (Pi + Ki) mod 26 Decryption Di = (Ei - Ki + 26) mod 26 Note: Di denotes the offset of the i-th character of the plaintext. Like offset of A is 0 and of B is 1 and so on. Below is the implementation of the idea. C++ Java Python3 C# Javascript // C++ code to implement Vigenere Cipher#include<bits/stdc++.h>using namespace std; // This function generates the key in// a cyclic manner until it's length isi'nt// equal to the length of original textstring generateKey(string str, string key){ int x = str.size(); for (int i = 0; ; i++) { if (x == i) i = 0; if (key.size() == str.size()) break; key.push_back(key[i]); } return key;} // This function returns the encrypted text// generated with the help of the keystring cipherText(string str, string key){ string cipher_text; for (int i = 0; i < str.size(); i++) { // converting in range 0-25 char x = (str[i] + key[i]) %26; // convert into alphabets(ASCII) x += 'A'; cipher_text.push_back(x); } return cipher_text;} // This function decrypts the encrypted text// and returns the original textstring originalText(string cipher_text, string key){ string orig_text; for (int i = 0 ; i < cipher_text.size(); i++) { // converting in range 0-25 char x = (cipher_text[i] - key[i] + 26) %26; // convert into alphabets(ASCII) x += 'A'; orig_text.push_back(x); } return orig_text;} // Driver program to test the above functionint main(){ string str = "GEEKSFORGEEKS"; string keyword = "AYUSH"; string key = generateKey(str, keyword); string cipher_text = cipherText(str, key); cout << "Ciphertext : " << cipher_text << "\n"; cout << "Original/Decrypted Text : " << originalText(cipher_text, key); return 0;} // Java code to implement Vigenere Cipher class GFG{ // This function generates the key in// a cyclic manner until it's length isi'nt// equal to the length of original textstatic String generateKey(String str, String key){ int x = str.length(); for (int i = 0; ; i++) { if (x == i) i = 0; if (key.length() == str.length()) break; key+=(key.charAt(i)); } return key;} // This function returns the encrypted text// generated with the help of the keystatic String cipherText(String str, String key){ String cipher_text=""; for (int i = 0; i < str.length(); i++) { // converting in range 0-25 int x = (str.charAt(i) + key.charAt(i)) %26; // convert into alphabets(ASCII) x += 'A'; cipher_text+=(char)(x); } return cipher_text;} // This function decrypts the encrypted text// and returns the original textstatic String originalText(String cipher_text, String key){ String orig_text=""; for (int i = 0 ; i < cipher_text.length() && i < key.length(); i++) { // converting in range 0-25 int x = (cipher_text.charAt(i) - key.charAt(i) + 26) %26; // convert into alphabets(ASCII) x += 'A'; orig_text+=(char)(x); } return orig_text;} // This function will convert the lower case character to Upper casestatic String LowerToUpper(String s){ StringBuffer str =new StringBuffer(s); for(int i = 0; i < s.length(); i++) { if(Character.isLowerCase(s.charAt(i))) { str.setCharAt(i, Character.toUpperCase(s.charAt(i))); } } s = str.toString(); return s;} // Driver codepublic static void main(String[] args){ String Str = "GEEKSFORGEEKS"; String Keyword = "AYUSH"; String str = LowerToUpper(Str); String keyword = LowerToUpper(Keyword); String key = generateKey(str, keyword); String cipher_text = cipherText(str, key); System.out.println("Ciphertext : " + cipher_text + "\n"); System.out.println("Original/Decrypted Text : " + originalText(cipher_text, key)); }} // This code has been contributed by 29AjayKumar # Python code to implement# Vigenere Cipher # This function generates the# key in a cyclic manner until# it's length isn't equal to# the length of original textdef generateKey(string, key): key = list(key) if len(string) == len(key): return(key) else: for i in range(len(string) - len(key)): key.append(key[i % len(key)]) return("" . join(key)) # This function returns the# encrypted text generated# with the help of the keydef cipherText(string, key): cipher_text = [] for i in range(len(string)): x = (ord(string[i]) + ord(key[i])) % 26 x += ord('A') cipher_text.append(chr(x)) return("" . join(cipher_text)) # This function decrypts the# encrypted text and returns# the original textdef originalText(cipher_text, key): orig_text = [] for i in range(len(cipher_text)): x = (ord(cipher_text[i]) - ord(key[i]) + 26) % 26 x += ord('A') orig_text.append(chr(x)) return("" . join(orig_text)) # Driver codeif __name__ == "__main__": string = "GEEKSFORGEEKS" keyword = "AYUSH" key = generateKey(string, keyword) cipher_text = cipherText(string,key) print("Ciphertext :", cipher_text) print("Original/Decrypted Text :", originalText(cipher_text, key)) # This code is contributed# by Pratik Somwanshi // C# code to implement Vigenere Cipherusing System; class GFG{ // This function generates the key in// a cyclic manner until it's length isi'nt// equal to the length of original textstatic String generateKey(String str, String key){ int x = str.Length; for (int i = 0; ; i++) { if (x == i) i = 0; if (key.Length == str.Length) break; key+=(key[i]); } return key;} // This function returns the encrypted text// generated with the help of the keystatic String cipherText(String str, String key){ String cipher_text=""; for (int i = 0; i < str.Length; i++) { // converting in range 0-25 int x = (str[i] + key[i]) %26; // convert into alphabets(ASCII) x += 'A'; cipher_text+=(char)(x); } return cipher_text;} // This function decrypts the encrypted text// and returns the original textstatic String originalText(String cipher_text, String key){ String orig_text=""; for (int i = 0 ; i < cipher_text.Length && i < key.Length; i++) { // converting in range 0-25 int x = (cipher_text[i] - key[i] + 26) %26; // convert into alphabets(ASCII) x += 'A'; orig_text+=(char)(x); } return orig_text;} // Driver codepublic static void Main(String[] args){ String str = "GEEKSFORGEEKS"; String keyword = "AYUSH"; String key = generateKey(str, keyword); String cipher_text = cipherText(str, key); Console.WriteLine("Ciphertext : " + cipher_text + "\n"); Console.WriteLine("Original/Decrypted Text : " + originalText(cipher_text, key)); }} /* This code contributed by PrinciRaj1992 */ <script> // JavaScript code to implement Vigenere Cipher // This function generates the key in// a cyclic manner until it's length isi'nt// equal to the length of original textfunction generateKey(str,key){ key=key.split(""); if(str.length == key.length) return key.join(""); else { let temp=key.length; for (let i = 0;i<(str.length-temp) ; i++) { key.push(key[i % ((key).length)]) } } return key.join("");} // This function returns the encrypted text// generated with the help of the keyfunction cipherText(str,key){ let cipher_text=""; for (let i = 0; i < str.length; i++) { // converting in range 0-25 let x = (str[i].charCodeAt(0) + key[i].charCodeAt(0)) %26; // convert into alphabets(ASCII) x += 'A'.charCodeAt(0); cipher_text+=String.fromCharCode(x); } return cipher_text;} // This function decrypts the encrypted text// and returns the original textfunction originalText(cipher_text,key){ let orig_text=""; for (let i = 0 ; i < cipher_text.length ; i++) { // converting in range 0-25 let x = (cipher_text[i].charCodeAt(0) - key[i].charCodeAt(0) + 26) %26; // convert into alphabets(ASCII) x += 'A'.charCodeAt(0); orig_text+=String.fromCharCode(x); } return orig_text;} // This function will convert the lower// case character to Upper casefunction LowerToUpper(s){ let str =(s).split(""); for(let i = 0; i < s.length; i++) { if(s[i] == s[i].toLowerCase()) { str[i] = s[i].toUpperCase(); } } s = str.toString(); return s;} // Driver codelet str = "GEEKSFORGEEKS";let keyword = "AYUSH"; let key = generateKey(str, keyword); let cipher_text = cipherText(str, key); document.write("Ciphertext : " + cipher_text + "<br><br>"); document.write("Original/Decrypted Text : " + originalText(cipher_text, key)+"<br>"); // This code is contributed by rag2127 </script> Ciphertext : GCYCZFMLYLEIM Original/Decrypted Text : GEEKSFORGEEKS This article is contributed by Ayush Khanduri. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. PratikSomwanshi 29AjayKumar princiraj1992 Akanksha_Rai Villan anonymous007 rag2127 kumaripunam984122 UMADEVIRUCS18323 hardikkoriintern cryptography Strings Technical Scripter Strings cryptography Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Length of the longest substring without repeating characters Convert string to char array in C++ Check whether two strings are anagram of each other Top 50 String Coding Problems for Interviews Reverse words in a given string What is Data Structure: Types, Classifications and Applications Print all the duplicates in the input string Reverse string in Python (6 different ways) Remove duplicates from a given string Array of Strings in C++ - 5 Different Ways to Create
[ { "code": null, "e": 54, "s": 26, "text": "\n05 Jul, 2022" }, { "code": null, "e": 358, "s": 54, "text": "Vigenere Cipher is a method of encrypting alphabetic text. It uses a simple form of polyalphabetic substitution. A polyalphabetic cipher is any cipher based on substitution, using multiple substitution alphabets. The encryption of the original text is done using the Vigenère square or Vigenère table." }, { "code": null, "e": 563, "s": 358, "text": "The table consists of the alphabets written out 26 times in different rows, each alphabet shifted cyclically to the left compared to the previous alphabet, corresponding to the 26 possible Caesar Ciphers." }, { "code": null, "e": 669, "s": 563, "text": "At different points in the encryption process, the cipher uses a different alphabet from one of the rows." }, { "code": null, "e": 733, "s": 669, "text": "The alphabet used at each point depends on a repeating keyword." }, { "code": null, "e": 743, "s": 733, "text": "Example: " }, { "code": null, "e": 1088, "s": 743, "text": "Input : Plaintext : GEEKSFORGEEKS\n Keyword : AYUSH\nOutput : Ciphertext : GCYCZFMLYLEIM\nFor generating key, the given keyword is repeated\nin a circular manner until it matches the length of \nthe plain text.\nThe keyword \"AYUSH\" generates the key \"AYUSHAYUSHAYU\"\nThe plain text is then encrypted using the process \nexplained below." }, { "code": null, "e": 1100, "s": 1088, "text": "Encryption:" }, { "code": null, "e": 1437, "s": 1100, "text": "The first letter of the plaintext, G is paired with A, the first letter of the key. So use row G and column A of the Vigenère square, namely G. Similarly, for the second letter of the plaintext, the second letter of the key is used, the letter at row E, and column Y is C. The rest of the plaintext is enciphered in a similar fashion. " }, { "code": null, "e": 1462, "s": 1437, "text": "Table to encrypt – Geeks" }, { "code": null, "e": 1904, "s": 1462, "text": "Decryption:Decryption is performed by going to the row in the table corresponding to the key, finding the position of the ciphertext letter in this row, and then using the column’s label as the plaintext. For example, in row A (from AYUSH), the ciphertext G appears in column G, which is the first plaintext letter. Next, we go to row Y (from AYUSH), locate the ciphertext C which is found in column E, thus E is the second plaintext letter." }, { "code": null, "e": 2019, "s": 1904, "text": "A more easy implementation could be to visualize Vigenère algebraically by converting [A-Z] into numbers [0–25]. " }, { "code": null, "e": 2140, "s": 2019, "text": "Encryption\nThe plaintext(P) and key(K) are added modulo 26.\nEi = (Pi + Ki) mod 26\n\nDecryption\nDi = (Ei - Ki + 26) mod 26" }, { "code": null, "e": 2255, "s": 2140, "text": "Note: Di denotes the offset of the i-th character of the plaintext. Like offset of A is 0 and of B is 1 and so on." }, { "code": null, "e": 2297, "s": 2255, "text": "Below is the implementation of the idea. " }, { "code": null, "e": 2301, "s": 2297, "text": "C++" }, { "code": null, "e": 2306, "s": 2301, "text": "Java" }, { "code": null, "e": 2314, "s": 2306, "text": "Python3" }, { "code": null, "e": 2317, "s": 2314, "text": "C#" }, { "code": null, "e": 2328, "s": 2317, "text": "Javascript" }, { "code": "// C++ code to implement Vigenere Cipher#include<bits/stdc++.h>using namespace std; // This function generates the key in// a cyclic manner until it's length isi'nt// equal to the length of original textstring generateKey(string str, string key){ int x = str.size(); for (int i = 0; ; i++) { if (x == i) i = 0; if (key.size() == str.size()) break; key.push_back(key[i]); } return key;} // This function returns the encrypted text// generated with the help of the keystring cipherText(string str, string key){ string cipher_text; for (int i = 0; i < str.size(); i++) { // converting in range 0-25 char x = (str[i] + key[i]) %26; // convert into alphabets(ASCII) x += 'A'; cipher_text.push_back(x); } return cipher_text;} // This function decrypts the encrypted text// and returns the original textstring originalText(string cipher_text, string key){ string orig_text; for (int i = 0 ; i < cipher_text.size(); i++) { // converting in range 0-25 char x = (cipher_text[i] - key[i] + 26) %26; // convert into alphabets(ASCII) x += 'A'; orig_text.push_back(x); } return orig_text;} // Driver program to test the above functionint main(){ string str = \"GEEKSFORGEEKS\"; string keyword = \"AYUSH\"; string key = generateKey(str, keyword); string cipher_text = cipherText(str, key); cout << \"Ciphertext : \" << cipher_text << \"\\n\"; cout << \"Original/Decrypted Text : \" << originalText(cipher_text, key); return 0;}", "e": 3934, "s": 2328, "text": null }, { "code": "// Java code to implement Vigenere Cipher class GFG{ // This function generates the key in// a cyclic manner until it's length isi'nt// equal to the length of original textstatic String generateKey(String str, String key){ int x = str.length(); for (int i = 0; ; i++) { if (x == i) i = 0; if (key.length() == str.length()) break; key+=(key.charAt(i)); } return key;} // This function returns the encrypted text// generated with the help of the keystatic String cipherText(String str, String key){ String cipher_text=\"\"; for (int i = 0; i < str.length(); i++) { // converting in range 0-25 int x = (str.charAt(i) + key.charAt(i)) %26; // convert into alphabets(ASCII) x += 'A'; cipher_text+=(char)(x); } return cipher_text;} // This function decrypts the encrypted text// and returns the original textstatic String originalText(String cipher_text, String key){ String orig_text=\"\"; for (int i = 0 ; i < cipher_text.length() && i < key.length(); i++) { // converting in range 0-25 int x = (cipher_text.charAt(i) - key.charAt(i) + 26) %26; // convert into alphabets(ASCII) x += 'A'; orig_text+=(char)(x); } return orig_text;} // This function will convert the lower case character to Upper casestatic String LowerToUpper(String s){ StringBuffer str =new StringBuffer(s); for(int i = 0; i < s.length(); i++) { if(Character.isLowerCase(s.charAt(i))) { str.setCharAt(i, Character.toUpperCase(s.charAt(i))); } } s = str.toString(); return s;} // Driver codepublic static void main(String[] args){ String Str = \"GEEKSFORGEEKS\"; String Keyword = \"AYUSH\"; String str = LowerToUpper(Str); String keyword = LowerToUpper(Keyword); String key = generateKey(str, keyword); String cipher_text = cipherText(str, key); System.out.println(\"Ciphertext : \" + cipher_text + \"\\n\"); System.out.println(\"Original/Decrypted Text : \" + originalText(cipher_text, key)); }} // This code has been contributed by 29AjayKumar", "e": 6143, "s": 3934, "text": null }, { "code": "# Python code to implement# Vigenere Cipher # This function generates the# key in a cyclic manner until# it's length isn't equal to# the length of original textdef generateKey(string, key): key = list(key) if len(string) == len(key): return(key) else: for i in range(len(string) - len(key)): key.append(key[i % len(key)]) return(\"\" . join(key)) # This function returns the# encrypted text generated# with the help of the keydef cipherText(string, key): cipher_text = [] for i in range(len(string)): x = (ord(string[i]) + ord(key[i])) % 26 x += ord('A') cipher_text.append(chr(x)) return(\"\" . join(cipher_text)) # This function decrypts the# encrypted text and returns# the original textdef originalText(cipher_text, key): orig_text = [] for i in range(len(cipher_text)): x = (ord(cipher_text[i]) - ord(key[i]) + 26) % 26 x += ord('A') orig_text.append(chr(x)) return(\"\" . join(orig_text)) # Driver codeif __name__ == \"__main__\": string = \"GEEKSFORGEEKS\" keyword = \"AYUSH\" key = generateKey(string, keyword) cipher_text = cipherText(string,key) print(\"Ciphertext :\", cipher_text) print(\"Original/Decrypted Text :\", originalText(cipher_text, key)) # This code is contributed# by Pratik Somwanshi", "e": 7520, "s": 6143, "text": null }, { "code": "// C# code to implement Vigenere Cipherusing System; class GFG{ // This function generates the key in// a cyclic manner until it's length isi'nt// equal to the length of original textstatic String generateKey(String str, String key){ int x = str.Length; for (int i = 0; ; i++) { if (x == i) i = 0; if (key.Length == str.Length) break; key+=(key[i]); } return key;} // This function returns the encrypted text// generated with the help of the keystatic String cipherText(String str, String key){ String cipher_text=\"\"; for (int i = 0; i < str.Length; i++) { // converting in range 0-25 int x = (str[i] + key[i]) %26; // convert into alphabets(ASCII) x += 'A'; cipher_text+=(char)(x); } return cipher_text;} // This function decrypts the encrypted text// and returns the original textstatic String originalText(String cipher_text, String key){ String orig_text=\"\"; for (int i = 0 ; i < cipher_text.Length && i < key.Length; i++) { // converting in range 0-25 int x = (cipher_text[i] - key[i] + 26) %26; // convert into alphabets(ASCII) x += 'A'; orig_text+=(char)(x); } return orig_text;} // Driver codepublic static void Main(String[] args){ String str = \"GEEKSFORGEEKS\"; String keyword = \"AYUSH\"; String key = generateKey(str, keyword); String cipher_text = cipherText(str, key); Console.WriteLine(\"Ciphertext : \" + cipher_text + \"\\n\"); Console.WriteLine(\"Original/Decrypted Text : \" + originalText(cipher_text, key)); }} /* This code contributed by PrinciRaj1992 */", "e": 9239, "s": 7520, "text": null }, { "code": "<script> // JavaScript code to implement Vigenere Cipher // This function generates the key in// a cyclic manner until it's length isi'nt// equal to the length of original textfunction generateKey(str,key){ key=key.split(\"\"); if(str.length == key.length) return key.join(\"\"); else { let temp=key.length; for (let i = 0;i<(str.length-temp) ; i++) { key.push(key[i % ((key).length)]) } } return key.join(\"\");} // This function returns the encrypted text// generated with the help of the keyfunction cipherText(str,key){ let cipher_text=\"\"; for (let i = 0; i < str.length; i++) { // converting in range 0-25 let x = (str[i].charCodeAt(0) + key[i].charCodeAt(0)) %26; // convert into alphabets(ASCII) x += 'A'.charCodeAt(0); cipher_text+=String.fromCharCode(x); } return cipher_text;} // This function decrypts the encrypted text// and returns the original textfunction originalText(cipher_text,key){ let orig_text=\"\"; for (let i = 0 ; i < cipher_text.length ; i++) { // converting in range 0-25 let x = (cipher_text[i].charCodeAt(0) - key[i].charCodeAt(0) + 26) %26; // convert into alphabets(ASCII) x += 'A'.charCodeAt(0); orig_text+=String.fromCharCode(x); } return orig_text;} // This function will convert the lower// case character to Upper casefunction LowerToUpper(s){ let str =(s).split(\"\"); for(let i = 0; i < s.length; i++) { if(s[i] == s[i].toLowerCase()) { str[i] = s[i].toUpperCase(); } } s = str.toString(); return s;} // Driver codelet str = \"GEEKSFORGEEKS\";let keyword = \"AYUSH\"; let key = generateKey(str, keyword); let cipher_text = cipherText(str, key); document.write(\"Ciphertext : \" + cipher_text + \"<br><br>\"); document.write(\"Original/Decrypted Text : \" + originalText(cipher_text, key)+\"<br>\"); // This code is contributed by rag2127 </script>", "e": 11309, "s": 9239, "text": null }, { "code": null, "e": 11376, "s": 11309, "text": "Ciphertext : GCYCZFMLYLEIM\nOriginal/Decrypted Text : GEEKSFORGEEKS" }, { "code": null, "e": 11675, "s": 11376, "text": "This article is contributed by Ayush Khanduri. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. " }, { "code": null, "e": 11691, "s": 11675, "text": "PratikSomwanshi" }, { "code": null, "e": 11703, "s": 11691, "text": "29AjayKumar" }, { "code": null, "e": 11717, "s": 11703, "text": "princiraj1992" }, { "code": null, "e": 11730, "s": 11717, "text": "Akanksha_Rai" }, { "code": null, "e": 11737, "s": 11730, "text": "Villan" }, { "code": null, "e": 11750, "s": 11737, "text": "anonymous007" }, { "code": null, "e": 11758, "s": 11750, "text": "rag2127" }, { "code": null, "e": 11776, "s": 11758, "text": "kumaripunam984122" }, { "code": null, "e": 11793, "s": 11776, "text": "UMADEVIRUCS18323" }, { "code": null, "e": 11810, "s": 11793, "text": "hardikkoriintern" }, { "code": null, "e": 11823, "s": 11810, "text": "cryptography" }, { "code": null, "e": 11831, "s": 11823, "text": "Strings" }, { "code": null, "e": 11850, "s": 11831, "text": "Technical Scripter" }, { "code": null, "e": 11858, "s": 11850, "text": "Strings" }, { "code": null, "e": 11871, "s": 11858, "text": "cryptography" }, { "code": null, "e": 11969, "s": 11871, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 12030, "s": 11969, "text": "Length of the longest substring without repeating characters" }, { "code": null, "e": 12066, "s": 12030, "text": "Convert string to char array in C++" }, { "code": null, "e": 12118, "s": 12066, "text": "Check whether two strings are anagram of each other" }, { "code": null, "e": 12163, "s": 12118, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 12195, "s": 12163, "text": "Reverse words in a given string" }, { "code": null, "e": 12259, "s": 12195, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 12304, "s": 12259, "text": "Print all the duplicates in the input string" }, { "code": null, "e": 12348, "s": 12304, "text": "Reverse string in Python (6 different ways)" }, { "code": null, "e": 12386, "s": 12348, "text": "Remove duplicates from a given string" } ]
What is the difference between .py and .pyc files ?
Python compliles the .py files and save it as .pyc file The .pyc contain the compiled bytecode of Python source files, A .pyc is not created for your main program file that you execute (only for imported modules). The .pyc file contains encoded python bytecode. If We Want to import module.The Module calculate Addition of Two Numbers Live Demo def recursive_sum(n): """Function to return the sum of recursive numbers""" if n <= 1: return n else: return n + recursive_sum(n-1) # change this value for a different result number = 16 if number < 0: print("Enter a positive number") else: print("The sum is",recursive_sum(number)) The sum is 136 If you store this program with the name "example",then it will be stored as "example.py" when you run a example.py file,it takes some to create a example.pyc file once the code is executed it first executes .py file where as code is first turned into byte code by the compiler in the form of "example.pyc” file.
[ { "code": null, "e": 1243, "s": 1187, "text": "Python compliles the .py files and save it as .pyc file" }, { "code": null, "e": 1401, "s": 1243, "text": "The .pyc contain the compiled bytecode of Python source files, A .pyc is not created for your main program file that you execute (only for imported modules)." }, { "code": null, "e": 1449, "s": 1401, "text": "The .pyc file contains encoded python bytecode." }, { "code": null, "e": 1522, "s": 1449, "text": "If We Want to import module.The Module calculate Addition of Two Numbers" }, { "code": null, "e": 1533, "s": 1522, "text": " Live Demo" }, { "code": null, "e": 1818, "s": 1533, "text": "def recursive_sum(n):\n\"\"\"Function to return the sum of recursive numbers\"\"\"\nif n <= 1:\nreturn n\nelse:\nreturn n + recursive_sum(n-1)\n\n# change this value for a different result\nnumber = 16\n\nif number < 0:\nprint(\"Enter a positive number\")\nelse:\nprint(\"The sum is\",recursive_sum(number))" }, { "code": null, "e": 1833, "s": 1818, "text": "The sum is 136" }, { "code": null, "e": 2145, "s": 1833, "text": "If you store this program with the name \"example\",then it will be stored as \"example.py\" when you run a example.py file,it takes some to create a example.pyc file once the code is executed it first executes .py file where as code is first turned into byte code by the compiler in the form of \"example.pyc” file." } ]
String.Format() Method in C# with Examples | Set – 3
28 May, 2020 In C#, Format() is a string method. This method is used to replace one or more format items in the specified string with the string representation of a specified object.In other words, this method is used to insert the value of the variable or an object or expression into another string. This method can be overloaded by passing different type of arguments to it. There are total 8 methods in the overload list of the Format() method in which 6 are discussed in Set-1 and Set-2, and remaining are discussed in this article. String.Format(String first, Object second) MethodString.Format(String, params Object[]) MethodString.Format(IFormatProvider, String, Object) Method String.Format(IFormatProvider, String, Object[]) MethodString.Format(String, Object, Object) MethodString.Format(String, Object, Object, Object) MethodString.Format(IFormatProvider, String, Object, Object) Method String.Format(IFormatProvider, String, Object, Object, Object) Method String.Format(String first, Object second) Method String.Format(String, params Object[]) Method String.Format(IFormatProvider, String, Object) Method String.Format(IFormatProvider, String, Object[]) Method String.Format(String, Object, Object) Method String.Format(String, Object, Object, Object) Method String.Format(IFormatProvider, String, Object, Object) Method String.Format(IFormatProvider, String, Object, Object, Object) Method This method is used to replaces the format items in a string with the string representation of two specified objects. A parameter supplies culture-specific formatting information. Syntax : public static string Format (IFormatProvider provider, string format, object arg0, object arg1); Parameter: This method has the following parameters: provider: This parameter is the object that supplies culture-specific formatting information. format: This parameter is the required composite format string. arg0: This parameter is the first object to format. arg1: This parameter is the second object to format. Return Value: This method returns the string. It is a copy of format in which the format items are replaced by the string representation of arg0 and arg1. Example : C# // C# program to illustrate the // String.Format(IFormatProvider,// String, Object, Object) Method using System; public class GFG { // Main method public static void Main(string[] args) { string formatString = "Value: {0,0}\n" + "NOT of Value: {1,0}"; int value1 = 169; System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("es-ES"); string result = String.Format (culture, formatString, value1, ~value1); Console.WriteLine(result); } } Output: Value: 169 NOT of Value: -170 This method is used to replaces the format items in a string with the string representation of three specified objects. An parameter supplies culture-specific formatting information. Syntax : public static string Format (IFormatProvider provider, string format, object arg0, object arg1, object arg2); Parameter: This method has the following parameters: provider: This parameter is the object that supplies culture-specific formatting information. format: This parameter is the required composite format string. arg0: This parameter is the first object to format. arg1: This parameter is the second object to format. arg2: This parameter is the third object to format. Return Value: This method returns the string. It is a copy of format in which the format items are replaced by the string representation of arg0, arg1 and arg2. Example : C# // C# program to illustrate the // String.Format(IFormatProvider,// String, Object, Object, Object) Method using System; public class GFG { // Main method public static void Main(string[] args) { string formatString = "Value 1: {0,0}\n" + "Value 2: {1,0}\n"+ "Sum of Values : {2,0}"; int value1 = 169; int value2 = 961; System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("es-ES"); string result = String.Format (culture, formatString, value1, value2, value1 + value2); Console.WriteLine(result); } } Output: Value 1: 169 Value 2: 961 Sum of Values : 1130 CSharp-method CSharp-string C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Multiple inheritance using interfaces Differences Between .NET Core and .NET Framework Extension Method in C# C# | List Class HashSet in C# with Examples C# | .NET Framework (Basic Architecture and Component Stack) Switch Statement in C# Partial Classes in C# Lambda Expressions in C# Hello World in C#
[ { "code": null, "e": 28, "s": 0, "text": "\n28 May, 2020" }, { "code": null, "e": 318, "s": 28, "text": "In C#, Format() is a string method. This method is used to replace one or more format items in the specified string with the string representation of a specified object.In other words, this method is used to insert the value of the variable or an object or expression into another string." }, { "code": null, "e": 555, "s": 318, "text": "This method can be overloaded by passing different type of arguments to it. There are total 8 methods in the overload list of the Format() method in which 6 are discussed in Set-1 and Set-2, and remaining are discussed in this article. " }, { "code": null, "e": 987, "s": 555, "text": "String.Format(String first, Object second) MethodString.Format(String, params Object[]) MethodString.Format(IFormatProvider, String, Object) Method String.Format(IFormatProvider, String, Object[]) MethodString.Format(String, Object, Object) MethodString.Format(String, Object, Object, Object) MethodString.Format(IFormatProvider, String, Object, Object) Method String.Format(IFormatProvider, String, Object, Object, Object) Method" }, { "code": null, "e": 1037, "s": 987, "text": "String.Format(String first, Object second) Method" }, { "code": null, "e": 1083, "s": 1037, "text": "String.Format(String, params Object[]) Method" }, { "code": null, "e": 1138, "s": 1083, "text": "String.Format(IFormatProvider, String, Object) Method " }, { "code": null, "e": 1194, "s": 1138, "text": "String.Format(IFormatProvider, String, Object[]) Method" }, { "code": null, "e": 1239, "s": 1194, "text": "String.Format(String, Object, Object) Method" }, { "code": null, "e": 1292, "s": 1239, "text": "String.Format(String, Object, Object, Object) Method" }, { "code": null, "e": 1356, "s": 1292, "text": "String.Format(IFormatProvider, String, Object, Object) Method " }, { "code": null, "e": 1426, "s": 1356, "text": "String.Format(IFormatProvider, String, Object, Object, Object) Method" }, { "code": null, "e": 1606, "s": 1426, "text": "This method is used to replaces the format items in a string with the string representation of two specified objects. A parameter supplies culture-specific formatting information." }, { "code": null, "e": 1615, "s": 1606, "text": "Syntax :" }, { "code": null, "e": 1713, "s": 1615, "text": "public static string Format (IFormatProvider provider, string format, object arg0, object arg1);\n" }, { "code": null, "e": 1766, "s": 1713, "text": "Parameter: This method has the following parameters:" }, { "code": null, "e": 1860, "s": 1766, "text": "provider: This parameter is the object that supplies culture-specific formatting information." }, { "code": null, "e": 1924, "s": 1860, "text": "format: This parameter is the required composite format string." }, { "code": null, "e": 1976, "s": 1924, "text": "arg0: This parameter is the first object to format." }, { "code": null, "e": 2029, "s": 1976, "text": "arg1: This parameter is the second object to format." }, { "code": null, "e": 2184, "s": 2029, "text": "Return Value: This method returns the string. It is a copy of format in which the format items are replaced by the string representation of arg0 and arg1." }, { "code": null, "e": 2195, "s": 2184, "text": "Example : " }, { "code": null, "e": 2198, "s": 2195, "text": "C#" }, { "code": "// C# program to illustrate the // String.Format(IFormatProvider,// String, Object, Object) Method using System; public class GFG { // Main method public static void Main(string[] args) { string formatString = \"Value: {0,0}\\n\" + \"NOT of Value: {1,0}\"; int value1 = 169; System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo(\"es-ES\"); string result = String.Format (culture, formatString, value1, ~value1); Console.WriteLine(result); } }", "e": 2813, "s": 2198, "text": null }, { "code": null, "e": 2823, "s": 2815, "text": "Output:" }, { "code": null, "e": 2854, "s": 2823, "text": "Value: 169\nNOT of Value: -170\n" }, { "code": null, "e": 3037, "s": 2854, "text": "This method is used to replaces the format items in a string with the string representation of three specified objects. An parameter supplies culture-specific formatting information." }, { "code": null, "e": 3046, "s": 3037, "text": "Syntax :" }, { "code": null, "e": 3157, "s": 3046, "text": "public static string Format (IFormatProvider provider, string format, object arg0, object arg1, object arg2);\n" }, { "code": null, "e": 3210, "s": 3157, "text": "Parameter: This method has the following parameters:" }, { "code": null, "e": 3304, "s": 3210, "text": "provider: This parameter is the object that supplies culture-specific formatting information." }, { "code": null, "e": 3368, "s": 3304, "text": "format: This parameter is the required composite format string." }, { "code": null, "e": 3420, "s": 3368, "text": "arg0: This parameter is the first object to format." }, { "code": null, "e": 3473, "s": 3420, "text": "arg1: This parameter is the second object to format." }, { "code": null, "e": 3525, "s": 3473, "text": "arg2: This parameter is the third object to format." }, { "code": null, "e": 3686, "s": 3525, "text": "Return Value: This method returns the string. It is a copy of format in which the format items are replaced by the string representation of arg0, arg1 and arg2." }, { "code": null, "e": 3697, "s": 3686, "text": "Example : " }, { "code": null, "e": 3700, "s": 3697, "text": "C#" }, { "code": "// C# program to illustrate the // String.Format(IFormatProvider,// String, Object, Object, Object) Method using System; public class GFG { // Main method public static void Main(string[] args) { string formatString = \"Value 1: {0,0}\\n\" + \"Value 2: {1,0}\\n\"+ \"Sum of Values : {2,0}\"; int value1 = 169; int value2 = 961; System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo(\"es-ES\"); string result = String.Format (culture, formatString, value1, value2, value1 + value2); Console.WriteLine(result); } }", "e": 4403, "s": 3700, "text": null }, { "code": null, "e": 4413, "s": 4405, "text": "Output:" }, { "code": null, "e": 4461, "s": 4413, "text": "Value 1: 169\nValue 2: 961\nSum of Values : 1130\n" }, { "code": null, "e": 4475, "s": 4461, "text": "CSharp-method" }, { "code": null, "e": 4489, "s": 4475, "text": "CSharp-string" }, { "code": null, "e": 4492, "s": 4489, "text": "C#" }, { "code": null, "e": 4590, "s": 4492, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4633, "s": 4590, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 4682, "s": 4633, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 4705, "s": 4682, "text": "Extension Method in C#" }, { "code": null, "e": 4721, "s": 4705, "text": "C# | List Class" }, { "code": null, "e": 4749, "s": 4721, "text": "HashSet in C# with Examples" }, { "code": null, "e": 4810, "s": 4749, "text": "C# | .NET Framework (Basic Architecture and Component Stack)" }, { "code": null, "e": 4833, "s": 4810, "text": "Switch Statement in C#" }, { "code": null, "e": 4855, "s": 4833, "text": "Partial Classes in C#" }, { "code": null, "e": 4880, "s": 4855, "text": "Lambda Expressions in C#" } ]
How to Create Image Overlay Hover using HTML & CSS ?
31 Mar, 2020 In this article, we will go over 5 different types of overlays: left, right, top, bottom, and fade. You are going to need two divs. One will be your overlay div, containing what will show up once the user hovers over the image, and the other will be a container that holds both the image and its overlay. The inner div, which represents the overlay, will have two classes. One that you will use to style all overlays and the other represents the specific overlay type (left, right, up, down, or fade). Your image should be placed outside the inner div (overlay) but inside the outer one (container). Don’t forget to add an alternative text describing the image to assist users that rely on the screen reader. HTML Code: <!DOCTYPE HTML><html> <head> <meta charset="UTF-8"> <title>Image Overlay</title></head> <body> <center> <h1 class="title"> GeeksforGeeks </h1> <b>Image Overlay</b> <br> <br> <div class="container"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200325132558/download311.png" class="image"> <div class="overlay overlayLeft"></div> </div> </center></body> </html> CSS Code: Set the container’s position relative to its normal position and define its width and height. The key to getting the overlay to work is to set its position to absolute. That means its positioned relative to its nearest positioned ancestor, which in this case is the image. So that the overlay isn’t always there and only shows up when the user hovers over the image, set its opacity to zero, meaning completely transparent. Use “background-color” to set the color of your overlay. Use “transition” so that the overlay gradually appears instead of popping up over the image. Since we set the opacity of the overlay to zero, once we hover over the container we want to set that opacity to 1. That means, once the user hovers over the container item, the overlay will appear. <style> body { text-align: center; } h1 { color: green; } .container img { width: 250px; height: 250px; } .container { position: relative; width: 400px; height: auto; }</style> Fade Overlay: Width and height of the overlay are the width and height of the image equal od div image. Once you hover over the image, the overlay appears on top of that image. Program:<!DOCTYPE HTML><html> <head> <meta charset="UTF-8"> <title>Image Overlay</title> <style> body { text-align: center; } h1 { color: green; } .container img { width: 250px; height: 250px; } .container { position: relative; width: 400px; height: auto; } .overlay { position: absolute; transition: all 0.3s ease; opacity: 0; background-color: #9bcd9b; } .container:hover .overlay { opacity: 1; } .overlayFade { height: 250px; width: 250px; top: 0; left: 75px; background-color: #9bcd9b; } </style></head> <body> <center> <h1 class="title"> GeeksforGeeks </h1> <b>Image Overlay</b> <br> <br> <div class="container"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200325132558/download311.png" class="image"> <div class="overlay overlayFade"></div> </div> </center></body> </html> <!DOCTYPE HTML><html> <head> <meta charset="UTF-8"> <title>Image Overlay</title> <style> body { text-align: center; } h1 { color: green; } .container img { width: 250px; height: 250px; } .container { position: relative; width: 400px; height: auto; } .overlay { position: absolute; transition: all 0.3s ease; opacity: 0; background-color: #9bcd9b; } .container:hover .overlay { opacity: 1; } .overlayFade { height: 250px; width: 250px; top: 0; left: 75px; background-color: #9bcd9b; } </style></head> <body> <center> <h1 class="title"> GeeksforGeeks </h1> <b>Image Overlay</b> <br> <br> <div class="container"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200325132558/download311.png" class="image"> <div class="overlay overlayFade"></div> </div> </center></body> </html> Output: Left Overlay: Height of the overlay is the height of the image (100%). Width is zero and set to left. Width is set to 100% once you hover over the image and gradually moves from left to right. Program:<!DOCTYPE HTML><html> <head> <meta charset="UTF-8"> <title>Image Overlay</title> <style> body { text-align: center; } h1 { color: green; } .container img { width: 250px; height: 250px; } .container { position: relative; width: 400px; height: auto; } .overlay { position: absolute; transition: all 0.3s ease; opacity: 0; background-color: #9bcd9b; } .container:hover .overlay { opacity: 1; } .overlayLeft{ height: 100%; width: 0; top: 0; left: 75px; background-color: #9bcd9b;; } .container:hover .overlayLeft{ width: 250px; } </style></head> <body> <center> <h1 class="title"> GeeksforGeeks </h1> <b>Image Overlay</b> <br> <br> <div class="container"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200325132558/download311.png" class="image"> <div class="overlay overlayLeft"></div> </div> </center></body> </html> <!DOCTYPE HTML><html> <head> <meta charset="UTF-8"> <title>Image Overlay</title> <style> body { text-align: center; } h1 { color: green; } .container img { width: 250px; height: 250px; } .container { position: relative; width: 400px; height: auto; } .overlay { position: absolute; transition: all 0.3s ease; opacity: 0; background-color: #9bcd9b; } .container:hover .overlay { opacity: 1; } .overlayLeft{ height: 100%; width: 0; top: 0; left: 75px; background-color: #9bcd9b;; } .container:hover .overlayLeft{ width: 250px; } </style></head> <body> <center> <h1 class="title"> GeeksforGeeks </h1> <b>Image Overlay</b> <br> <br> <div class="container"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200325132558/download311.png" class="image"> <div class="overlay overlayLeft"></div> </div> </center></body> </html> Output: Right Overlay: Height of the overlay is the height of the image (100%). Width is zero and set to right. Width is set to 100% once you hover over the image and gradually moves from right to left. Program:<!DOCTYPE HTML><html> <head> <meta charset="UTF-8"> <title>Image Overlay</title> <style> body { text-align: center; } h1 { color: green; } .container img { width: 250px; height: 250px; } .container { position: relative; width: 400px; height: auto; } .overlay { position: absolute; transition: all 0.3s ease; opacity: 0; background-color: #9bcd9b; } .container:hover .overlay { opacity: 1; } .overlayRight{ height: 100%; width: 0; top: 0; right: 75px; background-color: #9bcd9b;; } .container:hover .overlayRight{ width: 250px; } </style></head> <body> <center> <h1 class="title"> GeeksforGeeks </h1> <b>Image Overlay</b> <br> <br> <div class="container"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200325132558/download311.png" class="image"> <div class="overlay overlayRight"></div> </div> </center></body> </html> <!DOCTYPE HTML><html> <head> <meta charset="UTF-8"> <title>Image Overlay</title> <style> body { text-align: center; } h1 { color: green; } .container img { width: 250px; height: 250px; } .container { position: relative; width: 400px; height: auto; } .overlay { position: absolute; transition: all 0.3s ease; opacity: 0; background-color: #9bcd9b; } .container:hover .overlay { opacity: 1; } .overlayRight{ height: 100%; width: 0; top: 0; right: 75px; background-color: #9bcd9b;; } .container:hover .overlayRight{ width: 250px; } </style></head> <body> <center> <h1 class="title"> GeeksforGeeks </h1> <b>Image Overlay</b> <br> <br> <div class="container"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200325132558/download311.png" class="image"> <div class="overlay overlayRight"></div> </div> </center></body> </html> Output: Top Overlay: Width of the overlay is the width of the image (100%). Height is zero and set to top. Height is set to 100% once you hover over the image and gradually moves from top to bottom. Program:<!DOCTYPE HTML><html> <head> <meta charset="UTF-8"> <title>Image Overlay</title> <style> body { text-align: center; } h1 { color: green; } .container img { width: 250px; height: 250px; } .container { position: relative; width: 400px; height: auto; } .overlay { position: absolute; transition: all 0.3s ease; opacity: 0; background-color: #9bcd9b; } .container:hover .overlay { opacity: 1; } .overlayTop{ width: 250px; height: 0; top: 0; right: 75px; background-color: #9bcd9b;; } .container:hover .overlayTop{ height: 250px; } </style></head> <body> <center> <h1 class="title"> GeeksforGeeks </h1> <b>Image Overlay</b> <br> <br> <div class="container"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200325132558/download311.png" class="image"> <div class="overlay overlayTop"></div> </div> </center></body> </html> <!DOCTYPE HTML><html> <head> <meta charset="UTF-8"> <title>Image Overlay</title> <style> body { text-align: center; } h1 { color: green; } .container img { width: 250px; height: 250px; } .container { position: relative; width: 400px; height: auto; } .overlay { position: absolute; transition: all 0.3s ease; opacity: 0; background-color: #9bcd9b; } .container:hover .overlay { opacity: 1; } .overlayTop{ width: 250px; height: 0; top: 0; right: 75px; background-color: #9bcd9b;; } .container:hover .overlayTop{ height: 250px; } </style></head> <body> <center> <h1 class="title"> GeeksforGeeks </h1> <b>Image Overlay</b> <br> <br> <div class="container"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200325132558/download311.png" class="image"> <div class="overlay overlayTop"></div> </div> </center></body> </html> Output: Bottom Overlay: Width of the overlay is the width of the image (100%). Height is zero and set to bottom. Height is set to 100% once you hover over the image and gradually moves from bottom to top. Program:<!DOCTYPE HTML><html> <head> <meta charset="UTF-8"> <title>Image Overlay</title> <style> body { text-align: center; } h1 { color: green; } .container img { width: 250px; height: 250px; } .container { position: relative; width: 400px; height: auto; } .overlay { position: absolute; transition: all 0.3s ease; opacity: 0; background-color: #9bcd9b; } .container:hover .overlay { opacity: 1; } .overlayBottom{ width: 250px; height: 0; bottom: 0; right: 75px; background-color: #9bcd9b;; } .container:hover .overlayBottom{ height: 255px; } </style></head> <body> <center> <h1 class="title"> GeeksforGeeks </h1> <b>Image Overlay</b> <br> <br> <div class="container"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200325132558/download311.png" class="image"> <div class="overlay overlayBottom"></div> </div> </center></body> </html> <!DOCTYPE HTML><html> <head> <meta charset="UTF-8"> <title>Image Overlay</title> <style> body { text-align: center; } h1 { color: green; } .container img { width: 250px; height: 250px; } .container { position: relative; width: 400px; height: auto; } .overlay { position: absolute; transition: all 0.3s ease; opacity: 0; background-color: #9bcd9b; } .container:hover .overlay { opacity: 1; } .overlayBottom{ width: 250px; height: 0; bottom: 0; right: 75px; background-color: #9bcd9b;; } .container:hover .overlayBottom{ height: 255px; } </style></head> <body> <center> <h1 class="title"> GeeksforGeeks </h1> <b>Image Overlay</b> <br> <br> <div class="container"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200325132558/download311.png" class="image"> <div class="overlay overlayBottom"></div> </div> </center></body> </html> Output: CSS-Misc HTML-Misc CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a Tribute Page using HTML & CSS Types of CSS (Cascading Style Sheet) How to set space between the flexbox ? How to Upload Image into Database and Display it using PHP ? Build a Survey Form using HTML and CSS REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Design a Tribute Page using HTML & CSS
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Mar, 2020" }, { "code": null, "e": 530, "s": 28, "text": "In this article, we will go over 5 different types of overlays: left, right, top, bottom, and fade. You are going to need two divs. One will be your overlay div, containing what will show up once the user hovers over the image, and the other will be a container that holds both the image and its overlay. The inner div, which represents the overlay, will have two classes. One that you will use to style all overlays and the other represents the specific overlay type (left, right, up, down, or fade)." }, { "code": null, "e": 737, "s": 530, "text": "Your image should be placed outside the inner div (overlay) but inside the outer one (container). Don’t forget to add an alternative text describing the image to assist users that rely on the screen reader." }, { "code": null, "e": 748, "s": 737, "text": "HTML Code:" }, { "code": "<!DOCTYPE HTML><html> <head> <meta charset=\"UTF-8\"> <title>Image Overlay</title></head> <body> <center> <h1 class=\"title\"> GeeksforGeeks </h1> <b>Image Overlay</b> <br> <br> <div class=\"container\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200325132558/download311.png\" class=\"image\"> <div class=\"overlay overlayLeft\"></div> </div> </center></body> </html> ", "e": 1246, "s": 748, "text": null }, { "code": null, "e": 2029, "s": 1246, "text": "CSS Code: Set the container’s position relative to its normal position and define its width and height. The key to getting the overlay to work is to set its position to absolute. That means its positioned relative to its nearest positioned ancestor, which in this case is the image. So that the overlay isn’t always there and only shows up when the user hovers over the image, set its opacity to zero, meaning completely transparent. Use “background-color” to set the color of your overlay. Use “transition” so that the overlay gradually appears instead of popping up over the image. Since we set the opacity of the overlay to zero, once we hover over the container we want to set that opacity to 1. That means, once the user hovers over the container item, the overlay will appear." }, { "code": "<style> body { text-align: center; } h1 { color: green; } .container img { width: 250px; height: 250px; } .container { position: relative; width: 400px; height: auto; }</style>", "e": 2300, "s": 2029, "text": null }, { "code": null, "e": 2477, "s": 2300, "text": "Fade Overlay: Width and height of the overlay are the width and height of the image equal od div image. Once you hover over the image, the overlay appears on top of that image." }, { "code": null, "e": 3730, "s": 2477, "text": "Program:<!DOCTYPE HTML><html> <head> <meta charset=\"UTF-8\"> <title>Image Overlay</title> <style> body { text-align: center; } h1 { color: green; } .container img { width: 250px; height: 250px; } .container { position: relative; width: 400px; height: auto; } .overlay { position: absolute; transition: all 0.3s ease; opacity: 0; background-color: #9bcd9b; } .container:hover .overlay { opacity: 1; } .overlayFade { height: 250px; width: 250px; top: 0; left: 75px; background-color: #9bcd9b; } </style></head> <body> <center> <h1 class=\"title\"> GeeksforGeeks </h1> <b>Image Overlay</b> <br> <br> <div class=\"container\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200325132558/download311.png\" class=\"image\"> <div class=\"overlay overlayFade\"></div> </div> </center></body> </html>" }, { "code": "<!DOCTYPE HTML><html> <head> <meta charset=\"UTF-8\"> <title>Image Overlay</title> <style> body { text-align: center; } h1 { color: green; } .container img { width: 250px; height: 250px; } .container { position: relative; width: 400px; height: auto; } .overlay { position: absolute; transition: all 0.3s ease; opacity: 0; background-color: #9bcd9b; } .container:hover .overlay { opacity: 1; } .overlayFade { height: 250px; width: 250px; top: 0; left: 75px; background-color: #9bcd9b; } </style></head> <body> <center> <h1 class=\"title\"> GeeksforGeeks </h1> <b>Image Overlay</b> <br> <br> <div class=\"container\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200325132558/download311.png\" class=\"image\"> <div class=\"overlay overlayFade\"></div> </div> </center></body> </html>", "e": 4975, "s": 3730, "text": null }, { "code": null, "e": 4983, "s": 4975, "text": "Output:" }, { "code": null, "e": 5176, "s": 4983, "text": "Left Overlay: Height of the overlay is the height of the image (100%). Width is zero and set to left. Width is set to 100% once you hover over the image and gradually moves from left to right." }, { "code": null, "e": 6518, "s": 5176, "text": "Program:<!DOCTYPE HTML><html> <head> <meta charset=\"UTF-8\"> <title>Image Overlay</title> <style> body { text-align: center; } h1 { color: green; } .container img { width: 250px; height: 250px; } .container { position: relative; width: 400px; height: auto; } .overlay { position: absolute; transition: all 0.3s ease; opacity: 0; background-color: #9bcd9b; } .container:hover .overlay { opacity: 1; } .overlayLeft{ height: 100%; width: 0; top: 0; left: 75px; background-color: #9bcd9b;; } .container:hover .overlayLeft{ width: 250px; } </style></head> <body> <center> <h1 class=\"title\"> GeeksforGeeks </h1> <b>Image Overlay</b> <br> <br> <div class=\"container\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200325132558/download311.png\" class=\"image\"> <div class=\"overlay overlayLeft\"></div> </div> </center></body> </html> " }, { "code": "<!DOCTYPE HTML><html> <head> <meta charset=\"UTF-8\"> <title>Image Overlay</title> <style> body { text-align: center; } h1 { color: green; } .container img { width: 250px; height: 250px; } .container { position: relative; width: 400px; height: auto; } .overlay { position: absolute; transition: all 0.3s ease; opacity: 0; background-color: #9bcd9b; } .container:hover .overlay { opacity: 1; } .overlayLeft{ height: 100%; width: 0; top: 0; left: 75px; background-color: #9bcd9b;; } .container:hover .overlayLeft{ width: 250px; } </style></head> <body> <center> <h1 class=\"title\"> GeeksforGeeks </h1> <b>Image Overlay</b> <br> <br> <div class=\"container\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200325132558/download311.png\" class=\"image\"> <div class=\"overlay overlayLeft\"></div> </div> </center></body> </html> ", "e": 7852, "s": 6518, "text": null }, { "code": null, "e": 7860, "s": 7852, "text": "Output:" }, { "code": null, "e": 8055, "s": 7860, "text": "Right Overlay: Height of the overlay is the height of the image (100%). Width is zero and set to right. Width is set to 100% once you hover over the image and gradually moves from right to left." }, { "code": null, "e": 9401, "s": 8055, "text": "Program:<!DOCTYPE HTML><html> <head> <meta charset=\"UTF-8\"> <title>Image Overlay</title> <style> body { text-align: center; } h1 { color: green; } .container img { width: 250px; height: 250px; } .container { position: relative; width: 400px; height: auto; } .overlay { position: absolute; transition: all 0.3s ease; opacity: 0; background-color: #9bcd9b; } .container:hover .overlay { opacity: 1; } .overlayRight{ height: 100%; width: 0; top: 0; right: 75px; background-color: #9bcd9b;; } .container:hover .overlayRight{ width: 250px; } </style></head> <body> <center> <h1 class=\"title\"> GeeksforGeeks </h1> <b>Image Overlay</b> <br> <br> <div class=\"container\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200325132558/download311.png\" class=\"image\"> <div class=\"overlay overlayRight\"></div> </div> </center></body> </html> " }, { "code": "<!DOCTYPE HTML><html> <head> <meta charset=\"UTF-8\"> <title>Image Overlay</title> <style> body { text-align: center; } h1 { color: green; } .container img { width: 250px; height: 250px; } .container { position: relative; width: 400px; height: auto; } .overlay { position: absolute; transition: all 0.3s ease; opacity: 0; background-color: #9bcd9b; } .container:hover .overlay { opacity: 1; } .overlayRight{ height: 100%; width: 0; top: 0; right: 75px; background-color: #9bcd9b;; } .container:hover .overlayRight{ width: 250px; } </style></head> <body> <center> <h1 class=\"title\"> GeeksforGeeks </h1> <b>Image Overlay</b> <br> <br> <div class=\"container\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200325132558/download311.png\" class=\"image\"> <div class=\"overlay overlayRight\"></div> </div> </center></body> </html> ", "e": 10739, "s": 9401, "text": null }, { "code": null, "e": 10748, "s": 10739, "text": "Output: " }, { "code": null, "e": 10939, "s": 10748, "text": "Top Overlay: Width of the overlay is the width of the image (100%). Height is zero and set to top. Height is set to 100% once you hover over the image and gradually moves from top to bottom." }, { "code": null, "e": 12281, "s": 10939, "text": "Program:<!DOCTYPE HTML><html> <head> <meta charset=\"UTF-8\"> <title>Image Overlay</title> <style> body { text-align: center; } h1 { color: green; } .container img { width: 250px; height: 250px; } .container { position: relative; width: 400px; height: auto; } .overlay { position: absolute; transition: all 0.3s ease; opacity: 0; background-color: #9bcd9b; } .container:hover .overlay { opacity: 1; } .overlayTop{ width: 250px; height: 0; top: 0; right: 75px; background-color: #9bcd9b;; } .container:hover .overlayTop{ height: 250px; } </style></head> <body> <center> <h1 class=\"title\"> GeeksforGeeks </h1> <b>Image Overlay</b> <br> <br> <div class=\"container\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200325132558/download311.png\" class=\"image\"> <div class=\"overlay overlayTop\"></div> </div> </center></body> </html> " }, { "code": "<!DOCTYPE HTML><html> <head> <meta charset=\"UTF-8\"> <title>Image Overlay</title> <style> body { text-align: center; } h1 { color: green; } .container img { width: 250px; height: 250px; } .container { position: relative; width: 400px; height: auto; } .overlay { position: absolute; transition: all 0.3s ease; opacity: 0; background-color: #9bcd9b; } .container:hover .overlay { opacity: 1; } .overlayTop{ width: 250px; height: 0; top: 0; right: 75px; background-color: #9bcd9b;; } .container:hover .overlayTop{ height: 250px; } </style></head> <body> <center> <h1 class=\"title\"> GeeksforGeeks </h1> <b>Image Overlay</b> <br> <br> <div class=\"container\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200325132558/download311.png\" class=\"image\"> <div class=\"overlay overlayTop\"></div> </div> </center></body> </html> ", "e": 13615, "s": 12281, "text": null }, { "code": null, "e": 13624, "s": 13615, "text": "Output: " }, { "code": null, "e": 13821, "s": 13624, "text": "Bottom Overlay: Width of the overlay is the width of the image (100%). Height is zero and set to bottom. Height is set to 100% once you hover over the image and gradually moves from bottom to top." }, { "code": null, "e": 15159, "s": 13821, "text": "Program:<!DOCTYPE HTML><html> <head> <meta charset=\"UTF-8\"> <title>Image Overlay</title> <style> body { text-align: center; } h1 { color: green; } .container img { width: 250px; height: 250px; } .container { position: relative; width: 400px; height: auto; } .overlay { position: absolute; transition: all 0.3s ease; opacity: 0; background-color: #9bcd9b; } .container:hover .overlay { opacity: 1; } .overlayBottom{ width: 250px; height: 0; bottom: 0; right: 75px; background-color: #9bcd9b;; } .container:hover .overlayBottom{ height: 255px; } </style></head> <body> <center> <h1 class=\"title\"> GeeksforGeeks </h1> <b>Image Overlay</b> <br> <br> <div class=\"container\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200325132558/download311.png\" class=\"image\"> <div class=\"overlay overlayBottom\"></div> </div> </center></body> </html> " }, { "code": "<!DOCTYPE HTML><html> <head> <meta charset=\"UTF-8\"> <title>Image Overlay</title> <style> body { text-align: center; } h1 { color: green; } .container img { width: 250px; height: 250px; } .container { position: relative; width: 400px; height: auto; } .overlay { position: absolute; transition: all 0.3s ease; opacity: 0; background-color: #9bcd9b; } .container:hover .overlay { opacity: 1; } .overlayBottom{ width: 250px; height: 0; bottom: 0; right: 75px; background-color: #9bcd9b;; } .container:hover .overlayBottom{ height: 255px; } </style></head> <body> <center> <h1 class=\"title\"> GeeksforGeeks </h1> <b>Image Overlay</b> <br> <br> <div class=\"container\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200325132558/download311.png\" class=\"image\"> <div class=\"overlay overlayBottom\"></div> </div> </center></body> </html> ", "e": 16489, "s": 15159, "text": null }, { "code": null, "e": 16498, "s": 16489, "text": "Output: " }, { "code": null, "e": 16507, "s": 16498, "text": "CSS-Misc" }, { "code": null, "e": 16517, "s": 16507, "text": "HTML-Misc" }, { "code": null, "e": 16521, "s": 16517, "text": "CSS" }, { "code": null, "e": 16526, "s": 16521, "text": "HTML" }, { "code": null, "e": 16543, "s": 16526, "text": "Web Technologies" }, { "code": null, "e": 16570, "s": 16543, "text": "Web technologies Questions" }, { "code": null, "e": 16575, "s": 16570, "text": "HTML" }, { "code": null, "e": 16673, "s": 16575, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 16712, "s": 16673, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 16749, "s": 16712, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 16788, "s": 16749, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 16849, "s": 16788, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 16888, "s": 16849, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 16912, "s": 16888, "text": "REST API (Introduction)" }, { "code": null, "e": 16965, "s": 16912, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 17025, "s": 16965, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 17086, "s": 17025, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Total number of Spanning trees in a Cycle Graph
14 Apr, 2021 Given the number of vertices in a Cycle graph. The task is to find the Total number of Spanning trees possible. Note: A cycle/circular graph is a graph that contains only one cycle. A spanning tree is a shortest/minimum path in a graph that covers all the vertices of a graph. Examples: Input: Vertices = 3 Output: Total Spanning tree = 3 Input: Vertices = 4 Output: Total Spanning tree = 4 Example 1: For Cycle Graph with vertices = 3 Spanning Tree possible is 3 Example 2: For Cycle Graph with vertices = 4 Spanning Tree possible is 4 So, the number of spanning treess will always be equal to the number of vertices in a cycle graph. Below is the required implementation: C++ Java Python3 C# PHP Javascript // C++ program to find number of// spanning trees#include <bits/stdc++.h>using namespace std; // function that calculates the// total Spanning treeint Spanning(int vertices){ result = 0; result = vertices; return result;} // Driver codeint main(){ int vertices = 4; cout << "Spanning tree = " << Spanning(vertices); return 0;} // Java program to find number of// spanning trees import java.io.*; class GFG { // function that calculates the// total Spanning treestatic int Spanning(int vertices){ int result = 0; result = vertices; return result;} // Driver code public static void main (String[] args) { int vertices = 4; System.out.println("Spanning tree = " + Spanning(vertices)); }}// This code is contributed // by chandan_jnu.. # Python program to find number of# spanning trees # function that calculates the# total Spanning treedef Spanning( vertices): result = 0 result = vertices return result # Driver codevertices = 4print("Spanning tree = ", Spanning(vertices)) # This code is contributed# by Sanjit_Prasad // C# program to find number// of spanning treesusing System; // function that calculates// the total Spanning treeclass GFG{public int Spanning(int vertices){ int result = 0; result = vertices; return result;} // Driver codepublic static void Main(){ GFG g = new GFG(); int vertices = 4; Console.WriteLine("Spanning tree = {0}", g.Spanning(vertices));}} // This code is contributed// by Soumik <?php// PHP program to find number of// spanning trees // function that calculates the// total Spanning treefunction Spanning($vertices){ $result = 0; $result = $vertices; return $result;} // Driver code$vertices = 4; echo "Spanning tree = " . Spanning($vertices); // This code is contributed// by Ankita Saini?> <script> // Javascript program to find number of// spanning trees // Function that calculates the// total Spanning treefunction Spanning(vertices){ result = 0; result = vertices; return result;} // Driver codevar vertices = 4;document.write("Spanning tree = " + Spanning(vertices)); // This code is contributed by noob2000 </script> Spanning tree = 4 Chandan_Kumar SoumikMondal Sanjit_Prasad ankita_saini noob2000 Algorithms-Graph Minimum Spanning Tree graph-cycle Graph School Programming Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Find if there is a path between two vertices in a directed graph Introduction to Data Structures Find if there is a path between two vertices in an undirected graph What is Data Structure: Types, Classifications and Applications Top 50 Graph Coding Problems for Interviews Python Dictionary Reverse a string in Java Arrays in C/C++ Introduction To PYTHON Interfaces in Java
[ { "code": null, "e": 53, "s": 25, "text": "\n14 Apr, 2021" }, { "code": null, "e": 330, "s": 53, "text": "Given the number of vertices in a Cycle graph. The task is to find the Total number of Spanning trees possible. Note: A cycle/circular graph is a graph that contains only one cycle. A spanning tree is a shortest/minimum path in a graph that covers all the vertices of a graph." }, { "code": null, "e": 342, "s": 330, "text": "Examples: " }, { "code": null, "e": 447, "s": 342, "text": "Input: Vertices = 3\nOutput: Total Spanning tree = 3\n\nInput: Vertices = 4\nOutput: Total Spanning tree = 4" }, { "code": null, "e": 494, "s": 447, "text": "Example 1: For Cycle Graph with vertices = 3 " }, { "code": null, "e": 524, "s": 494, "text": "Spanning Tree possible is 3 " }, { "code": null, "e": 571, "s": 524, "text": "Example 2: For Cycle Graph with vertices = 4 " }, { "code": null, "e": 601, "s": 571, "text": "Spanning Tree possible is 4 " }, { "code": null, "e": 700, "s": 601, "text": "So, the number of spanning treess will always be equal to the number of vertices in a cycle graph." }, { "code": null, "e": 739, "s": 700, "text": "Below is the required implementation: " }, { "code": null, "e": 743, "s": 739, "text": "C++" }, { "code": null, "e": 748, "s": 743, "text": "Java" }, { "code": null, "e": 756, "s": 748, "text": "Python3" }, { "code": null, "e": 759, "s": 756, "text": "C#" }, { "code": null, "e": 763, "s": 759, "text": "PHP" }, { "code": null, "e": 774, "s": 763, "text": "Javascript" }, { "code": "// C++ program to find number of// spanning trees#include <bits/stdc++.h>using namespace std; // function that calculates the// total Spanning treeint Spanning(int vertices){ result = 0; result = vertices; return result;} // Driver codeint main(){ int vertices = 4; cout << \"Spanning tree = \" << Spanning(vertices); return 0;}", "e": 1121, "s": 774, "text": null }, { "code": "// Java program to find number of// spanning trees import java.io.*; class GFG { // function that calculates the// total Spanning treestatic int Spanning(int vertices){ int result = 0; result = vertices; return result;} // Driver code public static void main (String[] args) { int vertices = 4; System.out.println(\"Spanning tree = \" + Spanning(vertices)); }}// This code is contributed // by chandan_jnu..", "e": 1550, "s": 1121, "text": null }, { "code": "# Python program to find number of# spanning trees # function that calculates the# total Spanning treedef Spanning( vertices): result = 0 result = vertices return result # Driver codevertices = 4print(\"Spanning tree = \", Spanning(vertices)) # This code is contributed# by Sanjit_Prasad", "e": 1856, "s": 1550, "text": null }, { "code": "// C# program to find number// of spanning treesusing System; // function that calculates// the total Spanning treeclass GFG{public int Spanning(int vertices){ int result = 0; result = vertices; return result;} // Driver codepublic static void Main(){ GFG g = new GFG(); int vertices = 4; Console.WriteLine(\"Spanning tree = {0}\", g.Spanning(vertices));}} // This code is contributed// by Soumik", "e": 2294, "s": 1856, "text": null }, { "code": "<?php// PHP program to find number of// spanning trees // function that calculates the// total Spanning treefunction Spanning($vertices){ $result = 0; $result = $vertices; return $result;} // Driver code$vertices = 4; echo \"Spanning tree = \" . Spanning($vertices); // This code is contributed// by Ankita Saini?>", "e": 2626, "s": 2294, "text": null }, { "code": "<script> // Javascript program to find number of// spanning trees // Function that calculates the// total Spanning treefunction Spanning(vertices){ result = 0; result = vertices; return result;} // Driver codevar vertices = 4;document.write(\"Spanning tree = \" + Spanning(vertices)); // This code is contributed by noob2000 </script>", "e": 2982, "s": 2626, "text": null }, { "code": null, "e": 3000, "s": 2982, "text": "Spanning tree = 4" }, { "code": null, "e": 3016, "s": 3002, "text": "Chandan_Kumar" }, { "code": null, "e": 3029, "s": 3016, "text": "SoumikMondal" }, { "code": null, "e": 3043, "s": 3029, "text": "Sanjit_Prasad" }, { "code": null, "e": 3056, "s": 3043, "text": "ankita_saini" }, { "code": null, "e": 3065, "s": 3056, "text": "noob2000" }, { "code": null, "e": 3104, "s": 3065, "text": "Algorithms-Graph Minimum Spanning Tree" }, { "code": null, "e": 3116, "s": 3104, "text": "graph-cycle" }, { "code": null, "e": 3122, "s": 3116, "text": "Graph" }, { "code": null, "e": 3141, "s": 3122, "text": "School Programming" }, { "code": null, "e": 3147, "s": 3141, "text": "Graph" }, { "code": null, "e": 3245, "s": 3147, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3310, "s": 3245, "text": "Find if there is a path between two vertices in a directed graph" }, { "code": null, "e": 3342, "s": 3310, "text": "Introduction to Data Structures" }, { "code": null, "e": 3410, "s": 3342, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 3474, "s": 3410, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 3518, "s": 3474, "text": "Top 50 Graph Coding Problems for Interviews" }, { "code": null, "e": 3536, "s": 3518, "text": "Python Dictionary" }, { "code": null, "e": 3561, "s": 3536, "text": "Reverse a string in Java" }, { "code": null, "e": 3577, "s": 3561, "text": "Arrays in C/C++" }, { "code": null, "e": 3600, "s": 3577, "text": "Introduction To PYTHON" } ]
XAML - GridView
A GridView represents a control that displays data items in rows and columns. Actually, a ListView displays data. By default, it contains a GridView. The hierarchical inheritance of GridView class is as follows − Background Gets or sets a brush that provides the background of the control. (Inherited from Control) BorderThickness Gets or sets the border thickness of a control. (Inherited from Control) DataContext Gets or sets the data context for a FrameworkElement when it participates in data binding. (Inherited from FrameworkElement) FontFamily Gets or sets the font used to display text in the control. (Inherited from Control) FontSize Gets or sets the size of the text in this control. (Inherited from Control) FontStyle Gets or sets the style in which the text is rendered. (Inherited from Control) FontWeight Gets or sets the thickness of the specified font. (Inherited from Control) Foreground Gets or sets a brush that describes the foreground color. (Inherited from Control) GroupStyle Gets a collection of GroupStyle objects that define the appearance of each level of groups. (Inherited from ItemsControl) Header Gets or sets the content for the list header. (Inherited from ListViewBase) Height Gets or sets the suggested height of a FrameworkElement. (Inherited from FrameworkElement) HorizontalAlignment Gets or sets the horizontal alignment characteristics that are applied to a FrameworkElement when it is composed in a layout parent, such as a panel or items control. (Inherited from FrameworkElement) HorizontalContentAlignment Gets or sets the horizontal alignment of the control's content. (Inherited from Control) Items Gets the collection used to generate the content of the control. (Inherited from ItemsControl) ItemsSource Gets or sets an object source used to generate the content of the ItemsControl. (Inherited from ItemsControl) ItemTemplate Gets or sets the DataTemplate used to display each item. (Inherited from ItemsControl) Margin Gets or sets the outer margin of a FrameworkElement. (Inherited from FrameworkElement) Name Gets or sets the identifying name of the object. When a XAML processor creates the object tree from XAML markup, run-time code can refer to the XAML-declared object by this name. (Inherited from FrameworkElement) Opacity Gets or sets the degree of the object's opacity. (Inherited from UIElement) Resources Gets the locally defined resource dictionary. In XAML, you can establish resource items as child object elements of a frameworkElement.Resources property element, through XAML implicit collection syntax. (Inherited from FrameworkElement) SelectedIndex Gets or sets the index of the selected item. (Inherited from Selector) SelectedItem Gets or sets the selected item. (Inherited from Selector) SelectedItems Gets the currently selected items. (Inherited from ListViewBase) SelectedRanges Gets a collection of ItemIndexRange objects that describe the currently selected items in the list. (Inherited from ListViewBase) SelectedValue Gets or sets the value of the selected item, obtained by using the SelectedValuePath. (Inherited from Selector) Style Gets or sets an instance Style that is applied for this object during layout and rendering. (Inherited from FrameworkElement) VerticalAlignment Gets or sets the vertical alignment characteristics that are applied to a FrameworkElement when it is composed in a parent object such as a panel or items control. (Inherited from FrameworkElement) VerticalContentAlignment Gets or sets the vertical alignment of the control's content. (Inherited from Control) Width Gets or sets the width of a FrameworkElement. (Inherited from FrameworkElement) DataContextChanged Occurs when the value of the FrameworkElement.DataContext property changes. (Inherited from FrameworkElement) DragEnter Occurs when the input system reports an underlying drag event with this element as the target. (Inherited from UIElement) DragLeave Occurs when the input system reports an underlying drag event with this element as the origin. (Inherited from UIElement) DragOver Occurs when the input system reports an underlying drag event with this element as the potential drop target. (Inherited from UIElement) DragStarting Occurs when a drag operation is initiated. (Inherited from UIElement) Drop Occurs when the input system reports an underlying drop event with this element as the drop target. (Inherited from UIElement) ImageFailed Occurs when there is an error associated with image retrieval or format. ImageOpened Occurs when the image source is downloaded and decoded with no failure. You can use this event to determine the natural size of the image source. KeyDown Occurs when a keyboard key is pressed while the UIElement has focus. (Inherited from UIElement) KeyUp when a keyboard key is released while the UIElement has focus. (Inherited from UIElement) Arrange Positions child objects and determines a size for a UIElement. Parent objects that implement custom layout for their child elements should call this method from their layout override implementations to form a recursive layout update. (Inherited from UIElement) ClearValue Clears the local value of a dependency property. (Inherited from DependencyObject) FindName Retrieves an object that has the specified identifier name. (Inherited from FrameworkElement) GetValue Returns the current effective value of a dependency property from a DependencyObject. (Inherited from DependencyObject) ReadLocalValue Returns the local value of a dependency property, if a local value is set. (Inherited from DependencyObject) SetBinding Attaches a binding to a FrameworkElement, using the provided binding object. (Inherited from FrameworkElement) SetValue Sets the local value of a dependency property on a DependencyObject. (Inherited from DependencyObject) The following example shows the data (Name, ID, and Age) contained in a table. Here is the XAML implementation to create and initialize a GridView. <Window x:Class = "XAMLGridView.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "MainWindow" Height = "350" Width = "525"> <Grid> <ListView HorizontalAlignment = "Left" Height = "299"Margin = "10,10,0,0" VerticalAlignment = "Top" Width = "497" Name = "MenList"> <ListView.View> <GridView> <GridViewColumn Header = "Name" DisplayMemberBinding = "{Binding Name}" Width = "100"/> <GridViewColumn Header = "ID" DisplayMemberBinding = "{Binding ID}" Width = "100"/> <GridViewColumn Header = "Age" DisplayMemberBinding = "{Binding Age}" Width = "100"/> </GridView> </ListView.View> </ListView> </Grid> </Window> Here is the C# implementation to implement a person class. using System; using System.Windows; using System.Windows.Controls; namespace XAMLGridView { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); MenList.Items.Add(new Person() { Name = "Ali", ID = "123A", Age = 20 }); MenList.Items.Add(new Person() { Name = "Akram", ID = "456X", Age = 35 }); MenList.Items.Add(new Person() { Name = "Salman", ID = "333E", Age = 49 }); } } class Person { public string Name { get; set; } public string ID { get; set; } public int Age { get; set; } } } When you compile and execute the above code, it will produce the following output − We recommend you to execute the above example code and experiment with some other properties and events.
[ { "code": null, "e": 2270, "s": 2057, "text": "A GridView represents a control that displays data items in rows and columns. Actually, a ListView displays data. By default, it contains a GridView. The hierarchical inheritance of GridView class is as follows −" }, { "code": null, "e": 2281, "s": 2270, "text": "Background" }, { "code": null, "e": 2372, "s": 2281, "text": "Gets or sets a brush that provides the background of the control. (Inherited from Control)" }, { "code": null, "e": 2388, "s": 2372, "text": "BorderThickness" }, { "code": null, "e": 2461, "s": 2388, "text": "Gets or sets the border thickness of a control. (Inherited from Control)" }, { "code": null, "e": 2473, "s": 2461, "text": "DataContext" }, { "code": null, "e": 2598, "s": 2473, "text": "Gets or sets the data context for a FrameworkElement when it participates in data binding. (Inherited from FrameworkElement)" }, { "code": null, "e": 2609, "s": 2598, "text": "FontFamily" }, { "code": null, "e": 2693, "s": 2609, "text": "Gets or sets the font used to display text in the control. (Inherited from Control)" }, { "code": null, "e": 2702, "s": 2693, "text": "FontSize" }, { "code": null, "e": 2778, "s": 2702, "text": "Gets or sets the size of the text in this control. (Inherited from Control)" }, { "code": null, "e": 2788, "s": 2778, "text": "FontStyle" }, { "code": null, "e": 2867, "s": 2788, "text": "Gets or sets the style in which the text is rendered. (Inherited from Control)" }, { "code": null, "e": 2878, "s": 2867, "text": "FontWeight" }, { "code": null, "e": 2953, "s": 2878, "text": "Gets or sets the thickness of the specified font. (Inherited from Control)" }, { "code": null, "e": 2964, "s": 2953, "text": "Foreground" }, { "code": null, "e": 3047, "s": 2964, "text": "Gets or sets a brush that describes the foreground color. (Inherited from Control)" }, { "code": null, "e": 3058, "s": 3047, "text": "GroupStyle" }, { "code": null, "e": 3180, "s": 3058, "text": "Gets a collection of GroupStyle objects that define the appearance of each level of groups. (Inherited from ItemsControl)" }, { "code": null, "e": 3187, "s": 3180, "text": "Header" }, { "code": null, "e": 3263, "s": 3187, "text": "Gets or sets the content for the list header. (Inherited from ListViewBase)" }, { "code": null, "e": 3270, "s": 3263, "text": "Height" }, { "code": null, "e": 3361, "s": 3270, "text": "Gets or sets the suggested height of a FrameworkElement. (Inherited from FrameworkElement)" }, { "code": null, "e": 3381, "s": 3361, "text": "HorizontalAlignment" }, { "code": null, "e": 3582, "s": 3381, "text": "Gets or sets the horizontal alignment characteristics that are applied to a FrameworkElement when it is composed in a layout parent, such as a panel or items control. (Inherited from FrameworkElement)" }, { "code": null, "e": 3609, "s": 3582, "text": "HorizontalContentAlignment" }, { "code": null, "e": 3698, "s": 3609, "text": "Gets or sets the horizontal alignment of the control's content. (Inherited from Control)" }, { "code": null, "e": 3704, "s": 3698, "text": "Items" }, { "code": null, "e": 3799, "s": 3704, "text": "Gets the collection used to generate the content of the control. (Inherited from ItemsControl)" }, { "code": null, "e": 3811, "s": 3799, "text": "ItemsSource" }, { "code": null, "e": 3921, "s": 3811, "text": "Gets or sets an object source used to generate the content of the ItemsControl. (Inherited from ItemsControl)" }, { "code": null, "e": 3934, "s": 3921, "text": "ItemTemplate" }, { "code": null, "e": 4021, "s": 3934, "text": "Gets or sets the DataTemplate used to display each item. (Inherited from ItemsControl)" }, { "code": null, "e": 4028, "s": 4021, "text": "Margin" }, { "code": null, "e": 4115, "s": 4028, "text": "Gets or sets the outer margin of a FrameworkElement. (Inherited from FrameworkElement)" }, { "code": null, "e": 4120, "s": 4115, "text": "Name" }, { "code": null, "e": 4333, "s": 4120, "text": "Gets or sets the identifying name of the object. When a XAML processor creates the object tree from XAML markup, run-time code can refer to the XAML-declared object by this name. (Inherited from FrameworkElement)" }, { "code": null, "e": 4341, "s": 4333, "text": "Opacity" }, { "code": null, "e": 4417, "s": 4341, "text": "Gets or sets the degree of the object's opacity. (Inherited from UIElement)" }, { "code": null, "e": 4427, "s": 4417, "text": "Resources" }, { "code": null, "e": 4665, "s": 4427, "text": "Gets the locally defined resource dictionary. In XAML, you can establish resource items as child object elements of a frameworkElement.Resources property element, through XAML implicit collection syntax. (Inherited from FrameworkElement)" }, { "code": null, "e": 4679, "s": 4665, "text": "SelectedIndex" }, { "code": null, "e": 4750, "s": 4679, "text": "Gets or sets the index of the selected item. (Inherited from Selector)" }, { "code": null, "e": 4763, "s": 4750, "text": "SelectedItem" }, { "code": null, "e": 4821, "s": 4763, "text": "Gets or sets the selected item. (Inherited from Selector)" }, { "code": null, "e": 4835, "s": 4821, "text": "SelectedItems" }, { "code": null, "e": 4900, "s": 4835, "text": "Gets the currently selected items. (Inherited from ListViewBase)" }, { "code": null, "e": 4915, "s": 4900, "text": "SelectedRanges" }, { "code": null, "e": 5045, "s": 4915, "text": "Gets a collection of ItemIndexRange objects that describe the currently selected items in the list. (Inherited from ListViewBase)" }, { "code": null, "e": 5059, "s": 5045, "text": "SelectedValue" }, { "code": null, "e": 5171, "s": 5059, "text": "Gets or sets the value of the selected item, obtained by using the SelectedValuePath. (Inherited from Selector)" }, { "code": null, "e": 5177, "s": 5171, "text": "Style" }, { "code": null, "e": 5303, "s": 5177, "text": "Gets or sets an instance Style that is applied for this object during layout and rendering. (Inherited from FrameworkElement)" }, { "code": null, "e": 5321, "s": 5303, "text": "VerticalAlignment" }, { "code": null, "e": 5519, "s": 5321, "text": "Gets or sets the vertical alignment characteristics that are applied to a FrameworkElement when it is composed in a parent object such as a panel or items control. (Inherited from FrameworkElement)" }, { "code": null, "e": 5544, "s": 5519, "text": "VerticalContentAlignment" }, { "code": null, "e": 5631, "s": 5544, "text": "Gets or sets the vertical alignment of the control's content. (Inherited from Control)" }, { "code": null, "e": 5637, "s": 5631, "text": "Width" }, { "code": null, "e": 5717, "s": 5637, "text": "Gets or sets the width of a FrameworkElement. (Inherited from FrameworkElement)" }, { "code": null, "e": 5736, "s": 5717, "text": "DataContextChanged" }, { "code": null, "e": 5846, "s": 5736, "text": "Occurs when the value of the FrameworkElement.DataContext property changes. (Inherited from FrameworkElement)" }, { "code": null, "e": 5856, "s": 5846, "text": "DragEnter" }, { "code": null, "e": 5978, "s": 5856, "text": "Occurs when the input system reports an underlying drag event with this element as the target. (Inherited from UIElement)" }, { "code": null, "e": 5988, "s": 5978, "text": "DragLeave" }, { "code": null, "e": 6110, "s": 5988, "text": "Occurs when the input system reports an underlying drag event with this element as the origin. (Inherited from UIElement)" }, { "code": null, "e": 6119, "s": 6110, "text": "DragOver" }, { "code": null, "e": 6256, "s": 6119, "text": "Occurs when the input system reports an underlying drag event with this element as the potential drop target. (Inherited from UIElement)" }, { "code": null, "e": 6269, "s": 6256, "text": "DragStarting" }, { "code": null, "e": 6339, "s": 6269, "text": "Occurs when a drag operation is initiated. (Inherited from UIElement)" }, { "code": null, "e": 6344, "s": 6339, "text": "Drop" }, { "code": null, "e": 6471, "s": 6344, "text": "Occurs when the input system reports an underlying drop event with this element as the drop target. (Inherited from UIElement)" }, { "code": null, "e": 6483, "s": 6471, "text": "ImageFailed" }, { "code": null, "e": 6556, "s": 6483, "text": "Occurs when there is an error associated with image retrieval or format." }, { "code": null, "e": 6568, "s": 6556, "text": "ImageOpened" }, { "code": null, "e": 6714, "s": 6568, "text": "Occurs when the image source is downloaded and decoded with no failure. You can use this event to determine the natural size of the image source." }, { "code": null, "e": 6722, "s": 6714, "text": "KeyDown" }, { "code": null, "e": 6818, "s": 6722, "text": "Occurs when a keyboard key is pressed while the UIElement has focus. (Inherited from UIElement)" }, { "code": null, "e": 6824, "s": 6818, "text": "KeyUp" }, { "code": null, "e": 6914, "s": 6824, "text": "when a keyboard key is released while the UIElement has focus. (Inherited from UIElement)" }, { "code": null, "e": 6922, "s": 6914, "text": "Arrange" }, { "code": null, "e": 7183, "s": 6922, "text": "Positions child objects and determines a size for a UIElement. Parent objects that implement custom layout for their child elements should call this method from their layout override implementations to form a recursive layout update. (Inherited from UIElement)" }, { "code": null, "e": 7194, "s": 7183, "text": "ClearValue" }, { "code": null, "e": 7277, "s": 7194, "text": "Clears the local value of a dependency property. (Inherited from DependencyObject)" }, { "code": null, "e": 7286, "s": 7277, "text": "FindName" }, { "code": null, "e": 7380, "s": 7286, "text": "Retrieves an object that has the specified identifier name. (Inherited from FrameworkElement)" }, { "code": null, "e": 7389, "s": 7380, "text": "GetValue" }, { "code": null, "e": 7509, "s": 7389, "text": "Returns the current effective value of a dependency property from a DependencyObject. (Inherited from DependencyObject)" }, { "code": null, "e": 7524, "s": 7509, "text": "ReadLocalValue" }, { "code": null, "e": 7633, "s": 7524, "text": "Returns the local value of a dependency property, if a local value is set. (Inherited from DependencyObject)" }, { "code": null, "e": 7644, "s": 7633, "text": "SetBinding" }, { "code": null, "e": 7755, "s": 7644, "text": "Attaches a binding to a FrameworkElement, using the provided binding object. (Inherited from FrameworkElement)" }, { "code": null, "e": 7764, "s": 7755, "text": "SetValue" }, { "code": null, "e": 7867, "s": 7764, "text": "Sets the local value of a dependency property on a DependencyObject. (Inherited from DependencyObject)" }, { "code": null, "e": 8015, "s": 7867, "text": "The following example shows the data (Name, ID, and Age) contained in a table. Here is the XAML implementation to create and initialize a GridView." }, { "code": null, "e": 8954, "s": 8015, "text": "<Window x:Class = \"XAMLGridView.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 = \"525\"> \n\t\n <Grid> \n <ListView HorizontalAlignment = \"Left\" \n Height = \"299\"Margin = \"10,10,0,0\" \n VerticalAlignment = \"Top\" Width = \"497\" \n Name = \"MenList\"> \n\t\t\t\n <ListView.View> \n <GridView> \n <GridViewColumn Header = \"Name\" \n DisplayMemberBinding = \"{Binding Name}\" Width = \"100\"/> \n\t\t\n <GridViewColumn Header = \"ID\"\n DisplayMemberBinding = \"{Binding ID}\" Width = \"100\"/> \n\t\t\n <GridViewColumn Header = \"Age\" \n DisplayMemberBinding = \"{Binding Age}\" Width = \"100\"/> \n\t\t\n </GridView> \n </ListView.View>\n \n </ListView> \n </Grid> \n</Window>" }, { "code": null, "e": 9013, "s": 8954, "text": "Here is the C# implementation to implement a person class." }, { "code": null, "e": 9713, "s": 9013, "text": "using System; \nusing System.Windows; \nusing System.Windows.Controls;\n\nnamespace XAMLGridView { \n /// <summary> \n /// Interaction logic for MainWindow.xaml \n /// </summary> \n\t\n public partial class MainWindow : Window { \n public MainWindow() { \n InitializeComponent(); \n MenList.Items.Add(new Person() { Name = \"Ali\", ID = \"123A\", Age = 20 }); \n MenList.Items.Add(new Person() { Name = \"Akram\", ID = \"456X\", Age = 35 }); \n MenList.Items.Add(new Person() { Name = \"Salman\", ID = \"333E\", Age = 49 }); \n }\n }\n class Person { \n public string Name { get; set; } \n public string ID { get; set; } \n public int Age { get; set; } \n }\n}" }, { "code": null, "e": 9797, "s": 9713, "text": "When you compile and execute the above code, it will produce the following output −" } ]
Spring JSR-250 Annotations
Spring also supports JSR-250 based annotations which include @PostConstruct, @PreDestroy and @Resource annotations. Though these annotations are not really required because you already have other alternates, yet let us get a brief idea about them. To define the setup and teardown for a bean, we simply declare the <bean> with init-method and/or destroy-method parameters. The init-method attribute specifies a method that is to be called on the bean immediately upon instantiation. Similarly, the destroy-method specifies a method that is called just before a bean is removed from the container. You can use @PostConstruct annotation as an alternate of initialization callback and @PreDestroy annotation as an alternate of destruction callback as explained in the below example. Let us have a working Eclipse IDE in place and take the following steps to create a Spring application − Here is the content of HelloWorld.java file − package com.tutorialspoint; import javax.annotation.*; public class HelloWorld { private String message; public void setMessage(String message){ this.message = message; } public String getMessage(){ System.out.println("Your Message : " + message); return message; } @PostConstruct public void init(){ System.out.println("Bean is going through init."); } @PreDestroy public void destroy(){ System.out.println("Bean will destroy now."); } } Following is the content of the MainApp.java file. Here, you need to register a shutdown hook registerShutdownHook() method that is declared on the AbstractApplicationContext class. This will ensure a graceful shutdown and call the relevant destroy methods. package com.tutorialspoint; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { AbstractApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); HelloWorld obj = (HelloWorld) context.getBean("helloWorld"); obj.getMessage(); context.registerShutdownHook(); } } Following is the configuration file Beans.xml required for init and destroy methods − <?xml version = "1.0" encoding = "UTF-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns:context = "http://www.springframework.org/schema/context" xsi:schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:annotation-config/> <bean id = "helloWorld" class = "com.tutorialspoint.HelloWorld" init-method = "init" destroy-method = "destroy"> <property name = "message" value = "Hello World!"/> </bean> </beans> Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message − Bean is going through init. Your Message : Hello World! Bean will destroy now. You can use @Resource annotation on fields or setter methods and it works the same as in Java EE 5. The @Resource annotation takes a 'name' attribute which will be interpreted as the bean name to be injected. You can say, it follows by-name autowiring semantics as demonstrated in the following example − package com.tutorialspoint; import javax.annotation.Resource; public class TextEditor { private SpellChecker spellChecker; @Resource(name = "spellChecker") public void setSpellChecker( SpellChecker spellChecker ){ this.spellChecker = spellChecker; } public SpellChecker getSpellChecker(){ return spellChecker; } public void spellCheck(){ spellChecker.checkSpelling(); } } If no 'name' is specified explicitly, the default name is derived from the field name or setter method. In case of a field, it takes the field name; in case of a setter method, it takes the bean property name.
[ { "code": null, "e": 2674, "s": 2426, "text": "Spring also supports JSR-250 based annotations which include @PostConstruct, @PreDestroy and @Resource annotations. Though these annotations are not really required because you already have other alternates, yet let us get a brief idea about them." }, { "code": null, "e": 3023, "s": 2674, "text": "To define the setup and teardown for a bean, we simply declare the <bean> with init-method and/or destroy-method parameters. The init-method attribute specifies a method that is to be called on the bean immediately upon instantiation. Similarly, the destroy-method specifies a method that is called just before a bean is removed from the container." }, { "code": null, "e": 3206, "s": 3023, "text": "You can use @PostConstruct annotation as an alternate of initialization callback and @PreDestroy annotation as an alternate of destruction callback as explained in the below example." }, { "code": null, "e": 3311, "s": 3206, "text": "Let us have a working Eclipse IDE in place and take the following steps to create a Spring application −" }, { "code": null, "e": 3357, "s": 3311, "text": "Here is the content of HelloWorld.java file −" }, { "code": null, "e": 3870, "s": 3357, "text": "package com.tutorialspoint;\nimport javax.annotation.*;\n\npublic class HelloWorld {\n private String message;\n\n public void setMessage(String message){\n this.message = message;\n }\n public String getMessage(){\n System.out.println(\"Your Message : \" + message);\n return message;\n }\n \n @PostConstruct\n public void init(){\n System.out.println(\"Bean is going through init.\");\n }\n \n @PreDestroy\n public void destroy(){\n System.out.println(\"Bean will destroy now.\");\n }\n}" }, { "code": null, "e": 4128, "s": 3870, "text": "Following is the content of the MainApp.java file. Here, you need to register a shutdown hook registerShutdownHook() method that is declared on the AbstractApplicationContext class. This will ensure a graceful shutdown and call the relevant destroy methods." }, { "code": null, "e": 4600, "s": 4128, "text": "package com.tutorialspoint;\n\nimport org.springframework.context.support.AbstractApplicationContext;\nimport org.springframework.context.support.ClassPathXmlApplicationContext;\n\npublic class MainApp {\n public static void main(String[] args) {\n AbstractApplicationContext context = new ClassPathXmlApplicationContext(\"Beans.xml\");\n\n HelloWorld obj = (HelloWorld) context.getBean(\"helloWorld\");\n obj.getMessage();\n context.registerShutdownHook();\n }\n}" }, { "code": null, "e": 4686, "s": 4600, "text": "Following is the configuration file Beans.xml required for init and destroy methods −" }, { "code": null, "e": 5411, "s": 4686, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xmlns:context = \"http://www.springframework.org/schema/context\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\n http://www.springframework.org/schema/context\n http://www.springframework.org/schema/context/spring-context-3.0.xsd\">\n\n <context:annotation-config/>\n <bean id = \"helloWorld\" class = \"com.tutorialspoint.HelloWorld\"\n init-method = \"init\" destroy-method = \"destroy\">\n <property name = \"message\" value = \"Hello World!\"/>\n </bean>\n\n</beans>" }, { "code": null, "e": 5590, "s": 5411, "text": "Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −" }, { "code": null, "e": 5670, "s": 5590, "text": "Bean is going through init.\nYour Message : Hello World!\nBean will destroy now.\n" }, { "code": null, "e": 5975, "s": 5670, "text": "You can use @Resource annotation on fields or setter methods and it works the same as in Java EE 5. The @Resource annotation takes a 'name' attribute which will be interpreted as the bean name to be injected. You can say, it follows by-name autowiring semantics as demonstrated in the following example −" }, { "code": null, "e": 6392, "s": 5975, "text": "package com.tutorialspoint;\n\nimport javax.annotation.Resource;\n\npublic class TextEditor {\n private SpellChecker spellChecker;\n\n @Resource(name = \"spellChecker\")\n public void setSpellChecker( SpellChecker spellChecker ){\n this.spellChecker = spellChecker;\n }\n public SpellChecker getSpellChecker(){\n return spellChecker;\n }\n public void spellCheck(){\n spellChecker.checkSpelling();\n }\n}" } ]
Python Program for Product of unique prime factors of a number
03 Dec, 2018 Given a number n, we need to find the product of all of its unique prime factors. Prime factors: It is basically a factor of the number that is a prime number itself. Examples: Input: num = 10 Output: Product is 10 Explanation: Here, the input number is 10 having only 2 prime factors and they are 5 and 2. And hence their product is 10. Input : num = 25 Output: Product is 5 Explanation: Here, for the input to be 25 we have only one unique prime factor i.e 5. And hence the required product is 5. Method 1 (Simple)Using a loop from i = 2 to n and check if i is a factor of n then check if i is prime number itself if yes then store product in product variable and continue this process till i = n. # Python program to find sum of given# series. def productPrimeFactors(n): product = 1 for i in range(2, n+1): if (n % i == 0): isPrime = 1 for j in range(2, int(i/2 + 1)): if (i % j == 0): isPrime = 0 break # condition if \'i\' is Prime number # as well as factor of num if (isPrime): product = product * i return product # main()n = 44print (productPrimeFactors(n)) # Contributed by _omg Output: 22 Method 2 (Efficient) :The idea is based on Efficient program to print all prime factors of a given number # Python program to find product of # unique prime factors of a number import math def productPrimeFactors(n): product = 1 # Handle prime factor 2 explicitly so that # can optimally handle other prime factors. if (n % 2 == 0): product *= 2 while (n%2 == 0): n = n/2 # n must be odd at this point. So we can # skip one element (Note i = i +2) for i in range (3, int(math.sqrt(n)), 2): # While i divides n, print i and # divide n if (n % i == 0): product = product * i while (n%i == 0): n = n/i # This condition is to handle the case when n # is a prime number greater than 2 if (n > 2): product = product * n return product # main()n = 44print (int(productPrimeFactors(n))) # Contributed by _omg Output: 22 Please refer complete article on Product of unique prime factors of a number for more details! Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python | Convert string dictionary to dictionary Python program to add two numbers Python Program for Binary Search (Recursive and Iterative) Python Program for factorial of a number Python program to find second largest number in a list Iterate over characters of a string in Python Python | Convert set into a list Appending to list in Python dictionary Python | Convert a list into a tuple Add a key:value pair to dictionary in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Dec, 2018" }, { "code": null, "e": 195, "s": 28, "text": "Given a number n, we need to find the product of all of its unique prime factors. Prime factors: It is basically a factor of the number that is a prime number itself." }, { "code": null, "e": 205, "s": 195, "text": "Examples:" }, { "code": null, "e": 530, "s": 205, "text": "Input: num = 10\nOutput: Product is 10\nExplanation:\nHere, the input number is 10 having only 2 prime factors and they are 5 and 2.\nAnd hence their product is 10.\n\nInput : num = 25\nOutput: Product is 5\nExplanation:\nHere, for the input to be 25 we have only one unique prime factor i.e 5.\nAnd hence the required product is 5.\n" }, { "code": null, "e": 731, "s": 530, "text": "Method 1 (Simple)Using a loop from i = 2 to n and check if i is a factor of n then check if i is prime number itself if yes then store product in product variable and continue this process till i = n." }, { "code": "# Python program to find sum of given# series. def productPrimeFactors(n): product = 1 for i in range(2, n+1): if (n % i == 0): isPrime = 1 for j in range(2, int(i/2 + 1)): if (i % j == 0): isPrime = 0 break # condition if \\'i\\' is Prime number # as well as factor of num if (isPrime): product = product * i return product # main()n = 44print (productPrimeFactors(n)) # Contributed by _omg", "e": 1337, "s": 731, "text": null }, { "code": null, "e": 1345, "s": 1337, "text": "Output:" }, { "code": null, "e": 1349, "s": 1345, "text": "22\n" }, { "code": null, "e": 1455, "s": 1349, "text": "Method 2 (Efficient) :The idea is based on Efficient program to print all prime factors of a given number" }, { "code": "# Python program to find product of # unique prime factors of a number import math def productPrimeFactors(n): product = 1 # Handle prime factor 2 explicitly so that # can optimally handle other prime factors. if (n % 2 == 0): product *= 2 while (n%2 == 0): n = n/2 # n must be odd at this point. So we can # skip one element (Note i = i +2) for i in range (3, int(math.sqrt(n)), 2): # While i divides n, print i and # divide n if (n % i == 0): product = product * i while (n%i == 0): n = n/i # This condition is to handle the case when n # is a prime number greater than 2 if (n > 2): product = product * n return product # main()n = 44print (int(productPrimeFactors(n))) # Contributed by _omg", "e": 2334, "s": 1455, "text": null }, { "code": null, "e": 2342, "s": 2334, "text": "Output:" }, { "code": null, "e": 2346, "s": 2342, "text": "22\n" }, { "code": null, "e": 2441, "s": 2346, "text": "Please refer complete article on Product of unique prime factors of a number for more details!" }, { "code": null, "e": 2457, "s": 2441, "text": "Python Programs" }, { "code": null, "e": 2555, "s": 2457, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2604, "s": 2555, "text": "Python | Convert string dictionary to dictionary" }, { "code": null, "e": 2638, "s": 2604, "text": "Python program to add two numbers" }, { "code": null, "e": 2697, "s": 2638, "text": "Python Program for Binary Search (Recursive and Iterative)" }, { "code": null, "e": 2738, "s": 2697, "text": "Python Program for factorial of a number" }, { "code": null, "e": 2793, "s": 2738, "text": "Python program to find second largest number in a list" }, { "code": null, "e": 2839, "s": 2793, "text": "Iterate over characters of a string in Python" }, { "code": null, "e": 2872, "s": 2839, "text": "Python | Convert set into a list" }, { "code": null, "e": 2911, "s": 2872, "text": "Appending to list in Python dictionary" }, { "code": null, "e": 2948, "s": 2911, "text": "Python | Convert a list into a tuple" } ]
MATLAB | RGB image to grayscale image conversion
25 Jun, 2018 An RGB image can be viewed as three images( a red scale image, a green scale image and a blue scale image) stacked on top of each other. In MATLAB, an RGB image is basically a M*N*3 array of colour pixel, where each colour pixel is a triplet which corresponds to red, blue and green colour component of RGB image at a specified spatial location. Similarly, A Grayscale image can be viewed as a single layered image. In MATLAB, a grayscale image is basically M*N array whose values have been scaled to represent intensities. In MATLAB, there is a function called rgb2gray() is available to convert RGB image to grayscale image. Here we will convert an RGB image to grayscale image without using rgb2gray() function. Our key idea is to convert an RGB image pixel which a triplet value corresponding to red, blue and green colour component of an image at a specified spatial location to a single value by calculating a weighted sum of all three colour component. Algorithm for conversion: Read RGB colour image into MATLAB environmentExtract Red, blue and green colour components from RGB image into 3 different 2-D matricesCreate a new matrix with the same number of rows and columns as RGB image, containing all zeros .Convert each RGB pixel values at location (i, j) to grayscale values by forming a weighted sum of the Red, Green, and Blue colour components and assign it to corresponding location (i, j) in new matrixgrayscale value at (i, j) = 0.2989 * R(i, j) + 0.5870 * G(i, j) + 0.1140 * B(i, j);Note: The coefficients that is used to calculate grayscale values are identical to those that is used to calculate luminance (E’y) in Rec. ITU-R BT.601-7 (Recommendation by radio-communication sector of ITU for Broadcasting service (Television)) Read RGB colour image into MATLAB environment Extract Red, blue and green colour components from RGB image into 3 different 2-D matrices Create a new matrix with the same number of rows and columns as RGB image, containing all zeros . Convert each RGB pixel values at location (i, j) to grayscale values by forming a weighted sum of the Red, Green, and Blue colour components and assign it to corresponding location (i, j) in new matrix grayscale value at (i, j) = 0.2989 * R(i, j) + 0.5870 * G(i, j) + 0.1140 * B(i, j); Note: The coefficients that is used to calculate grayscale values are identical to those that is used to calculate luminance (E’y) in Rec. ITU-R BT.601-7 (Recommendation by radio-communication sector of ITU for Broadcasting service (Television)) Implementation: % Function will take a colour image as input and will return a grayscale image function [gray_img] = colouredToGray(img) % Extract Red colour component to R, Green colour component to G % and Blue colour component to B R=img(:, :, 1); G=img(:, :, 2); B=img(:, :, 3); % Getting number of rows in M and number of column in N of RGB image matrix % ~ is used to ignore dimension of RGB image % as size(img) function will return row, column and dimension of the RGB image [M, N, ~]=size(img); % creating a new 2-d matrix 'gray_img' of size M*N of 'uint8' data type with all % elements as zero gray_img=zeros(M, N, 'uint8'); % calculating grayscale values by forming a weighted sum of the R, G, and B components % for each pixel for i=1:M for j=1:N gray_img(i, j)=(R(i, j)*0.2989)+(G(i, j)*0.5870)+(B(i, j)*0.114); end end end The above function will be called from MATLAB command window >> % Reading an RGB image file in MATLAB environment >> img=imread('apple.jpg'); >> % The above function will be called here >> I=colouredToGray(img); >> figure, imshow(I); Input: Output: Advantages: To store a single colour pixel of an RGB colour image we will need 8*3 = 24 bits (8 bit for each colour component), but when we convert an RGB image to grayscale image, only 8 bit is required to store a single pixel of the image. So we will need 33 % less memory to store grayscale image than to store an RGB image Grayscale images are much easier to work within a variety of task like In many morphological operation and image segmentation problem, it is easier to work with single layered image (Grayscale image ) than a three-layered image (RGB colour image ) It is also easier to distinguish features of an image when we deal with a single layered image Image-Processing Advanced Computer Subject Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n25 Jun, 2018" }, { "code": null, "e": 398, "s": 52, "text": "An RGB image can be viewed as three images( a red scale image, a green scale image and a blue scale image) stacked on top of each other. In MATLAB, an RGB image is basically a M*N*3 array of colour pixel, where each colour pixel is a triplet which corresponds to red, blue and green colour component of RGB image at a specified spatial location." }, { "code": null, "e": 576, "s": 398, "text": "Similarly, A Grayscale image can be viewed as a single layered image. In MATLAB, a grayscale image is basically M*N array whose values have been scaled to represent intensities." }, { "code": null, "e": 767, "s": 576, "text": "In MATLAB, there is a function called rgb2gray() is available to convert RGB image to grayscale image. Here we will convert an RGB image to grayscale image without using rgb2gray() function." }, { "code": null, "e": 1012, "s": 767, "text": "Our key idea is to convert an RGB image pixel which a triplet value corresponding to red, blue and green colour component of an image at a specified spatial location to a single value by calculating a weighted sum of all three colour component." }, { "code": null, "e": 1038, "s": 1012, "text": "Algorithm for conversion:" }, { "code": null, "e": 1800, "s": 1038, "text": "Read RGB colour image into MATLAB environmentExtract Red, blue and green colour components from RGB image into 3 different 2-D matricesCreate a new matrix with the same number of rows and columns as RGB image, containing all zeros .Convert each RGB pixel values at location (i, j) to grayscale values by forming a weighted sum of the Red, Green, and Blue colour components and assign it to corresponding location (i, j) in new matrixgrayscale value at (i, j) = 0.2989 * R(i, j) + 0.5870 * G(i, j) + 0.1140 * B(i, j);Note: The coefficients that is used to calculate grayscale values are identical to those that is used to calculate luminance (E’y) in Rec. ITU-R BT.601-7 (Recommendation by radio-communication sector of ITU for Broadcasting service (Television))" }, { "code": null, "e": 1846, "s": 1800, "text": "Read RGB colour image into MATLAB environment" }, { "code": null, "e": 1937, "s": 1846, "text": "Extract Red, blue and green colour components from RGB image into 3 different 2-D matrices" }, { "code": null, "e": 2035, "s": 1937, "text": "Create a new matrix with the same number of rows and columns as RGB image, containing all zeros ." }, { "code": null, "e": 2237, "s": 2035, "text": "Convert each RGB pixel values at location (i, j) to grayscale values by forming a weighted sum of the Red, Green, and Blue colour components and assign it to corresponding location (i, j) in new matrix" }, { "code": null, "e": 2321, "s": 2237, "text": "grayscale value at (i, j) = 0.2989 * R(i, j) + 0.5870 * G(i, j) + 0.1140 * B(i, j);" }, { "code": null, "e": 2567, "s": 2321, "text": "Note: The coefficients that is used to calculate grayscale values are identical to those that is used to calculate luminance (E’y) in Rec. ITU-R BT.601-7 (Recommendation by radio-communication sector of ITU for Broadcasting service (Television))" }, { "code": null, "e": 2583, "s": 2567, "text": "Implementation:" }, { "code": null, "e": 3550, "s": 2583, "text": "% Function will take a colour image as input and will return a grayscale image \nfunction [gray_img] = colouredToGray(img)\n % Extract Red colour component to R, Green colour component to G \n % and Blue colour component to B \n R=img(:, :, 1);\n G=img(:, :, 2);\n B=img(:, :, 3);\n\n % Getting number of rows in M and number of column in N of RGB image matrix \n % ~ is used to ignore dimension of RGB image\n % as size(img) function will return row, column and dimension of the RGB image\n [M, N, ~]=size(img);\n\n % creating a new 2-d matrix 'gray_img' of size M*N of 'uint8' data type with all \n % elements as zero \n gray_img=zeros(M, N, 'uint8');\n\n % calculating grayscale values by forming a weighted sum of the R, G, and B components\n % for each pixel\n for i=1:M\n for j=1:N\n gray_img(i, j)=(R(i, j)*0.2989)+(G(i, j)*0.5870)+(B(i, j)*0.114);\n end\n end\nend\n" }, { "code": null, "e": 3611, "s": 3550, "text": "The above function will be called from MATLAB command window" }, { "code": null, "e": 3788, "s": 3611, "text": ">> % Reading an RGB image file in MATLAB environment \n>> img=imread('apple.jpg');\n\n>> % The above function will be called here\n>> I=colouredToGray(img);\n>> figure, imshow(I);\n" }, { "code": null, "e": 3795, "s": 3788, "text": "Input:" }, { "code": null, "e": 3803, "s": 3795, "text": "Output:" }, { "code": null, "e": 3815, "s": 3803, "text": "Advantages:" }, { "code": null, "e": 4130, "s": 3815, "text": "To store a single colour pixel of an RGB colour image we will need 8*3 = 24 bits (8 bit for each colour component), but when we convert an RGB image to grayscale image, only 8 bit is required to store a single pixel of the image. So we will need 33 % less memory to store grayscale image than to store an RGB image" }, { "code": null, "e": 4378, "s": 4130, "text": "Grayscale images are much easier to work within a variety of task like In many morphological operation and image segmentation problem, it is easier to work with single layered image (Grayscale image ) than a three-layered image (RGB colour image )" }, { "code": null, "e": 4473, "s": 4378, "text": "It is also easier to distinguish features of an image when we deal with a single layered image" }, { "code": null, "e": 4490, "s": 4473, "text": "Image-Processing" }, { "code": null, "e": 4516, "s": 4490, "text": "Advanced Computer Subject" } ]
JQuery | Set focus on a form input text field on page load
23 May, 2019 The task is to set the focus on form input text field using JQuery. To do so, Here are a few of the most used techniques discussed.First focus() method need to be discussed. jQuery focus() Method:The focus event happens when an element gets focus (Either selected by a mouse click or by “tab-navigating” to it).This method triggers the focus event, or adds a function to run when the focus event occurs.Syntax:Trigger the focus event for selected elements:$(selector).focus() Attach a function to the focus event:$(selector).focus(function) Parameters:function: This parameter is optional. It specifies the function to execute when the focus event occurs. Trigger the focus event for selected elements:$(selector).focus() $(selector).focus() Attach a function to the focus event:$(selector).focus(function) $(selector).focus(function) Parameters: function: This parameter is optional. It specifies the function to execute when the focus event occurs. Example 1: In this example the form input text field gets the focus as page loads by using focus() method . Here the input element is selected by input keyword in JQuery selector. <!DOCTYPE HTML><html> <head> <title> JQuery | Set focus on a form input text field on page load. </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> This input box gets the focus as the page loads. </p> <form id="form"> Input : <input type="text" name="input_field" /> </form> <br> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> $("input:text").focus(); </script></body> </html> Output: Before page loads: After page loads: Example 2: In this example the form input text field gets the focus as page loads by using focus() method . Here the input element is selected by id of form element and its own id in JQuery selector. <!DOCTYPE HTML><html> <head> <title> JQuery | Set focus on a form input text field on page load. </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> This input box gets the focus as the page loads. </p> <form id="form"> Input : <input id="form_input" type="text" name="input_field" /> </form> <br> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> $("#form #form_input").focus(); </script></body> </html> Output: Before page loads: After page loads: jQuery-Misc JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n23 May, 2019" }, { "code": null, "e": 202, "s": 28, "text": "The task is to set the focus on form input text field using JQuery. To do so, Here are a few of the most used techniques discussed.First focus() method need to be discussed." }, { "code": null, "e": 684, "s": 202, "text": "jQuery focus() Method:The focus event happens when an element gets focus (Either selected by a mouse click or by “tab-navigating” to it).This method triggers the focus event, or adds a function to run when the focus event occurs.Syntax:Trigger the focus event for selected elements:$(selector).focus()\nAttach a function to the focus event:$(selector).focus(function)\nParameters:function: This parameter is optional. It specifies the function to execute when the focus event occurs." }, { "code": null, "e": 751, "s": 684, "text": "Trigger the focus event for selected elements:$(selector).focus()\n" }, { "code": null, "e": 772, "s": 751, "text": "$(selector).focus()\n" }, { "code": null, "e": 838, "s": 772, "text": "Attach a function to the focus event:$(selector).focus(function)\n" }, { "code": null, "e": 867, "s": 838, "text": "$(selector).focus(function)\n" }, { "code": null, "e": 879, "s": 867, "text": "Parameters:" }, { "code": null, "e": 983, "s": 879, "text": "function: This parameter is optional. It specifies the function to execute when the focus event occurs." }, { "code": null, "e": 1163, "s": 983, "text": "Example 1: In this example the form input text field gets the focus as page loads by using focus() method . Here the input element is selected by input keyword in JQuery selector." }, { "code": "<!DOCTYPE HTML><html> <head> <title> JQuery | Set focus on a form input text field on page load. </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> This input box gets the focus as the page loads. </p> <form id=\"form\"> Input : <input type=\"text\" name=\"input_field\" /> </form> <br> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> $(\"input:text\").focus(); </script></body> </html>", "e": 1971, "s": 1163, "text": null }, { "code": null, "e": 1979, "s": 1971, "text": "Output:" }, { "code": null, "e": 1998, "s": 1979, "text": "Before page loads:" }, { "code": null, "e": 2016, "s": 1998, "text": "After page loads:" }, { "code": null, "e": 2216, "s": 2016, "text": "Example 2: In this example the form input text field gets the focus as page loads by using focus() method . Here the input element is selected by id of form element and its own id in JQuery selector." }, { "code": "<!DOCTYPE HTML><html> <head> <title> JQuery | Set focus on a form input text field on page load. </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> This input box gets the focus as the page loads. </p> <form id=\"form\"> Input : <input id=\"form_input\" type=\"text\" name=\"input_field\" /> </form> <br> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> $(\"#form #form_input\").focus(); </script></body> </html>", "e": 3073, "s": 2216, "text": null }, { "code": null, "e": 3081, "s": 3073, "text": "Output:" }, { "code": null, "e": 3100, "s": 3081, "text": "Before page loads:" }, { "code": null, "e": 3118, "s": 3100, "text": "After page loads:" }, { "code": null, "e": 3130, "s": 3118, "text": "jQuery-Misc" }, { "code": null, "e": 3141, "s": 3130, "text": "JavaScript" }, { "code": null, "e": 3158, "s": 3141, "text": "Web Technologies" } ]
JavaScript Array slice() Method
04 Oct, 2021 Below is the example of Array slice() method. Example:<script>function func() { // Original Array var arr = [23,56,87,32,75,13]; // Extracted array var new_arr = arr.slice(2,4); document.write(arr); document.write("<br>"); document.write(new_arr);}func();</script> <script>function func() { // Original Array var arr = [23,56,87,32,75,13]; // Extracted array var new_arr = arr.slice(2,4); document.write(arr); document.write("<br>"); document.write(new_arr);}func();</script> Output:[23,56,87,32,75,13] [87,32] [23,56,87,32,75,13] [87,32] The arr.slice() method returns a new array containing a portion of the array on which it is implemented. The original remains unchanged. Syntax: arr.slice(begin, end) Parameters: This method accepts two parameters as mentioned above and described below: begin: This parameter defines the starting index from where the portion is to be extracted. If this argument is missing then the method takes begin as 0 as it is the default start value. end: This parameter is the index up to which the portion is to be extracted (excluding the end index). If this argument is not defined then the array till the end is extracted as it is the default end value If the end value is greater than the length of the array, then the end value changes to length of the array. Return value: This method returns a new array containing some portion of the original array. Below examples illustrate the JavaScript Array slice() method: Example 1: In this example the slice() method extracts the entire array from the given string and returns it as the answer, Since no arguments were passed to it.var arr = [23,56,87,32,75,13]; var new_arr = arr.slice(); document.write(arr); document.write(new_arr); Output:[23,56,87,32,75,13] [23,56,87,32,75,13] var arr = [23,56,87,32,75,13]; var new_arr = arr.slice(); document.write(arr); document.write(new_arr); Output: [23,56,87,32,75,13] [23,56,87,32,75,13] Example 2: In this example the slice() method extracts the array starting from index 2 till the end of the array and returns it as the answer.var arr = [23,56,87,32,75,13]; var new_arr = arr.slice(2); document.write(arr); document.write(new_arr); Output:[23,56,87,32,75,13] [87,32,75,13] var arr = [23,56,87,32,75,13]; var new_arr = arr.slice(2); document.write(arr); document.write(new_arr); Output: [23,56,87,32,75,13] [87,32,75,13] Example 3: In this example the slice() method extracts the array from the given array starting from index 2 and including all the elements less than the index 4.var arr = [23,56,87,32,75,13]; var new_arr = arr.slice(2,4); document.write(arr); document.write(new_arr); Output:[23,56,87,32,75,13] [87,32] var arr = [23,56,87,32,75,13]; var new_arr = arr.slice(2,4); document.write(arr); document.write(new_arr); Output: [23,56,87,32,75,13] [87,32] Code for the above method is provided below: Program 1: <script>function func() { //Original Array var arr = [23,56,87,32,75,13]; //Extracted array var new_arr = arr.slice(); document.write(arr); document.write("<br>"); document.write(new_arr);}func();</script> Output: [23,56,87,32,75,13] [23,56,87,32,75,13] Program 2: <script>function func() { //Original Array var arr = [23,56,87,32,75,13]; //Extracted array var new_arr = arr.slice(2); document.write(arr); document.write("<br>"); document.write(new_arr); }func();</script> Output: [23,56,87,32,75,13] [87,32,75,13] Supported Browsers: The browsers supported by JavaScript Array slice() method are listed below: Google Chrome 1 above Edge 12 and above Firefox 1 and above Internet Explorer 4 and above Opera 4 and above Safari 1 and above ysachin2314 javascript-array JavaScript-Methods JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Oct, 2021" }, { "code": null, "e": 74, "s": 28, "text": "Below is the example of Array slice() method." }, { "code": null, "e": 318, "s": 74, "text": "Example:<script>function func() { // Original Array var arr = [23,56,87,32,75,13]; // Extracted array var new_arr = arr.slice(2,4); document.write(arr); document.write(\"<br>\"); document.write(new_arr);}func();</script>" }, { "code": "<script>function func() { // Original Array var arr = [23,56,87,32,75,13]; // Extracted array var new_arr = arr.slice(2,4); document.write(arr); document.write(\"<br>\"); document.write(new_arr);}func();</script>", "e": 554, "s": 318, "text": null }, { "code": null, "e": 589, "s": 554, "text": "Output:[23,56,87,32,75,13]\n[87,32]" }, { "code": null, "e": 617, "s": 589, "text": "[23,56,87,32,75,13]\n[87,32]" }, { "code": null, "e": 754, "s": 617, "text": "The arr.slice() method returns a new array containing a portion of the array on which it is implemented. The original remains unchanged." }, { "code": null, "e": 762, "s": 754, "text": "Syntax:" }, { "code": null, "e": 784, "s": 762, "text": "arr.slice(begin, end)" }, { "code": null, "e": 871, "s": 784, "text": "Parameters: This method accepts two parameters as mentioned above and described below:" }, { "code": null, "e": 1058, "s": 871, "text": "begin: This parameter defines the starting index from where the portion is to be extracted. If this argument is missing then the method takes begin as 0 as it is the default start value." }, { "code": null, "e": 1374, "s": 1058, "text": "end: This parameter is the index up to which the portion is to be extracted (excluding the end index). If this argument is not defined then the array till the end is extracted as it is the default end value If the end value is greater than the length of the array, then the end value changes to length of the array." }, { "code": null, "e": 1467, "s": 1374, "text": "Return value: This method returns a new array containing some portion of the original array." }, { "code": null, "e": 1530, "s": 1467, "text": "Below examples illustrate the JavaScript Array slice() method:" }, { "code": null, "e": 1843, "s": 1530, "text": "Example 1: In this example the slice() method extracts the entire array from the given string and returns it as the answer, Since no arguments were passed to it.var arr = [23,56,87,32,75,13];\nvar new_arr = arr.slice();\ndocument.write(arr);\ndocument.write(new_arr);\nOutput:[23,56,87,32,75,13]\n[23,56,87,32,75,13]\n" }, { "code": null, "e": 1948, "s": 1843, "text": "var arr = [23,56,87,32,75,13];\nvar new_arr = arr.slice();\ndocument.write(arr);\ndocument.write(new_arr);\n" }, { "code": null, "e": 1956, "s": 1948, "text": "Output:" }, { "code": null, "e": 1997, "s": 1956, "text": "[23,56,87,32,75,13]\n[23,56,87,32,75,13]\n" }, { "code": null, "e": 2286, "s": 1997, "text": "Example 2: In this example the slice() method extracts the array starting from index 2 till the end of the array and returns it as the answer.var arr = [23,56,87,32,75,13];\nvar new_arr = arr.slice(2);\ndocument.write(arr);\ndocument.write(new_arr);\nOutput:[23,56,87,32,75,13]\n[87,32,75,13]\n" }, { "code": null, "e": 2392, "s": 2286, "text": "var arr = [23,56,87,32,75,13];\nvar new_arr = arr.slice(2);\ndocument.write(arr);\ndocument.write(new_arr);\n" }, { "code": null, "e": 2400, "s": 2392, "text": "Output:" }, { "code": null, "e": 2435, "s": 2400, "text": "[23,56,87,32,75,13]\n[87,32,75,13]\n" }, { "code": null, "e": 2739, "s": 2435, "text": "Example 3: In this example the slice() method extracts the array from the given array starting from index 2 and including all the elements less than the index 4.var arr = [23,56,87,32,75,13];\nvar new_arr = arr.slice(2,4);\ndocument.write(arr);\ndocument.write(new_arr);\nOutput:[23,56,87,32,75,13]\n[87,32]\n" }, { "code": null, "e": 2847, "s": 2739, "text": "var arr = [23,56,87,32,75,13];\nvar new_arr = arr.slice(2,4);\ndocument.write(arr);\ndocument.write(new_arr);\n" }, { "code": null, "e": 2855, "s": 2847, "text": "Output:" }, { "code": null, "e": 2884, "s": 2855, "text": "[23,56,87,32,75,13]\n[87,32]\n" }, { "code": null, "e": 2929, "s": 2884, "text": "Code for the above method is provided below:" }, { "code": null, "e": 2940, "s": 2929, "text": "Program 1:" }, { "code": "<script>function func() { //Original Array var arr = [23,56,87,32,75,13]; //Extracted array var new_arr = arr.slice(); document.write(arr); document.write(\"<br>\"); document.write(new_arr);}func();</script>", "e": 3171, "s": 2940, "text": null }, { "code": null, "e": 3179, "s": 3171, "text": "Output:" }, { "code": null, "e": 3220, "s": 3179, "text": "[23,56,87,32,75,13]\n[23,56,87,32,75,13]\n" }, { "code": null, "e": 3231, "s": 3220, "text": "Program 2:" }, { "code": "<script>function func() { //Original Array var arr = [23,56,87,32,75,13]; //Extracted array var new_arr = arr.slice(2); document.write(arr); document.write(\"<br>\"); document.write(new_arr); }func();</script>", "e": 3464, "s": 3231, "text": null }, { "code": null, "e": 3472, "s": 3464, "text": "Output:" }, { "code": null, "e": 3507, "s": 3472, "text": "[23,56,87,32,75,13]\n[87,32,75,13]\n" }, { "code": null, "e": 3603, "s": 3507, "text": "Supported Browsers: The browsers supported by JavaScript Array slice() method are listed below:" }, { "code": null, "e": 3625, "s": 3603, "text": "Google Chrome 1 above" }, { "code": null, "e": 3643, "s": 3625, "text": "Edge 12 and above" }, { "code": null, "e": 3663, "s": 3643, "text": "Firefox 1 and above" }, { "code": null, "e": 3693, "s": 3663, "text": "Internet Explorer 4 and above" }, { "code": null, "e": 3711, "s": 3693, "text": "Opera 4 and above" }, { "code": null, "e": 3730, "s": 3711, "text": "Safari 1 and above" }, { "code": null, "e": 3742, "s": 3730, "text": "ysachin2314" }, { "code": null, "e": 3759, "s": 3742, "text": "javascript-array" }, { "code": null, "e": 3778, "s": 3759, "text": "JavaScript-Methods" }, { "code": null, "e": 3789, "s": 3778, "text": "JavaScript" }, { "code": null, "e": 3806, "s": 3789, "text": "Web Technologies" } ]
Start/Stop/Restart Services Using Systemctl in Linux
11 Feb, 2021 Systemctl is a controller or utility of Systemd(is an init system with compost for a set of programs executed in the background), with auxiliary in manage services, these commands are executed in mode root if you aren’t mode root the system, requesting the password of root. systemctl list-unit-files --type service -all Syntax: sudo systemctl start service.service The command start serves for starting (activate) one or more units specified on the command line. Example: sudo systemctl start mariadb Command Start Syntax: sudo systemctl stop service.service The command stop serves for stopping the service or (deactivate) one or more units specified on the command line. Example: sudo systemctl stop mariadb Command Stop and Status Syntax: sudo systemctl status service.service The command status serves to check the status of the service. Show terse runtime status information about one or more units, followed by the most recent log data from the journal. If no units are specified, show system status. Example: sudo systemctl status mariadb Command Status Syntax: sudo systemctl restart service.service The command restart serves for restarting the service in execution. Stop and then start one or more units specified on the command line. If the units are not running yet, they will be started. Example: sudo systemctl restart mariadb Command Restart Syntax: sudo systemctl enable name_service.service The enable command serves for executing the service since the initialization if consists of one or more units or unit instances. This will create a set of symlinks, as encoded in the [Install] sections of the indicated unit files. the system manager configuration is reloaded (in a way equivalent to daemon-reload), in order to ensure the changes are taken into account immediately. Example sudo systemctl enable mariadb Command Enable Command Status Syntax: sudo systemctl disable name_service.service The disable command serves for withdrawing the service since the initialization of one or more units. This removes all symlinks to the unit files backing the specified units from the unit configuration directory and hence undoes any changes made by enabling or link. Example: sudo systemctl disable mariadb Command Disable Command Status Linux-Tools Picked Technical Scripter 2020 Linux-Unix Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Feb, 2021" }, { "code": null, "e": 303, "s": 28, "text": "Systemctl is a controller or utility of Systemd(is an init system with compost for a set of programs executed in the background), with auxiliary in manage services, these commands are executed in mode root if you aren’t mode root the system, requesting the password of root." }, { "code": null, "e": 349, "s": 303, "text": "systemctl list-unit-files --type service -all" }, { "code": null, "e": 357, "s": 349, "text": "Syntax:" }, { "code": null, "e": 394, "s": 357, "text": "sudo systemctl start service.service" }, { "code": null, "e": 492, "s": 394, "text": "The command start serves for starting (activate) one or more units specified on the command line." }, { "code": null, "e": 501, "s": 492, "text": "Example:" }, { "code": null, "e": 530, "s": 501, "text": "sudo systemctl start mariadb" }, { "code": null, "e": 544, "s": 530, "text": "Command Start" }, { "code": null, "e": 552, "s": 544, "text": "Syntax:" }, { "code": null, "e": 588, "s": 552, "text": "sudo systemctl stop service.service" }, { "code": null, "e": 702, "s": 588, "text": "The command stop serves for stopping the service or (deactivate) one or more units specified on the command line." }, { "code": null, "e": 711, "s": 702, "text": "Example:" }, { "code": null, "e": 739, "s": 711, "text": "sudo systemctl stop mariadb" }, { "code": null, "e": 763, "s": 739, "text": "Command Stop and Status" }, { "code": null, "e": 771, "s": 763, "text": "Syntax:" }, { "code": null, "e": 809, "s": 771, "text": "sudo systemctl status service.service" }, { "code": null, "e": 1036, "s": 809, "text": "The command status serves to check the status of the service. Show terse runtime status information about one or more units, followed by the most recent log data from the journal. If no units are specified, show system status." }, { "code": null, "e": 1045, "s": 1036, "text": "Example:" }, { "code": null, "e": 1075, "s": 1045, "text": "sudo systemctl status mariadb" }, { "code": null, "e": 1090, "s": 1075, "text": "Command Status" }, { "code": null, "e": 1098, "s": 1090, "text": "Syntax:" }, { "code": null, "e": 1137, "s": 1098, "text": "sudo systemctl restart service.service" }, { "code": null, "e": 1330, "s": 1137, "text": "The command restart serves for restarting the service in execution. Stop and then start one or more units specified on the command line. If the units are not running yet, they will be started." }, { "code": null, "e": 1339, "s": 1330, "text": "Example:" }, { "code": null, "e": 1370, "s": 1339, "text": "sudo systemctl restart mariadb" }, { "code": null, "e": 1386, "s": 1370, "text": "Command Restart" }, { "code": null, "e": 1394, "s": 1386, "text": "Syntax:" }, { "code": null, "e": 1437, "s": 1394, "text": "sudo systemctl enable name_service.service" }, { "code": null, "e": 1821, "s": 1437, "text": "The enable command serves for executing the service since the initialization if consists of one or more units or unit instances. This will create a set of symlinks, as encoded in the [Install] sections of the indicated unit files. the system manager configuration is reloaded (in a way equivalent to daemon-reload), in order to ensure the changes are taken into account immediately. " }, { "code": null, "e": 1829, "s": 1821, "text": "Example" }, { "code": null, "e": 1859, "s": 1829, "text": "sudo systemctl enable mariadb" }, { "code": null, "e": 1874, "s": 1859, "text": "Command Enable" }, { "code": null, "e": 1889, "s": 1874, "text": "Command Status" }, { "code": null, "e": 1897, "s": 1889, "text": "Syntax:" }, { "code": null, "e": 1941, "s": 1897, "text": "sudo systemctl disable name_service.service" }, { "code": null, "e": 2208, "s": 1941, "text": "The disable command serves for withdrawing the service since the initialization of one or more units. This removes all symlinks to the unit files backing the specified units from the unit configuration directory and hence undoes any changes made by enabling or link." }, { "code": null, "e": 2217, "s": 2208, "text": "Example:" }, { "code": null, "e": 2248, "s": 2217, "text": "sudo systemctl disable mariadb" }, { "code": null, "e": 2264, "s": 2248, "text": "Command Disable" }, { "code": null, "e": 2279, "s": 2264, "text": "Command Status" }, { "code": null, "e": 2291, "s": 2279, "text": "Linux-Tools" }, { "code": null, "e": 2298, "s": 2291, "text": "Picked" }, { "code": null, "e": 2322, "s": 2298, "text": "Technical Scripter 2020" }, { "code": null, "e": 2333, "s": 2322, "text": "Linux-Unix" }, { "code": null, "e": 2352, "s": 2333, "text": "Technical Scripter" } ]
Enable In-Built Dark Mode on Windows 10
06 Jun, 2022 Most of us love to surf our desktop and apps through dark mode as it will reduce our eye strain and resultantly makes us more productive But many of us do not know how to enable dark mode on a Windows system. Windows 10 comes with the dark mode inbuilt. This can be achieved through the settings menu and it applies a dark theme to apps you get from the Windows Store. To enable dark mode in your Windows machine follow the below steps: Step 1: Navigate to your settings and click on personalization. Click on personalization Step 2: Click on Colors. Click on Colors Step 3: Now choose your color and set it as dark to enable dark mode. Enabling Dark Mode At this stage, the system sets itself into the Dark Mode. A simple before and after image from the Dark Mode is depicted below: The PC before enabling Dark Mode. Normal Mode The PC after enabling Dark Mode. Dark Mode sumitgumber28 Technical Scripter 2020 How To Technical Scripter TechTips Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n06 Jun, 2022" }, { "code": null, "e": 422, "s": 53, "text": "Most of us love to surf our desktop and apps through dark mode as it will reduce our eye strain and resultantly makes us more productive But many of us do not know how to enable dark mode on a Windows system. Windows 10 comes with the dark mode inbuilt. This can be achieved through the settings menu and it applies a dark theme to apps you get from the Windows Store." }, { "code": null, "e": 490, "s": 422, "text": "To enable dark mode in your Windows machine follow the below steps:" }, { "code": null, "e": 554, "s": 490, "text": "Step 1: Navigate to your settings and click on personalization." }, { "code": null, "e": 579, "s": 554, "text": "Click on personalization" }, { "code": null, "e": 604, "s": 579, "text": "Step 2: Click on Colors." }, { "code": null, "e": 620, "s": 604, "text": "Click on Colors" }, { "code": null, "e": 690, "s": 620, "text": "Step 3: Now choose your color and set it as dark to enable dark mode." }, { "code": null, "e": 709, "s": 690, "text": "Enabling Dark Mode" }, { "code": null, "e": 837, "s": 709, "text": "At this stage, the system sets itself into the Dark Mode. A simple before and after image from the Dark Mode is depicted below:" }, { "code": null, "e": 871, "s": 837, "text": "The PC before enabling Dark Mode." }, { "code": null, "e": 883, "s": 871, "text": "Normal Mode" }, { "code": null, "e": 916, "s": 883, "text": "The PC after enabling Dark Mode." }, { "code": null, "e": 926, "s": 916, "text": "Dark Mode" }, { "code": null, "e": 940, "s": 926, "text": "sumitgumber28" }, { "code": null, "e": 964, "s": 940, "text": "Technical Scripter 2020" }, { "code": null, "e": 971, "s": 964, "text": "How To" }, { "code": null, "e": 990, "s": 971, "text": "Technical Scripter" }, { "code": null, "e": 999, "s": 990, "text": "TechTips" } ]
Python Program to check for almost similar Strings
02 Feb, 2021 Given two strings, the task here is to write a python program that can test if they are almost similar. Similarity of strings is being checked on the criteria of frequency difference of each character which should be greater than a threshold here represented by K. Input : test_str1 = ‘aabcdaa’, test_str2 = “abbaccd”, K = 2 Output : True Explanation : ‘a’ occurs 4 times in str1, and 2 times in str2, 4 – 2 = 2, in range, similarly, all chars in range, hence true. Input : test_str1 = ‘aabcdaaa’, test_str2 = “abbaccda”, K = 3 Output : True Explanation : ‘a’ occurs 5 times in str1, and 3 times in str2, 5 – 3 = 2, in range, similarly, all chars in range, hence true. Method 1 : Using ascii_lowecase, dictionary comprehension, loop and abs() In this, we compute all the frequencies of all the characters in both strings using dictionary comprehension and loop. Next, each character is iterated from alphabetic lowercase ascii characters and tested for frequency difference in both strings using abs(), if any difference computes to greater than K, result is flagged off. Example Python3 from string import ascii_lowercase # function to compute frequencies def get_freq(test_str): # starting at 0 count freqs = {char: 0 for char in ascii_lowercase} # counting frequencies for char in test_str: freqs[char] += 1 return freqs # initializing stringstest_str1 = 'aabcdaa'test_str2 = "abbaccd" # printing original stringsprint("The original string 1 is : " + str(test_str1))print("The original string 2 is : " + str(test_str2)) # initializing KK = 2 # getting frequenciesfreqs_1 = get_freq(test_str1)freqs_2 = get_freq(test_str2) # checking for frequenciesres = Truefor char in ascii_lowercase: if abs(freqs_1[char] - freqs_2[char]) > K: res = False break # printing resultprint("Are strings similar ? : " + str(res)) Output: The original string 1 is : aabcdaa The original string 2 is : abbaccd Are strings similar ? : True Method 2 : Using Counter() and max() In this, we perform task of getting individual characters’ frequency using Counter() and get the maximum difference using max(), if greater than K, then result is flagged off. Example: Python3 from collections import Counter # initializing stringstest_str1 = 'aabcdaa'test_str2 = "abbaccd" # printing original stringsprint("The original string 1 is : " + str(test_str1))print("The original string 2 is : " + str(test_str2)) # initializing KK = 2 # extracting frequenciescnt1 = Counter(test_str1.lower())cnt2 = Counter(test_str2.lower()) # getting maximum differenceres = Trueif max((cnt1 - cnt2).values()) > K or max((cnt2 - cnt1).values()) > K: res = False # printing resultprint("Are strings similar ? : " + str(res)) Output: The original string 1 is : aabcdaa The original string 2 is : abbaccd Are strings similar ? : True Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Introduction To PYTHON Python OOPs Concepts Python | os.path.join() method Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python program to check whether a number is Prime or not Python | Convert string dictionary to dictionary
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Feb, 2021" }, { "code": null, "e": 293, "s": 28, "text": "Given two strings, the task here is to write a python program that can test if they are almost similar. Similarity of strings is being checked on the criteria of frequency difference of each character which should be greater than a threshold here represented by K." }, { "code": null, "e": 353, "s": 293, "text": "Input : test_str1 = ‘aabcdaa’, test_str2 = “abbaccd”, K = 2" }, { "code": null, "e": 367, "s": 353, "text": "Output : True" }, { "code": null, "e": 494, "s": 367, "text": "Explanation : ‘a’ occurs 4 times in str1, and 2 times in str2, 4 – 2 = 2, in range, similarly, all chars in range, hence true." }, { "code": null, "e": 556, "s": 494, "text": "Input : test_str1 = ‘aabcdaaa’, test_str2 = “abbaccda”, K = 3" }, { "code": null, "e": 570, "s": 556, "text": "Output : True" }, { "code": null, "e": 697, "s": 570, "text": "Explanation : ‘a’ occurs 5 times in str1, and 3 times in str2, 5 – 3 = 2, in range, similarly, all chars in range, hence true." }, { "code": null, "e": 771, "s": 697, "text": "Method 1 : Using ascii_lowecase, dictionary comprehension, loop and abs()" }, { "code": null, "e": 1100, "s": 771, "text": "In this, we compute all the frequencies of all the characters in both strings using dictionary comprehension and loop. Next, each character is iterated from alphabetic lowercase ascii characters and tested for frequency difference in both strings using abs(), if any difference computes to greater than K, result is flagged off." }, { "code": null, "e": 1108, "s": 1100, "text": "Example" }, { "code": null, "e": 1116, "s": 1108, "text": "Python3" }, { "code": "from string import ascii_lowercase # function to compute frequencies def get_freq(test_str): # starting at 0 count freqs = {char: 0 for char in ascii_lowercase} # counting frequencies for char in test_str: freqs[char] += 1 return freqs # initializing stringstest_str1 = 'aabcdaa'test_str2 = \"abbaccd\" # printing original stringsprint(\"The original string 1 is : \" + str(test_str1))print(\"The original string 2 is : \" + str(test_str2)) # initializing KK = 2 # getting frequenciesfreqs_1 = get_freq(test_str1)freqs_2 = get_freq(test_str2) # checking for frequenciesres = Truefor char in ascii_lowercase: if abs(freqs_1[char] - freqs_2[char]) > K: res = False break # printing resultprint(\"Are strings similar ? : \" + str(res))", "e": 1896, "s": 1116, "text": null }, { "code": null, "e": 1904, "s": 1896, "text": "Output:" }, { "code": null, "e": 1939, "s": 1904, "text": "The original string 1 is : aabcdaa" }, { "code": null, "e": 1974, "s": 1939, "text": "The original string 2 is : abbaccd" }, { "code": null, "e": 2003, "s": 1974, "text": "Are strings similar ? : True" }, { "code": null, "e": 2040, "s": 2003, "text": "Method 2 : Using Counter() and max()" }, { "code": null, "e": 2216, "s": 2040, "text": "In this, we perform task of getting individual characters’ frequency using Counter() and get the maximum difference using max(), if greater than K, then result is flagged off." }, { "code": null, "e": 2225, "s": 2216, "text": "Example:" }, { "code": null, "e": 2233, "s": 2225, "text": "Python3" }, { "code": "from collections import Counter # initializing stringstest_str1 = 'aabcdaa'test_str2 = \"abbaccd\" # printing original stringsprint(\"The original string 1 is : \" + str(test_str1))print(\"The original string 2 is : \" + str(test_str2)) # initializing KK = 2 # extracting frequenciescnt1 = Counter(test_str1.lower())cnt2 = Counter(test_str2.lower()) # getting maximum differenceres = Trueif max((cnt1 - cnt2).values()) > K or max((cnt2 - cnt1).values()) > K: res = False # printing resultprint(\"Are strings similar ? : \" + str(res))", "e": 2769, "s": 2233, "text": null }, { "code": null, "e": 2777, "s": 2769, "text": "Output:" }, { "code": null, "e": 2812, "s": 2777, "text": "The original string 1 is : aabcdaa" }, { "code": null, "e": 2847, "s": 2812, "text": "The original string 2 is : abbaccd" }, { "code": null, "e": 2876, "s": 2847, "text": "Are strings similar ? : True" }, { "code": null, "e": 2899, "s": 2876, "text": "Python string-programs" }, { "code": null, "e": 2906, "s": 2899, "text": "Python" }, { "code": null, "e": 2922, "s": 2906, "text": "Python Programs" }, { "code": null, "e": 3020, "s": 2922, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3052, "s": 3020, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3079, "s": 3052, "text": "Python Classes and Objects" }, { "code": null, "e": 3102, "s": 3079, "text": "Introduction To PYTHON" }, { "code": null, "e": 3123, "s": 3102, "text": "Python OOPs Concepts" }, { "code": null, "e": 3154, "s": 3123, "text": "Python | os.path.join() method" }, { "code": null, "e": 3176, "s": 3154, "text": "Defaultdict in Python" }, { "code": null, "e": 3215, "s": 3176, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 3253, "s": 3215, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 3310, "s": 3253, "text": "Python program to check whether a number is Prime or not" } ]
Sequences of given length where every element is more than or equal to twice of previous
21 Jun, 2022 Given two integers m & n, find the number of possible sequences of length n such that each of the next element is greater than or equal to twice of the previous element but less than or equal to m. Examples : Input : m = 10, n = 4 Output : 4 There should be n elements and value of last element should be at-most m. The sequences are {1, 2, 4, 8}, {1, 2, 4, 9}, {1, 2, 4, 10}, {1, 2, 5, 10} Input : m = 5, n = 2 Output : 6 The sequences are {1, 2}, {1, 3}, {1, 4}, {1, 5}, {2, 4}, {2, 5} As per the given condition the n-th value of the sequence can be at most m. There can be two cases for n-th element: If it is m, then the (n-1)th element is at most m/2. We recur for m/2 and n-1.If it is not m, then it is at most is m-1. We recur for (m-1) and n. If it is m, then the (n-1)th element is at most m/2. We recur for m/2 and n-1. If it is not m, then it is at most is m-1. We recur for (m-1) and n. The total number of sequences is the sum of the number of sequences including m and the number of sequences where m is not included. Thus the original problem of finding number of sequences of length n with max value m can be subdivided into independent subproblems of finding number of sequences of length n with max value m-1 and number of sequences of length n-1 with max value m/2. C++ Java Python3 C# PHP Javascript // C++ program to count total number// of special sequences of length n where#include <iostream>using namespace std; // Recursive function to find the number of special// sequencesint getTotalNumberOfSequences(int m, int n){ // A special sequence cannot exist if length // n is more than the maximum value m. if (m < n) return 0; // If n is 0, found an empty special sequence if (n == 0) return 1; // There can be two possibilities : (1) Reduce // last element value (2) Consider last element // as m and reduce number of terms return getTotalNumberOfSequences(m - 1, n) + getTotalNumberOfSequences(m / 2, n - 1);} // Driver codeint main(){ int m = 10; int n = 4; cout << "Total number of possible sequences " << getTotalNumberOfSequences(m, n); return 0;} // This code is contributed by shivanisinghss2110 // Java program to count total number// of special sequences of length n whereclass Sequences{ // Recursive function to find the number of special // sequences static int getTotalNumberOfSequences(int m, int n) { // A special sequence cannot exist if length // n is more than the maximum value m. if(m < n) return 0; // If n is 0, found an empty special sequence if(n == 0) return 1; // There can be two possibilities : (1) Reduce // last element value (2) Consider last element // as m and reduce number of terms return getTotalNumberOfSequences (m-1, n) + getTotalNumberOfSequences (m/2, n-1); } // main function public static void main (String[] args) { int m = 10; int n = 4; System.out.println("Total number of possible sequences "+ getTotalNumberOfSequences(m, n)); }} #Python3 program to count total number of#special sequences of length n where#Recursive function to find the number of# special sequencesdef getTotalNumberOfSequences(m,n): #A special sequence cannot exist if length #n is more than the maximum value m. if m<n: return 0 #If n is 0, found an empty special sequence if n==0: return 1 #There can be two possibilities : (1) Reduce #last element value (2) Consider last element #as m and reduce number of terms res=(getTotalNumberOfSequences(m-1,n)+ getTotalNumberOfSequences(m//2,n-1)) return res #Driver Codeif __name__=='__main__': m=10 n=4 print('Total number of possible sequences:',getTotalNumberOfSequences(m,n)) #This code is contributed by sahilshelangia // C# program to count total number// of special sequences of length n// where every element is more than// or equal to twice of previoususing System; class GFG{ // Recursive function to find // the number of special sequences static int getTotalNumberOfSequences(int m, int n) { // A special sequence cannot exist if length // n is more than the maximum value m. if(m < n) return 0; // If n is 0, found an empty special sequence if(n == 0) return 1; // There can be two possibilities : (1) Reduce // last element value (2) Consider last element // as m and reduce number of terms return getTotalNumberOfSequences (m-1, n) + getTotalNumberOfSequences (m/2, n-1); } // Driver code public static void Main () { int m = 10; int n = 4; Console.Write("Total number of possible sequences " + getTotalNumberOfSequences(m, n)); }} // This code is contributed by nitin mittal. <?php// PHP program to count total// number of special sequences// of length n where // Recursive function to find// the number of special sequencesfunction getTotalNumberOfSequences($m, $n){ // A special sequence cannot // exist if length n is more // than the maximum value m. if ($m < $n) return 0; // If n is 0, found an empty // special sequence if ($n == 0) return 1; // There can be two possibilities : // (1) Reduce last element value // (2) Consider last element // as m and reduce number of terms return getTotalNumberOfSequences($m - 1, $n) + getTotalNumberOfSequences($m / 2, $n - 1);} // Driver Code $m = 10; $n = 4; echo("Total number of possible sequences "); echo (getTotalNumberOfSequences($m, $n)); // This code is contributed by nitin mittal.?> <script>// program to count total number of special sequences// of length n where // Recursive function to find the number of special// sequences function getTotalNumberOfSequences( m, n){ // A special sequence cannot exist if length // n is more than the maximum value m. if (m < n) return 0; // If n is 0, found an empty special sequence if (n == 0) return 1; // There can be two possibilities : (1) Reduce // last element value (2) Consider last element // as m and reduce number of terms return getTotalNumberOfSequences (m-1, n) + getTotalNumberOfSequences (m/2, n-1);} // Driver Code let m = 10; let n = 4; document.write ("Total number of possible sequences ", getTotalNumberOfSequences(m, n)); // This code is contributed by anikakapoor.</script> Output: Total number of possible sequences 4 Complexity Analysis: Time Complexity: O(2m) in the worst case Space Complexity: O(m), depth of recursion tree is m in the worst case. Note that the above function computes the same sub problems again and again. Consider the following tree for f(10, 4). Recursive Tree for m= 10 and N =4 We can solve this problem using dynamic programming. C++ Java Python3 C# PHP Javascript // C program to count total number of special sequences// of length N where#include <stdio.h> // DP based function to find the number of special// sequencesint getTotalNumberOfSequences(int m, int n){ // define T and build in bottom manner to store // number of special sequences of length n and // maximum value m int T[m+1][n+1]; for (int i=0; i<m+1; i++) { for (int j=0; j<n+1; j++) { // Base case : If length of sequence is 0 // or maximum value is 0, there cannot // exist any special sequence if (i == 0 || j == 0) T[i][j] = 0; // if length of sequence is more than // the maximum value, special sequence // cannot exist else if (i < j) T[i][j] = 0; // If length of sequence is 1 then the // number of special sequences is equal // to the maximum value // For example with maximum value 2 and // length 1, there can be 2 special // sequences {1}, {2} else if (j == 1) T[i][j] = i; // otherwise calculate else T[i][j] = T[i-1][j] + T[i/2][j-1]; } } return T[m][n];} // Driver Codeint main(){ int m = 10; int n = 4; printf("Total number of possible sequences %d", getTotalNumberOfSequences(m, n)); return 0;} // Efficient java program to count total number// of special sequences of length n whereclass Sequences{ // DP based function to find the number of special // sequences static int getTotalNumberOfSequences(int m, int n) { // define T and build in bottom manner to store // number of special sequences of length n and // maximum value m int T[][]=new int[m+1][n+1]; for (int i=0; i<m+1; i++) { for (int j=0; j<n+1; j++) { // Base case : If length of sequence is 0 // or maximum value is 0, there cannot // exist any special sequence if (i == 0 || j == 0) T[i][j] = 0; // if length of sequence is more than // the maximum value, special sequence // cannot exist else if (i < j) T[i][j] = 0; // If length of sequence is 1 then the // number of special sequences is equal // to the maximum value // For example with maximum value 2 and // length 1, there can be 2 special // sequences {1}, {2} else if (j == 1) T[i][j] = i; // otherwise calculate else T[i][j] = T[i-1][j] + T[i/2][j-1]; } } return T[m][n]; } // main function public static void main (String[] args) { int m = 10; int n = 4; System.out.println("Total number of possible sequences "+ getTotalNumberOfSequences(m, n)); }} #Python3 program to count total number of#special sequences of length N where #DP based function to find the number# of special sequencedef getTotalNumberOfSequences(m,n): #define T and build in bottom manner to store #number of special sequences of length n and #maximum value m T=[[0 for i in range(n+1)] for i in range(m+1)] for i in range(m+1): for j in range(n+1): #Base case : If length of sequence is 0 # or maximum value is 0, there cannot #exist any special sequence if i==0 or j==0: T[i][j]=0 #if length of sequence is more than #the maximum value, special sequence # cannot exist elif i<j: T[i][j]=0 # If length of sequence is 1 then the # number of special sequences is equal # to the maximum value # For example with maximum value 2 and # length 1, there can be 2 special # sequences {1}, {2} elif j==1: T[i][j]=i else: T[i][j]=T[i-1][j]+T[i//2][j-1] return T[m][n] #Driver Codeif __name__=='__main__': m=10 n=4 print('Total number of possible sequences ',getTotalNumberOfSequences(m, n)) #This code is contributed by sahilshelangia // Efficient C# program to count total number// of special sequences of length n whereusing System;class Sequences { // DP based function to find // the number of special // sequences static int getTotalNumberOfSequences(int m, int n) { // define T and build in // bottom manner to store // number of special sequences // of length n and maximum value m int [,]T=new int[m + 1, n + 1]; for (int i = 0; i < m + 1; i++) { for (int j = 0; j < n + 1; j++) { // Base case : If length // of sequence is 0 // or maximum value is // 0, there cannot // exist any special // sequence if (i == 0 || j == 0) T[i, j] = 0; // if length of sequence // is more than the maximum // value, special sequence // cannot exist else if (i < j) T[i,j] = 0; // If length of sequence is 1 then the // number of special sequences is equal // to the maximum value // For example with maximum value 2 and // length 1, there can be 2 special // sequences {1}, {2} else if (j == 1) T[i,j] = i; // otherwise calculate else T[i,j] = T[i - 1, j] + T[i / 2, j - 1]; } } return T[m,n]; } // Driver Code public static void Main () { int m = 10; int n = 4; Console.WriteLine("Total number of possible sequences "+ getTotalNumberOfSequences(m, n)); }} // This code is contributed by anuj_67. <?php// PHP program to count total// number of special sequences// of length N where // DP based function to find// the number of special// sequencesfunction getTotalNumberOfSequences($m, $n){ // define T and build in bottom // manner to store number of // special sequences of length // n and maximum value m $T = array(array()); for ($i = 0; $i < $m + 1; $i++) { for ($j = 0; $j < $n + 1; $j++) { // Base case : If length of // sequence is 0 or maximum // value is 0, there cannot // exist any special sequence if ($i == 0 or $j == 0) $T[$i][$j] = 0; // if length of sequence is // more than the maximum value, // special sequence cannot exist else if ($i < $j) $T[$i][$j] = 0; // If length of sequence is // 1 then the number of // special sequences is equal // to the maximum value // For example with maximum // value 2 and length 1, there // can be 2 special sequences // {1}, {2} else if ($j == 1) $T[$i][$j] = $i; // otherwise calculate else $T[$i][$j] = $T[$i - 1][$j] + $T[$i / 2][$j - 1]; } } return $T[$m][$n];} // Driver Code $m = 10; $n = 4; echo "Total number of possible sequences ", getTotalNumberOfSequences($m, $n); // This code is contributed by anuj_67.?> <script> // Efficient javascript program to count total number // of special sequences of length n where // DP based function to find the number of special // sequences function getTotalNumberOfSequences(m, n) { // define T and build in bottom manner to store // number of special sequences of length n and // maximum value m let T = new Array(m+1); for (let i=0; i<m+1; i++) { T[i] = new Array(n+1); for (let j=0; j<n+1; j++) { // Base case : If length of sequence is 0 // or maximum value is 0, there cannot // exist any special sequence if (i == 0 || j == 0) T[i][j] = 0; // if length of sequence is more than // the maximum value, special sequence // cannot exist else if (i < j) T[i][j] = 0; // If length of sequence is 1 then the // number of special sequences is equal // to the maximum value // For example with maximum value 2 and // length 1, there can be 2 special // sequences {1}, {2} else if (j == 1) T[i][j] = i; // otherwise calculate else T[i][j] = T[i-1][j] + T[parseInt(i/2, 10)][j-1]; } } return T[m][n]; } let m = 10; let n = 4; document.write("Total number of possible sequences "+ getTotalNumberOfSequences(m, n)); // This code is contributed rameshtravel07.</script> Output: 4 Time Complexity : O(m x n) Auxiliary Space : O(m x n) This article is contributed by Bahubali. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal vt_m sahilshelangia _singhsatinder_ anikakapoor rameshtravel07 shivanisinghss2110 sainitushar438 Divide and Conquer Dynamic Programming Dynamic Programming Divide and Conquer Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n21 Jun, 2022" }, { "code": null, "e": 252, "s": 54, "text": "Given two integers m & n, find the number of possible sequences of length n such that each of the next element is greater than or equal to twice of the previous element but less than or equal to m." }, { "code": null, "e": 264, "s": 252, "text": "Examples : " }, { "code": null, "e": 579, "s": 264, "text": "Input : m = 10, n = 4\nOutput : 4\nThere should be n elements and value of last\nelement should be at-most m.\nThe sequences are {1, 2, 4, 8}, {1, 2, 4, 9},\n {1, 2, 4, 10}, {1, 2, 5, 10}\n\nInput : m = 5, n = 2\nOutput : 6\nThe sequences are {1, 2}, {1, 3}, {1, 4},\n {1, 5}, {2, 4}, {2, 5}" }, { "code": null, "e": 698, "s": 579, "text": "As per the given condition the n-th value of the sequence can be at most m. There can be two cases for n-th element: " }, { "code": null, "e": 845, "s": 698, "text": "If it is m, then the (n-1)th element is at most m/2. We recur for m/2 and n-1.If it is not m, then it is at most is m-1. We recur for (m-1) and n." }, { "code": null, "e": 924, "s": 845, "text": "If it is m, then the (n-1)th element is at most m/2. We recur for m/2 and n-1." }, { "code": null, "e": 993, "s": 924, "text": "If it is not m, then it is at most is m-1. We recur for (m-1) and n." }, { "code": null, "e": 1379, "s": 993, "text": "The total number of sequences is the sum of the number of sequences including m and the number of sequences where m is not included. Thus the original problem of finding number of sequences of length n with max value m can be subdivided into independent subproblems of finding number of sequences of length n with max value m-1 and number of sequences of length n-1 with max value m/2." }, { "code": null, "e": 1383, "s": 1379, "text": "C++" }, { "code": null, "e": 1388, "s": 1383, "text": "Java" }, { "code": null, "e": 1396, "s": 1388, "text": "Python3" }, { "code": null, "e": 1399, "s": 1396, "text": "C#" }, { "code": null, "e": 1403, "s": 1399, "text": "PHP" }, { "code": null, "e": 1414, "s": 1403, "text": "Javascript" }, { "code": "// C++ program to count total number// of special sequences of length n where#include <iostream>using namespace std; // Recursive function to find the number of special// sequencesint getTotalNumberOfSequences(int m, int n){ // A special sequence cannot exist if length // n is more than the maximum value m. if (m < n) return 0; // If n is 0, found an empty special sequence if (n == 0) return 1; // There can be two possibilities : (1) Reduce // last element value (2) Consider last element // as m and reduce number of terms return getTotalNumberOfSequences(m - 1, n) + getTotalNumberOfSequences(m / 2, n - 1);} // Driver codeint main(){ int m = 10; int n = 4; cout << \"Total number of possible sequences \" << getTotalNumberOfSequences(m, n); return 0;} // This code is contributed by shivanisinghss2110", "e": 2303, "s": 1414, "text": null }, { "code": "// Java program to count total number// of special sequences of length n whereclass Sequences{ // Recursive function to find the number of special // sequences static int getTotalNumberOfSequences(int m, int n) { // A special sequence cannot exist if length // n is more than the maximum value m. if(m < n) return 0; // If n is 0, found an empty special sequence if(n == 0) return 1; // There can be two possibilities : (1) Reduce // last element value (2) Consider last element // as m and reduce number of terms return getTotalNumberOfSequences (m-1, n) + getTotalNumberOfSequences (m/2, n-1); } // main function public static void main (String[] args) { int m = 10; int n = 4; System.out.println(\"Total number of possible sequences \"+ getTotalNumberOfSequences(m, n)); }}", "e": 3267, "s": 2303, "text": null }, { "code": "#Python3 program to count total number of#special sequences of length n where#Recursive function to find the number of# special sequencesdef getTotalNumberOfSequences(m,n): #A special sequence cannot exist if length #n is more than the maximum value m. if m<n: return 0 #If n is 0, found an empty special sequence if n==0: return 1 #There can be two possibilities : (1) Reduce #last element value (2) Consider last element #as m and reduce number of terms res=(getTotalNumberOfSequences(m-1,n)+ getTotalNumberOfSequences(m//2,n-1)) return res #Driver Codeif __name__=='__main__': m=10 n=4 print('Total number of possible sequences:',getTotalNumberOfSequences(m,n)) #This code is contributed by sahilshelangia", "e": 4044, "s": 3267, "text": null }, { "code": "// C# program to count total number// of special sequences of length n// where every element is more than// or equal to twice of previoususing System; class GFG{ // Recursive function to find // the number of special sequences static int getTotalNumberOfSequences(int m, int n) { // A special sequence cannot exist if length // n is more than the maximum value m. if(m < n) return 0; // If n is 0, found an empty special sequence if(n == 0) return 1; // There can be two possibilities : (1) Reduce // last element value (2) Consider last element // as m and reduce number of terms return getTotalNumberOfSequences (m-1, n) + getTotalNumberOfSequences (m/2, n-1); } // Driver code public static void Main () { int m = 10; int n = 4; Console.Write(\"Total number of possible sequences \" + getTotalNumberOfSequences(m, n)); }} // This code is contributed by nitin mittal.", "e": 5100, "s": 4044, "text": null }, { "code": "<?php// PHP program to count total// number of special sequences// of length n where // Recursive function to find// the number of special sequencesfunction getTotalNumberOfSequences($m, $n){ // A special sequence cannot // exist if length n is more // than the maximum value m. if ($m < $n) return 0; // If n is 0, found an empty // special sequence if ($n == 0) return 1; // There can be two possibilities : // (1) Reduce last element value // (2) Consider last element // as m and reduce number of terms return getTotalNumberOfSequences($m - 1, $n) + getTotalNumberOfSequences($m / 2, $n - 1);} // Driver Code $m = 10; $n = 4; echo(\"Total number of possible sequences \"); echo (getTotalNumberOfSequences($m, $n)); // This code is contributed by nitin mittal.?>", "e": 5947, "s": 5100, "text": null }, { "code": "<script>// program to count total number of special sequences// of length n where // Recursive function to find the number of special// sequences function getTotalNumberOfSequences( m, n){ // A special sequence cannot exist if length // n is more than the maximum value m. if (m < n) return 0; // If n is 0, found an empty special sequence if (n == 0) return 1; // There can be two possibilities : (1) Reduce // last element value (2) Consider last element // as m and reduce number of terms return getTotalNumberOfSequences (m-1, n) + getTotalNumberOfSequences (m/2, n-1);} // Driver Code let m = 10; let n = 4; document.write (\"Total number of possible sequences \", getTotalNumberOfSequences(m, n)); // This code is contributed by anikakapoor.</script>", "e": 6814, "s": 5947, "text": null }, { "code": null, "e": 6823, "s": 6814, "text": "Output: " }, { "code": null, "e": 6860, "s": 6823, "text": "Total number of possible sequences 4" }, { "code": null, "e": 6881, "s": 6860, "text": "Complexity Analysis:" }, { "code": null, "e": 6923, "s": 6881, "text": "Time Complexity: O(2m) in the worst case" }, { "code": null, "e": 6995, "s": 6923, "text": "Space Complexity: O(m), depth of recursion tree is m in the worst case." }, { "code": null, "e": 7114, "s": 6995, "text": "Note that the above function computes the same sub problems again and again. Consider the following tree for f(10, 4)." }, { "code": null, "e": 7148, "s": 7114, "text": "Recursive Tree for m= 10 and N =4" }, { "code": null, "e": 7201, "s": 7148, "text": "We can solve this problem using dynamic programming." }, { "code": null, "e": 7205, "s": 7201, "text": "C++" }, { "code": null, "e": 7210, "s": 7205, "text": "Java" }, { "code": null, "e": 7218, "s": 7210, "text": "Python3" }, { "code": null, "e": 7221, "s": 7218, "text": "C#" }, { "code": null, "e": 7225, "s": 7221, "text": "PHP" }, { "code": null, "e": 7236, "s": 7225, "text": "Javascript" }, { "code": "// C program to count total number of special sequences// of length N where#include <stdio.h> // DP based function to find the number of special// sequencesint getTotalNumberOfSequences(int m, int n){ // define T and build in bottom manner to store // number of special sequences of length n and // maximum value m int T[m+1][n+1]; for (int i=0; i<m+1; i++) { for (int j=0; j<n+1; j++) { // Base case : If length of sequence is 0 // or maximum value is 0, there cannot // exist any special sequence if (i == 0 || j == 0) T[i][j] = 0; // if length of sequence is more than // the maximum value, special sequence // cannot exist else if (i < j) T[i][j] = 0; // If length of sequence is 1 then the // number of special sequences is equal // to the maximum value // For example with maximum value 2 and // length 1, there can be 2 special // sequences {1}, {2} else if (j == 1) T[i][j] = i; // otherwise calculate else T[i][j] = T[i-1][j] + T[i/2][j-1]; } } return T[m][n];} // Driver Codeint main(){ int m = 10; int n = 4; printf(\"Total number of possible sequences %d\", getTotalNumberOfSequences(m, n)); return 0;}", "e": 8803, "s": 7236, "text": null }, { "code": "// Efficient java program to count total number// of special sequences of length n whereclass Sequences{ // DP based function to find the number of special // sequences static int getTotalNumberOfSequences(int m, int n) { // define T and build in bottom manner to store // number of special sequences of length n and // maximum value m int T[][]=new int[m+1][n+1]; for (int i=0; i<m+1; i++) { for (int j=0; j<n+1; j++) { // Base case : If length of sequence is 0 // or maximum value is 0, there cannot // exist any special sequence if (i == 0 || j == 0) T[i][j] = 0; // if length of sequence is more than // the maximum value, special sequence // cannot exist else if (i < j) T[i][j] = 0; // If length of sequence is 1 then the // number of special sequences is equal // to the maximum value // For example with maximum value 2 and // length 1, there can be 2 special // sequences {1}, {2} else if (j == 1) T[i][j] = i; // otherwise calculate else T[i][j] = T[i-1][j] + T[i/2][j-1]; } } return T[m][n]; } // main function public static void main (String[] args) { int m = 10; int n = 4; System.out.println(\"Total number of possible sequences \"+ getTotalNumberOfSequences(m, n)); }}", "e": 10627, "s": 8803, "text": null }, { "code": "#Python3 program to count total number of#special sequences of length N where #DP based function to find the number# of special sequencedef getTotalNumberOfSequences(m,n): #define T and build in bottom manner to store #number of special sequences of length n and #maximum value m T=[[0 for i in range(n+1)] for i in range(m+1)] for i in range(m+1): for j in range(n+1): #Base case : If length of sequence is 0 # or maximum value is 0, there cannot #exist any special sequence if i==0 or j==0: T[i][j]=0 #if length of sequence is more than #the maximum value, special sequence # cannot exist elif i<j: T[i][j]=0 # If length of sequence is 1 then the # number of special sequences is equal # to the maximum value # For example with maximum value 2 and # length 1, there can be 2 special # sequences {1}, {2} elif j==1: T[i][j]=i else: T[i][j]=T[i-1][j]+T[i//2][j-1] return T[m][n] #Driver Codeif __name__=='__main__': m=10 n=4 print('Total number of possible sequences ',getTotalNumberOfSequences(m, n)) #This code is contributed by sahilshelangia", "e": 11951, "s": 10627, "text": null }, { "code": "// Efficient C# program to count total number// of special sequences of length n whereusing System;class Sequences { // DP based function to find // the number of special // sequences static int getTotalNumberOfSequences(int m, int n) { // define T and build in // bottom manner to store // number of special sequences // of length n and maximum value m int [,]T=new int[m + 1, n + 1]; for (int i = 0; i < m + 1; i++) { for (int j = 0; j < n + 1; j++) { // Base case : If length // of sequence is 0 // or maximum value is // 0, there cannot // exist any special // sequence if (i == 0 || j == 0) T[i, j] = 0; // if length of sequence // is more than the maximum // value, special sequence // cannot exist else if (i < j) T[i,j] = 0; // If length of sequence is 1 then the // number of special sequences is equal // to the maximum value // For example with maximum value 2 and // length 1, there can be 2 special // sequences {1}, {2} else if (j == 1) T[i,j] = i; // otherwise calculate else T[i,j] = T[i - 1, j] + T[i / 2, j - 1]; } } return T[m,n]; } // Driver Code public static void Main () { int m = 10; int n = 4; Console.WriteLine(\"Total number of possible sequences \"+ getTotalNumberOfSequences(m, n)); }} // This code is contributed by anuj_67.", "e": 13989, "s": 11951, "text": null }, { "code": "<?php// PHP program to count total// number of special sequences// of length N where // DP based function to find// the number of special// sequencesfunction getTotalNumberOfSequences($m, $n){ // define T and build in bottom // manner to store number of // special sequences of length // n and maximum value m $T = array(array()); for ($i = 0; $i < $m + 1; $i++) { for ($j = 0; $j < $n + 1; $j++) { // Base case : If length of // sequence is 0 or maximum // value is 0, there cannot // exist any special sequence if ($i == 0 or $j == 0) $T[$i][$j] = 0; // if length of sequence is // more than the maximum value, // special sequence cannot exist else if ($i < $j) $T[$i][$j] = 0; // If length of sequence is // 1 then the number of // special sequences is equal // to the maximum value // For example with maximum // value 2 and length 1, there // can be 2 special sequences // {1}, {2} else if ($j == 1) $T[$i][$j] = $i; // otherwise calculate else $T[$i][$j] = $T[$i - 1][$j] + $T[$i / 2][$j - 1]; } } return $T[$m][$n];} // Driver Code $m = 10; $n = 4; echo \"Total number of possible sequences \", getTotalNumberOfSequences($m, $n); // This code is contributed by anuj_67.?>", "e": 15728, "s": 13989, "text": null }, { "code": "<script> // Efficient javascript program to count total number // of special sequences of length n where // DP based function to find the number of special // sequences function getTotalNumberOfSequences(m, n) { // define T and build in bottom manner to store // number of special sequences of length n and // maximum value m let T = new Array(m+1); for (let i=0; i<m+1; i++) { T[i] = new Array(n+1); for (let j=0; j<n+1; j++) { // Base case : If length of sequence is 0 // or maximum value is 0, there cannot // exist any special sequence if (i == 0 || j == 0) T[i][j] = 0; // if length of sequence is more than // the maximum value, special sequence // cannot exist else if (i < j) T[i][j] = 0; // If length of sequence is 1 then the // number of special sequences is equal // to the maximum value // For example with maximum value 2 and // length 1, there can be 2 special // sequences {1}, {2} else if (j == 1) T[i][j] = i; // otherwise calculate else T[i][j] = T[i-1][j] + T[parseInt(i/2, 10)][j-1]; } } return T[m][n]; } let m = 10; let n = 4; document.write(\"Total number of possible sequences \"+ getTotalNumberOfSequences(m, n)); // This code is contributed rameshtravel07.</script>", "e": 17569, "s": 15728, "text": null }, { "code": null, "e": 17578, "s": 17569, "text": "Output: " }, { "code": null, "e": 17580, "s": 17578, "text": "4" }, { "code": null, "e": 17634, "s": 17580, "text": "Time Complexity : O(m x n) Auxiliary Space : O(m x n)" }, { "code": null, "e": 18051, "s": 17634, "text": "This article is contributed by Bahubali. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 18064, "s": 18051, "text": "nitin mittal" }, { "code": null, "e": 18069, "s": 18064, "text": "vt_m" }, { "code": null, "e": 18084, "s": 18069, "text": "sahilshelangia" }, { "code": null, "e": 18100, "s": 18084, "text": "_singhsatinder_" }, { "code": null, "e": 18112, "s": 18100, "text": "anikakapoor" }, { "code": null, "e": 18127, "s": 18112, "text": "rameshtravel07" }, { "code": null, "e": 18146, "s": 18127, "text": "shivanisinghss2110" }, { "code": null, "e": 18161, "s": 18146, "text": "sainitushar438" }, { "code": null, "e": 18180, "s": 18161, "text": "Divide and Conquer" }, { "code": null, "e": 18200, "s": 18180, "text": "Dynamic Programming" }, { "code": null, "e": 18220, "s": 18200, "text": "Dynamic Programming" }, { "code": null, "e": 18239, "s": 18220, "text": "Divide and Conquer" } ]
Pattern Printing question asked in CGI Coding Round
22 Oct, 2021 Write a program that receives a number as input and prints it in the following format as shown below. Examples : Input : n = 3 Output : 1*2*3*10*11*12 --4*5*8*9 ----6*7 Input : n = 4 Output : 1*2*3*4*17*18*19*20 --5*6*7*14*15*16 ----8*9*12*13 ------10*11 Asked in CGI coding round Approach: The approach is to see the problem, not as a single task but three tasks which, on combining, complete the main task. The three tasks are printing the left-half of the pattern, printing dashes(-), and printing the right-half of the pattern. Combining all three tasks, we would be able to print the pattern. left-half of pattern 1*2*3* --4*5* ----6* A function printdashes() to print the "-". right-half of pattern 10*11*12 *8*9 7 Below is the implementation. C++ Java Python3 C# PHP Javascript // C program to print the given pattern#include <stdio.h> // utility function to print "-" in every// row. This will take care of printing// "-" in the start of every rowvoid printdashes(int k){ int i; for (i = 1; i <= k; i++) printf("-");} // function to print the patternvoid pattern(int n){ // variables for vertical left half /* 1*2*3* --4*5* ----6* */ int row, column, dashes = 0; int i, j, dash_counter = 0; int value = 1; // variables for vertical right half /* 10*11*12 *8*9 7 */ int k, l, decrementor = 0; int column_decrementor = 0; int support = n - 1; int temp = ((n * n) + 1); int temp1 = (n * 2) - 1; int z = temp; int tracker; for (i = 1; i <= n; i++) { printdashes(dash_counter); // This part will take care of the vertical // left half of the pattern for (j = 1; j <= (2 * n) - dash_counter; j++) { // Printing the "*" in even positions if (j % 2 == 0) printf("*"); else { printf("%d", value); value++; } } // This part will take care of the vertical // right half of the pattern for (k = 1; k <= (temp1 - decrementor); k++) { // Printing the "*" in even positions if (k % 2 == 0) printf("*"); else { if (k == 1) tracker = temp; printf("%d", temp); temp++; } } decrementor += 2; temp = tracker - support; support--; // In every row, the number of dash counts // is increased by 2 dash_counter += 2; printf("\n"); }} // driver programint main(){ int n = 3; pattern(n); return 0;} // Java program to print the given pattern class GFG { // utility function to print "-" in every// row. This will take care of printing// "-" in the start of every rowstatic void printdashes(int k){ int i; for (i = 1; i <= k; i++) System.out.print("-");} // function to print the patternstatic void pattern(int n) { // variables for vertical left half /* 1*2*3* --4*5* ----6* */ int row, column, dashes = 0; int i, j, dash_counter = 0; int value = 1; // variables for vertical right half /* 10*11*12 *8*9 7 */ int k, l, decrementor = 0; int column_decrementor = 0; int support = n - 1; int temp = ((n * n) + 1); int temp1 = (n * 2) - 1; int z = temp; int tracker = 0; for (i = 1; i <= n; i++) { printdashes(dash_counter); // This part will take care of the vertical // left half of the pattern for (j = 1; j <= (2 * n) - dash_counter; j++) { // Printing the "*" in even positions if (j % 2 == 0) System.out.print("*"); else { System.out.print(value); value++; } } // This part will take care of the vertical // right half of the pattern for (k = 1; k <= (temp1 - decrementor); k++) { // Printing the "*" in even positions if (k % 2 == 0) System.out.print("*"); else { if (k == 1) tracker = temp; System.out.print(temp); temp++; } } decrementor += 2; temp = tracker - support; support--; // In every row, the number of dash counts // is increased by 2 dash_counter += 2; System.out.print("\n"); }} // Driver codepublic static void main(String arg[]) { int n = 3; pattern(n);}} // This code is contributed by Anant Agarwal. # Python program to print# the given pattern # utility function to# print "-" in every# row. This will take# care of printing# "-" in the start of every rowdef printdashes(k): for i in range(1,k+1): print("-",end="") # function to print the patterndef pattern(n): # variables for vertical left half ''' 1*2*3* --4*5* ----6* ''' dashes = 0 dash_counter = 0 value = 1 # variables for vertical right half ''' 10*11*12 *8*9 7 ''' decrementor = 0 column_decrementor = 0 support = n - 1 temp = ((n * n) + 1) temp1 = (n * 2) - 1 z = temp for i in range(1,n+1): printdashes(dash_counter) # This part will take # care of the vertical # left half of the pattern for j in range(1,(((2 * n) - dash_counter)+1)): # Printing the "*" in even positions if (j % 2 == 0): print("*",end="") else: print(value,end="") value=value+1 # This part will take # care of the vertical # right half of the pattern for k in range(1,((temp1 - decrementor)+1)): # Printing the "*" in even positions if (k % 2 == 0): print("*",end="") else: if (k == 1): tracker = temp print(temp,end="") temp=temp + 1 decrementor =decrementor + 2 temp = tracker - support support=support - 1 # In every row, the number of dash counts # is increased by 2 dash_counter =dash_counter + 2 print("") # driver programn = 3pattern(n) # This code is contributed# by Anant Agarwal. // C# program to print the given patternusing System;class GFG { // utility function to print "-" in every// row. This will take care of printing// "-" in the start of every rowstatic void printdashes(int k){ int i; for (i = 1; i <= k; i++) Console.Write("-");} // function to print the patternstatic void pattern(int n) { // variables for vertical left half /* 1*2*3* --4*5* ----6* */ int i, j, dash_counter = 0; int value = 1; // variables for vertical right half /* 10*11*12 *8*9 7 */ int k, decrementor = 0; int support = n - 1; int temp = ((n * n) + 1); int temp1 = (n * 2) - 1; int tracker = 0; for (i = 1; i <= n; i++) { printdashes(dash_counter); // This part will take care of the vertical // left half of the pattern for (j = 1; j <= (2 * n) - dash_counter; j++) { // Printing the "*" in even positions if (j % 2 == 0) Console.Write("*"); else { Console.Write(value); value++; } } // This part will take care of the vertical // right half of the pattern for (k = 1; k <= (temp1 - decrementor); k++) { // Printing the "*" in even positions if (k % 2 == 0) Console.Write("*"); else { if (k == 1) tracker = temp; Console.Write(temp); temp++; } } decrementor += 2; temp = tracker - support; support--; // In every row, the number of dash counts // is increased by 2 dash_counter += 2; Console.WriteLine(); }} // Driver codepublic static void Main() { int n = 3; pattern(n);}} // This code is contributed by vt_m. <?php// PHP program to print the given pattern // function to print the patternfunction pattern($n){ // variables for vertical left half $dashes = 0; $dash_counter = 0; $value = 1; // variables for vertical right half $decrementor = 0; $column_decrementor = 0; $support = $n - 1; $temp = (($n * $n) + 1); $temp1 = ($n * 2) - 1; $z = $temp; for ($i = 1; $i <= $n; $i++) { // loop for printing dash for ($dd = 1; $dd <= $dash_counter; $dd++) printf("-"); // This part will take care of the // vertical left half of the pattern for ($j = 1; $j <= (2 * $n) - $dash_counter; $j++) { // Printing the "*" in even // positions if ($j % 2 == 0) printf("*"); else { printf($value); $value++; } } // This part will take care // of the vertical right half // of the pattern for ($k = 1; $k <= ($temp1 - $decrementor); $k++) { // Printing the "*" in even // positions if ($k % 2 == 0) printf("*"); else { if ($k == 1) $tracker = $temp; printf($temp); $temp++; } } $decrementor += 2; $temp = $tracker - $support; $support--; // In every row, the number of // dash counts is increased by 2 $dash_counter += 2; printf("\n"); }} // Driver code$n = 3;pattern($n); // This code is contributed by mits?> <script> // javascript program to print the given pattern // utility function to print "-" in every// row. This will take care of printing// "-" in the start of every row function printdashes(k){ var i; for (i = 1; i <= k; i++) document.write("-");} // function to print the patternfunction pattern(n) { // variables for vertical left half /* 1*2*3* --4*5* ----6* */ var row, column, dashes = 0; var i, j, dash_counter = 0; var value = 1; // variables for vertical right half /* 10*11*12 *8*9 7 */ var k, l, decrementor = 0; var column_decrementor = 0; var support = n - 1; var temp = ((n * n) + 1); var temp1 = (n * 2) - 1; var z = temp; var tracker = 0; for (i = 1; i <= n; i++) { printdashes(dash_counter); // This part will take care of the vertical // left half of the pattern for (j = 1; j <= (2 * n) - dash_counter; j++) { // Printing the "*" in even positions if (j % 2 == 0) document.write("*"); else { document.write(value); value++; } } // This part will take care of the vertical // right half of the pattern for (k = 1; k <= (temp1 - decrementor); k++) { // Printing the "*" in even positions if (k % 2 == 0) document.write("*"); else { if (k == 1) tracker = temp; document.write(temp); temp++; } } decrementor += 2; temp = tracker - support; support--; // In every row, the number of dash counts // is increased by 2 dash_counter += 2; document.write("<br>"); }} // Driver codevar n = 3;pattern(n); // This code is contributed by 29AjayKumar</script> Output : 1*2*3*10*11*12 --4*5*8*9 ----6*7 Another approach : C++ C Java Python3 C# Javascript // C++ program to print the given pattern#include <iostream>using namespace std; // function to print the patternvoid printPattern(int row){ int x = 1; int z = (row * row) + 1; int col = row == 1 ? 1 : (row * 4) - 1; for(int i = 1; i <= row; i++) { int t = z; for(int j = 1; j <= col - ((i - 1) * 2); j++) { if ((i * 2) - 2 >= j) { cout << "-"; } else { if(col == 1) { cout << x; } else if(j <= col/2 && j % 2 == 1) { cout << x; x++; } else if(j > col/2 && j % 2 == 1) { cout << t; t++; } else { cout << "*"; } } } z = (z - row) + i; cout << "\n"; }} // Driver codeint main(){ int row = 3; printPattern(row); return 0;} // This code is contributed by shubhamsingh10 // C program to print the given pattern#include<stdio.h> // function to print the patternvoid printPattern(int row){ int x = 1; int z = (row * row) + 1; int col = row == 1 ? 1 : (row * 4) - 1; for(int i = 1; i <= row; i++) { int t = z; for(int j = 1; j <= col - ((i - 1) * 2); j++) { if ((i * 2) - 2 >= j) { printf("-"); } else { if(col == 1) { printf("%d", x); } else if(j <= col/2 && j % 2 == 1) { printf("%d", x); x++; } else if(j > col/2 && j % 2 == 1) { printf("%d", t);; t++; } else { printf("*"); } } } z = (z - row) + i; printf("\n"); }} // Driver codeint main(){ int row = 3; printPattern(row); return 0;} // This code is contributed by ankurmishra1794 // Java program to print the given patternclass GFG{ // function to print the patternstatic void printPattern(int row){ int x = 1; int z = (row * row) + 1; int col = row == 1 ? 1 : (row * 4) - 1; for(int i = 1; i <= row; i++) { int t = z; for(int j = 1; j <= col -((i - 1) * 2); j++) { if ((i * 2) - 2 >= j) { System.out.print("-"); } else { if(col == 1) { System.out.print(x); } else if(j <= col/2 && j % 2 == 1) { System.out.print(x); x++; } else if(j > col/2 && j % 2 == 1) { System.out.print(t); t++; } else { System.out.print("*"); } } } z = (z - row) + i; System.out.print("\n"); }} // Driver codepublic static void main(String[] args){ int row = 3; printPattern(row);}} /* This code is contributed by PrinciRaj1992 */ # Python3 program to print the given pattern # Function to print the patterndef printPattern(row): x = 1 z = (row * row) + 1 if row == 1: col = 1 else: col = (row * 4) - 1 for i in range(1, row + 1): t = z for j in range(1, col - ((i - 1) * 2) + 1): if ((i * 2) - 2 >= j): print("", end = "-") else: if (col == 1): print(x, end = "") elif (j <= col / 2 and j % 2 == 1): print(x, end = "") x += 1 elif (j > col / 2 and j % 2 == 1): print(t, end = "") t += 1 else: print("*", end = "") z = (z - row) + i print() # Driver coderow = 3 printPattern(row) # This code is contributed by shivani // C# program to print the given patternusing System; class GFG{ // function to print the patternstatic void printPattern(int row){ int x = 1; int z = (row * row) + 1; int col = row == 1 ? 1 : (row * 4) - 1; for(int i = 1; i <= row; i++) { int t = z; for(int j = 1; j <= col -((i - 1) * 2); j++) { if ((i * 2) - 2 >= j) { Console.Write("-"); } else { if(col == 1) { Console.Write(x); } else if(j <= col/2 && j % 2 == 1) { Console.Write(x); x++; } else if(j > col/2 && j % 2 == 1) { Console.Write(t); t++; } else { Console.Write("*"); } } } z = (z - row) + i; Console.Write("\n"); }} // Driver codepublic static void Main(String[] args){ int row = 3; printPattern(row);}} // This code is contributed by 29AjayKumar <script> // javascript program to print the given pattern // function to print the patternfunction printPattern(row){ var x = 1; var z = (row * row) + 1; var col = row == 1 ? 1 : (row * 4) - 1; for(var i = 1; i <= row; i++) { var t = z; for(var j = 1; j <= col -((i - 1) * 2); j++) { if ((i * 2) - 2 >= j) { document.write("-"); } else { if(col == 1) { document.write(x); } else if(j <= col/2 && j % 2 == 1) { document.write(x); x++; } else if(j > col/2 && j % 2 == 1) { document.write(t); t++; } else { document.write("*"); } } } z = (z - row) + i; document.write("<br>"); }} // Driver codevar row = 3;printPattern(row); // This code is contributed by 29AjayKumar</script> Output : 1*2*3*10*11*12 --4*5*8*9 ----6*7 Another approach : Python3 def pattern(n): size = n*(n+1) # prev1 will be used to keep track of last number # printed in left half of pattern prev1 = 0 # prev2 will be used to keep track of last number # printed in right half of pattern prev2 = size for i in range(n): # print the '-' print('-'*(2*i), end = '') # l1 to store numbers of left half to be printed l1 = [j for j in range(prev1+1, prev1+n-i+1)] # l2 to store numbers of right half to be printed l2 = [j for j in range(prev2-(n-i)+1,prev2+1)] # combine l1 and l2 and print the list separated by * print(*l1+l2, sep = '*') # decrease prev2 and increase prev1 prev2 -= (n-i) prev1 += (n-i) # driver programn = 3pattern(n) # This code is contributed# by Akash Jain (ultrainstinct). Output : 1*2*3*10*11*12 --4*5*8*9 ----6*7 Another approach : Python3 n = 4temp_number = (n*n)+ncounter = 1for i in range(n): temp_list = [] for j in range(n-i): temp_list.append(counter) temp_list.append(temp_number-counter+1) counter += 1 temp_list.sort() temp_list = [str(each) for each in temp_list] [print("--", end="") for k in range(i)] print("*".join(temp_list)) Output: 1*2*3*4*17*18*19*20 --5*6*7*14*15*16 ----8*9*12*13 ------10*11 This article is contributed by MAZHAR IMAM KHAN. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Mithun Kumar ankurmishra1794 princiraj1992 29AjayKumar ask4nishant ultrainstinct MayankGupta6 shivanisinghss2110 arorakashish0911 CGI pattern-printing School Programming CGI pattern-printing Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Oct, 2021" }, { "code": null, "e": 167, "s": 52, "text": "Write a program that receives a number as input and prints it in the following format as shown below. Examples : " }, { "code": null, "e": 310, "s": 167, "text": "Input : n = 3\nOutput :\n1*2*3*10*11*12\n--4*5*8*9\n----6*7\n\nInput : n = 4\nOutput :\n1*2*3*4*17*18*19*20\n--5*6*7*14*15*16\n----8*9*12*13\n------10*11" }, { "code": null, "e": 336, "s": 310, "text": "Asked in CGI coding round" }, { "code": null, "e": 654, "s": 336, "text": "Approach: The approach is to see the problem, not as a single task but three tasks which, on combining, complete the main task. The three tasks are printing the left-half of the pattern, printing dashes(-), and printing the right-half of the pattern. Combining all three tasks, we would be able to print the pattern. " }, { "code": null, "e": 781, "s": 654, "text": "left-half of pattern\n1*2*3*\n--4*5*\n----6*\n\nA function printdashes() to print the \"-\".\n\nright-half of\n\n pattern\n10*11*12\n*8*9\n7" }, { "code": null, "e": 810, "s": 781, "text": "Below is the implementation." }, { "code": null, "e": 814, "s": 810, "text": "C++" }, { "code": null, "e": 819, "s": 814, "text": "Java" }, { "code": null, "e": 827, "s": 819, "text": "Python3" }, { "code": null, "e": 830, "s": 827, "text": "C#" }, { "code": null, "e": 834, "s": 830, "text": "PHP" }, { "code": null, "e": 845, "s": 834, "text": "Javascript" }, { "code": "// C program to print the given pattern#include <stdio.h> // utility function to print \"-\" in every// row. This will take care of printing// \"-\" in the start of every rowvoid printdashes(int k){ int i; for (i = 1; i <= k; i++) printf(\"-\");} // function to print the patternvoid pattern(int n){ // variables for vertical left half /* 1*2*3* --4*5* ----6* */ int row, column, dashes = 0; int i, j, dash_counter = 0; int value = 1; // variables for vertical right half /* 10*11*12 *8*9 7 */ int k, l, decrementor = 0; int column_decrementor = 0; int support = n - 1; int temp = ((n * n) + 1); int temp1 = (n * 2) - 1; int z = temp; int tracker; for (i = 1; i <= n; i++) { printdashes(dash_counter); // This part will take care of the vertical // left half of the pattern for (j = 1; j <= (2 * n) - dash_counter; j++) { // Printing the \"*\" in even positions if (j % 2 == 0) printf(\"*\"); else { printf(\"%d\", value); value++; } } // This part will take care of the vertical // right half of the pattern for (k = 1; k <= (temp1 - decrementor); k++) { // Printing the \"*\" in even positions if (k % 2 == 0) printf(\"*\"); else { if (k == 1) tracker = temp; printf(\"%d\", temp); temp++; } } decrementor += 2; temp = tracker - support; support--; // In every row, the number of dash counts // is increased by 2 dash_counter += 2; printf(\"\\n\"); }} // driver programint main(){ int n = 3; pattern(n); return 0;}", "e": 2707, "s": 845, "text": null }, { "code": "// Java program to print the given pattern class GFG { // utility function to print \"-\" in every// row. This will take care of printing// \"-\" in the start of every rowstatic void printdashes(int k){ int i; for (i = 1; i <= k; i++) System.out.print(\"-\");} // function to print the patternstatic void pattern(int n) { // variables for vertical left half /* 1*2*3* --4*5* ----6* */ int row, column, dashes = 0; int i, j, dash_counter = 0; int value = 1; // variables for vertical right half /* 10*11*12 *8*9 7 */ int k, l, decrementor = 0; int column_decrementor = 0; int support = n - 1; int temp = ((n * n) + 1); int temp1 = (n * 2) - 1; int z = temp; int tracker = 0; for (i = 1; i <= n; i++) { printdashes(dash_counter); // This part will take care of the vertical // left half of the pattern for (j = 1; j <= (2 * n) - dash_counter; j++) { // Printing the \"*\" in even positions if (j % 2 == 0) System.out.print(\"*\"); else { System.out.print(value); value++; } } // This part will take care of the vertical // right half of the pattern for (k = 1; k <= (temp1 - decrementor); k++) { // Printing the \"*\" in even positions if (k % 2 == 0) System.out.print(\"*\"); else { if (k == 1) tracker = temp; System.out.print(temp); temp++; } } decrementor += 2; temp = tracker - support; support--; // In every row, the number of dash counts // is increased by 2 dash_counter += 2; System.out.print(\"\\n\"); }} // Driver codepublic static void main(String arg[]) { int n = 3; pattern(n);}} // This code is contributed by Anant Agarwal.", "e": 4494, "s": 2707, "text": null }, { "code": "# Python program to print# the given pattern # utility function to# print \"-\" in every# row. This will take# care of printing# \"-\" in the start of every rowdef printdashes(k): for i in range(1,k+1): print(\"-\",end=\"\") # function to print the patterndef pattern(n): # variables for vertical left half ''' 1*2*3* --4*5* ----6* ''' dashes = 0 dash_counter = 0 value = 1 # variables for vertical right half ''' 10*11*12 *8*9 7 ''' decrementor = 0 column_decrementor = 0 support = n - 1 temp = ((n * n) + 1) temp1 = (n * 2) - 1 z = temp for i in range(1,n+1): printdashes(dash_counter) # This part will take # care of the vertical # left half of the pattern for j in range(1,(((2 * n) - dash_counter)+1)): # Printing the \"*\" in even positions if (j % 2 == 0): print(\"*\",end=\"\") else: print(value,end=\"\") value=value+1 # This part will take # care of the vertical # right half of the pattern for k in range(1,((temp1 - decrementor)+1)): # Printing the \"*\" in even positions if (k % 2 == 0): print(\"*\",end=\"\") else: if (k == 1): tracker = temp print(temp,end=\"\") temp=temp + 1 decrementor =decrementor + 2 temp = tracker - support support=support - 1 # In every row, the number of dash counts # is increased by 2 dash_counter =dash_counter + 2 print(\"\") # driver programn = 3pattern(n) # This code is contributed# by Anant Agarwal.", "e": 6305, "s": 4494, "text": null }, { "code": "// C# program to print the given patternusing System;class GFG { // utility function to print \"-\" in every// row. This will take care of printing// \"-\" in the start of every rowstatic void printdashes(int k){ int i; for (i = 1; i <= k; i++) Console.Write(\"-\");} // function to print the patternstatic void pattern(int n) { // variables for vertical left half /* 1*2*3* --4*5* ----6* */ int i, j, dash_counter = 0; int value = 1; // variables for vertical right half /* 10*11*12 *8*9 7 */ int k, decrementor = 0; int support = n - 1; int temp = ((n * n) + 1); int temp1 = (n * 2) - 1; int tracker = 0; for (i = 1; i <= n; i++) { printdashes(dash_counter); // This part will take care of the vertical // left half of the pattern for (j = 1; j <= (2 * n) - dash_counter; j++) { // Printing the \"*\" in even positions if (j % 2 == 0) Console.Write(\"*\"); else { Console.Write(value); value++; } } // This part will take care of the vertical // right half of the pattern for (k = 1; k <= (temp1 - decrementor); k++) { // Printing the \"*\" in even positions if (k % 2 == 0) Console.Write(\"*\"); else { if (k == 1) tracker = temp; Console.Write(temp); temp++; } } decrementor += 2; temp = tracker - support; support--; // In every row, the number of dash counts // is increased by 2 dash_counter += 2; Console.WriteLine(); }} // Driver codepublic static void Main() { int n = 3; pattern(n);}} // This code is contributed by vt_m.", "e": 7983, "s": 6305, "text": null }, { "code": "<?php// PHP program to print the given pattern // function to print the patternfunction pattern($n){ // variables for vertical left half $dashes = 0; $dash_counter = 0; $value = 1; // variables for vertical right half $decrementor = 0; $column_decrementor = 0; $support = $n - 1; $temp = (($n * $n) + 1); $temp1 = ($n * 2) - 1; $z = $temp; for ($i = 1; $i <= $n; $i++) { // loop for printing dash for ($dd = 1; $dd <= $dash_counter; $dd++) printf(\"-\"); // This part will take care of the // vertical left half of the pattern for ($j = 1; $j <= (2 * $n) - $dash_counter; $j++) { // Printing the \"*\" in even // positions if ($j % 2 == 0) printf(\"*\"); else { printf($value); $value++; } } // This part will take care // of the vertical right half // of the pattern for ($k = 1; $k <= ($temp1 - $decrementor); $k++) { // Printing the \"*\" in even // positions if ($k % 2 == 0) printf(\"*\"); else { if ($k == 1) $tracker = $temp; printf($temp); $temp++; } } $decrementor += 2; $temp = $tracker - $support; $support--; // In every row, the number of // dash counts is increased by 2 $dash_counter += 2; printf(\"\\n\"); }} // Driver code$n = 3;pattern($n); // This code is contributed by mits?>", "e": 9734, "s": 7983, "text": null }, { "code": "<script> // javascript program to print the given pattern // utility function to print \"-\" in every// row. This will take care of printing// \"-\" in the start of every row function printdashes(k){ var i; for (i = 1; i <= k; i++) document.write(\"-\");} // function to print the patternfunction pattern(n) { // variables for vertical left half /* 1*2*3* --4*5* ----6* */ var row, column, dashes = 0; var i, j, dash_counter = 0; var value = 1; // variables for vertical right half /* 10*11*12 *8*9 7 */ var k, l, decrementor = 0; var column_decrementor = 0; var support = n - 1; var temp = ((n * n) + 1); var temp1 = (n * 2) - 1; var z = temp; var tracker = 0; for (i = 1; i <= n; i++) { printdashes(dash_counter); // This part will take care of the vertical // left half of the pattern for (j = 1; j <= (2 * n) - dash_counter; j++) { // Printing the \"*\" in even positions if (j % 2 == 0) document.write(\"*\"); else { document.write(value); value++; } } // This part will take care of the vertical // right half of the pattern for (k = 1; k <= (temp1 - decrementor); k++) { // Printing the \"*\" in even positions if (k % 2 == 0) document.write(\"*\"); else { if (k == 1) tracker = temp; document.write(temp); temp++; } } decrementor += 2; temp = tracker - support; support--; // In every row, the number of dash counts // is increased by 2 dash_counter += 2; document.write(\"<br>\"); }} // Driver codevar n = 3;pattern(n); // This code is contributed by 29AjayKumar</script>", "e": 11624, "s": 9734, "text": null }, { "code": null, "e": 11634, "s": 11624, "text": "Output : " }, { "code": null, "e": 11667, "s": 11634, "text": "1*2*3*10*11*12\n--4*5*8*9\n----6*7" }, { "code": null, "e": 11688, "s": 11667, "text": "Another approach : " }, { "code": null, "e": 11692, "s": 11688, "text": "C++" }, { "code": null, "e": 11694, "s": 11692, "text": "C" }, { "code": null, "e": 11699, "s": 11694, "text": "Java" }, { "code": null, "e": 11707, "s": 11699, "text": "Python3" }, { "code": null, "e": 11710, "s": 11707, "text": "C#" }, { "code": null, "e": 11721, "s": 11710, "text": "Javascript" }, { "code": "// C++ program to print the given pattern#include <iostream>using namespace std; // function to print the patternvoid printPattern(int row){ int x = 1; int z = (row * row) + 1; int col = row == 1 ? 1 : (row * 4) - 1; for(int i = 1; i <= row; i++) { int t = z; for(int j = 1; j <= col - ((i - 1) * 2); j++) { if ((i * 2) - 2 >= j) { cout << \"-\"; } else { if(col == 1) { cout << x; } else if(j <= col/2 && j % 2 == 1) { cout << x; x++; } else if(j > col/2 && j % 2 == 1) { cout << t; t++; } else { cout << \"*\"; } } } z = (z - row) + i; cout << \"\\n\"; }} // Driver codeint main(){ int row = 3; printPattern(row); return 0;} // This code is contributed by shubhamsingh10", "e": 12852, "s": 11721, "text": null }, { "code": "// C program to print the given pattern#include<stdio.h> // function to print the patternvoid printPattern(int row){ int x = 1; int z = (row * row) + 1; int col = row == 1 ? 1 : (row * 4) - 1; for(int i = 1; i <= row; i++) { int t = z; for(int j = 1; j <= col - ((i - 1) * 2); j++) { if ((i * 2) - 2 >= j) { printf(\"-\"); } else { if(col == 1) { printf(\"%d\", x); } else if(j <= col/2 && j % 2 == 1) { printf(\"%d\", x); x++; } else if(j > col/2 && j % 2 == 1) { printf(\"%d\", t);; t++; } else { printf(\"*\"); } } } z = (z - row) + i; printf(\"\\n\"); }} // Driver codeint main(){ int row = 3; printPattern(row); return 0;} // This code is contributed by ankurmishra1794", "e": 13979, "s": 12852, "text": null }, { "code": "// Java program to print the given patternclass GFG{ // function to print the patternstatic void printPattern(int row){ int x = 1; int z = (row * row) + 1; int col = row == 1 ? 1 : (row * 4) - 1; for(int i = 1; i <= row; i++) { int t = z; for(int j = 1; j <= col -((i - 1) * 2); j++) { if ((i * 2) - 2 >= j) { System.out.print(\"-\"); } else { if(col == 1) { System.out.print(x); } else if(j <= col/2 && j % 2 == 1) { System.out.print(x); x++; } else if(j > col/2 && j % 2 == 1) { System.out.print(t); t++; } else { System.out.print(\"*\"); } } } z = (z - row) + i; System.out.print(\"\\n\"); }} // Driver codepublic static void main(String[] args){ int row = 3; printPattern(row);}} /* This code is contributed by PrinciRaj1992 */", "e": 15182, "s": 13979, "text": null }, { "code": "# Python3 program to print the given pattern # Function to print the patterndef printPattern(row): x = 1 z = (row * row) + 1 if row == 1: col = 1 else: col = (row * 4) - 1 for i in range(1, row + 1): t = z for j in range(1, col - ((i - 1) * 2) + 1): if ((i * 2) - 2 >= j): print(\"\", end = \"-\") else: if (col == 1): print(x, end = \"\") elif (j <= col / 2 and j % 2 == 1): print(x, end = \"\") x += 1 elif (j > col / 2 and j % 2 == 1): print(t, end = \"\") t += 1 else: print(\"*\", end = \"\") z = (z - row) + i print() # Driver coderow = 3 printPattern(row) # This code is contributed by shivani", "e": 16092, "s": 15182, "text": null }, { "code": "// C# program to print the given patternusing System; class GFG{ // function to print the patternstatic void printPattern(int row){ int x = 1; int z = (row * row) + 1; int col = row == 1 ? 1 : (row * 4) - 1; for(int i = 1; i <= row; i++) { int t = z; for(int j = 1; j <= col -((i - 1) * 2); j++) { if ((i * 2) - 2 >= j) { Console.Write(\"-\"); } else { if(col == 1) { Console.Write(x); } else if(j <= col/2 && j % 2 == 1) { Console.Write(x); x++; } else if(j > col/2 && j % 2 == 1) { Console.Write(t); t++; } else { Console.Write(\"*\"); } } } z = (z - row) + i; Console.Write(\"\\n\"); }} // Driver codepublic static void Main(String[] args){ int row = 3; printPattern(row);}} // This code is contributed by 29AjayKumar", "e": 17268, "s": 16092, "text": null }, { "code": "<script> // javascript program to print the given pattern // function to print the patternfunction printPattern(row){ var x = 1; var z = (row * row) + 1; var col = row == 1 ? 1 : (row * 4) - 1; for(var i = 1; i <= row; i++) { var t = z; for(var j = 1; j <= col -((i - 1) * 2); j++) { if ((i * 2) - 2 >= j) { document.write(\"-\"); } else { if(col == 1) { document.write(x); } else if(j <= col/2 && j % 2 == 1) { document.write(x); x++; } else if(j > col/2 && j % 2 == 1) { document.write(t); t++; } else { document.write(\"*\"); } } } z = (z - row) + i; document.write(\"<br>\"); }} // Driver codevar row = 3;printPattern(row); // This code is contributed by 29AjayKumar</script>", "e": 18415, "s": 17268, "text": null }, { "code": null, "e": 18426, "s": 18415, "text": "Output : " }, { "code": null, "e": 18459, "s": 18426, "text": "1*2*3*10*11*12\n--4*5*8*9\n----6*7" }, { "code": null, "e": 18480, "s": 18459, "text": "Another approach : " }, { "code": null, "e": 18488, "s": 18480, "text": "Python3" }, { "code": "def pattern(n): size = n*(n+1) # prev1 will be used to keep track of last number # printed in left half of pattern prev1 = 0 # prev2 will be used to keep track of last number # printed in right half of pattern prev2 = size for i in range(n): # print the '-' print('-'*(2*i), end = '') # l1 to store numbers of left half to be printed l1 = [j for j in range(prev1+1, prev1+n-i+1)] # l2 to store numbers of right half to be printed l2 = [j for j in range(prev2-(n-i)+1,prev2+1)] # combine l1 and l2 and print the list separated by * print(*l1+l2, sep = '*') # decrease prev2 and increase prev1 prev2 -= (n-i) prev1 += (n-i) # driver programn = 3pattern(n) # This code is contributed# by Akash Jain (ultrainstinct).", "e": 19372, "s": 18488, "text": null }, { "code": null, "e": 19383, "s": 19372, "text": "Output : " }, { "code": null, "e": 19416, "s": 19383, "text": "1*2*3*10*11*12\n--4*5*8*9\n----6*7" }, { "code": null, "e": 19436, "s": 19416, "text": "Another approach : " }, { "code": null, "e": 19444, "s": 19436, "text": "Python3" }, { "code": "n = 4temp_number = (n*n)+ncounter = 1for i in range(n): temp_list = [] for j in range(n-i): temp_list.append(counter) temp_list.append(temp_number-counter+1) counter += 1 temp_list.sort() temp_list = [str(each) for each in temp_list] [print(\"--\", end=\"\") for k in range(i)] print(\"*\".join(temp_list))", "e": 19784, "s": 19444, "text": null }, { "code": null, "e": 19792, "s": 19784, "text": "Output:" }, { "code": null, "e": 19855, "s": 19792, "text": "1*2*3*4*17*18*19*20\n--5*6*7*14*15*16\n----8*9*12*13\n------10*11" }, { "code": null, "e": 20280, "s": 19855, "text": "This article is contributed by MAZHAR IMAM KHAN. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 20293, "s": 20280, "text": "Mithun Kumar" }, { "code": null, "e": 20309, "s": 20293, "text": "ankurmishra1794" }, { "code": null, "e": 20323, "s": 20309, "text": "princiraj1992" }, { "code": null, "e": 20335, "s": 20323, "text": "29AjayKumar" }, { "code": null, "e": 20347, "s": 20335, "text": "ask4nishant" }, { "code": null, "e": 20361, "s": 20347, "text": "ultrainstinct" }, { "code": null, "e": 20374, "s": 20361, "text": "MayankGupta6" }, { "code": null, "e": 20393, "s": 20374, "text": "shivanisinghss2110" }, { "code": null, "e": 20410, "s": 20393, "text": "arorakashish0911" }, { "code": null, "e": 20414, "s": 20410, "text": "CGI" }, { "code": null, "e": 20431, "s": 20414, "text": "pattern-printing" }, { "code": null, "e": 20450, "s": 20431, "text": "School Programming" }, { "code": null, "e": 20454, "s": 20450, "text": "CGI" }, { "code": null, "e": 20471, "s": 20454, "text": "pattern-printing" } ]
C Program to create a House using Graphics
14 Jun, 2020 Prerequisite: graphics.h, How to include graphics.h in CodeBlocks? The task is to write C program to create a house using graphics. To run the program we have the include the below header file: #include <graphic.h> Setting Up the Environment: Download the WinBGlm zip file from this link.Extract the WinBGlm zip at any desired directory as shown below:Copy the header file graphic.h and winbgim.h and paste these file inside the folder Program Files->CodeBlock->MinGW->Include_folder.Also copy the libbgi.a and paste inside the folder Program Files->CodeBlock->MinGW-> lib_folder.After this open your Code::Blocks and goto the Setting->Compiler->Linker Settings as shown below:Add New and Browse the file where the libbgi.a is available which is lib folder.And in other linker option paste this: “lbgi lgdi32 -lcomdlg32 -luuid -loleaut32 -lole32“, Click on OK and Exit from Code::Blocks. Download the WinBGlm zip file from this link. Extract the WinBGlm zip at any desired directory as shown below: Copy the header file graphic.h and winbgim.h and paste these file inside the folder Program Files->CodeBlock->MinGW->Include_folder. Also copy the libbgi.a and paste inside the folder Program Files->CodeBlock->MinGW-> lib_folder. After this open your Code::Blocks and goto the Setting->Compiler->Linker Settings as shown below: Add New and Browse the file where the libbgi.a is available which is lib folder. And in other linker option paste this: “lbgi lgdi32 -lcomdlg32 -luuid -loleaut32 -lole32“, Click on OK and Exit from Code::Blocks. Approach: We will create a house with the help of several lines and rectangles. Below are the steps: We will draw a line in graphics by passing 4 numbers to line() function as:line(a, b, c, d)The above function will draw a line from coordinates (a, b) to (c, d) in the output window.IWe will draw a rectangle in graphics by passing 4 numbers to rectangle() function as:line(left, top, right, bottom)The above function will draw a rectangle with coordinates of left, right, top and bottom.The setfillstyle() function which sets any fill pattern in any shape created in C program using graphics.The floodfill() function is used to fill an enclosed area with any color. We will draw a line in graphics by passing 4 numbers to line() function as:line(a, b, c, d)The above function will draw a line from coordinates (a, b) to (c, d) in the output window. line(a, b, c, d)The above function will draw a line from coordinates (a, b) to (c, d) in the output window. IWe will draw a rectangle in graphics by passing 4 numbers to rectangle() function as:line(left, top, right, bottom)The above function will draw a rectangle with coordinates of left, right, top and bottom. line(left, top, right, bottom)The above function will draw a rectangle with coordinates of left, right, top and bottom. The setfillstyle() function which sets any fill pattern in any shape created in C program using graphics. The floodfill() function is used to fill an enclosed area with any color. Below is the implementation of the above approach: // C program to draw a house using// graphics.h library#include <conio.h>#include <graphics.h>#include <stdio.h> // Driver Codevoid main(){ // Initialize of gdriver with // DETECT macros int gdriver = DETECT, gmode; // Initialize structure of // the house initgraph(&gdriver, &gmode, ""); // Create lines for structure // of the House line(100, 100, 150, 50); line(150, 50, 200, 100); line(150, 50, 350, 50); line(350, 50, 400, 100); // Draw rectangle to give proper // shape to the house rectangle(100, 100, 200, 200); rectangle(200, 100, 400, 200); rectangle(130, 130, 170, 200); rectangle(250, 120, 350, 180); // Set color using setfillstyle() // which take style and color as // an argument setfillstyle(2, 3); // Fill the shapes with colors white floodfill(131, 131, WHITE); floodfill(201, 101, WHITE); // Change the filling color setfillstyle(11, 7); // Fill the shapes with changed colors floodfill(101, 101, WHITE); floodfill(150, 52, WHITE); floodfill(163, 55, WHITE); floodfill(251, 121, WHITE); // Close the initialized gdriver closegraph();} Output:Below is the output of the above program: c-graphics computer-graphics C Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n14 Jun, 2020" }, { "code": null, "e": 120, "s": 53, "text": "Prerequisite: graphics.h, How to include graphics.h in CodeBlocks?" }, { "code": null, "e": 185, "s": 120, "text": "The task is to write C program to create a house using graphics." }, { "code": null, "e": 247, "s": 185, "text": "To run the program we have the include the below header file:" }, { "code": null, "e": 269, "s": 247, "text": "#include <graphic.h>\n" }, { "code": null, "e": 297, "s": 269, "text": "Setting Up the Environment:" }, { "code": null, "e": 942, "s": 297, "text": "Download the WinBGlm zip file from this link.Extract the WinBGlm zip at any desired directory as shown below:Copy the header file graphic.h and winbgim.h and paste these file inside the folder Program Files->CodeBlock->MinGW->Include_folder.Also copy the libbgi.a and paste inside the folder Program Files->CodeBlock->MinGW-> lib_folder.After this open your Code::Blocks and goto the Setting->Compiler->Linker Settings as shown below:Add New and Browse the file where the libbgi.a is available which is lib folder.And in other linker option paste this: “lbgi lgdi32 -lcomdlg32 -luuid -loleaut32 -lole32“, Click on OK and Exit from Code::Blocks." }, { "code": null, "e": 988, "s": 942, "text": "Download the WinBGlm zip file from this link." }, { "code": null, "e": 1053, "s": 988, "text": "Extract the WinBGlm zip at any desired directory as shown below:" }, { "code": null, "e": 1186, "s": 1053, "text": "Copy the header file graphic.h and winbgim.h and paste these file inside the folder Program Files->CodeBlock->MinGW->Include_folder." }, { "code": null, "e": 1283, "s": 1186, "text": "Also copy the libbgi.a and paste inside the folder Program Files->CodeBlock->MinGW-> lib_folder." }, { "code": null, "e": 1381, "s": 1283, "text": "After this open your Code::Blocks and goto the Setting->Compiler->Linker Settings as shown below:" }, { "code": null, "e": 1462, "s": 1381, "text": "Add New and Browse the file where the libbgi.a is available which is lib folder." }, { "code": null, "e": 1593, "s": 1462, "text": "And in other linker option paste this: “lbgi lgdi32 -lcomdlg32 -luuid -loleaut32 -lole32“, Click on OK and Exit from Code::Blocks." }, { "code": null, "e": 1694, "s": 1593, "text": "Approach: We will create a house with the help of several lines and rectangles. Below are the steps:" }, { "code": null, "e": 2260, "s": 1694, "text": "We will draw a line in graphics by passing 4 numbers to line() function as:line(a, b, c, d)The above function will draw a line from coordinates (a, b) to (c, d) in the output window.IWe will draw a rectangle in graphics by passing 4 numbers to rectangle() function as:line(left, top, right, bottom)The above function will draw a rectangle with coordinates of left, right, top and bottom.The setfillstyle() function which sets any fill pattern in any shape created in C program using graphics.The floodfill() function is used to fill an enclosed area with any color." }, { "code": null, "e": 2443, "s": 2260, "text": "We will draw a line in graphics by passing 4 numbers to line() function as:line(a, b, c, d)The above function will draw a line from coordinates (a, b) to (c, d) in the output window." }, { "code": null, "e": 2551, "s": 2443, "text": "line(a, b, c, d)The above function will draw a line from coordinates (a, b) to (c, d) in the output window." }, { "code": null, "e": 2757, "s": 2551, "text": "IWe will draw a rectangle in graphics by passing 4 numbers to rectangle() function as:line(left, top, right, bottom)The above function will draw a rectangle with coordinates of left, right, top and bottom." }, { "code": null, "e": 2877, "s": 2757, "text": "line(left, top, right, bottom)The above function will draw a rectangle with coordinates of left, right, top and bottom." }, { "code": null, "e": 2983, "s": 2877, "text": "The setfillstyle() function which sets any fill pattern in any shape created in C program using graphics." }, { "code": null, "e": 3057, "s": 2983, "text": "The floodfill() function is used to fill an enclosed area with any color." }, { "code": null, "e": 3108, "s": 3057, "text": "Below is the implementation of the above approach:" }, { "code": "// C program to draw a house using// graphics.h library#include <conio.h>#include <graphics.h>#include <stdio.h> // Driver Codevoid main(){ // Initialize of gdriver with // DETECT macros int gdriver = DETECT, gmode; // Initialize structure of // the house initgraph(&gdriver, &gmode, \"\"); // Create lines for structure // of the House line(100, 100, 150, 50); line(150, 50, 200, 100); line(150, 50, 350, 50); line(350, 50, 400, 100); // Draw rectangle to give proper // shape to the house rectangle(100, 100, 200, 200); rectangle(200, 100, 400, 200); rectangle(130, 130, 170, 200); rectangle(250, 120, 350, 180); // Set color using setfillstyle() // which take style and color as // an argument setfillstyle(2, 3); // Fill the shapes with colors white floodfill(131, 131, WHITE); floodfill(201, 101, WHITE); // Change the filling color setfillstyle(11, 7); // Fill the shapes with changed colors floodfill(101, 101, WHITE); floodfill(150, 52, WHITE); floodfill(163, 55, WHITE); floodfill(251, 121, WHITE); // Close the initialized gdriver closegraph();}", "e": 4285, "s": 3108, "text": null }, { "code": null, "e": 4334, "s": 4285, "text": "Output:Below is the output of the above program:" }, { "code": null, "e": 4345, "s": 4334, "text": "c-graphics" }, { "code": null, "e": 4363, "s": 4345, "text": "computer-graphics" }, { "code": null, "e": 4374, "s": 4363, "text": "C Programs" } ]
Decoding: State Of The Art Object Detection | by Kb Pachauri | Towards Data Science
EfficientDet is a neural network architecture which achieves State-Of-The-Art (SOTA) results (~55.1 Average Precision) on object detection (Microsoft COCO dataset) task with much lesser (~4x-9x) complexity than the previous detectors [2]. The key building blocks of EfficientDet are Compound ScalingBi-directional Feature Pyramid Network (BiFPN) Compound Scaling Bi-directional Feature Pyramid Network (BiFPN) Scaling up ConvNets in width (b), depth(c), or resolution (d) is widely used to achieve better accuracy, but require tedious manual tuning when scaling is done in 2 or 3 dimensions and still led to sub-optimal accuracy and efficiency. Compound scaling (e) uses a single compound coefficient φ to scale network width, depth, and resolution in a principled way according to the below equations. The compound scaling is formulated as an optimization problem given the baseline network and target flops find out the scaling coefficient for scaling the base network as shown in the above equations and is done in 2 steps: “1. Fix φ = 1, assume 2x more resources available, do a grid search of ⍺, β, γ based on the above equations. 2. Fix ⍺, β, γ as constants and scale-up baseline network with different φ ” [3] The parameter of above left equation Fi (Input Layer), Li (Number of layers), Hi (Height), Wi (Width), Ci (Number of channels) are predefined parameters of the baseline network as shown in the below Efficient network details table, and w, d, r are coefficient for scaling network width, depth, and resolution. The parameters of the above right equation φ control resources for model scaling, while ⍺, β, γ controls depth, width, or resolution scaling respectively. Since compound scaling does not change layer operators in the baseline network, having a strong baseline network is also critical. “The baseline network is selected by leveraging a multi-objective neural architecture search that optimizes accuracy and FLOPs”[3]. Multi-scale feature fusion aggregates feature at different resolutions and widely used practice to learn scale-invariant features. Feature Pyramid Network [FPN] (a) fuse features top-down from level 3 to 7 and is limited by one direction information flow, Path Aggregation Network [PANet] (b) adds bottom-up pathway on top of FPN, NAS-FPN (c) uses neural architecture search to find cross-scale feature network topology and required 1000+ hours of search. Also found network using NAS-FPN is irregular and difficult to interpret. [2] BiFPN (d) integrates bi-directional cross-scale connections with weighted feature fusion. The below equation and block diagram describe the fused feature for level 6. P7_in, P6_in (x, y, w) are the input features at level 6/7 respectively, P5_out is the out features at level-5, P6_out (x, y, w) is the out fused features at level-6. P7_in features are upsampled using nearest-neighbor interpolation and P5_out features are downsampled using max-pooling for the features fusion at level 6. The WeightedAddition layer implements fast normalized fusion, positive weights are ensured by applying Relu on each weight in the WeightedAddition layer. EfficientDet architecture uses 4 major networks, EfficientNet backbone, BiFPN, Bounding box prediction, and class prediction network. Input Image resolution: Since BiFPN uses features from level 3–7, input resolution must be divisible by pow(2, 7) = 128, and the input image is scaled according to the below equation BiFPN network: Since depth needs to be rounded to the smallest integers, depth is scaled linearly. For width (#channels) exponentially grow BiFPN, for width grid search is performed and the optimal value of 1.35 was chosen Backbone network: EfficientDet uses the EfficientNet network without any change, to reuse pre-trained weights of the imagenet model. The below table shows the efficientNet B0 and B7 network details. EfficientNet uses mobile inverted bottleneck MBConv as a building block and relies on the idea of depthwise separable convolution and residual connection which enable faster training and better accuracy. These MBConv blocks as shown in the above image, are scaled according to the compound scaling coefficient φ (num_repeat) in the backbone network. Box/class prediction network: The width of the box and class prediction network is scaled according to BiFPN network width and depth linearly scales according to the below equation. The below table shows the scaling config of EfficientDet detectors according to the compound coefficient φ. #Make sure python3 pip3 is installed and updatedsudo apt-get updatesudo apt install python3-pip sudo -H pip3 install -U pip (to upgrade the pip to latest version)#Clone EfficientDet git repogit clone https://github.com/google/automl.gitcd ~/automl/efficientdet#Install all the EfficientDet requirementspip3 install -r requirements.txt#Download the pretrained weights. Bold d0 represent the model version and can be in the range d0-d7.wget https://storage.googleapis.com/cloud-tpu-checkpoints/efficientdet/coco/efficientdet-d0.tar.gztar zxf efficientdet-d0.tar.gzmkdir -p ./savedmodels/efficient-d0# Export saved model.python3.6 model_inspect.py --runmode=saved_model --model_name=efficientdet-d0 --ckpt_path=./efficientdet-d0 --hparams="image_size=1920x1280" --saved_model_dir=./savedmodels/efficientdet-d0#Make output dir and do inferencing with the saved modelmkdir -p outdirpython3.6 model_inspect.py --runmode=saved_model_infer --model_name=efficientdet-d0 --saved_model_dir=./savedmodels/efficientdet-d0 --input_image=path_to_input_image --output_image_dir=./output --min_score_thresh=0.6 EfficientDet output looks to be better on the tested images with respect to the cloud vision APIs. A detailed comparative analysis is required to conclude EfficientDet quality with respect to production cloud vision APIs. EfficientDet with novel BiFPN and compound scaling will definitely serve as a new foundation of future object detection related research and will make object detection models practically useful for many more real-world applications. Thanks for reading the article, I hope you found this to be helpful. If you did, please share it on your favorite social media so other folks can find it, too. Also, let us know in the comment section if something is not clear or incorrect.
[ { "code": null, "e": 455, "s": 172, "text": "EfficientDet is a neural network architecture which achieves State-Of-The-Art (SOTA) results (~55.1 Average Precision) on object detection (Microsoft COCO dataset) task with much lesser (~4x-9x) complexity than the previous detectors [2]. The key building blocks of EfficientDet are" }, { "code": null, "e": 518, "s": 455, "text": "Compound ScalingBi-directional Feature Pyramid Network (BiFPN)" }, { "code": null, "e": 535, "s": 518, "text": "Compound Scaling" }, { "code": null, "e": 582, "s": 535, "text": "Bi-directional Feature Pyramid Network (BiFPN)" }, { "code": null, "e": 975, "s": 582, "text": "Scaling up ConvNets in width (b), depth(c), or resolution (d) is widely used to achieve better accuracy, but require tedious manual tuning when scaling is done in 2 or 3 dimensions and still led to sub-optimal accuracy and efficiency. Compound scaling (e) uses a single compound coefficient φ to scale network width, depth, and resolution in a principled way according to the below equations." }, { "code": null, "e": 1199, "s": 975, "text": "The compound scaling is formulated as an optimization problem given the baseline network and target flops find out the scaling coefficient for scaling the base network as shown in the above equations and is done in 2 steps:" }, { "code": null, "e": 1308, "s": 1199, "text": "“1. Fix φ = 1, assume 2x more resources available, do a grid search of ⍺, β, γ based on the above equations." }, { "code": null, "e": 1389, "s": 1308, "text": "2. Fix ⍺, β, γ as constants and scale-up baseline network with different φ ” [3]" }, { "code": null, "e": 2117, "s": 1389, "text": "The parameter of above left equation Fi (Input Layer), Li (Number of layers), Hi (Height), Wi (Width), Ci (Number of channels) are predefined parameters of the baseline network as shown in the below Efficient network details table, and w, d, r are coefficient for scaling network width, depth, and resolution. The parameters of the above right equation φ control resources for model scaling, while ⍺, β, γ controls depth, width, or resolution scaling respectively. Since compound scaling does not change layer operators in the baseline network, having a strong baseline network is also critical. “The baseline network is selected by leveraging a multi-objective neural architecture search that optimizes accuracy and FLOPs”[3]." }, { "code": null, "e": 2651, "s": 2117, "text": "Multi-scale feature fusion aggregates feature at different resolutions and widely used practice to learn scale-invariant features. Feature Pyramid Network [FPN] (a) fuse features top-down from level 3 to 7 and is limited by one direction information flow, Path Aggregation Network [PANet] (b) adds bottom-up pathway on top of FPN, NAS-FPN (c) uses neural architecture search to find cross-scale feature network topology and required 1000+ hours of search. Also found network using NAS-FPN is irregular and difficult to interpret. [2]" }, { "code": null, "e": 2818, "s": 2651, "text": "BiFPN (d) integrates bi-directional cross-scale connections with weighted feature fusion. The below equation and block diagram describe the fused feature for level 6." }, { "code": null, "e": 3295, "s": 2818, "text": "P7_in, P6_in (x, y, w) are the input features at level 6/7 respectively, P5_out is the out features at level-5, P6_out (x, y, w) is the out fused features at level-6. P7_in features are upsampled using nearest-neighbor interpolation and P5_out features are downsampled using max-pooling for the features fusion at level 6. The WeightedAddition layer implements fast normalized fusion, positive weights are ensured by applying Relu on each weight in the WeightedAddition layer." }, { "code": null, "e": 3429, "s": 3295, "text": "EfficientDet architecture uses 4 major networks, EfficientNet backbone, BiFPN, Bounding box prediction, and class prediction network." }, { "code": null, "e": 3612, "s": 3429, "text": "Input Image resolution: Since BiFPN uses features from level 3–7, input resolution must be divisible by pow(2, 7) = 128, and the input image is scaled according to the below equation" }, { "code": null, "e": 3835, "s": 3612, "text": "BiFPN network: Since depth needs to be rounded to the smallest integers, depth is scaled linearly. For width (#channels) exponentially grow BiFPN, for width grid search is performed and the optimal value of 1.35 was chosen" }, { "code": null, "e": 4034, "s": 3835, "text": "Backbone network: EfficientDet uses the EfficientNet network without any change, to reuse pre-trained weights of the imagenet model. The below table shows the efficientNet B0 and B7 network details." }, { "code": null, "e": 4384, "s": 4034, "text": "EfficientNet uses mobile inverted bottleneck MBConv as a building block and relies on the idea of depthwise separable convolution and residual connection which enable faster training and better accuracy. These MBConv blocks as shown in the above image, are scaled according to the compound scaling coefficient φ (num_repeat) in the backbone network." }, { "code": null, "e": 4566, "s": 4384, "text": "Box/class prediction network: The width of the box and class prediction network is scaled according to BiFPN network width and depth linearly scales according to the below equation." }, { "code": null, "e": 4674, "s": 4566, "text": "The below table shows the scaling config of EfficientDet detectors according to the compound coefficient φ." }, { "code": null, "e": 5768, "s": 4674, "text": "#Make sure python3 pip3 is installed and updatedsudo apt-get updatesudo apt install python3-pip sudo -H pip3 install -U pip (to upgrade the pip to latest version)#Clone EfficientDet git repogit clone https://github.com/google/automl.gitcd ~/automl/efficientdet#Install all the EfficientDet requirementspip3 install -r requirements.txt#Download the pretrained weights. Bold d0 represent the model version and can be in the range d0-d7.wget https://storage.googleapis.com/cloud-tpu-checkpoints/efficientdet/coco/efficientdet-d0.tar.gztar zxf efficientdet-d0.tar.gzmkdir -p ./savedmodels/efficient-d0# Export saved model.python3.6 model_inspect.py --runmode=saved_model --model_name=efficientdet-d0 --ckpt_path=./efficientdet-d0 --hparams=\"image_size=1920x1280\" --saved_model_dir=./savedmodels/efficientdet-d0#Make output dir and do inferencing with the saved modelmkdir -p outdirpython3.6 model_inspect.py --runmode=saved_model_infer --model_name=efficientdet-d0 --saved_model_dir=./savedmodels/efficientdet-d0 --input_image=path_to_input_image --output_image_dir=./output --min_score_thresh=0.6" }, { "code": null, "e": 6223, "s": 5768, "text": "EfficientDet output looks to be better on the tested images with respect to the cloud vision APIs. A detailed comparative analysis is required to conclude EfficientDet quality with respect to production cloud vision APIs. EfficientDet with novel BiFPN and compound scaling will definitely serve as a new foundation of future object detection related research and will make object detection models practically useful for many more real-world applications." } ]
TestLink - Quick Guide
TestLink is a test management tool used for project management, bug tracking and test management. It follows a centralized test management concept that helps to communicate easily for rapid development of tasks across QA teams and other stakeholders. It keeps the requirement specification and test specification in sync. Following salient features of TestLink need to be noted to understand the topic better. TestLink is open source test management tool. There is no license is required to use TestLink. TestLink is open source test management tool. There is no license is required to use TestLink. It is developed and maintained by Teamtest. It is developed and maintained by Teamtest. It is licensed under GPL – General Public License. It is licensed under GPL – General Public License. It supports different Windows OS such as Windows XP, Vista, 7, etc. along with other cloud-based support. It supports different Windows OS such as Windows XP, Vista, 7, etc. along with other cloud-based support. It provides free access to tools for multiple users. It provides free access to tools for multiple users. It can be integrated with many other tools – JIRA, Bugzilla, FogBugz, VersionOne, etc. It can be integrated with many other tools – JIRA, Bugzilla, FogBugz, VersionOne, etc. Following points describe the various usages of TestLink. Useful in tracking all QA activities from the first phase of software testing lifecycle. Useful in tracking all QA activities from the first phase of software testing lifecycle. Useful in Project Management, Task Tracking, Requirement Management and Test Management. Useful in Project Management, Task Tracking, Requirement Management and Test Management. Supports all macro level activities performed by QA. Supports all macro level activities performed by QA. Useful in performing QA tasks such as writing test cases, execution reports, etc. Useful in performing QA tasks such as writing test cases, execution reports, etc. Supports both manual as well as automated test execution. Supports both manual as well as automated test execution. Following table lists some of the important specifications of TestLink. Application Copyright It is developed and maintained by Teamtest. It is an open source tool. Tool Scope It can be used as a Test Automation framework. It is utilized as a Testing Utility. Testing Methods Agile Testing Black box testing Exploratory Testing Functional/Manual Testing Traditional Testing Tool Objectives Desktop Testing Web Testing Management Features Requirement Management Test Management Report Software Requirements Apache: 2.2.2.1 MySQL : 5.5.16 PHP: 5.3.8 PhpMyAdmin: 3.4.5 Filezilla FTP Server: 0.9.39 Tomcat: 7.0.21 Error Handling Capture screenshots User Interface Available COM API Direct UI GUI usability TestLink has a wide range of features to attract QAs and other stakeholders for test management. Following table lists the core features of TestLink. Testing Supports TestLink supports the following test methodologies − Agile testing Black box testing Exploratory testing Functional/Manual and Automation testing Traditional testing Centralize & organize TestLink tool creates, centralizes, organizes and manages test cases very effectively and efficiently. TestLink tool creates, centralizes, organizes and manages test cases very effectively and efficiently. Easily import test cases from CSV/XML and other management tool. Easily import test cases from CSV/XML and other management tool. It can create multiple versions of test cases for comparison and uses. It can create multiple versions of test cases for comparison and uses. It can share test case repository across different projects, releases and sprints. It can share test case repository across different projects, releases and sprints. Manage & Track Execution It supports run and re-run of test execution suites. It kicks off automation suite as well using XML-RPC. It supports run and re-run of test execution suites. It kicks off automation suite as well using XML-RPC. It captures step-by-step test execution history with detailed explanation. It captures step-by-step test execution history with detailed explanation. It supports test run specific configuration and parameters. It supports test run specific configuration and parameters. Notification Email can be sent for a particular task to users. Email can be sent for a particular task to users. Use @mention to get the attention of a specific team member at Comments/Description. Use @mention to get the attention of a specific team member at Comments/Description. Power Search TestLink supports powerful search functionality with Hotkeys features. TestLink supports powerful search functionality with Hotkeys features. TestLink supports free text search. TestLink supports free text search. TestLink supports syntax search. TestLink supports syntax search. Reports TestLink supports multiple reports. TestLink supports multiple reports. It supports test case and test execution reports. It supports test case and test execution reports. Requirement and traceability reports. Requirement and traceability reports. Defect reports. Defect reports. It supports cross-project report as well. It supports cross-project report as well. Scale with Team Growth TestLink supports any business team and any project, irrespective of the size and complexity. Integration TestLink supports numerous add-ins to connect with different softwares to make work easy. TestLink supports numerous add-ins to connect with different softwares to make work easy. Wide range of add-ins make it universal across the globe – JIRA, Mantis, Bugzilla, Trac, etc. Wide range of add-ins make it universal across the globe – JIRA, Mantis, Bugzilla, Trac, etc. It also supports Rally and VersionOne integration. It also supports Rally and VersionOne integration. Common Features It supports Drag and Drop interface. It supports Drag and Drop interface. It supports Test Grid Analysis. It supports Test Grid Analysis. It can clone the entire test case repository along the project setting, such as email notification and more. It can clone the entire test case repository along the project setting, such as email notification and more. Customization It supports customization of UI using Smarty templates. It supports customization of UI using Smarty templates. It supports to create and assign the user’s keyword. It supports to create and assign the user’s keyword. Following are some points to note before we go for the installation of TestLink. TestLink is a web application; it provides a private website to an individual or a set of requested users belonging to the same company/project. TestLink is a web application; it provides a private website to an individual or a set of requested users belonging to the same company/project. TestLink can be run at the server side. TestLink can be run at the server side. TestLink is a PHP based application and supports all OS platforms such as Windows, Linux of different versions, MAC, etc. TestLink is a PHP based application and supports all OS platforms such as Windows, Linux of different versions, MAC, etc. TestLink supports all famous browsers such as Chrome, IE, Mozilla, and Safari. TestLink supports all famous browsers such as Chrome, IE, Mozilla, and Safari. Since TestLink is a web-application it follows the concept of client/server. It means that TestLink can be installed centrally on a server and users can interact with it through web browsers using a website from any computer. Web Server − TestLink supports Apache 2.2.2.1. However, it can work with any latest web server software. TestLink only uses .php file. Configure the web server with .php extension only. Web Server − TestLink supports Apache 2.2.2.1. However, it can work with any latest web server software. TestLink only uses .php file. Configure the web server with .php extension only. PHP − The web server should support PHP. It can be installed as CGI or any other integration technology. It is recommended to use 5.3.8 PHP version. PHP − The web server should support PHP. It can be installed as CGI or any other integration technology. It is recommended to use 5.3.8 PHP version. Mandatory PHP Extensions − Extensions for RDBMS are mysqli, pgsql, oci8, sqlsrv. Mbstring is required for Unicode – UTF-8 support. Mandatory PHP Extensions − Extensions for RDBMS are mysqli, pgsql, oci8, sqlsrv. Mbstring is required for Unicode – UTF-8 support. Optional Extensions − Curl, GD, Fileinfo Optional Extensions − Curl, GD, Fileinfo Database − TestLink requires database to store its data. MySQL (5.5.16) is recommended. Database − TestLink requires database to store its data. MySQL (5.5.16) is recommended. FileZilla FTP Server − FileZilla FTP Server 0.9.39 is required to install XAMPP as optional. FileZilla FTP Server − FileZilla FTP Server 0.9.39 is required to install XAMPP as optional. You can install all the requirements separately either manually or through an automatic process to use TestLink. If the user has required knowledge about the installation process, the user can install all the discussed requirements one-by-one separately before proceeding to TestLink. Alternatively, there are many all-in-one packages available and can automatically install in the system by exe file. Here, we will take the help of XAMPP to install the pre-requisites easily. Step 1 − Go to https://www.apachefriends.org/index.html and click XAMPP for Windows as shown in the following screenshot. Step 2 − A pop-up will be displayed to save the file. Click Save File. It will start to download the file. Step 3 − Run the .exe file to run the installation wizard. After clicking the .exe file, the XAMPP Setup wizard is displayed as shown in the following screenshot. Click Next. Step 4 − Next, the wizard displays all the component files (shown in the following screenshot) that will be installed. Click Next after selecting the components. Step 5 − Provide a folder name where XAMPP will be installed and click Next. Step 6 − Ready to Install wizard is displayed. Click Next to start the installation. Step 7 − After successful installation, it will prompt to start the control panel. Select the checkbox and click Finish. It will open the XAMPP control panel as displayed in the following screenshot. Step 8 − Click the Start button for Apache and MySQL required for TestLink as shown in the above screenshot. Step 9 − To verify whether all the pre-requisites such as Apache, PHP and MySQL is installed properly, navigate to any of the browser and type http://localhost. Then, press Enter. Step 10 − It will display the dashboard of XAMPP. Click phpAdmin at the right top corner of the screenshot. It will display General Settings, Application Settings, Details of Database, Web Server and phpMyAdmin as shown in the following screenshot. If the installation is not proper, this page won’t display. Till this point, all the pre-requisites are successfully installed in the system. After successful installation of XAMPP, we need to work with TestLink. Step 1 − Go to https://sourceforge.net/projects/testlink/ and click Download. Step 2 − Now unzip the downloaded .tar file and rename the folder name as TestLink. Step 3 − Go to XAMPP folder where it is installed and navigate to htdocs folder. Place the TestLink folder here as shown in the following screenshot. Step 4 − Go to TestLink package and open “config.inc.php” file, update path “$tlCfg→log_path” and “$g_repositoryPath” as below − $tlCfg→log_path = ‘D:/xampp/htdocs/testlink/logs/’; $g_repositoryPath = ‘D:/xampp/htdocs/testlink/upload area/’; Step 5 − Now open a browser and type http://localhost/Testlink in the navigation bar and press Enter. It will display the installation page of TestLink. Step 6 − Click New Installation. Step 7 − Check the checkbox for Terms and Conditions and click the Continue button. The system will check the pre-requisites to ensure everything is fine. A Continue button will appear at the bottom, otherwise an error message will be displayed. Step 8 − Click Continue as shown in the following screenshot. Step 9 − In the next step, Database Admin and Admin password is required to define MySQL access. TestLink admin username/password can be anything given by the user. Database login/password: root/<empty> (Default login/password of MYSQL for xampp) Step 10 − Click “Process TestLink Setup” button. You should see the TestLink “Installation was successful!” message being displayed. Step 11 − Now again navigate to http://localhost/testlink You will see the login page as shown in the following screenshot. To login into TestLink, go to your sample website, http://localhost/testlink. It will open a login page as shown in the following screenshot. Step 1 − Enter admin as both username and Password. Admin is the default credential. Step 2 − Click the Log in button. Following screenshot shows how to login into TestLink using credentials − Due to unsuccessful login, an error page is displayed. Error may occur due to wrong combination of email id or password. Following screenshot shows the error message, the user receives if the credentials are not correct. If you forgot the password, to recover it, following are the steps − Step 1 − Click the “Lost Password?” link below the Log in button. Step 2 − Enter the Login Name. Step 3 − Click Send. Following screenshot shows how to recover the password if you forgot. You will get an email with the details of username or a link to reset the password. On successful login, the system dashboard will display if the account is associated with any project by admin or if you can create a sample project. Following screenshot displays the Create a Project page of TestLink on successful login. To add a project, you should have Admin role. Once you log in for the first time as an Admin, TestLink opens the Create a new project form. You cannot see any other page until the project is created or assigned to you. Following are the steps involved to add a project into TestLink − Usually to create a project, an option is available at the Test Project Management menu as shown in the following screenshot. Step 1 − Enter the following details into Create a Project form − Name − It should be a unique project name. Prefix − It is used for test case ID to identify the test cases. Project description − Details about the project. Enhanced features − You can check the checkboxes based on the requirement of the project. It allows to select which features you want such as Requirement, Automation, etc. Issue tracker − If any issue tracker is linked with TestLink, it will be displayed here. Step 2 − Select the Availability option and then click the Create button as shown in below. Clicking the Create button adds the project along with Delete and Active/Inactive switch for Requirement and Active features as shown in the following screenshot. Step 3 − You can view the project by selecting a project name from the “Test Project” dropdown at the top right corner of the screen as seen below. After logging into TestLink, Dashboard is the first page that is displayed as soon as you are assigned to a project. Dashboard is customized by Admin. Based on the roles, admin can set the access of TestLink. Following screenshot shows the overview of the Dashboard page of TestLink. Following are some points to note with regards to the dashboard. The tool bar icons present at the top left corner of TestLink page will be the same across all pages/screen of TestLink. My Settings, Project, Requirement Specification, Test Specification, User Management and Event as the main links. These links are used to navigate to the respective functionality. The tool bar icons present at the top left corner of TestLink page will be the same across all pages/screen of TestLink. My Settings, Project, Requirement Specification, Test Specification, User Management and Event as the main links. These links are used to navigate to the respective functionality. The navigation bar contains the links that provide a quick access to the most useful functions of TestLink. The navigation bar contains the links that provide a quick access to the most useful functions of TestLink. On the left side of the page - System, Test Project, Requirement Specification and Test Specification categories are present. These categories present different links for quick access to all the features of TestLink. On the left side of the page - System, Test Project, Requirement Specification and Test Specification categories are present. These categories present different links for quick access to all the features of TestLink. On the right side, Test Plan category has Test Plan Management link to add or manage a test plan. On the right side, Test Plan category has Test Plan Management link to add or manage a test plan. On the top left side of the screen, a Search functionality is available while on the right side, there is a Test Project dropdown. On the top left side of the screen, a Search functionality is available while on the right side, there is a Test Project dropdown. My Settings icon is present at the top left corner of the screen as the first icon. Following screenshot shows the My Settings icon encircled in red. Once you click the icon, it opens the settings page where various information is available to update. First, there is Personal Data where you can update your first name, last name, email id or Locale. Then, there is the Personal Password section, where you can change the login password. The third section shows API interface, where you can generate a personal API key. In the last section, you can view the login history. The logout icon is present at the top left side of the screen, beside the My Settings icon. After clicking the Logout icon, you can go back to the login page and the active session ends. To utilize all TestLink features, you have to login again. In the following screenshot the logout icon is encircled in red. In this chapter, you will learn how to create, edit, and delete a project in TestLink. TestLink supports multiple projects at a time. To create a Project, you should have Admin permissions. Following are the steps to create a Project. Step 1 − To create a new project, click Test Project → Test Project Management at dashboard as shown in the following screenshot. It will display all the available projects along with filters and Create a button at the top. Step 2 − Click the Create button as shown in the following screenshot. It opens the Create Project page. Step 3 − Enter the following details into Create a Project form: Name − It should be a unique project name. Prefix − It is used for test case ID to identify the test cases. Project description − Details about the project. Enhanced features − You can check the checkboxes based on the requirement of the project. It allows to select the features that you wish such as Requirement, Automation, etc. Issue tracker integration − If any issue tracker is linked with TestLink, it will be displayed here. Step 4 − Select the Availability option and then click the Create button as shown in the following screenshot. Clicking the Create button adds the project into the system. To edit a project, you should have Edit Project Permission. Following are the steps to edit the project details − Step 1 − Click Test Project → Test Project Management. It will display all the available projects. Step 2 − Click the Project Name to edit the details as shown in the following screenshot. Step 3 − It opens the Project Details in edit mode. You can update the details in any of the sections and click the Save button. To delete a project, you should have Delete project Permission. Step 1 − Click Test Project → Test Project Management. It will display all the available projects along with a delete icon in red at the right corner as shown in the following screenshot. Step 2 − Click the Delete icon related to the respective project. It will display a warning message for deletion along with an advice to deactivate rather than delete a project. Following screenshot displays the same. Step 3 − Click the Yes button. It will refresh the page and the project will be removed from the list. In the Inventory, you can list all hardware details required in the project. To access this feature, you should enable it while creating a project or in the edit project page. You can access the Inventory by navigating to Test Project → Inventory in Dashboard as shown in the below screenshot. Inventory offers three actions − Create, Edit and Delete. Following are the steps to create a record in inventory − Step 1 − Click Inventory on the Dashboard to visit the Inventory page. Step 2 − Click the Create link present at the left top corner of the screen. It will open a pop-up form to define a device data. Step 3 − Enter the following details − Host Name IP Address Owner Purpose − It supports up to 2000 characters. Hardware − It supports up to 2000 characters. Notes − It supports up to 2000 characters. Step 4 − Click the Save button. Once you click Save, a new row gets added along with all the entered details as shown in the following screenshot. To edit a record, a row must be selected. Following are the steps to edit a record − Step 1 − Click the Host Name to select a record to edit in the Inventory page. Step 2 − Click the Edit link present at the top left corner of the screen. It will open a pop-up form to define a device data. Step 3 − Update the following details − Host Name IP Address Owner Purpose − It supports up to 2000 characters. Hardware − It supports up to 2000 characters. Notes − It supports up to 2000 characters. Step 4 − Click the Save button. Step 5 − Once you click the Save button, all the details get updated and saved in the same row. Following are the steps to delete a record − Step 1 − Click the Host Name to select a record to delete in the Inventory page. Step 2 − Click the Delete link present at the top left corner of the screen. It will ask for confirmation to delete. Step 3 − Click Yes to delete the record. You will receive a successful deletion message and the row gets deleted as shown in the following screenshot. Test planning, is the most important activity to ensure that there is initially a list of tasks and milestones in a baseline plan to track the progress of the project. It also defines the size of the test effort. It is the main document often called as the master test plan or a project test plan and is usually developed during the early phase of the project. To create a test plan, you should have Create Test Plan Permission. Following are the steps to create a test plan − Step 1 − Go to Test Plan → Test Plan Management on the dashboard as shown in the following screenshot. If any test plan is listed for the project, it displays the list of test plans. Otherwise, it displays a message to create a test plan to support the test execution functionality. Step 2 − Click the Create button as shown in the following screenshot. It displays the test plan create form. Step 3 − Enter the following details in the form. Name − It should be the name of the test plan. Name − It should be the name of the test plan. Description − This field should contain the detailed information of a test plan. Generally, a test plan consists of the following information. Description − This field should contain the detailed information of a test plan. Generally, a test plan consists of the following information. Test plan identifier Unique identifying reference. Introduction A brief introduction about the project and of the document. Test items A test item is a software item that is the application under test. Features to be tested A feature that needs to tested on the testware. Features not to be tested Identify the features and the reasons for not including as part of testing. Approach Details about the overall approach to testing. Item pass/fail criteria Documented whether a software item has passed or failed its test. Test deliverables Deliverables that are part of the testing process, such as test plans, test specifications and test summary reports. Testing tasks All tasks for planning and executing the testing. Environmental needs Defining the environmental requirements such as hardware, software, OS, network configurations, and tools required. Responsibilities Lists the roles and responsibilities of the team members. Staffing and training needs Captures the actual staffing requirements and any specific skills and training requirements. Schedule States the important project delivery dates and key milestones. Risks and Mitigation High-level project risks and assumptions as well as a mitigating plan for each identified risk. Approvals Captures all approvers of the document, their titles and the sign-off date. Testlink supports images, table, links, special characters, etc. to make content rich description. There are 2 checkboxes as can be seen in the following screenshot. Active − It will activate the document after creation and you can utilize this document in test execution or any other activities as a reference. Active − It will activate the document after creation and you can utilize this document in test execution or any other activities as a reference. Public − It allows other users to use this document. It will be visible to other users as well who are linked with this project. If this checkbox is unchecked, only the person who has created can use and view this document. Public − It allows other users to use this document. It will be visible to other users as well who are linked with this project. If this checkbox is unchecked, only the person who has created can use and view this document. Step 4 − Click the Create button present at the bottom of the form. Once you click Create, you can see the added Test Plan along with a few icons at the extreme right of screen as seen below. These icons are delete the test plan, export links to the test cases and platform, import links to the test cases and platform, Assign Role and test execution from left to right as displayed in below screenshot. To edit a test plan, you should have Edit Permission. Following are the steps to edit a test plan. Step 1 − Click the Test Plan name to open the details. The name of the Test Plan is present in the first column and it is hyperlinked as shown in the following screenshot. Step 2 − It opens the test plan details in edit mode. You can edit the name, description, and selection of Active and Public mode. Step 3 − Attach a file in the test plan. This feature is available in the edit mode only. While creating the test plan, you can add images/tables into the description. However, attaching a file option is not available. Step 4 − After updating the details, click Update to finish editing. Following screenshot displays how to edit a test plan. To delete a plan, you should have Delete Permission. If a test plan is deleted, it deletes both the test plan and all of its corresponding data. Data includes test cases, results, etc. Following are the steps to delete a build − Step 1 − Go to the Test Plan Management → Test Plan from the dashboard. Step 2 − Click the Delete icon corresponding to the row of the test plan that needs to be deleted as seen below. A pop-up will be displayed for a confirmation to delete. Step 3 − Click Yes as shown below. The page gets refreshed and the test plan will be deleted. To achieve the objective of a Release, there could be multiple builds. Build is always associated with only one Release. A build fulfills the partial objective of Release with limited functionalities. In TestLink, test execution is made up of both builds and test cases. If the build is not created for a project, you won’t be able to perform test execution. To create a Build, you should have Create Builds permission. Following are the steps to create a Build − Step 1 − Go to Test Plan → Build/Releases from the dashboard. It opens the Build Management page along with the available builds. Step 2 − Click the Create button as shown below. It opens the Create a new build form. Step 3 − Enter the following fields in the form − Title − A build is identified by its title. Each build is related to the active Test Plan. Title − A build is identified by its title. Each build is related to the active Test Plan. Description − Description should include a list of delivered packages, fixes or features, approvals, status, etc. Description − Description should include a list of delivered packages, fixes or features, approvals, status, etc. Active − A build has two attributes - Active / Inactive – defines whether the build can be used. Inactive builds are not listed on the execution and reports pages. Open / Closed – Test results can be modified only for open builds. Ensure that the Build date must is within the Release Timeline. Active − A build has two attributes - Active / Inactive – defines whether the build can be used. Inactive builds are not listed on the execution and reports pages. Open / Closed – Test results can be modified only for open builds. Ensure that the Build date must is within the Release Timeline. Release Timeline − It should be a future date. Release Timeline − It should be a future date. Step 4 − After entering all the details, click the Create button to add the build. To edit a build, you should have Edit Builds permission. Following are the steps to edit a build − Step 1 − Select a Build to edit and click the build title to open the details as shown below. It opens the build details in the edit mode as shown in the following screenshot. Step 2 − After updating the build details, click the Save button. To delete a Build, you should have Delete Builds permission. Following are the steps to delete a build − Step 1 − Go to the Test Plan Management − Builds/Releases from the dashboard. Step 2 − Click the Delete icon corresponding to the row of the build that needs to be deleted as shown below. A pop-up will be displayed for confirmation to delete. Step 3 − Click Yes as shown in the following screenshot. The page will be refreshed and the build will be deleted. Test Specification defines the structure of Test Design. Creation of Test Suits and Cases are done through test specification. However, one project can have only one test specification. Test Specification can be accessed by navigating to Test Specification → Test Specification from the dashboard. It is divided into two panels − Settings and Filter (Left side) and Test Project (right side). You can create test suite/cases by working on the right side. After navigating to test specification, Filters are displayed on the left side panel of the screen. Filters help out to narrow down the search and provide unique test cases. Following are the steps to use the Filter functionality − Step 1 − Go to the filter section on the left side of the screen. Step 2 − Provide different filter options as the following − Test Case ID Test Case ID Test Case Title Test Case Title Status − You can select multiple choices at a time from the dropdown. It supports Any, Draft, Ready for Review, Review in Progress, Rework, Obsolete, Future and Final. Status − You can select multiple choices at a time from the dropdown. It supports Any, Draft, Ready for Review, Review in Progress, Rework, Obsolete, Future and Final. Importance − You can select multiple choices at a time from the dropdown. It supports Any, Help, Medium and Low. Importance − You can select multiple choices at a time from the dropdown. It supports Any, Help, Medium and Low. Execution Type − It is a single selection dropdown. It supports Any, Manual or Automated option. Execution Type − It is a single selection dropdown. It supports Any, Manual or Automated option. Step 3 − After selection, click the Apply button to display the result. Reset Filters button will remove all selection in default mode. You can expand the tree to display the structure of the result. On the right side, Test Project is displayed. Test Project name is hyperlinked. When you click the name, it displays the details of the project in edit form, where you can update the project details. After the name, it displays Project Description and Attached files. It supports a feature to add an attachment. You can browse and upload the file to the project. It supports max 1048576 Bytes. You can upload up to a maximum size of the file. You can upload multiple files to the project. At the top of the screen, there is a settings symbol , called Actions You can add test suites and test cases by clicking this symbol. Test suite is a container that has a set of tests which helps the testers in executing and reporting the test execution status. It can take any of the three states namely Active, In progress, and Completed. A test case can be added to multiple test suites and test plans. After creating a test plan, test suites are created, which in turn can have any number of tests. TestLink supports tree structure for test suites. There could be multiple sub-test suites under a test suite. To create a Test Suite, you should have Create Test Suites permission. Following are the steps to create a Test Suite − Step 1 − Navigate to Test Specification → Test Specification from the dashboard. Step 2 − Click the Setting type icon known as Actions on this page, present on the right panel as shown in the following screenshot. It will open Test Suite Operations. Step 3 − Click the + icon to create a new suite as shown below. It opens the create test suite page. Step 4 − Enter the following fields in the form − Name of Test Suite Name of Test Suite Details Details Keywords − It displays all the available keywords. You can assign them based on relation. Keywords − It displays all the available keywords. You can assign them based on relation. Step 5 − Click the Save button as displayed in the following screenshot. Once you click Save, you will see the test suite in tree structure on the left side panel of the screen. The details are available on the right side of the screen. To edit a test suite, you should have Edit Test Suite Permission. Following are the steps to edit a test suite − Step 1 − Select test suite from the tree structure on the left panel and click the settings known as actions to open the Test Suite Operations as shown below. It displays Test Suite Operations. Step 2 − Click the Edit (pencil) icon as shown below. It opens the Test Suite details on the edit page. Step 3 − Edit Name, Details or any other fields and click the Save button to update the test suite. To move/copy a test suite, you should have Create/Edit Test Suite permission. This functionality allows creating a duplicate of a Test Suite or reordering of the structure. Step 1 − To copy/move a test suite into another project, select test suites those need to be copied/moved and click the setting icon known as Actions. It will open Test suite Operations. Step 2 − Click the Move or Copy symbol as shown in the following screenshot. Step 3 − It opens the Move/Copy page where you can select the target container, destination position, and whether the keywords and requirements should be copied/moved to the target container. Step 4 − After selection, click the Copy or Move button according to requirement as shown in the following screenshot. The Copy button will copy the test suite in both of the projects, while the move button will move the test suite from the current project to the target project. To delete a Test Suite, you should have Delete Test Suite permission. Step 1 − To delete a test suite, select test suites those need to be deleted and click the setting icon known as Actions. It will open Test suite Operations. Step 2 − Click the delete symbol as shown below. A confirmation message will be displayed to delete. Step 3 − Click Yes to delete the test suite as shown in the following screenshot. The page will be refreshed and the test suite will be deleted from the Tree structure on the left side panel of the screen. A successful deletion message is also displayed as shown below. A test case is a document, which has a set of test data, preconditions, expected results and post-conditions, developed for a particular test scenario in order to verify compliance against a specific requirement. Test case acts as the starting point for test execution, and after applying a set of input value the application has a definitive outcome and leaves the system at some endpoint, also known as execution post-condition. To create a Test Case, you should have Create Test Cases permission. Following are the steps to create a Test Case − Step 1 − Navigate to Test Specification → Test Specification from the dashboard. Step 2 − Select the test suite from the tree structure on the left side panel on the screen. Step 3 − Click the Setting type icon known as Actions on this page, present on the right panel of the screen as shown below. It will open Test Suite Operations as well as Test Case Operations. Step 4 − Click the + icon of Test Case Operations to create a new test case as shown below. It opens the create test case page. Step 5 − Enter the following fields in the form − Name of Test Case Name of Test Case Summary Summary Pre-conditions Pre-conditions Select Status, Importance and Execution type Select Status, Importance and Execution type Enter the estimated execution type in minutes Enter the estimated execution type in minutes Keywords − It displays all the available keywords. You can assign them based on the relation. Keywords − It displays all the available keywords. You can assign them based on the relation. Step 6 − Click the Create button as displayed in the following screenshot. Once you click the Create button, you can see the test case in the tree structure on the left side panel as well as the details are available on the right side of the screen. To edit a test case, you should have Edit Test Case permission. Following are the steps to edit a test case − Step 1 − Select the test case from the tree structure on the left panel of the screen and click the settings known as actions to display all the available options. Step 2 − Click the Edit button as shown below. It opens the Test case details in the edit page. Step 3 − You can edit the Name, Details or any other fields as shown below. Step 4 − Click the Save button to update the test case. To Move/Copy a test case, you should have Create/Edit Test Suite permission. This functionality allows creating a duplicate test case or reordering of the structure. Step 1 − To copy/move a test suite into another project, select the test cases that need to be copied/moved and click the setting icon known as Actions. Step 2 − Click the Move/Copy button as shown below. Step 3 − It opens the Move/Copy page. You can select the test suite to move or copy a new test case name and decide whether the keywords and requirements should be copied/moved to the target suite. Step 4 − After selection, click the Copy or Move button according to requirement. Step 5 − The Copy button will copy the test suite in both of the suites, while the move button will move the test case from the current suite to the target suite. Following screenshot shows how to copy/move the test case to another suite − To delete a Test Case, you should have Delete Test Case permission. Step 1 − To delete a test case, select the test case from the suite that needs to be deleted and click the setting icon known as Actions. Step 2 − Once done, click the delete button as shown below. A confirmation message will be displayed to delete. Click Yes to delete the test cases as shown in following screenshot. The page will be refreshed and the test case will be deleted from the tree structure on the left side panel of the screen. A successful deletion message will be displayed as shown below. This feature is very useful when one test case has many versions. Active/Inactive attribute helps to recognize which test case should be used. Step 1 − To create a new version of the test case, click the button “Create a new version” as shown below. It will create a new version of test case and a successful message will be displayed as shown below. Once a new version is created, by default it is in Active mode. It is recommended to deactivate the version of previous test case before creating a new version. Deactivate Test Case Version is not available in "Add Test Cases to Test Plan". This can be useful for test designers. They can edit or change the Test Case Version and only when they decide it is completed, change the Status to ACTIVE for it to be available to be used in a Test Plan. Step 2 − After clicking on Actions, the button - Deactivate this version – is displayed. Step 3 − Once you click the button, a message that the test case version is deactivated is displayed and the button changes to “Activate this version”. TestLink supports XML and CVS file to import data. It supports importing the data for test suites, test cases, requirements, test execution results, keywords, etc. However, for few cases it supports only XML and in few cases both XML and CVS. Following table displays the functionalities that support import and those that support file format. Sample File − Following is the XML file with keywords that can be used to import test suites. <testsuite name = "Child Suite2"> <details>abc</details> <testcase name = "Sample test case2"> <summary>test case sample- update</summary> <preconditions>1. TestLink should be installed</preconditions> <steps> <step> <step_number>1</step_number> <actions>Go to www.google.com</actions> <expectedresults>Google Home page should display</expectedresults> </step> </steps> <keywords> <keyword name = "Sample Test"> <notes>abc</notes> </keyword> </keywords> </testcase> </testsuite> If you don’t want to add the keyword, the keyword section can be removed from the XML file. If you don’t want to add the keyword, the keyword section can be removed from the XML file. If you want to import multiple test cases, add <testcase> section multiple times with all sub-nodes. If you want to import multiple test cases, add <testcase> section multiple times with all sub-nodes. If only test cases need to be imported in an already existing test suite, remove the <testsuite> tag and start the XML file with <testcase>. If only test cases need to be imported in an already existing test suite, remove the <testsuite> tag and start the XML file with <testcase>. Step 1 − To import the test suite, go to Test Specifications → Test Specification from the dashboard. Step 2 − Select the project and the folder on the left pane where you want to import the test suite. OR To import only test cases, select the nearest test suite folders where the test cases should be imported. Step 3 − Click the Actions icon on the right pane as shown below. It displays the test suite operations. Step 4 − Click the Import icon as shown below − OR To upload only test cases, click the Import icon present in Test Case Operations (below the Test Suite Operations). It opens the Import Test Suite page. By default, the file type is selected as XML. Step 5 − Fill in the following details − File − Select the XML file and upload it. Max size of the file should be 400KB. File − Select the XML file and upload it. Max size of the file should be 400KB. Consider test case as duplicate if: Select the appropriate option from the list. Consider test case as duplicate if: Select the appropriate option from the list. Action for duplicate: Select the appropriate option from the list. Action for duplicate: Select the appropriate option from the list. Step 6 − Click the Upload file button as shown below − Step 7 − After import, a successful message is displayed as shown below. Sample XLS file to import multiple test cases as the following − Unlock panic button Press panic button Press confirm The first row won’t be imported. It is supposed to have a column description. Step 1 − To import test cases, go to Test Specifications → Test Specification from the dashboard. Step 2 − Select the nearest test suite folders, where the test cases should be imported. Step 3 − Click the Actions icon on the right pane. It displays Test Case Operations. Step 4 − Click the Import icon as shown below. It opens the Import test case page. Step 5 − By default, the file type selected is XML. Change it to XLS/CSV and enter the following details − File − Select the file and upload it. Max size of the file should be 400KB. File − Select the file and upload it. Max size of the file should be 400KB. Consider test case as duplicate if − Select the appropriate option from the list. Consider test case as duplicate if − Select the appropriate option from the list. Action for duplicate − Select the appropriate option from the list. Action for duplicate − Select the appropriate option from the list. Step 6 − Click the Upload file button as shown below. TestLink supports XML and CSV file to import the requirements. Sample XML file for Requirement would be as follows − <requirements> <requirement> <docid>ENG-0001</docid> <title>Add a product</title> <description>ABC</description> </requirement> <requirement> <docid>ENG-0002</docid> <title>Add price </title> <description>Price</description> </requirement> </requirements> Sample CSV file for Requirement would be as follows − ENG-0001,Add a product,ABC ENG-0002,Add price,Price Step 1 − To import the requirements, go to Requirement Specification → Requirement Specification from the dashboard. Step 2 − Select the Requirement Specification folder where the requirements should be imported on the left panel. Step 3 − Click the Action icon present on the top of the right pane. It displays the Requirement Operations page. Step 4 − Click the Import button as shown below. It displays the requirement import page. Step 5 − Enter the following details. File Type − You can select CSV, XML or other forms of CSV and XML files as listed. File Type − You can select CSV, XML or other forms of CSV and XML files as listed. File − Upload the corresponding file. File − Upload the corresponding file. Consider test case as duplicate if − Select the appropriate option from the list. Consider test case as duplicate if − Select the appropriate option from the list. Action for duplicate − Select the appropriate option from the list. Action for duplicate − Select the appropriate option from the list. Step 6 − Click the Upload file button as shown below. After upload, it displays Import done message along with the imported details. After upload, it displays Import done message along with the imported details. Similarly, keywords, platforms, and results can be imported using supported file and the respective section accessing the dashboard. TestLink supports XML and CSV file to export data. It supports exporting the data of test suites, test cases, requirements, test execution results, keywords, etc. However, for a few cases it supports only XML and in few cases both XML and CSV. Following table displays the functionalities that support export and file format. TestLink supports XML and CSV to export the requirement data. Step 1 − Go to Requirement Specification → Requirement Specification from the dashboard. Step 2 − To export all the Requirement Specifications, select the parent folder from the left pane and click the Export All Requirement Specification button on the right side as follows. Step 3 − To export any one requirement specification with all the requirement details inside the folder, select the folder in the left pane and click the Actions icon on the right pane. It displays the Requirement Specification Operation page. Step 4 − Click Export. OR If you want to only export the Requirement Details but not Requirement Specification, click the Export button present under Requirement Operations (present below the Requirement Specification Operations section) as shown below. Once any of these Export buttons is clicked, it displays the Export Requirement page. Step 5 − Export Filename can be edited. Choose the file type. Then, click the Export button as shown below. It will download the corresponding files into the local drive that can be accessed by navigating the Downloads folder. TestLink supports XML to export test suites and cases data. Step 1 − Go to Test Specification → Test Specification from the dashboard. Step 2 − To export all the test suites, select the parent folder from the left pane and click the Action icon on the right pane. It opens the test suite operations page. Step 3 − Click Export All Test Suites icon on the right side as shown below. Step 4 − To export any one test suite with all the test cases inside the folder, select the folder on the left pane and click the Actions icon on the right pane. It displays Test Suite Operations page. Step 5 − Click Export. OR If you want to only export Test Cases but not Test Suites, click the Export button present under Test Case Operations as shown below. Once any of these Export buttons is clicked, it displays the Export Test Suite/Case page. Step 6 − The Export Filename can be edited. Choose the file type. You can select and narrow down the exported data by selecting the checkbox for available details. Step 7 − Click the Export button as shown below. It will download the corresponding files into the local drive that can be accessed by navigating the Downloads folder. Test Plan contains a set of test cases those are in scope. Before starting the execution, a test plan must have test sets. A test case cannot be executed before assigning it to any test plan. Following are the steps to add test cases to a test plan. Step 1 − Go to Test Plan contents → Add/Remove test cases from the Dashboard as shown below. It opens the Add/Remove Test Cases page. Step 2 − Search the folder using filter on the left panel and click the test case folder. It displays Test Plan − Add Test cases to Test Plan page on the right panel. Step 3 − Check all the available test cases to add to the test plan. Step 4 − Select from Assign dropdown to assign this to a person. Step 5 − Select a build as well. Step 6 − Click the Add Selected button to add the test case to a test plan. After clicking Add selected, the color of the test case gets changed. Step 7 − The Add selected button changes to Add/Remove selected as shown in the following screenshot. To remove test cases from a test plan the following steps should be performed − Step 1 − Go to Test Plan contents → Add/ Remove test cases from the Dashboard as shown below. It opens the Add/Remove Test Cases page. Step 2 − Search the folder using a filter on the left panel and click the test case folder. It displays Test Plan − Add Test cases to Test Plan page on the right panel. Step 3 − Select the test cases that need to be removed. Step 4 − Click the Add/Remove selected button as shown below. Search functionality is used to narrow down the displayed result. TestLink supports a wide range of search functionalities with a lot of fields to find out a specific result. TestLink supports the following search functionalities − Search Requirements Search Requirements Specification Search Test Cases Common Search Text Box As seen in the following screenshot, at the top, there is a search text box used to find the specific test case. Usually a test case ID starts with SP-<index>. You can enter numbers to find a specific test case directly. This text box is present across all the pages. In the requirement specification section, TestLink supports the Search Requirements functionality. Following steps should be performed to use Search Requirements − Step 1 − Go to Requirement Specifications → Search Requirements as shown below. It opens the Requirement Search page. The search is not case sensitive. Result includes just requirements from the actual Test Project. Step 2 − Write the searched string to an appropriate box. Leave unused fields as blank. Step 3 − Choose the required keyword or leave the value as 'Not applied'. It has the following list of supported fields to find the requirement − Req. Doc ID, Version, Title, Scope, Status, Type, Expected no. of test cases, Has relation of type, Creation Date from, Creation Date to, Modification Date from, Modification date to, Test Case ID and Log Message. Step 4 − Click the 'Find' button. All fulfilling requirements are shown. You can modify requirements via 'Title' link. In the requirement specification section, TestLink supports the Search Requirement Specifications functionality. Following steps should be performed to use Search Requirement Specifications − Step 1 − Go to Requirement Specifications → Search Requirement Specifications as shown below. It opens the Requirement Specifications Search page. The search is not case sensitive. Result includes just the requirement specifications from the actual Test Project. Step 2 − Write the searched string to an appropriate box. Leave the unused fields in the form as blank. Step 3 − Choose the required keyword or leave the value as 'Not applied'. It has the following list of supported fields to find the requirement specifications − Req. Doc ID, Title, Scope, Type and Log Message. Step 4 − Click the 'Find' button. All fulfilling requirement specifications are shown. You can modify requirements via 'Title' link. In the Test specification section, TestLink supports the Search Test Cases functionality. Following are the steps to be performed to use Search Test Cases. Step 1 − Go to Test Specification → Search Test Cases as shown in the following screenshot. It opens the Search Test Cases page. The search is not case sensitive. Result includes just test cases from the actual Test Project. Step 2 − Write the searched string to an appropriate box. Leave the unused fields in the form as blank. Step 3 − Choose the required keyword or leave the value as 'Not applied'. It has the following list of supported fields to find the test case − Test case ID, Version, Title, Test Importance, Status, Summary, Pre-conditions, Steps, Expected Result, Created by, Edited by, Modified date from, Modification date to, Jolly or Keyword and Req. Doc ID. Step 4 − Click the 'Find' button. All fulfilling test cases are shown. You can modify test cases via 'Title' link. Keywords are used to categorize test cases. Keywords are ideal for filtering. It is not categorizing and placing the same test cases at one place; keywords help to bring test cases from different folders with the same scope together using the same keywords. For Example − Regression Test Cases, Smoke Test Cases, Solaris and Change Request, etc. To create keywords, you should have create keyword permission. Step 1 − Go to Test Project → Keyword Management from the dashboard as shown below. It opens the Keyword Management page along with the Create Keyword button. Step 2 − Click the Create Keyword button as shown below. It opens the Create Keyword page. Step 3 − Enter the Keyword and Description. Step 4 − Click the Save button a shown below. List of saved keywords gets displayed at Keyword Management page. Following are the steps to assign keywords − Step 1 − Go to Test Project → Keyword Management from the dashboard as shown below. It opens the Keyword Management page along with the Assign to Test Cases button. Step 2 − Click the Assign to Test Cases button as shown below. Step 3 − Select a Test Suite or Test Case on the tree view on the left. The topmost box that shows up on the right hand side will allow you to assign the available keywords to every single test case. Step 4 − After selection, click the Save button as shown in the following screenshot. Finally, you will get a successful message that the item is updated. You can generate the Test Specification as a document. Step 1 − To generate a Test Specification, go to Test Specification → Test Specification from the dashboard. It opens the Test Specification page. Step 2 − Select the folder to generate a test specification document, either the root project folder or the suite folder on the left side. Step 3 − Click the Settings icon known as Action present on the right side panel as shown below. It opens the Test Suite Operations page. You can see two options − Test Spec document (HTML) on the new window and another option Download Test spec document (Pseudo word) as shown below. After clicking the option, you will get the Test specification details as follows. Requirements are high-level descriptions about particular system services, constraints, or a detailed specification generated during the requirements gathering process. TestLink supports Requirement Specification where you can create a Requirement and take various actions such as Edit, Delete, or Freeze the version, etc. To create a requirement, you should have the Create Requirement permission. Following are the steps to create a requirement − Step 1 − Go to Requirement Specification → Requirement Specification from the dashboard as shown below. Step 2 − On the left side, Search the folder structure where you want to add a requirement. Step 3 − Click the Create button present on the right side panel as shown below. It opens the create requirement page where you can specify the Document ID, Title, Scope and the type of requirement. Step 4 − Click the Save button to add the requirement in the list as shown below. It adds the parent folder as Requirement Specification. Step 5 − Click the parent folder and then click the Settings icon known as Actions displayed on the right side panel as shown in the following screenshot. It shows Requirement Operations page. Step 6 − Click the Create button as displayed in the following screenshot. It displays the Create Requirement form. Step 7 − Enter the following fields before clicking the Save button. Document ID − Unique ID to identify. Document ID − Unique ID to identify. Title − A unique title and must be within 100 characters. Title − A unique title and must be within 100 characters. Scope − It is text into HTML format. Scope − It is text into HTML format. Status − It can have value as Valid, Draft, Review, Rework, Finish, implemented, Not testable and Obsolete. Status − It can have value as Valid, Draft, Review, Rework, Finish, implemented, Not testable and Obsolete. Type − It could have a value as Informational, Feature, Use Case, User Interface, Non-Functional, Constraint or System Function. Type − It could have a value as Informational, Feature, Use Case, User Interface, Non-Functional, Constraint or System Function. Number of test cases needed − An estimated test case needs to cover the requirement. Number of test cases needed − An estimated test case needs to cover the requirement. After clicking Save, the requirement gets added and is displayed with additional fields. Step 8 − Add Coverage by clicking the + icon. Step 9 − Add the relation of the current requirement with any existing requirement as parent, child, related to, blocks or depends on. In addition, you can attach a file as well for more details about requirement as shown in the following screenshot. Requirement Overview is one of the useful features of TestLink. You can see all the listed requirements at one place along with all the available versions in case there is more than one. Go to Requirement Specification → Requirement Overview from the dashboard as shown below. It displays the Requirement Overview page with the list of requirements. This Overview shows all the requirements (last or all versions) and all the related attributes. In addition, all the defined custom fields for requirements is displayed in a separate column. The show all versions will be displayed if you check the checkbox at top “Show all versions of each requirement”. Coverage − A value of e.g. "20% (4/20)" means that 20 Test Cases have to be created for this Requirement to test it completely. 4 of those have already been created and linked to this Requirement, which makes the coverage of 20 percent. Following screenshot displays the Requirement Overview page. By clicking the pencil icon, you can edit the requirement details as shown in the above screenshot. It opens a new window along with the requirement detail in edit mode. TestLink supports the feature to assign Test Case for execution to different users. Assigning test cases affects both the execution and reports. On the execution page, you can sort the executable Test Cases to view whom they are assigned to. In the reports section, you can see the remaining test cases grouped by the tester’s name. If there are no test cases assigned to a tester, it defaults to none. A Tester can also see the metrics of his/her own executed tests. Following are the steps to assign a test case − Step 1 − Go to Test Plan contents → Assign test cases execution from the dashboard as shown below. Step 2 − On the left side of the screen, search the test suite and click it. It displays the details and test cases present on the right side. Step 3 − Select the test case to be assigned. Verify if any existing user is present. The ‘Assigned To’ field displays the user name if it is assigned. Step 4 − Go to Assign text box and start typing the name of the user. It will display the list of matched users, from which you can select the user name. Step 5 − Click the Save button present at the top of the screen. After assigning the test case, the user name appears in the Assigned to section along with a red symbol. Step 6 − If the assigned user needs to be removed, simply click the red symbol , it will remove the assigned user. Bulk user assignment is almost similar to a normal assignment. The only difference being multiple users can be assigned at a time to a single as well as multiple test cases. Following are the steps for bulk user assignment − Step 1 − Go to Test Plan contents → Assign test cases execution from the dashboard as shown in the following screenshot. Step 2 − On the left side search the test suite and click it. It displays the details and test cases present on the right side panel. Step 3 − Select the multiple test cases to be assigned to multiple users. Verify if any existing user is present. The ‘Assigned To’ field displays the user name if it is assigned. Step 4 − Go to Bulk User Assignment test box at the top. Start typing the name of the user. It will display the list of matched users from where the user name can be selected. Add multiple users in the text box. Step 5 − Click the Do button present on the right side of the text box. It displays the users name in the Assign To field of each selected test cases. Step 6 − Click the Save button to assign the test cases to these users. After assigning the test case, the user name appears in the Assigned to section along with a red symbol. Step 7 − If the assigned user needs to be removed , simply click the red symbol, it will remove the assigned user. For bulk user removal, first select the test cases from which the assigned users need to be removed. Click “Do bulk user remove” button present on the top of the screen. It removes the assigned user of that test case. Platform means a place or configuration of system where a test case has to be executed. A platform can be different web browsers such as Chrome, Safari, IE, Mozilla, etc. or different operating systems, hardware devices or configurations. The chosen platforms should be associated with Test Plan where test cases are executed. A test project might need several platforms to test before releasing a product. Test cases must be connected with Platforms as well as Test Plans too. To use the Platform feature, it should be created first under Platform Management. You should have Platform Management right to create a platform. Following are the steps to create a platform. Step 1 − Go to Test Project → Platform Management from the dashboard as shown below. It displays the Platform Management page. Step 2 − Click the Create Platform button as shown below. It opens the Create platform form. Step 3 − Enter the Platform Name and Description. Step 4 − Click the Save button. After clicking Save, the platform gets listed in the Platform Management. Step 1 − Navigate to Test Project → Platform Management. It displays a list of all available platforms along with the delete symbol in red as X. Step 2 − Click the Delete symbol as shown below. A delete confirmation pop-up displays. Step 3 − Click the Yes button. The page gets refreshed and the platform is delisted from the page. Milestones are associated with the project and is one of the best ways to track the progress and timeline. It is similar to the small targets in a project. A milestone can be an important target such as a planned public software release, an internal test version, a new beta release for an important customer, etc. Once stakeholders add milestones to TestLink, the users can assign test runs to specific milestones. It helps to track the milestone’s progress separately. Especially, if multiple milestones are in progress in parallel or if the users have many test runs active at the same time. Following are the steps to add a milestone. Step 1 − Go to Test Plan → Milestone Overview from the dashboard as shown below. It opens the Milestone page along with the Create button. Step 2 − Click the Create button as shown below. It opens the Create Milestone forms. Step 3 − Enter the Name, Target Date and Start Date. There are sub-milestones as Complete test with high priority, Complete test with medium priority and Complete test with low priority. Step 4 − After entering the percentage, click the Save button. You can see the status and progress of the milestone as shown in the following screenshot. Step 1 − Navigate to Test Plan → Milestone Overview. It displays a list of all available milestones along with the delete symbol in red as X. Step 2 − Click the Delete symbol as shown below. A delete confirmation pop-up is displayed. Step 3 − Click the Yes button as shown below. The page gets refreshed and the Milestone is delisted from the page. Before starting the actual execution, setup of the execution suite is the required step to track the progress and the status of execution. This stage is called as test execution setup. Before execution, make sure the following documents are ready − Test specification is written and mentioned in the project. Test Plan is created and reviewed. Test cases are created and mapped into the test plan for coverage. At least one build is created for the project. You should have proper permission for execution and to work in this test plan. Following are the steps to set the navigation and settings for executing test cases. Step 1 − Go to Test Execution → Execute Tests from the dashboard as shown below. It opens Execute Test page where Settings and Filters are present on the left panel. Along with these two, there is a tree menu as well. Step 2 − Select Test Plan and build at the setting section. Step 3 − In the filter section, you can narrow down the tree structure present below the filter. Following screenshots displays Navigation & Settings in execute tests page − You should specify one of the active Builds to add test case execution results. If you do not specify, the latest build is set by default. Build label specifies the exact package of application under test for tracking purposes. Each Test Case may be run one or more times per Build. However, it's recommended that only one test cycle should be executed against a Build. Builds can be created by Test Leader using the Create New Build page. The tree menu in the navigation pane below the Filter section displays the filtered list of Test Cases in the Test Plan. By selecting the test case, it allows to open an appropriate Test Case for test execution on the right panel. Test Suites in the tree menu display Test Plan details and build details as shown in the following screenshot. Test execution is the process of executing the code and comparing the expected and actual results. By default, a test case remains in No Run status. Once a status is assigned to a test case, it cannot revert to the no Run status. A test case can be assigned a result as Passed, Failed or Blocked. TestLink supports to assign a result to individual test steps as well. You can assign Passed, Failed or Blocked status at each individual step of a test case. Passed − When a test case or step matches the expected result, it is marked as Passed. Passed − When a test case or step matches the expected result, it is marked as Passed. Failed − When a test case or step deviates from the expected result, it is marked as Failed. Failed − When a test case or step deviates from the expected result, it is marked as Failed. Blocked − When a test case or step cannot be executed due to an outstanding issue, it is marked as Blocked. Blocked − When a test case or step cannot be executed due to an outstanding issue, it is marked as Blocked. Once a test case or test step is executed, the result should be assigned to those. Following steps should be performed while insering a test result − Step 1 − Go to Test Execution → Execution Tests or Test Cases Assigned to Me as shown below. Step 2 − Select the test case from the left panel. It displays all the details and steps of the test cases. Step 3 − In the test step, there are Execution Notes and Result column. After execution, you can enter comments as Execution Notes. Step 4 − Select Results as Passed, Failed or Blocked. You can also attach an image or screenshot file as an artefact in support of result selection. Step 5 − In the Notes/Description section present below, enter overall comment for the test case execution. Step 6 − On the right side of Notes/Description, Execution duration (min) is present. Enter the number of minutes spent while executing this test case. Step 7 − Below the Execution Duration text box, three icons are present to select the overall result status for the test case. Icons are Passed, Failed and Blocked from left to right. After selection, the overall result gets updated with all execution iterations. Step 8 − Click the Print icon to view detailed execution result. The symbol is present in Run Mode column at the extreme right as shown below. It opens a new window with details of execution and comment step-wise as shown below. You can delete the execution result by clicking the delete red symbol as X, present in Run Mode column. It opens a confirmation pop-up to delete. Click the OK button. Reports and Metrics group the results of execution at one place that helps to track the progress of the project. To access the Report and Metrics section, select Test Execution → Test Reports and Metrics from the dashboard as shown below. The left pane is used to navigate to each report and operate controls of reports behavior and display. The button “Print” initializes the printing of the right pane (no navigation will be printed). You can print as HTML or Pseudo MS Word. You can also email the report in HTML format. The right pane displays a summary of each report. These metrics display the current status of a Test Plan by the following criteria - test suite, owner, milestone, priority and keyword. In addition to this, it also displays the basic metrics for all enabled builds. The current status is determined by the recent Build where Test Cases are executed. For instance, if a Test Case is executed in multiple builds, only the latest result is counted. Last Test Result is a concept used in many reports, and is determined as follows − The order of Builds is created into a Test Plan. For example, if a test fails in Build 1, and is marked as pass in Build 2, the latest result will pass. The order of Builds is created into a Test Plan. For example, if a test fails in Build 1, and is marked as pass in Build 2, the latest result will pass. If a Test Case is executed multiple times on the same Build, the most recent execution will be considered. For example, if Build 3 is released and marked as “pass” at 1PM and marked as “fail” at 5PM – will be considered as fail. If a Test Case is executed multiple times on the same Build, the most recent execution will be considered. For example, if Build 3 is released and marked as “pass” at 1PM and marked as “fail” at 5PM – will be considered as fail. Test Cases listed as “No Run” in a Build is not considered. For example, if a test case is marked as “pass” in Build 1 and don't execute in Build 2, the last result will be considered as “pass”. Test Cases listed as “No Run” in a Build is not considered. For example, if a test case is marked as “pass” in Build 1 and don't execute in Build 2, the last result will be considered as “pass”. When you click General Test Plan Metrics on the left side of the screen, it displays all the results as shown below. Results by Top Level Test Suites − It lists the results of each top level suite. It displays the number of test cases with status as Passed, Failed, Blocked, Not run, and Completed (%). Results for top level suites include all children suites. Results by Build − It lists the execution results for every Build. For each Build, it displays the total Test Cases, total pass, % passed, total failed, % failed, blocked, % blocked, not run, and % not run. If a Test Case has been executed twice on the same Build, the most recent execution will be taken into account. Results by Keyword − It lists all the keywords assigned to cases in the current Test Plan, and the results associated with them. For each keyword, it displays the total Test Cases, total pass, % passed, total failed, % failed, blocked, % blocked, not run and % not run. In the Reports module, you can create, view, and export reports supported by TestLink. TestLink supports a wide range of reports at all phases of STLC to better track the progress such as test execution, requirements coverage, and test case creation details. These reports fetch the most important information to prepare any of the metrics. When you navigate to Test Reports and Metrics from the dashboard, it displays the list of available reports for different activities on the left panel. On the right panel, it displays the details of the selected report as shown below. This report displays all of the currently blocked, failed, passed or not run Test Cases. It shows the last test case execution result for each build. In addition, the last column shows the last test case execution result for the last created build. “Last Test Result” logic (which is described above under General Test Plan Metrics) is used to determine if a Test Case should be considered blocked, failed, passed or no run. Blocked and failed Test Case reports will display the associated bugs if the user is an associate of integrated bug tracking system with TestLink. To access the Test Result Matrix, click the Test Result Matrix on the left pane. it displays the report on the right side as shown in the following screenshot. This report is available in Test Report and Metrics, if the requirements are linked with test cases of the current Test Project. The Report is generated against one Requirement Specification document selected from Build and Status dropdown. There are two sections − metrics and results overview. Following metrics are available − Total number of requirements Requirements within TestLink Requirements covered by Test Cases Requirements not covered by Test Cases Requirements not covered or not tested Requirements not tested Requirements are divided into four sections. Each requirement is listed together with all related Test Cases (colored according to Test Case result) − Passed Requirements Failed Requirements Blocked Requirements Not-executed Requirements Following screenshot displays Requirement Report − This report requires graphic library installed on the web server. “Last Test Result” logic is used for all four charts. To access the Charts, click the Charts on the left pane as shown below. Report contains the following charts − Pie chart of overall passed / failed / blocked / and not run Test Cases as shown above. Bar chart of Results by Keyword as shown below. Bar chart of Results by Top Level Suite as shown below. The bars in the bar charts are colored such that the user can identify the approximate number of passed, failed, blocked, and not run cases. Print Add Notes Bookmark this page
[ { "code": null, "e": 2640, "s": 2318, "text": "TestLink is a test management tool used for project management, bug tracking and test management. It follows a centralized test management concept that helps to communicate easily for rapid development of tasks across QA teams and other stakeholders. It keeps the requirement specification and test specification in sync." }, { "code": null, "e": 2728, "s": 2640, "text": "Following salient features of TestLink need to be noted to understand the topic better." }, { "code": null, "e": 2823, "s": 2728, "text": "TestLink is open source test management tool. There is no license is required to use TestLink." }, { "code": null, "e": 2918, "s": 2823, "text": "TestLink is open source test management tool. There is no license is required to use TestLink." }, { "code": null, "e": 2962, "s": 2918, "text": "It is developed and maintained by Teamtest." }, { "code": null, "e": 3006, "s": 2962, "text": "It is developed and maintained by Teamtest." }, { "code": null, "e": 3057, "s": 3006, "text": "It is licensed under GPL – General Public License." }, { "code": null, "e": 3108, "s": 3057, "text": "It is licensed under GPL – General Public License." }, { "code": null, "e": 3214, "s": 3108, "text": "It supports different Windows OS such as Windows XP, Vista, 7, etc. along with other cloud-based support." }, { "code": null, "e": 3320, "s": 3214, "text": "It supports different Windows OS such as Windows XP, Vista, 7, etc. along with other cloud-based support." }, { "code": null, "e": 3373, "s": 3320, "text": "It provides free access to tools for multiple users." }, { "code": null, "e": 3426, "s": 3373, "text": "It provides free access to tools for multiple users." }, { "code": null, "e": 3513, "s": 3426, "text": "It can be integrated with many other tools – JIRA, Bugzilla, FogBugz, VersionOne, etc." }, { "code": null, "e": 3600, "s": 3513, "text": "It can be integrated with many other tools – JIRA, Bugzilla, FogBugz, VersionOne, etc." }, { "code": null, "e": 3658, "s": 3600, "text": "Following points describe the various usages of TestLink." }, { "code": null, "e": 3747, "s": 3658, "text": "Useful in tracking all QA activities from the first phase of software testing lifecycle." }, { "code": null, "e": 3836, "s": 3747, "text": "Useful in tracking all QA activities from the first phase of software testing lifecycle." }, { "code": null, "e": 3925, "s": 3836, "text": "Useful in Project Management, Task Tracking, Requirement Management and Test Management." }, { "code": null, "e": 4014, "s": 3925, "text": "Useful in Project Management, Task Tracking, Requirement Management and Test Management." }, { "code": null, "e": 4067, "s": 4014, "text": "Supports all macro level activities performed by QA." }, { "code": null, "e": 4120, "s": 4067, "text": "Supports all macro level activities performed by QA." }, { "code": null, "e": 4202, "s": 4120, "text": "Useful in performing QA tasks such as writing test cases, execution reports, etc." }, { "code": null, "e": 4284, "s": 4202, "text": "Useful in performing QA tasks such as writing test cases, execution reports, etc." }, { "code": null, "e": 4342, "s": 4284, "text": "Supports both manual as well as automated test execution." }, { "code": null, "e": 4400, "s": 4342, "text": "Supports both manual as well as automated test execution." }, { "code": null, "e": 4472, "s": 4400, "text": "Following table lists some of the important specifications of TestLink." }, { "code": null, "e": 4494, "s": 4472, "text": "Application Copyright" }, { "code": null, "e": 4565, "s": 4494, "text": "It is developed and maintained by Teamtest. It is an open source tool." }, { "code": null, "e": 4576, "s": 4565, "text": "Tool Scope" }, { "code": null, "e": 4660, "s": 4576, "text": "It can be used as a Test Automation framework. It is utilized as a Testing Utility." }, { "code": null, "e": 4676, "s": 4660, "text": "Testing Methods" }, { "code": null, "e": 4690, "s": 4676, "text": "Agile Testing" }, { "code": null, "e": 4708, "s": 4690, "text": "Black box testing" }, { "code": null, "e": 4728, "s": 4708, "text": "Exploratory Testing" }, { "code": null, "e": 4754, "s": 4728, "text": "Functional/Manual Testing" }, { "code": null, "e": 4774, "s": 4754, "text": "Traditional Testing" }, { "code": null, "e": 4790, "s": 4774, "text": "Tool Objectives" }, { "code": null, "e": 4806, "s": 4790, "text": "Desktop Testing" }, { "code": null, "e": 4818, "s": 4806, "text": "Web Testing" }, { "code": null, "e": 4838, "s": 4818, "text": "Management Features" }, { "code": null, "e": 4861, "s": 4838, "text": "Requirement Management" }, { "code": null, "e": 4877, "s": 4861, "text": "Test Management" }, { "code": null, "e": 4884, "s": 4877, "text": "Report" }, { "code": null, "e": 4906, "s": 4884, "text": "Software Requirements" }, { "code": null, "e": 4922, "s": 4906, "text": "Apache: 2.2.2.1" }, { "code": null, "e": 4937, "s": 4922, "text": "MySQL : 5.5.16" }, { "code": null, "e": 4948, "s": 4937, "text": "PHP: 5.3.8" }, { "code": null, "e": 4966, "s": 4948, "text": "PhpMyAdmin: 3.4.5" }, { "code": null, "e": 4995, "s": 4966, "text": "Filezilla FTP Server: 0.9.39" }, { "code": null, "e": 5010, "s": 4995, "text": "Tomcat: 7.0.21" }, { "code": null, "e": 5025, "s": 5010, "text": "Error Handling" }, { "code": null, "e": 5045, "s": 5025, "text": "Capture screenshots" }, { "code": null, "e": 5070, "s": 5045, "text": "User Interface Available" }, { "code": null, "e": 5078, "s": 5070, "text": "COM API" }, { "code": null, "e": 5088, "s": 5078, "text": "Direct UI" }, { "code": null, "e": 5102, "s": 5088, "text": "GUI usability" }, { "code": null, "e": 5199, "s": 5102, "text": "TestLink has a wide range of features to attract QAs and other stakeholders for test management." }, { "code": null, "e": 5252, "s": 5199, "text": "Following table lists the core features of TestLink." }, { "code": null, "e": 5269, "s": 5252, "text": "Testing Supports" }, { "code": null, "e": 5322, "s": 5269, "text": "TestLink supports the following test methodologies −" }, { "code": null, "e": 5336, "s": 5322, "text": "Agile testing" }, { "code": null, "e": 5354, "s": 5336, "text": "Black box testing" }, { "code": null, "e": 5374, "s": 5354, "text": "Exploratory testing" }, { "code": null, "e": 5415, "s": 5374, "text": "Functional/Manual and Automation testing" }, { "code": null, "e": 5435, "s": 5415, "text": "Traditional testing" }, { "code": null, "e": 5457, "s": 5435, "text": "Centralize & organize" }, { "code": null, "e": 5560, "s": 5457, "text": "TestLink tool creates, centralizes, organizes and manages test cases very effectively and efficiently." }, { "code": null, "e": 5663, "s": 5560, "text": "TestLink tool creates, centralizes, organizes and manages test cases very effectively and efficiently." }, { "code": null, "e": 5728, "s": 5663, "text": "Easily import test cases from CSV/XML and other management tool." }, { "code": null, "e": 5793, "s": 5728, "text": "Easily import test cases from CSV/XML and other management tool." }, { "code": null, "e": 5864, "s": 5793, "text": "It can create multiple versions of test cases for comparison and uses." }, { "code": null, "e": 5935, "s": 5864, "text": "It can create multiple versions of test cases for comparison and uses." }, { "code": null, "e": 6018, "s": 5935, "text": "It can share test case repository across different projects, releases and sprints." }, { "code": null, "e": 6101, "s": 6018, "text": "It can share test case repository across different projects, releases and sprints." }, { "code": null, "e": 6126, "s": 6101, "text": "Manage & Track Execution" }, { "code": null, "e": 6232, "s": 6126, "text": "It supports run and re-run of test execution suites. It kicks off automation suite as well using XML-RPC." }, { "code": null, "e": 6338, "s": 6232, "text": "It supports run and re-run of test execution suites. It kicks off automation suite as well using XML-RPC." }, { "code": null, "e": 6413, "s": 6338, "text": "It captures step-by-step test execution history with detailed explanation." }, { "code": null, "e": 6488, "s": 6413, "text": "It captures step-by-step test execution history with detailed explanation." }, { "code": null, "e": 6548, "s": 6488, "text": "It supports test run specific configuration and parameters." }, { "code": null, "e": 6608, "s": 6548, "text": "It supports test run specific configuration and parameters." }, { "code": null, "e": 6621, "s": 6608, "text": "Notification" }, { "code": null, "e": 6671, "s": 6621, "text": "Email can be sent for a particular task to users." }, { "code": null, "e": 6721, "s": 6671, "text": "Email can be sent for a particular task to users." }, { "code": null, "e": 6806, "s": 6721, "text": "Use @mention to get the attention of a specific team member at Comments/Description." }, { "code": null, "e": 6891, "s": 6806, "text": "Use @mention to get the attention of a specific team member at Comments/Description." }, { "code": null, "e": 6904, "s": 6891, "text": "Power Search" }, { "code": null, "e": 6975, "s": 6904, "text": "TestLink supports powerful search functionality with Hotkeys features." }, { "code": null, "e": 7046, "s": 6975, "text": "TestLink supports powerful search functionality with Hotkeys features." }, { "code": null, "e": 7082, "s": 7046, "text": "TestLink supports free text search." }, { "code": null, "e": 7118, "s": 7082, "text": "TestLink supports free text search." }, { "code": null, "e": 7151, "s": 7118, "text": "TestLink supports syntax search." }, { "code": null, "e": 7184, "s": 7151, "text": "TestLink supports syntax search." }, { "code": null, "e": 7192, "s": 7184, "text": "Reports" }, { "code": null, "e": 7228, "s": 7192, "text": "TestLink supports multiple reports." }, { "code": null, "e": 7264, "s": 7228, "text": "TestLink supports multiple reports." }, { "code": null, "e": 7314, "s": 7264, "text": "It supports test case and test execution reports." }, { "code": null, "e": 7364, "s": 7314, "text": "It supports test case and test execution reports." }, { "code": null, "e": 7402, "s": 7364, "text": "Requirement and traceability reports." }, { "code": null, "e": 7440, "s": 7402, "text": "Requirement and traceability reports." }, { "code": null, "e": 7456, "s": 7440, "text": "Defect reports." }, { "code": null, "e": 7472, "s": 7456, "text": "Defect reports." }, { "code": null, "e": 7514, "s": 7472, "text": "It supports cross-project report as well." }, { "code": null, "e": 7556, "s": 7514, "text": "It supports cross-project report as well." }, { "code": null, "e": 7579, "s": 7556, "text": "Scale with Team Growth" }, { "code": null, "e": 7673, "s": 7579, "text": "TestLink supports any business team and any project, irrespective of the size and complexity." }, { "code": null, "e": 7685, "s": 7673, "text": "Integration" }, { "code": null, "e": 7775, "s": 7685, "text": "TestLink supports numerous add-ins to connect with different softwares to make work easy." }, { "code": null, "e": 7865, "s": 7775, "text": "TestLink supports numerous add-ins to connect with different softwares to make work easy." }, { "code": null, "e": 7959, "s": 7865, "text": "Wide range of add-ins make it universal across the globe – JIRA, Mantis, Bugzilla, Trac, etc." }, { "code": null, "e": 8053, "s": 7959, "text": "Wide range of add-ins make it universal across the globe – JIRA, Mantis, Bugzilla, Trac, etc." }, { "code": null, "e": 8104, "s": 8053, "text": "It also supports Rally and VersionOne integration." }, { "code": null, "e": 8155, "s": 8104, "text": "It also supports Rally and VersionOne integration." }, { "code": null, "e": 8171, "s": 8155, "text": "Common Features" }, { "code": null, "e": 8208, "s": 8171, "text": "It supports Drag and Drop interface." }, { "code": null, "e": 8245, "s": 8208, "text": "It supports Drag and Drop interface." }, { "code": null, "e": 8277, "s": 8245, "text": "It supports Test Grid Analysis." }, { "code": null, "e": 8309, "s": 8277, "text": "It supports Test Grid Analysis." }, { "code": null, "e": 8418, "s": 8309, "text": "It can clone the entire test case repository along the project setting, such as email notification and more." }, { "code": null, "e": 8527, "s": 8418, "text": "It can clone the entire test case repository along the project setting, such as email notification and more." }, { "code": null, "e": 8541, "s": 8527, "text": "Customization" }, { "code": null, "e": 8597, "s": 8541, "text": "It supports customization of UI using Smarty templates." }, { "code": null, "e": 8653, "s": 8597, "text": "It supports customization of UI using Smarty templates." }, { "code": null, "e": 8706, "s": 8653, "text": "It supports to create and assign the user’s keyword." }, { "code": null, "e": 8759, "s": 8706, "text": "It supports to create and assign the user’s keyword." }, { "code": null, "e": 8840, "s": 8759, "text": "Following are some points to note before we go for the installation of TestLink." }, { "code": null, "e": 8985, "s": 8840, "text": "TestLink is a web application; it provides a private website to an individual or a set of requested users belonging to the same company/project." }, { "code": null, "e": 9130, "s": 8985, "text": "TestLink is a web application; it provides a private website to an individual or a set of requested users belonging to the same company/project." }, { "code": null, "e": 9170, "s": 9130, "text": "TestLink can be run at the server side." }, { "code": null, "e": 9210, "s": 9170, "text": "TestLink can be run at the server side." }, { "code": null, "e": 9332, "s": 9210, "text": "TestLink is a PHP based application and supports all OS platforms such as Windows, Linux of different versions, MAC, etc." }, { "code": null, "e": 9454, "s": 9332, "text": "TestLink is a PHP based application and supports all OS platforms such as Windows, Linux of different versions, MAC, etc." }, { "code": null, "e": 9533, "s": 9454, "text": "TestLink supports all famous browsers such as Chrome, IE, Mozilla, and Safari." }, { "code": null, "e": 9612, "s": 9533, "text": "TestLink supports all famous browsers such as Chrome, IE, Mozilla, and Safari." }, { "code": null, "e": 9838, "s": 9612, "text": "Since TestLink is a web-application it follows the concept of client/server. It means that TestLink can be installed centrally on a server and users can interact with it through web browsers using a website from any computer." }, { "code": null, "e": 10024, "s": 9838, "text": "Web Server − TestLink supports Apache 2.2.2.1. However, it can work with any latest web server software. TestLink only uses .php file. Configure the web server with .php extension only." }, { "code": null, "e": 10210, "s": 10024, "text": "Web Server − TestLink supports Apache 2.2.2.1. However, it can work with any latest web server software. TestLink only uses .php file. Configure the web server with .php extension only." }, { "code": null, "e": 10359, "s": 10210, "text": "PHP − The web server should support PHP. It can be installed as CGI or any other integration technology. It is recommended to use 5.3.8 PHP version." }, { "code": null, "e": 10508, "s": 10359, "text": "PHP − The web server should support PHP. It can be installed as CGI or any other integration technology. It is recommended to use 5.3.8 PHP version." }, { "code": null, "e": 10639, "s": 10508, "text": "Mandatory PHP Extensions − Extensions for RDBMS are mysqli, pgsql, oci8, sqlsrv.\nMbstring is required for Unicode – UTF-8 support." }, { "code": null, "e": 10770, "s": 10639, "text": "Mandatory PHP Extensions − Extensions for RDBMS are mysqli, pgsql, oci8, sqlsrv.\nMbstring is required for Unicode – UTF-8 support." }, { "code": null, "e": 10811, "s": 10770, "text": "Optional Extensions − Curl, GD, Fileinfo" }, { "code": null, "e": 10852, "s": 10811, "text": "Optional Extensions − Curl, GD, Fileinfo" }, { "code": null, "e": 10940, "s": 10852, "text": "Database − TestLink requires database to store its data. MySQL (5.5.16) is recommended." }, { "code": null, "e": 11028, "s": 10940, "text": "Database − TestLink requires database to store its data. MySQL (5.5.16) is recommended." }, { "code": null, "e": 11121, "s": 11028, "text": "FileZilla FTP Server − FileZilla FTP Server 0.9.39 is required to install XAMPP as optional." }, { "code": null, "e": 11214, "s": 11121, "text": "FileZilla FTP Server − FileZilla FTP Server 0.9.39 is required to install XAMPP as optional." }, { "code": null, "e": 11327, "s": 11214, "text": "You can install all the requirements separately either manually or through an automatic process to use TestLink." }, { "code": null, "e": 11499, "s": 11327, "text": "If the user has required knowledge about the installation process, the user can install all the discussed requirements one-by-one separately before proceeding to TestLink." }, { "code": null, "e": 11691, "s": 11499, "text": "Alternatively, there are many all-in-one packages available and can automatically install in the system by exe file. Here, we will take the help of XAMPP to install the pre-requisites easily." }, { "code": null, "e": 11813, "s": 11691, "text": "Step 1 − Go to https://www.apachefriends.org/index.html and click XAMPP for Windows as shown in the following screenshot." }, { "code": null, "e": 11920, "s": 11813, "text": "Step 2 − A pop-up will be displayed to save the file. Click Save File. It will start to download the file." }, { "code": null, "e": 12095, "s": 11920, "text": "Step 3 − Run the .exe file to run the installation wizard. After clicking the .exe file, the XAMPP Setup wizard is displayed as shown in the following screenshot. Click Next." }, { "code": null, "e": 12257, "s": 12095, "text": "Step 4 − Next, the wizard displays all the component files (shown in the following screenshot) that will be installed. Click Next after selecting the components." }, { "code": null, "e": 12334, "s": 12257, "text": "Step 5 − Provide a folder name where XAMPP will be installed and click Next." }, { "code": null, "e": 12419, "s": 12334, "text": "Step 6 − Ready to Install wizard is displayed. Click Next to start the installation." }, { "code": null, "e": 12619, "s": 12419, "text": "Step 7 − After successful installation, it will prompt to start the control panel. Select the checkbox and click Finish. It will open the XAMPP control panel as displayed in the following screenshot." }, { "code": null, "e": 12728, "s": 12619, "text": "Step 8 − Click the Start button for Apache and MySQL required for TestLink as shown in the above screenshot." }, { "code": null, "e": 12908, "s": 12728, "text": "Step 9 − To verify whether all the pre-requisites such as Apache, PHP and MySQL is installed properly, navigate to any of the browser and type http://localhost. Then, press Enter." }, { "code": null, "e": 13016, "s": 12908, "text": "Step 10 − It will display the dashboard of XAMPP. Click phpAdmin at the right top corner of the screenshot." }, { "code": null, "e": 13157, "s": 13016, "text": "It will display General Settings, Application Settings, Details of Database, Web Server and phpMyAdmin as shown in the following screenshot." }, { "code": null, "e": 13299, "s": 13157, "text": "If the installation is not proper, this page won’t display. Till this point, all the pre-requisites are successfully installed in the system." }, { "code": null, "e": 13370, "s": 13299, "text": "After successful installation of XAMPP, we need to work with TestLink." }, { "code": null, "e": 13448, "s": 13370, "text": "Step 1 − Go to https://sourceforge.net/projects/testlink/ and click Download." }, { "code": null, "e": 13532, "s": 13448, "text": "Step 2 − Now unzip the downloaded .tar file and rename the folder name as TestLink." }, { "code": null, "e": 13682, "s": 13532, "text": "Step 3 − Go to XAMPP folder where it is installed and navigate to htdocs folder. Place the TestLink folder here as shown in the following screenshot." }, { "code": null, "e": 13811, "s": 13682, "text": "Step 4 − Go to TestLink package and open “config.inc.php” file, update path “$tlCfg→log_path” and “$g_repositoryPath” as below −" }, { "code": null, "e": 13863, "s": 13811, "text": "$tlCfg→log_path = ‘D:/xampp/htdocs/testlink/logs/’;" }, { "code": null, "e": 13924, "s": 13863, "text": "$g_repositoryPath = ‘D:/xampp/htdocs/testlink/upload area/’;" }, { "code": null, "e": 14077, "s": 13924, "text": "Step 5 − Now open a browser and type http://localhost/Testlink in the navigation bar and press Enter. It will display the installation page of TestLink." }, { "code": null, "e": 14110, "s": 14077, "text": "Step 6 − Click New Installation." }, { "code": null, "e": 14194, "s": 14110, "text": "Step 7 − Check the checkbox for Terms and Conditions and click the Continue button." }, { "code": null, "e": 14356, "s": 14194, "text": "The system will check the pre-requisites to ensure everything is fine. A Continue button will appear at the bottom, otherwise an error message will be displayed." }, { "code": null, "e": 14418, "s": 14356, "text": "Step 8 − Click Continue as shown in the following screenshot." }, { "code": null, "e": 14583, "s": 14418, "text": "Step 9 − In the next step, Database Admin and Admin password is required to define MySQL access. TestLink admin username/password can be anything given by the user." }, { "code": null, "e": 14665, "s": 14583, "text": "Database login/password: root/<empty> (Default login/password of MYSQL for xampp)" }, { "code": null, "e": 14798, "s": 14665, "text": "Step 10 − Click “Process TestLink Setup” button. You should see the TestLink “Installation was successful!” message being displayed." }, { "code": null, "e": 14856, "s": 14798, "text": "Step 11 − Now again navigate to http://localhost/testlink" }, { "code": null, "e": 14922, "s": 14856, "text": "You will see the login page as shown in the following screenshot." }, { "code": null, "e": 15064, "s": 14922, "text": "To login into TestLink, go to your sample website, http://localhost/testlink. It will open a login page as shown in the following screenshot." }, { "code": null, "e": 15149, "s": 15064, "text": "Step 1 − Enter admin as both username and Password. Admin is the default credential." }, { "code": null, "e": 15183, "s": 15149, "text": "Step 2 − Click the Log in button." }, { "code": null, "e": 15257, "s": 15183, "text": "Following screenshot shows how to login into TestLink using credentials −" }, { "code": null, "e": 15378, "s": 15257, "text": "Due to unsuccessful login, an error page is displayed. Error may occur due to wrong combination of email id or password." }, { "code": null, "e": 15478, "s": 15378, "text": "Following screenshot shows the error message, the user receives if the credentials are not correct." }, { "code": null, "e": 15547, "s": 15478, "text": "If you forgot the password, to recover it, following are the steps −" }, { "code": null, "e": 15613, "s": 15547, "text": "Step 1 − Click the “Lost Password?” link below the Log in button." }, { "code": null, "e": 15644, "s": 15613, "text": "Step 2 − Enter the Login Name." }, { "code": null, "e": 15665, "s": 15644, "text": "Step 3 − Click Send." }, { "code": null, "e": 15735, "s": 15665, "text": "Following screenshot shows how to recover the password if you forgot." }, { "code": null, "e": 15819, "s": 15735, "text": "You will get an email with the details of username or a link to reset the password." }, { "code": null, "e": 15968, "s": 15819, "text": "On successful login, the system dashboard will display if the account is associated with any project by admin or if you can create a sample project." }, { "code": null, "e": 16057, "s": 15968, "text": "Following screenshot displays the Create a Project page of TestLink on successful login." }, { "code": null, "e": 16276, "s": 16057, "text": "To add a project, you should have Admin role. Once you log in for the first time as an Admin, TestLink opens the Create a new project form. You cannot see any other page until the project is created or assigned to you." }, { "code": null, "e": 16342, "s": 16276, "text": "Following are the steps involved to add a project into TestLink −" }, { "code": null, "e": 16468, "s": 16342, "text": "Usually to create a project, an option is available at the Test Project Management menu as shown in the following screenshot." }, { "code": null, "e": 16534, "s": 16468, "text": "Step 1 − Enter the following details into Create a Project form −" }, { "code": null, "e": 16577, "s": 16534, "text": "Name − It should be a unique project name." }, { "code": null, "e": 16642, "s": 16577, "text": "Prefix − It is used for test case ID to identify the test cases." }, { "code": null, "e": 16691, "s": 16642, "text": "Project description − Details about the project." }, { "code": null, "e": 16863, "s": 16691, "text": "Enhanced features − You can check the checkboxes based on the requirement of the project. It allows to select which features you want such as Requirement, Automation, etc." }, { "code": null, "e": 16952, "s": 16863, "text": "Issue tracker − If any issue tracker is linked with TestLink, it will be displayed here." }, { "code": null, "e": 17044, "s": 16952, "text": "Step 2 − Select the Availability option and then click the Create button as shown in below." }, { "code": null, "e": 17207, "s": 17044, "text": "Clicking the Create button adds the project along with Delete and Active/Inactive switch for Requirement and Active features as shown in the following screenshot." }, { "code": null, "e": 17355, "s": 17207, "text": "Step 3 − You can view the project by selecting a project name from the “Test Project” dropdown at the top right corner of the screen as seen below." }, { "code": null, "e": 17564, "s": 17355, "text": "After logging into TestLink, Dashboard is the first page that is displayed as soon as you are assigned to a project. Dashboard is customized by Admin. Based on the roles, admin can set the access of TestLink." }, { "code": null, "e": 17639, "s": 17564, "text": "Following screenshot shows the overview of the Dashboard page of TestLink." }, { "code": null, "e": 17704, "s": 17639, "text": "Following are some points to note with regards to the dashboard." }, { "code": null, "e": 18005, "s": 17704, "text": "The tool bar icons present at the top left corner of TestLink page will be the same across all pages/screen of TestLink. My Settings, Project, Requirement Specification, Test Specification, User Management and Event as the main links. These links are used to navigate to the respective functionality." }, { "code": null, "e": 18306, "s": 18005, "text": "The tool bar icons present at the top left corner of TestLink page will be the same across all pages/screen of TestLink. My Settings, Project, Requirement Specification, Test Specification, User Management and Event as the main links. These links are used to navigate to the respective functionality." }, { "code": null, "e": 18414, "s": 18306, "text": "The navigation bar contains the links that provide a quick access to the most useful functions of TestLink." }, { "code": null, "e": 18522, "s": 18414, "text": "The navigation bar contains the links that provide a quick access to the most useful functions of TestLink." }, { "code": null, "e": 18739, "s": 18522, "text": "On the left side of the page - System, Test Project, Requirement Specification and Test Specification categories are present. These categories present different links for quick access to all the features of TestLink." }, { "code": null, "e": 18956, "s": 18739, "text": "On the left side of the page - System, Test Project, Requirement Specification and Test Specification categories are present. These categories present different links for quick access to all the features of TestLink." }, { "code": null, "e": 19054, "s": 18956, "text": "On the right side, Test Plan category has Test Plan Management link to add or manage a test plan." }, { "code": null, "e": 19152, "s": 19054, "text": "On the right side, Test Plan category has Test Plan Management link to add or manage a test plan." }, { "code": null, "e": 19283, "s": 19152, "text": "On the top left side of the screen, a Search functionality is available while on the right side, there is a Test Project dropdown." }, { "code": null, "e": 19414, "s": 19283, "text": "On the top left side of the screen, a Search functionality is available while on the right side, there is a Test Project dropdown." }, { "code": null, "e": 19564, "s": 19414, "text": "My Settings icon is present at the top left corner of the screen as the first icon. Following screenshot shows the My Settings icon encircled in red." }, { "code": null, "e": 19666, "s": 19564, "text": "Once you click the icon, it opens the settings page where various information is available to update." }, { "code": null, "e": 19765, "s": 19666, "text": "First, there is Personal Data where you can update your first name, last name, email id or Locale." }, { "code": null, "e": 19852, "s": 19765, "text": "Then, there is the Personal Password section, where you can change the login password." }, { "code": null, "e": 19934, "s": 19852, "text": "The third section shows API interface, where you can generate a personal API key." }, { "code": null, "e": 19987, "s": 19934, "text": "In the last section, you can view the login history." }, { "code": null, "e": 20233, "s": 19987, "text": "The logout icon is present at the top left side of the screen, beside the My Settings icon. After clicking the Logout icon, you can go back to the login page and the active session ends. To utilize all TestLink features, you have to login again." }, { "code": null, "e": 20298, "s": 20233, "text": "In the following screenshot the logout icon is encircled in red." }, { "code": null, "e": 20385, "s": 20298, "text": "In this chapter, you will learn how to create, edit, and delete a project in TestLink." }, { "code": null, "e": 20432, "s": 20385, "text": "TestLink supports multiple projects at a time." }, { "code": null, "e": 20533, "s": 20432, "text": "To create a Project, you should have Admin permissions. Following are the steps to create a Project." }, { "code": null, "e": 20663, "s": 20533, "text": "Step 1 − To create a new project, click Test Project → Test Project Management at dashboard as shown in the following screenshot." }, { "code": null, "e": 20757, "s": 20663, "text": "It will display all the available projects along with filters and Create a button at the top." }, { "code": null, "e": 20828, "s": 20757, "text": "Step 2 − Click the Create button as shown in the following screenshot." }, { "code": null, "e": 20862, "s": 20828, "text": "It opens the Create Project page." }, { "code": null, "e": 20927, "s": 20862, "text": "Step 3 − Enter the following details into Create a Project form:" }, { "code": null, "e": 20970, "s": 20927, "text": "Name − It should be a unique project name." }, { "code": null, "e": 21035, "s": 20970, "text": "Prefix − It is used for test case ID to identify the test cases." }, { "code": null, "e": 21084, "s": 21035, "text": "Project description − Details about the project." }, { "code": null, "e": 21259, "s": 21084, "text": "Enhanced features − You can check the checkboxes based on the requirement of the project. It allows to select the features that you wish such as Requirement, Automation, etc." }, { "code": null, "e": 21360, "s": 21259, "text": "Issue tracker integration − If any issue tracker is linked with TestLink, it will be displayed here." }, { "code": null, "e": 21471, "s": 21360, "text": "Step 4 − Select the Availability option and then click the Create button as shown in the following screenshot." }, { "code": null, "e": 21532, "s": 21471, "text": "Clicking the Create button adds the project into the system." }, { "code": null, "e": 21592, "s": 21532, "text": "To edit a project, you should have Edit Project Permission." }, { "code": null, "e": 21646, "s": 21592, "text": "Following are the steps to edit the project details −" }, { "code": null, "e": 21701, "s": 21646, "text": "Step 1 − Click Test Project → Test Project Management." }, { "code": null, "e": 21745, "s": 21701, "text": "It will display all the available projects." }, { "code": null, "e": 21835, "s": 21745, "text": "Step 2 − Click the Project Name to edit the details as shown in the following screenshot." }, { "code": null, "e": 21964, "s": 21835, "text": "Step 3 − It opens the Project Details in edit mode. You can update the details in any of the sections and click the Save button." }, { "code": null, "e": 22028, "s": 21964, "text": "To delete a project, you should have Delete project Permission." }, { "code": null, "e": 22083, "s": 22028, "text": "Step 1 − Click Test Project → Test Project Management." }, { "code": null, "e": 22216, "s": 22083, "text": "It will display all the available projects along with a delete icon in red at the right corner as shown in the following screenshot." }, { "code": null, "e": 22282, "s": 22216, "text": "Step 2 − Click the Delete icon related to the respective project." }, { "code": null, "e": 22434, "s": 22282, "text": "It will display a warning message for deletion along with an advice to deactivate rather than delete a project. Following screenshot displays the same." }, { "code": null, "e": 22537, "s": 22434, "text": "Step 3 − Click the Yes button. It will refresh the page and the project will be removed from the list." }, { "code": null, "e": 22713, "s": 22537, "text": "In the Inventory, you can list all hardware details required in the project. To access this feature, you should enable it while creating a project or in the edit project page." }, { "code": null, "e": 22889, "s": 22713, "text": "You can access the Inventory by navigating to Test Project → Inventory in Dashboard as shown in the below screenshot. Inventory offers three actions − Create, Edit and Delete." }, { "code": null, "e": 22947, "s": 22889, "text": "Following are the steps to create a record in inventory −" }, { "code": null, "e": 23018, "s": 22947, "text": "Step 1 − Click Inventory on the Dashboard to visit the Inventory page." }, { "code": null, "e": 23147, "s": 23018, "text": "Step 2 − Click the Create link present at the left top corner of the screen. It will open a pop-up form to define a device data." }, { "code": null, "e": 23186, "s": 23147, "text": "Step 3 − Enter the following details −" }, { "code": null, "e": 23196, "s": 23186, "text": "Host Name" }, { "code": null, "e": 23207, "s": 23196, "text": "IP Address" }, { "code": null, "e": 23213, "s": 23207, "text": "Owner" }, { "code": null, "e": 23258, "s": 23213, "text": "Purpose − It supports up to 2000 characters." }, { "code": null, "e": 23304, "s": 23258, "text": "Hardware − It supports up to 2000 characters." }, { "code": null, "e": 23347, "s": 23304, "text": "Notes − It supports up to 2000 characters." }, { "code": null, "e": 23379, "s": 23347, "text": "Step 4 − Click the Save button." }, { "code": null, "e": 23494, "s": 23379, "text": "Once you click Save, a new row gets added along with all the entered details as shown in the following screenshot." }, { "code": null, "e": 23536, "s": 23494, "text": "To edit a record, a row must be selected." }, { "code": null, "e": 23579, "s": 23536, "text": "Following are the steps to edit a record −" }, { "code": null, "e": 23658, "s": 23579, "text": "Step 1 − Click the Host Name to select a record to edit in the Inventory page." }, { "code": null, "e": 23785, "s": 23658, "text": "Step 2 − Click the Edit link present at the top left corner of the screen. It will open a pop-up form to define a device data." }, { "code": null, "e": 23825, "s": 23785, "text": "Step 3 − Update the following details −" }, { "code": null, "e": 23835, "s": 23825, "text": "Host Name" }, { "code": null, "e": 23846, "s": 23835, "text": "IP Address" }, { "code": null, "e": 23852, "s": 23846, "text": "Owner" }, { "code": null, "e": 23897, "s": 23852, "text": "Purpose − It supports up to 2000 characters." }, { "code": null, "e": 23943, "s": 23897, "text": "Hardware − It supports up to 2000 characters." }, { "code": null, "e": 23986, "s": 23943, "text": "Notes − It supports up to 2000 characters." }, { "code": null, "e": 24018, "s": 23986, "text": "Step 4 − Click the Save button." }, { "code": null, "e": 24114, "s": 24018, "text": "Step 5 − Once you click the Save button, all the details get updated and saved in the same row." }, { "code": null, "e": 24159, "s": 24114, "text": "Following are the steps to delete a record −" }, { "code": null, "e": 24240, "s": 24159, "text": "Step 1 − Click the Host Name to select a record to delete in the Inventory page." }, { "code": null, "e": 24357, "s": 24240, "text": "Step 2 − Click the Delete link present at the top left corner of the screen. It will ask for confirmation to delete." }, { "code": null, "e": 24398, "s": 24357, "text": "Step 3 − Click Yes to delete the record." }, { "code": null, "e": 24508, "s": 24398, "text": "You will receive a successful deletion message and the row gets deleted as shown in the following screenshot." }, { "code": null, "e": 24721, "s": 24508, "text": "Test planning, is the most important activity to ensure that there is initially a list of tasks and milestones in a baseline plan to track the progress of the project. It also defines the size of the test effort." }, { "code": null, "e": 24869, "s": 24721, "text": "It is the main document often called as the master test plan or a project test plan and is usually developed during the early phase of the project." }, { "code": null, "e": 24937, "s": 24869, "text": "To create a test plan, you should have Create Test Plan Permission." }, { "code": null, "e": 24985, "s": 24937, "text": "Following are the steps to create a test plan −" }, { "code": null, "e": 25088, "s": 24985, "text": "Step 1 − Go to Test Plan → Test Plan Management on the dashboard as shown in the following screenshot." }, { "code": null, "e": 25268, "s": 25088, "text": "If any test plan is listed for the project, it displays the list of test plans. Otherwise, it displays a message to create a test plan to support the test execution functionality." }, { "code": null, "e": 25339, "s": 25268, "text": "Step 2 − Click the Create button as shown in the following screenshot." }, { "code": null, "e": 25378, "s": 25339, "text": "It displays the test plan create form." }, { "code": null, "e": 25428, "s": 25378, "text": "Step 3 − Enter the following details in the form." }, { "code": null, "e": 25475, "s": 25428, "text": "Name − It should be the name of the test plan." }, { "code": null, "e": 25522, "s": 25475, "text": "Name − It should be the name of the test plan." }, { "code": null, "e": 25665, "s": 25522, "text": "Description − This field should contain the detailed information of a test plan. Generally, a test plan consists of the following information." }, { "code": null, "e": 25808, "s": 25665, "text": "Description − This field should contain the detailed information of a test plan. Generally, a test plan consists of the following information." }, { "code": null, "e": 25829, "s": 25808, "text": "Test plan identifier" }, { "code": null, "e": 25859, "s": 25829, "text": "Unique identifying reference." }, { "code": null, "e": 25872, "s": 25859, "text": "Introduction" }, { "code": null, "e": 25932, "s": 25872, "text": "A brief introduction about the project and of the document." }, { "code": null, "e": 25943, "s": 25932, "text": "Test items" }, { "code": null, "e": 26010, "s": 25943, "text": "A test item is a software item that is the application under test." }, { "code": null, "e": 26032, "s": 26010, "text": "Features to be tested" }, { "code": null, "e": 26080, "s": 26032, "text": "A feature that needs to tested on the testware." }, { "code": null, "e": 26106, "s": 26080, "text": "Features not to be tested" }, { "code": null, "e": 26182, "s": 26106, "text": "Identify the features and the reasons for not including as part of testing." }, { "code": null, "e": 26191, "s": 26182, "text": "Approach" }, { "code": null, "e": 26238, "s": 26191, "text": "Details about the overall approach to testing." }, { "code": null, "e": 26262, "s": 26238, "text": "Item pass/fail criteria" }, { "code": null, "e": 26328, "s": 26262, "text": "Documented whether a software item has passed or failed its test." }, { "code": null, "e": 26346, "s": 26328, "text": "Test deliverables" }, { "code": null, "e": 26463, "s": 26346, "text": "Deliverables that are part of the testing process, such as test plans, test specifications and test summary reports." }, { "code": null, "e": 26477, "s": 26463, "text": "Testing tasks" }, { "code": null, "e": 26527, "s": 26477, "text": "All tasks for planning and executing the testing." }, { "code": null, "e": 26547, "s": 26527, "text": "Environmental needs" }, { "code": null, "e": 26663, "s": 26547, "text": "Defining the environmental requirements such as hardware, software, OS, network configurations, and tools required." }, { "code": null, "e": 26680, "s": 26663, "text": "Responsibilities" }, { "code": null, "e": 26738, "s": 26680, "text": "Lists the roles and responsibilities of the team members." }, { "code": null, "e": 26766, "s": 26738, "text": "Staffing and training needs" }, { "code": null, "e": 26859, "s": 26766, "text": "Captures the actual staffing requirements and any specific skills and training requirements." }, { "code": null, "e": 26868, "s": 26859, "text": "Schedule" }, { "code": null, "e": 26932, "s": 26868, "text": "States the important project delivery dates and key milestones." }, { "code": null, "e": 26953, "s": 26932, "text": "Risks and Mitigation" }, { "code": null, "e": 27049, "s": 26953, "text": "High-level project risks and assumptions as well as a mitigating plan for each identified risk." }, { "code": null, "e": 27059, "s": 27049, "text": "Approvals" }, { "code": null, "e": 27135, "s": 27059, "text": "Captures all approvers of the document, their titles and the sign-off date." }, { "code": null, "e": 27234, "s": 27135, "text": "Testlink supports images, table, links, special characters, etc. to make content rich description." }, { "code": null, "e": 27301, "s": 27234, "text": "There are 2 checkboxes as can be seen in the following screenshot." }, { "code": null, "e": 27447, "s": 27301, "text": "Active − It will activate the document after creation and you can utilize this document in test execution or any other activities as a reference." }, { "code": null, "e": 27593, "s": 27447, "text": "Active − It will activate the document after creation and you can utilize this document in test execution or any other activities as a reference." }, { "code": null, "e": 27817, "s": 27593, "text": "Public − It allows other users to use this document. It will be visible to other users as well who are linked with this project. If this checkbox is unchecked, only the person who has created can use and view this document." }, { "code": null, "e": 28041, "s": 27817, "text": "Public − It allows other users to use this document. It will be visible to other users as well who are linked with this project. If this checkbox is unchecked, only the person who has created can use and view this document." }, { "code": null, "e": 28109, "s": 28041, "text": "Step 4 − Click the Create button present at the bottom of the form." }, { "code": null, "e": 28233, "s": 28109, "text": "Once you click Create, you can see the added Test Plan along with a few icons at the extreme right of screen as seen below." }, { "code": null, "e": 28445, "s": 28233, "text": "These icons are delete the test plan, export links to the test cases and platform, import links to the test cases and platform, Assign Role and test execution from left to right as displayed in below screenshot." }, { "code": null, "e": 28499, "s": 28445, "text": "To edit a test plan, you should have Edit Permission." }, { "code": null, "e": 28544, "s": 28499, "text": "Following are the steps to edit a test plan." }, { "code": null, "e": 28716, "s": 28544, "text": "Step 1 − Click the Test Plan name to open the details. The name of the Test Plan is present in the first column and it is hyperlinked as shown in the following screenshot." }, { "code": null, "e": 28847, "s": 28716, "text": "Step 2 − It opens the test plan details in edit mode. You can edit the name, description, and selection of Active and Public mode." }, { "code": null, "e": 29066, "s": 28847, "text": "Step 3 − Attach a file in the test plan. This feature is available in the edit mode only. While creating the test plan, you can add images/tables into the description. However, attaching a file option is not available." }, { "code": null, "e": 29135, "s": 29066, "text": "Step 4 − After updating the details, click Update to finish editing." }, { "code": null, "e": 29190, "s": 29135, "text": "Following screenshot displays how to edit a test plan." }, { "code": null, "e": 29243, "s": 29190, "text": "To delete a plan, you should have Delete Permission." }, { "code": null, "e": 29375, "s": 29243, "text": "If a test plan is deleted, it deletes both the test plan and all of its corresponding data. Data includes test cases, results, etc." }, { "code": null, "e": 29419, "s": 29375, "text": "Following are the steps to delete a build −" }, { "code": null, "e": 29491, "s": 29419, "text": "Step 1 − Go to the Test Plan Management → Test Plan from the dashboard." }, { "code": null, "e": 29604, "s": 29491, "text": "Step 2 − Click the Delete icon corresponding to the row of the test plan that needs to be deleted as seen below." }, { "code": null, "e": 29661, "s": 29604, "text": "A pop-up will be displayed for a confirmation to delete." }, { "code": null, "e": 29696, "s": 29661, "text": "Step 3 − Click Yes as shown below." }, { "code": null, "e": 29755, "s": 29696, "text": "The page gets refreshed and the test plan will be deleted." }, { "code": null, "e": 29956, "s": 29755, "text": "To achieve the objective of a Release, there could be multiple builds. Build is always associated with only one Release. A build fulfills the partial objective of Release with limited functionalities." }, { "code": null, "e": 30114, "s": 29956, "text": "In TestLink, test execution is made up of both builds and test cases. If the build is not created for a project, you won’t be able to perform test execution." }, { "code": null, "e": 30175, "s": 30114, "text": "To create a Build, you should have Create Builds permission." }, { "code": null, "e": 30219, "s": 30175, "text": "Following are the steps to create a Build −" }, { "code": null, "e": 30281, "s": 30219, "text": "Step 1 − Go to Test Plan → Build/Releases from the dashboard." }, { "code": null, "e": 30349, "s": 30281, "text": "It opens the Build Management page along with the available builds." }, { "code": null, "e": 30398, "s": 30349, "text": "Step 2 − Click the Create button as shown below." }, { "code": null, "e": 30436, "s": 30398, "text": "It opens the Create a new build form." }, { "code": null, "e": 30486, "s": 30436, "text": "Step 3 − Enter the following fields in the form −" }, { "code": null, "e": 30577, "s": 30486, "text": "Title − A build is identified by its title. Each build is related to the active Test Plan." }, { "code": null, "e": 30668, "s": 30577, "text": "Title − A build is identified by its title. Each build is related to the active Test Plan." }, { "code": null, "e": 30782, "s": 30668, "text": "Description − Description should include a list of delivered packages, fixes or features, approvals, status, etc." }, { "code": null, "e": 30896, "s": 30782, "text": "Description − Description should include a list of delivered packages, fixes or features, approvals, status, etc." }, { "code": null, "e": 31191, "s": 30896, "text": "Active − A build has two attributes - Active / Inactive – defines whether the build can be used. Inactive builds are not listed on the execution and reports pages. Open / Closed – Test results can be modified only for open builds. Ensure that the Build date must is within the Release Timeline." }, { "code": null, "e": 31486, "s": 31191, "text": "Active − A build has two attributes - Active / Inactive – defines whether the build can be used. Inactive builds are not listed on the execution and reports pages. Open / Closed – Test results can be modified only for open builds. Ensure that the Build date must is within the Release Timeline." }, { "code": null, "e": 31533, "s": 31486, "text": "Release Timeline − It should be a future date." }, { "code": null, "e": 31580, "s": 31533, "text": "Release Timeline − It should be a future date." }, { "code": null, "e": 31663, "s": 31580, "text": "Step 4 − After entering all the details, click the Create button to add the build." }, { "code": null, "e": 31762, "s": 31663, "text": "To edit a build, you should have Edit Builds permission. Following are the steps to edit a build −" }, { "code": null, "e": 31856, "s": 31762, "text": "Step 1 − Select a Build to edit and click the build title to open the details as shown below." }, { "code": null, "e": 31938, "s": 31856, "text": "It opens the build details in the edit mode as shown in the following screenshot." }, { "code": null, "e": 32004, "s": 31938, "text": "Step 2 − After updating the build details, click the Save button." }, { "code": null, "e": 32065, "s": 32004, "text": "To delete a Build, you should have Delete Builds permission." }, { "code": null, "e": 32109, "s": 32065, "text": "Following are the steps to delete a build −" }, { "code": null, "e": 32187, "s": 32109, "text": "Step 1 − Go to the Test Plan Management − Builds/Releases from the dashboard." }, { "code": null, "e": 32297, "s": 32187, "text": "Step 2 − Click the Delete icon corresponding to the row of the build that needs to be deleted as shown below." }, { "code": null, "e": 32352, "s": 32297, "text": "A pop-up will be displayed for confirmation to delete." }, { "code": null, "e": 32409, "s": 32352, "text": "Step 3 − Click Yes as shown in the following screenshot." }, { "code": null, "e": 32467, "s": 32409, "text": "The page will be refreshed and the build will be deleted." }, { "code": null, "e": 32653, "s": 32467, "text": "Test Specification defines the structure of Test Design. Creation of Test Suits and Cases are done through test specification. However, one project can have only one test specification." }, { "code": null, "e": 32765, "s": 32653, "text": "Test Specification can be accessed by navigating to Test Specification → Test Specification from the dashboard." }, { "code": null, "e": 32860, "s": 32765, "text": "It is divided into two panels − Settings and Filter (Left side) and Test Project (right side)." }, { "code": null, "e": 32922, "s": 32860, "text": "You can create test suite/cases by working on the right side." }, { "code": null, "e": 33096, "s": 32922, "text": "After navigating to test specification, Filters are displayed on the left side panel of the screen. Filters help out to narrow down the search and provide unique test cases." }, { "code": null, "e": 33154, "s": 33096, "text": "Following are the steps to use the Filter functionality −" }, { "code": null, "e": 33220, "s": 33154, "text": "Step 1 − Go to the filter section on the left side of the screen." }, { "code": null, "e": 33281, "s": 33220, "text": "Step 2 − Provide different filter options as the following −" }, { "code": null, "e": 33294, "s": 33281, "text": "Test Case ID" }, { "code": null, "e": 33307, "s": 33294, "text": "Test Case ID" }, { "code": null, "e": 33323, "s": 33307, "text": "Test Case Title" }, { "code": null, "e": 33339, "s": 33323, "text": "Test Case Title" }, { "code": null, "e": 33507, "s": 33339, "text": "Status − You can select multiple choices at a time from the dropdown. It supports Any, Draft, Ready for Review, Review in Progress, Rework, Obsolete, Future and Final." }, { "code": null, "e": 33675, "s": 33507, "text": "Status − You can select multiple choices at a time from the dropdown. It supports Any, Draft, Ready for Review, Review in Progress, Rework, Obsolete, Future and Final." }, { "code": null, "e": 33788, "s": 33675, "text": "Importance − You can select multiple choices at a time from the dropdown. It supports Any, Help, Medium and Low." }, { "code": null, "e": 33901, "s": 33788, "text": "Importance − You can select multiple choices at a time from the dropdown. It supports Any, Help, Medium and Low." }, { "code": null, "e": 33998, "s": 33901, "text": "Execution Type − It is a single selection dropdown. It supports Any, Manual or Automated option." }, { "code": null, "e": 34095, "s": 33998, "text": "Execution Type − It is a single selection dropdown. It supports Any, Manual or Automated option." }, { "code": null, "e": 34231, "s": 34095, "text": "Step 3 − After selection, click the Apply button to display the result. Reset Filters button will remove all selection in default mode." }, { "code": null, "e": 34295, "s": 34231, "text": "You can expand the tree to display the structure of the result." }, { "code": null, "e": 34341, "s": 34295, "text": "On the right side, Test Project is displayed." }, { "code": null, "e": 34375, "s": 34341, "text": "Test Project name is hyperlinked." }, { "code": null, "e": 34495, "s": 34375, "text": "When you click the name, it displays the details of the project in edit form, where you can update the project details." }, { "code": null, "e": 34784, "s": 34495, "text": "After the name, it displays Project Description and Attached files. It supports a feature to add an attachment. You can browse and upload the file to the project. It supports max 1048576 Bytes. You can upload up to a maximum size of the file. You can upload multiple files to the project." }, { "code": null, "e": 34854, "s": 34784, "text": "At the top of the screen, there is a settings symbol , called Actions" }, { "code": null, "e": 34918, "s": 34854, "text": "You can add test suites and test cases by clicking this symbol." }, { "code": null, "e": 35125, "s": 34918, "text": "Test suite is a container that has a set of tests which helps the testers in executing and reporting the test execution status. It can take any of the three states namely Active, In progress, and Completed." }, { "code": null, "e": 35287, "s": 35125, "text": "A test case can be added to multiple test suites and test plans. After creating a test plan, test suites are created, which in turn can have any number of tests." }, { "code": null, "e": 35397, "s": 35287, "text": "TestLink supports tree structure for test suites. There could be multiple sub-test suites under a test suite." }, { "code": null, "e": 35468, "s": 35397, "text": "To create a Test Suite, you should have Create Test Suites permission." }, { "code": null, "e": 35517, "s": 35468, "text": "Following are the steps to create a Test Suite −" }, { "code": null, "e": 35598, "s": 35517, "text": "Step 1 − Navigate to Test Specification → Test Specification from the dashboard." }, { "code": null, "e": 35732, "s": 35598, "text": "Step 2 − Click the Setting type icon known as Actions on this page, present on the right panel as shown in the following screenshot." }, { "code": null, "e": 35768, "s": 35732, "text": "It will open Test Suite Operations." }, { "code": null, "e": 35832, "s": 35768, "text": "Step 3 − Click the + icon to create a new suite as shown below." }, { "code": null, "e": 35869, "s": 35832, "text": "It opens the create test suite page." }, { "code": null, "e": 35919, "s": 35869, "text": "Step 4 − Enter the following fields in the form −" }, { "code": null, "e": 35938, "s": 35919, "text": "Name of Test Suite" }, { "code": null, "e": 35957, "s": 35938, "text": "Name of Test Suite" }, { "code": null, "e": 35965, "s": 35957, "text": "Details" }, { "code": null, "e": 35973, "s": 35965, "text": "Details" }, { "code": null, "e": 36063, "s": 35973, "text": "Keywords − It displays all the available keywords. You can assign them based on relation." }, { "code": null, "e": 36153, "s": 36063, "text": "Keywords − It displays all the available keywords. You can assign them based on relation." }, { "code": null, "e": 36226, "s": 36153, "text": "Step 5 − Click the Save button as displayed in the following screenshot." }, { "code": null, "e": 36390, "s": 36226, "text": "Once you click Save, you will see the test suite in tree structure on the left side panel of the screen. The details are available on the right side of the screen." }, { "code": null, "e": 36456, "s": 36390, "text": "To edit a test suite, you should have Edit Test Suite Permission." }, { "code": null, "e": 36503, "s": 36456, "text": "Following are the steps to edit a test suite −" }, { "code": null, "e": 36662, "s": 36503, "text": "Step 1 − Select test suite from the tree structure on the left panel and click the settings known as actions to open the Test Suite Operations as shown below." }, { "code": null, "e": 36697, "s": 36662, "text": "It displays Test Suite Operations." }, { "code": null, "e": 36751, "s": 36697, "text": "Step 2 − Click the Edit (pencil) icon as shown below." }, { "code": null, "e": 36801, "s": 36751, "text": "It opens the Test Suite details on the edit page." }, { "code": null, "e": 36901, "s": 36801, "text": "Step 3 − Edit Name, Details or any other fields and click the Save button to update the test suite." }, { "code": null, "e": 37074, "s": 36901, "text": "To move/copy a test suite, you should have Create/Edit Test Suite permission. This functionality allows creating a duplicate of a Test Suite or reordering of the structure." }, { "code": null, "e": 37225, "s": 37074, "text": "Step 1 − To copy/move a test suite into another project, select test suites those need to be copied/moved and click the setting icon known as Actions." }, { "code": null, "e": 37261, "s": 37225, "text": "It will open Test suite Operations." }, { "code": null, "e": 37338, "s": 37261, "text": "Step 2 − Click the Move or Copy symbol as shown in the following screenshot." }, { "code": null, "e": 37530, "s": 37338, "text": "Step 3 − It opens the Move/Copy page where you can select the target container, destination position, and whether the keywords and requirements should be copied/moved to the target container." }, { "code": null, "e": 37810, "s": 37530, "text": "Step 4 − After selection, click the Copy or Move button according to requirement as shown in the following screenshot. The Copy button will copy the test suite in both of the projects, while the move button will move the test suite from the current project to the target project." }, { "code": null, "e": 37880, "s": 37810, "text": "To delete a Test Suite, you should have Delete Test Suite permission." }, { "code": null, "e": 38038, "s": 37880, "text": "Step 1 − To delete a test suite, select test suites those need to be deleted and click the setting icon known as Actions. It will open Test suite Operations." }, { "code": null, "e": 38087, "s": 38038, "text": "Step 2 − Click the delete symbol as shown below." }, { "code": null, "e": 38139, "s": 38087, "text": "A confirmation message will be displayed to delete." }, { "code": null, "e": 38221, "s": 38139, "text": "Step 3 − Click Yes to delete the test suite as shown in the following screenshot." }, { "code": null, "e": 38345, "s": 38221, "text": "The page will be refreshed and the test suite will be deleted from the Tree structure on the left side panel of the screen." }, { "code": null, "e": 38409, "s": 38345, "text": "A successful deletion message is also displayed as shown below." }, { "code": null, "e": 38622, "s": 38409, "text": "A test case is a document, which has a set of test data, preconditions, expected results and post-conditions, developed for a particular test scenario in order to verify compliance against a specific requirement." }, { "code": null, "e": 38840, "s": 38622, "text": "Test case acts as the starting point for test execution, and after applying a set of input value the application has a definitive outcome and leaves the system at some endpoint, also known as execution post-condition." }, { "code": null, "e": 38909, "s": 38840, "text": "To create a Test Case, you should have Create Test Cases permission." }, { "code": null, "e": 38957, "s": 38909, "text": "Following are the steps to create a Test Case −" }, { "code": null, "e": 39038, "s": 38957, "text": "Step 1 − Navigate to Test Specification → Test Specification from the dashboard." }, { "code": null, "e": 39131, "s": 39038, "text": "Step 2 − Select the test suite from the tree structure on the left side panel on the screen." }, { "code": null, "e": 39256, "s": 39131, "text": "Step 3 − Click the Setting type icon known as Actions on this page, present on the right panel of the screen as shown below." }, { "code": null, "e": 39324, "s": 39256, "text": "It will open Test Suite Operations as well as Test Case Operations." }, { "code": null, "e": 39416, "s": 39324, "text": "Step 4 − Click the + icon of Test Case Operations to create a new test case as shown below." }, { "code": null, "e": 39452, "s": 39416, "text": "It opens the create test case page." }, { "code": null, "e": 39502, "s": 39452, "text": "Step 5 − Enter the following fields in the form −" }, { "code": null, "e": 39520, "s": 39502, "text": "Name of Test Case" }, { "code": null, "e": 39538, "s": 39520, "text": "Name of Test Case" }, { "code": null, "e": 39546, "s": 39538, "text": "Summary" }, { "code": null, "e": 39554, "s": 39546, "text": "Summary" }, { "code": null, "e": 39569, "s": 39554, "text": "Pre-conditions" }, { "code": null, "e": 39584, "s": 39569, "text": "Pre-conditions" }, { "code": null, "e": 39629, "s": 39584, "text": "Select Status, Importance and Execution type" }, { "code": null, "e": 39674, "s": 39629, "text": "Select Status, Importance and Execution type" }, { "code": null, "e": 39720, "s": 39674, "text": "Enter the estimated execution type in minutes" }, { "code": null, "e": 39766, "s": 39720, "text": "Enter the estimated execution type in minutes" }, { "code": null, "e": 39860, "s": 39766, "text": "Keywords − It displays all the available keywords. You can assign them based on the relation." }, { "code": null, "e": 39954, "s": 39860, "text": "Keywords − It displays all the available keywords. You can assign them based on the relation." }, { "code": null, "e": 40029, "s": 39954, "text": "Step 6 − Click the Create button as displayed in the following screenshot." }, { "code": null, "e": 40204, "s": 40029, "text": "Once you click the Create button, you can see the test case in the tree structure on the left side panel as well as the details are available on the right side of the screen." }, { "code": null, "e": 40268, "s": 40204, "text": "To edit a test case, you should have Edit Test Case permission." }, { "code": null, "e": 40314, "s": 40268, "text": "Following are the steps to edit a test case −" }, { "code": null, "e": 40478, "s": 40314, "text": "Step 1 − Select the test case from the tree structure on the left panel of the screen and click the settings known as actions to display all the available options." }, { "code": null, "e": 40525, "s": 40478, "text": "Step 2 − Click the Edit button as shown below." }, { "code": null, "e": 40574, "s": 40525, "text": "It opens the Test case details in the edit page." }, { "code": null, "e": 40650, "s": 40574, "text": "Step 3 − You can edit the Name, Details or any other fields as shown below." }, { "code": null, "e": 40706, "s": 40650, "text": "Step 4 − Click the Save button to update the test case." }, { "code": null, "e": 40872, "s": 40706, "text": "To Move/Copy a test case, you should have Create/Edit Test Suite permission. This functionality allows creating a duplicate test case or reordering of the structure." }, { "code": null, "e": 41025, "s": 40872, "text": "Step 1 − To copy/move a test suite into another project, select the test cases that need to be copied/moved and click the setting icon known as Actions." }, { "code": null, "e": 41077, "s": 41025, "text": "Step 2 − Click the Move/Copy button as shown below." }, { "code": null, "e": 41275, "s": 41077, "text": "Step 3 − It opens the Move/Copy page. You can select the test suite to move or copy a new test case name and decide whether the keywords and requirements should be copied/moved to the target suite." }, { "code": null, "e": 41357, "s": 41275, "text": "Step 4 − After selection, click the Copy or Move button according to requirement." }, { "code": null, "e": 41520, "s": 41357, "text": "Step 5 − The Copy button will copy the test suite in both of the suites, while the move button will move the test case from the current suite to the target suite." }, { "code": null, "e": 41597, "s": 41520, "text": "Following screenshot shows how to copy/move the test case to another suite −" }, { "code": null, "e": 41665, "s": 41597, "text": "To delete a Test Case, you should have Delete Test Case permission." }, { "code": null, "e": 41803, "s": 41665, "text": "Step 1 − To delete a test case, select the test case from the suite that needs to be deleted and click the setting icon known as Actions." }, { "code": null, "e": 41863, "s": 41803, "text": "Step 2 − Once done, click the delete button as shown below." }, { "code": null, "e": 41984, "s": 41863, "text": "A confirmation message will be displayed to delete. Click Yes to delete the test cases as shown in following screenshot." }, { "code": null, "e": 42107, "s": 41984, "text": "The page will be refreshed and the test case will be deleted from the tree structure on the left side panel of the screen." }, { "code": null, "e": 42171, "s": 42107, "text": "A successful deletion message will be displayed as shown below." }, { "code": null, "e": 42314, "s": 42171, "text": "This feature is very useful when one test case has many versions. Active/Inactive attribute helps to recognize which test case should be used." }, { "code": null, "e": 42421, "s": 42314, "text": "Step 1 − To create a new version of the test case, click the button “Create a new version” as shown below." }, { "code": null, "e": 42522, "s": 42421, "text": "It will create a new version of test case and a successful message will be displayed as shown below." }, { "code": null, "e": 42586, "s": 42522, "text": "Once a new version is created, by default it is in Active mode." }, { "code": null, "e": 42683, "s": 42586, "text": "It is recommended to deactivate the version of previous test case before creating a new version." }, { "code": null, "e": 42969, "s": 42683, "text": "Deactivate Test Case Version is not available in \"Add Test Cases to Test Plan\". This can be useful for test designers. They can edit or change the Test Case Version and only when they decide it is completed, change the Status to ACTIVE for it to be available to be used in a Test Plan." }, { "code": null, "e": 43058, "s": 42969, "text": "Step 2 − After clicking on Actions, the button - Deactivate this version – is displayed." }, { "code": null, "e": 43210, "s": 43058, "text": "Step 3 − Once you click the button, a message that the test case version is deactivated is displayed and the button changes to “Activate this version”." }, { "code": null, "e": 43453, "s": 43210, "text": "TestLink supports XML and CVS file to import data. It supports importing the data for test suites, test cases, requirements, test execution results, keywords, etc. However, for few cases it supports only XML and in few cases both XML and CVS." }, { "code": null, "e": 43554, "s": 43453, "text": "Following table displays the functionalities that support import and those that support file format." }, { "code": null, "e": 43648, "s": 43554, "text": "Sample File − Following is the XML file with keywords that can be used to import test suites." }, { "code": null, "e": 44270, "s": 43648, "text": "<testsuite name = \"Child Suite2\">\n <details>abc</details>\n <testcase name = \"Sample test case2\">\n <summary>test case sample- update</summary>\n <preconditions>1. TestLink should be installed</preconditions>\n \n <steps>\n <step>\n <step_number>1</step_number>\n <actions>Go to www.google.com</actions>\n <expectedresults>Google Home page should display</expectedresults>\n </step>\n </steps>\n \n <keywords>\n <keyword name = \"Sample Test\">\n <notes>abc</notes>\n </keyword>\n </keywords>\n </testcase>\n</testsuite>" }, { "code": null, "e": 44362, "s": 44270, "text": "If you don’t want to add the keyword, the keyword section can be removed from the XML file." }, { "code": null, "e": 44454, "s": 44362, "text": "If you don’t want to add the keyword, the keyword section can be removed from the XML file." }, { "code": null, "e": 44555, "s": 44454, "text": "If you want to import multiple test cases, add <testcase> section multiple times with all sub-nodes." }, { "code": null, "e": 44656, "s": 44555, "text": "If you want to import multiple test cases, add <testcase> section multiple times with all sub-nodes." }, { "code": null, "e": 44797, "s": 44656, "text": "If only test cases need to be imported in an already existing test suite, remove the <testsuite> tag and start the XML file with <testcase>." }, { "code": null, "e": 44938, "s": 44797, "text": "If only test cases need to be imported in an already existing test suite, remove the <testsuite> tag and start the XML file with <testcase>." }, { "code": null, "e": 45040, "s": 44938, "text": "Step 1 − To import the test suite, go to Test Specifications → Test Specification from the dashboard." }, { "code": null, "e": 45141, "s": 45040, "text": "Step 2 − Select the project and the folder on the left pane where you want to import the test suite." }, { "code": null, "e": 45144, "s": 45141, "text": "OR" }, { "code": null, "e": 45250, "s": 45144, "text": "To import only test cases, select the nearest test suite folders where the test cases should be imported." }, { "code": null, "e": 45316, "s": 45250, "text": "Step 3 − Click the Actions icon on the right pane as shown below." }, { "code": null, "e": 45355, "s": 45316, "text": "It displays the test suite operations." }, { "code": null, "e": 45403, "s": 45355, "text": "Step 4 − Click the Import icon as shown below −" }, { "code": null, "e": 45406, "s": 45403, "text": "OR" }, { "code": null, "e": 45522, "s": 45406, "text": "To upload only test cases, click the Import icon present in Test Case Operations (below the Test Suite Operations)." }, { "code": null, "e": 45605, "s": 45522, "text": "It opens the Import Test Suite page. By default, the file type is selected as XML." }, { "code": null, "e": 45646, "s": 45605, "text": "Step 5 − Fill in the following details −" }, { "code": null, "e": 45726, "s": 45646, "text": "File − Select the XML file and upload it. Max size of the file should be 400KB." }, { "code": null, "e": 45806, "s": 45726, "text": "File − Select the XML file and upload it. Max size of the file should be 400KB." }, { "code": null, "e": 45887, "s": 45806, "text": "Consider test case as duplicate if: Select the appropriate option from the list." }, { "code": null, "e": 45968, "s": 45887, "text": "Consider test case as duplicate if: Select the appropriate option from the list." }, { "code": null, "e": 46035, "s": 45968, "text": "Action for duplicate: Select the appropriate option from the list." }, { "code": null, "e": 46102, "s": 46035, "text": "Action for duplicate: Select the appropriate option from the list." }, { "code": null, "e": 46157, "s": 46102, "text": "Step 6 − Click the Upload file button as shown below −" }, { "code": null, "e": 46230, "s": 46157, "text": "Step 7 − After import, a successful message is displayed as shown below." }, { "code": null, "e": 46295, "s": 46230, "text": "Sample XLS file to import multiple test cases as the following −" }, { "code": null, "e": 46315, "s": 46295, "text": "Unlock panic button" }, { "code": null, "e": 46334, "s": 46315, "text": "Press panic button" }, { "code": null, "e": 46348, "s": 46334, "text": "Press confirm" }, { "code": null, "e": 46426, "s": 46348, "text": "The first row won’t be imported. It is supposed to have a column description." }, { "code": null, "e": 46524, "s": 46426, "text": "Step 1 − To import test cases, go to Test Specifications → Test Specification from the dashboard." }, { "code": null, "e": 46613, "s": 46524, "text": "Step 2 − Select the nearest test suite folders, where the test cases should be imported." }, { "code": null, "e": 46664, "s": 46613, "text": "Step 3 − Click the Actions icon on the right pane." }, { "code": null, "e": 46698, "s": 46664, "text": "It displays Test Case Operations." }, { "code": null, "e": 46745, "s": 46698, "text": "Step 4 − Click the Import icon as shown below." }, { "code": null, "e": 46781, "s": 46745, "text": "It opens the Import test case page." }, { "code": null, "e": 46888, "s": 46781, "text": "Step 5 − By default, the file type selected is XML. Change it to XLS/CSV and enter the following details −" }, { "code": null, "e": 46964, "s": 46888, "text": "File − Select the file and upload it. Max size of the file should be 400KB." }, { "code": null, "e": 47040, "s": 46964, "text": "File − Select the file and upload it. Max size of the file should be 400KB." }, { "code": null, "e": 47122, "s": 47040, "text": "Consider test case as duplicate if − Select the appropriate option from the list." }, { "code": null, "e": 47204, "s": 47122, "text": "Consider test case as duplicate if − Select the appropriate option from the list." }, { "code": null, "e": 47272, "s": 47204, "text": "Action for duplicate − Select the appropriate option from the list." }, { "code": null, "e": 47340, "s": 47272, "text": "Action for duplicate − Select the appropriate option from the list." }, { "code": null, "e": 47394, "s": 47340, "text": "Step 6 − Click the Upload file button as shown below." }, { "code": null, "e": 47457, "s": 47394, "text": "TestLink supports XML and CSV file to import the requirements." }, { "code": null, "e": 47511, "s": 47457, "text": "Sample XML file for Requirement would be as follows −" }, { "code": null, "e": 47819, "s": 47511, "text": "<requirements>\n <requirement>\n <docid>ENG-0001</docid>\n <title>Add a product</title>\n <description>ABC</description>\n </requirement>\n \n <requirement>\n <docid>ENG-0002</docid>\n <title>Add price </title>\n <description>Price</description>\n </requirement>\n</requirements>" }, { "code": null, "e": 47873, "s": 47819, "text": "Sample CSV file for Requirement would be as follows −" }, { "code": null, "e": 47927, "s": 47873, "text": "ENG-0001,Add a product,ABC\n\nENG-0002,Add price,Price\n" }, { "code": null, "e": 48044, "s": 47927, "text": "Step 1 − To import the requirements, go to Requirement Specification → Requirement Specification from the dashboard." }, { "code": null, "e": 48158, "s": 48044, "text": "Step 2 − Select the Requirement Specification folder where the requirements should be imported on the left panel." }, { "code": null, "e": 48227, "s": 48158, "text": "Step 3 − Click the Action icon present on the top of the right pane." }, { "code": null, "e": 48272, "s": 48227, "text": "It displays the Requirement Operations page." }, { "code": null, "e": 48321, "s": 48272, "text": "Step 4 − Click the Import button as shown below." }, { "code": null, "e": 48362, "s": 48321, "text": "It displays the requirement import page." }, { "code": null, "e": 48400, "s": 48362, "text": "Step 5 − Enter the following details." }, { "code": null, "e": 48483, "s": 48400, "text": "File Type − You can select CSV, XML or other forms of CSV and XML files as listed." }, { "code": null, "e": 48566, "s": 48483, "text": "File Type − You can select CSV, XML or other forms of CSV and XML files as listed." }, { "code": null, "e": 48604, "s": 48566, "text": "File − Upload the corresponding file." }, { "code": null, "e": 48642, "s": 48604, "text": "File − Upload the corresponding file." }, { "code": null, "e": 48724, "s": 48642, "text": "Consider test case as duplicate if − Select the appropriate option from the list." }, { "code": null, "e": 48806, "s": 48724, "text": "Consider test case as duplicate if − Select the appropriate option from the list." }, { "code": null, "e": 48874, "s": 48806, "text": "Action for duplicate − Select the appropriate option from the list." }, { "code": null, "e": 48942, "s": 48874, "text": "Action for duplicate − Select the appropriate option from the list." }, { "code": null, "e": 48996, "s": 48942, "text": "Step 6 − Click the Upload file button as shown below." }, { "code": null, "e": 49075, "s": 48996, "text": "After upload, it displays Import done message along with the imported details." }, { "code": null, "e": 49154, "s": 49075, "text": "After upload, it displays Import done message along with the imported details." }, { "code": null, "e": 49287, "s": 49154, "text": "Similarly, keywords, platforms, and results can be imported using supported file and the respective section accessing the dashboard." }, { "code": null, "e": 49531, "s": 49287, "text": "TestLink supports XML and CSV file to export data. It supports exporting the data of test suites, test cases, requirements, test execution results, keywords, etc. However, for a few cases it supports only XML and in few cases both XML and CSV." }, { "code": null, "e": 49613, "s": 49531, "text": "Following table displays the functionalities that support export and file format." }, { "code": null, "e": 49675, "s": 49613, "text": "TestLink supports XML and CSV to export the requirement data." }, { "code": null, "e": 49764, "s": 49675, "text": "Step 1 − Go to Requirement Specification → Requirement Specification from the dashboard." }, { "code": null, "e": 49951, "s": 49764, "text": "Step 2 − To export all the Requirement Specifications, select the parent folder from the left pane and click the Export All Requirement Specification button on the right side as follows." }, { "code": null, "e": 50137, "s": 49951, "text": "Step 3 − To export any one requirement specification with all the requirement details inside the folder, select the folder in the left pane and click the Actions icon on the right pane." }, { "code": null, "e": 50195, "s": 50137, "text": "It displays the Requirement Specification Operation page." }, { "code": null, "e": 50218, "s": 50195, "text": "Step 4 − Click Export." }, { "code": null, "e": 50221, "s": 50218, "text": "OR" }, { "code": null, "e": 50449, "s": 50221, "text": "If you want to only export the Requirement Details but not Requirement Specification, click the Export button present under Requirement Operations (present below the Requirement Specification Operations section) as shown below." }, { "code": null, "e": 50535, "s": 50449, "text": "Once any of these Export buttons is clicked, it displays the Export Requirement page." }, { "code": null, "e": 50643, "s": 50535, "text": "Step 5 − Export Filename can be edited. Choose the file type. Then, click the Export button as shown below." }, { "code": null, "e": 50762, "s": 50643, "text": "It will download the corresponding files into the local drive that can be accessed by navigating the Downloads folder." }, { "code": null, "e": 50822, "s": 50762, "text": "TestLink supports XML to export test suites and cases data." }, { "code": null, "e": 50897, "s": 50822, "text": "Step 1 − Go to Test Specification → Test Specification from the dashboard." }, { "code": null, "e": 51026, "s": 50897, "text": "Step 2 − To export all the test suites, select the parent folder from the left pane and click the Action icon on the right pane." }, { "code": null, "e": 51067, "s": 51026, "text": "It opens the test suite operations page." }, { "code": null, "e": 51144, "s": 51067, "text": "Step 3 − Click Export All Test Suites icon on the right side as shown below." }, { "code": null, "e": 51306, "s": 51144, "text": "Step 4 − To export any one test suite with all the test cases inside the folder, select the folder on the left pane and click the Actions icon on the right pane." }, { "code": null, "e": 51346, "s": 51306, "text": "It displays Test Suite Operations page." }, { "code": null, "e": 51369, "s": 51346, "text": "Step 5 − Click Export." }, { "code": null, "e": 51372, "s": 51369, "text": "OR" }, { "code": null, "e": 51506, "s": 51372, "text": "If you want to only export Test Cases but not Test Suites, click the Export button present under Test Case Operations as shown below." }, { "code": null, "e": 51596, "s": 51506, "text": "Once any of these Export buttons is clicked, it displays the Export Test Suite/Case page." }, { "code": null, "e": 51662, "s": 51596, "text": "Step 6 − The Export Filename can be edited. Choose the file type." }, { "code": null, "e": 51760, "s": 51662, "text": "You can select and narrow down the exported data by selecting the checkbox for available details." }, { "code": null, "e": 51809, "s": 51760, "text": "Step 7 − Click the Export button as shown below." }, { "code": null, "e": 51928, "s": 51809, "text": "It will download the corresponding files into the local drive that can be accessed by navigating the Downloads folder." }, { "code": null, "e": 52120, "s": 51928, "text": "Test Plan contains a set of test cases those are in scope. Before starting the execution, a test plan must have test sets. A test case cannot be executed before assigning it to any test plan." }, { "code": null, "e": 52178, "s": 52120, "text": "Following are the steps to add test cases to a test plan." }, { "code": null, "e": 52271, "s": 52178, "text": "Step 1 − Go to Test Plan contents → Add/Remove test cases from the Dashboard as shown below." }, { "code": null, "e": 52312, "s": 52271, "text": "It opens the Add/Remove Test Cases page." }, { "code": null, "e": 52402, "s": 52312, "text": "Step 2 − Search the folder using filter on the left panel and click the test case folder." }, { "code": null, "e": 52479, "s": 52402, "text": "It displays Test Plan − Add Test cases to Test Plan page on the right panel." }, { "code": null, "e": 52548, "s": 52479, "text": "Step 3 − Check all the available test cases to add to the test plan." }, { "code": null, "e": 52613, "s": 52548, "text": "Step 4 − Select from Assign dropdown to assign this to a person." }, { "code": null, "e": 52646, "s": 52613, "text": "Step 5 − Select a build as well." }, { "code": null, "e": 52722, "s": 52646, "text": "Step 6 − Click the Add Selected button to add the test case to a test plan." }, { "code": null, "e": 52792, "s": 52722, "text": "After clicking Add selected, the color of the test case gets changed." }, { "code": null, "e": 52894, "s": 52792, "text": "Step 7 − The Add selected button changes to Add/Remove selected as shown in the following screenshot." }, { "code": null, "e": 52974, "s": 52894, "text": "To remove test cases from a test plan the following steps should be performed −" }, { "code": null, "e": 53068, "s": 52974, "text": "Step 1 − Go to Test Plan contents → Add/ Remove test cases from the Dashboard as shown below." }, { "code": null, "e": 53109, "s": 53068, "text": "It opens the Add/Remove Test Cases page." }, { "code": null, "e": 53201, "s": 53109, "text": "Step 2 − Search the folder using a filter on the left panel and click the test case folder." }, { "code": null, "e": 53278, "s": 53201, "text": "It displays Test Plan − Add Test cases to Test Plan page on the right panel." }, { "code": null, "e": 53334, "s": 53278, "text": "Step 3 − Select the test cases that need to be removed." }, { "code": null, "e": 53396, "s": 53334, "text": "Step 4 − Click the Add/Remove selected button as shown below." }, { "code": null, "e": 53571, "s": 53396, "text": "Search functionality is used to narrow down the displayed result. TestLink supports a wide range of search functionalities with a lot of fields to find out a specific result." }, { "code": null, "e": 53628, "s": 53571, "text": "TestLink supports the following search functionalities −" }, { "code": null, "e": 53648, "s": 53628, "text": "Search Requirements" }, { "code": null, "e": 53682, "s": 53648, "text": "Search Requirements Specification" }, { "code": null, "e": 53700, "s": 53682, "text": "Search Test Cases" }, { "code": null, "e": 53723, "s": 53700, "text": "Common Search Text Box" }, { "code": null, "e": 53991, "s": 53723, "text": "As seen in the following screenshot, at the top, there is a search text box used to find the specific test case. Usually a test case ID starts with SP-<index>. You can enter numbers to find a specific test case directly. This text box is present across all the pages." }, { "code": null, "e": 54090, "s": 53991, "text": "In the requirement specification section, TestLink supports the Search Requirements functionality." }, { "code": null, "e": 54155, "s": 54090, "text": "Following steps should be performed to use Search Requirements −" }, { "code": null, "e": 54235, "s": 54155, "text": "Step 1 − Go to Requirement Specifications → Search Requirements as shown below." }, { "code": null, "e": 54273, "s": 54235, "text": "It opens the Requirement Search page." }, { "code": null, "e": 54371, "s": 54273, "text": "The search is not case sensitive. Result includes just requirements from the actual Test Project." }, { "code": null, "e": 54459, "s": 54371, "text": "Step 2 − Write the searched string to an appropriate box. Leave unused fields as blank." }, { "code": null, "e": 54533, "s": 54459, "text": "Step 3 − Choose the required keyword or leave the value as 'Not applied'." }, { "code": null, "e": 54605, "s": 54533, "text": "It has the following list of supported fields to find the requirement −" }, { "code": null, "e": 54819, "s": 54605, "text": "Req. Doc ID, Version, Title, Scope, Status, Type, Expected no. of test cases, Has relation of type, Creation Date from, Creation Date to, Modification Date from, Modification date to, Test Case ID and Log Message." }, { "code": null, "e": 54853, "s": 54819, "text": "Step 4 − Click the 'Find' button." }, { "code": null, "e": 54938, "s": 54853, "text": "All fulfilling requirements are shown. You can modify requirements via 'Title' link." }, { "code": null, "e": 55051, "s": 54938, "text": "In the requirement specification section, TestLink supports the Search Requirement Specifications functionality." }, { "code": null, "e": 55130, "s": 55051, "text": "Following steps should be performed to use Search Requirement Specifications −" }, { "code": null, "e": 55224, "s": 55130, "text": "Step 1 − Go to Requirement Specifications → Search Requirement Specifications as shown below." }, { "code": null, "e": 55393, "s": 55224, "text": "It opens the Requirement Specifications Search page. The search is not case sensitive. Result includes just the requirement specifications from the actual Test Project." }, { "code": null, "e": 55497, "s": 55393, "text": "Step 2 − Write the searched string to an appropriate box. Leave the unused fields in the form as blank." }, { "code": null, "e": 55571, "s": 55497, "text": "Step 3 − Choose the required keyword or leave the value as 'Not applied'." }, { "code": null, "e": 55658, "s": 55571, "text": "It has the following list of supported fields to find the requirement specifications −" }, { "code": null, "e": 55707, "s": 55658, "text": "Req. Doc ID, Title, Scope, Type and Log Message." }, { "code": null, "e": 55741, "s": 55707, "text": "Step 4 − Click the 'Find' button." }, { "code": null, "e": 55840, "s": 55741, "text": "All fulfilling requirement specifications are shown. You can modify requirements via 'Title' link." }, { "code": null, "e": 55930, "s": 55840, "text": "In the Test specification section, TestLink supports the Search Test Cases functionality." }, { "code": null, "e": 55996, "s": 55930, "text": "Following are the steps to be performed to use Search Test Cases." }, { "code": null, "e": 56088, "s": 55996, "text": "Step 1 − Go to Test Specification → Search Test Cases as shown in the following screenshot." }, { "code": null, "e": 56221, "s": 56088, "text": "It opens the Search Test Cases page. The search is not case sensitive. Result includes just test cases from the actual Test Project." }, { "code": null, "e": 56325, "s": 56221, "text": "Step 2 − Write the searched string to an appropriate box. Leave the unused fields in the form as blank." }, { "code": null, "e": 56399, "s": 56325, "text": "Step 3 − Choose the required keyword or leave the value as 'Not applied'." }, { "code": null, "e": 56469, "s": 56399, "text": "It has the following list of supported fields to find the test case −" }, { "code": null, "e": 56672, "s": 56469, "text": "Test case ID, Version, Title, Test Importance, Status, Summary, Pre-conditions, Steps, Expected Result, Created by, Edited by, Modified date from, Modification date to, Jolly or Keyword and Req. Doc ID." }, { "code": null, "e": 56706, "s": 56672, "text": "Step 4 − Click the 'Find' button." }, { "code": null, "e": 56787, "s": 56706, "text": "All fulfilling test cases are shown. You can modify test cases via 'Title' link." }, { "code": null, "e": 57133, "s": 56787, "text": "Keywords are used to categorize test cases. Keywords are ideal for filtering. It is not categorizing and placing the same test cases at one place; keywords help to bring test cases from different folders with the same scope together using the same keywords. For Example − Regression Test Cases, Smoke Test Cases, Solaris and Change Request, etc." }, { "code": null, "e": 57196, "s": 57133, "text": "To create keywords, you should have create keyword permission." }, { "code": null, "e": 57280, "s": 57196, "text": "Step 1 − Go to Test Project → Keyword Management from the dashboard as shown below." }, { "code": null, "e": 57355, "s": 57280, "text": "It opens the Keyword Management page along with the Create Keyword button." }, { "code": null, "e": 57412, "s": 57355, "text": "Step 2 − Click the Create Keyword button as shown below." }, { "code": null, "e": 57446, "s": 57412, "text": "It opens the Create Keyword page." }, { "code": null, "e": 57490, "s": 57446, "text": "Step 3 − Enter the Keyword and Description." }, { "code": null, "e": 57536, "s": 57490, "text": "Step 4 − Click the Save button a shown below." }, { "code": null, "e": 57602, "s": 57536, "text": "List of saved keywords gets displayed at Keyword Management page." }, { "code": null, "e": 57647, "s": 57602, "text": "Following are the steps to assign keywords −" }, { "code": null, "e": 57731, "s": 57647, "text": "Step 1 − Go to Test Project → Keyword Management from the dashboard as shown below." }, { "code": null, "e": 57812, "s": 57731, "text": "It opens the Keyword Management page along with the Assign to Test Cases button." }, { "code": null, "e": 57875, "s": 57812, "text": "Step 2 − Click the Assign to Test Cases button as shown below." }, { "code": null, "e": 57947, "s": 57875, "text": "Step 3 − Select a Test Suite or Test Case on the tree view on the left." }, { "code": null, "e": 58075, "s": 57947, "text": "The topmost box that shows up on the right hand side will allow you to assign the available keywords to every single test case." }, { "code": null, "e": 58161, "s": 58075, "text": "Step 4 − After selection, click the Save button as shown in the following screenshot." }, { "code": null, "e": 58230, "s": 58161, "text": "Finally, you will get a successful message that the item is updated." }, { "code": null, "e": 58285, "s": 58230, "text": "You can generate the Test Specification as a document." }, { "code": null, "e": 58394, "s": 58285, "text": "Step 1 − To generate a Test Specification, go to Test Specification → Test Specification from the dashboard." }, { "code": null, "e": 58432, "s": 58394, "text": "It opens the Test Specification page." }, { "code": null, "e": 58571, "s": 58432, "text": "Step 2 − Select the folder to generate a test specification document, either the root project folder or the suite folder on the left side." }, { "code": null, "e": 58668, "s": 58571, "text": "Step 3 − Click the Settings icon known as Action present on the right side panel as shown below." }, { "code": null, "e": 58709, "s": 58668, "text": "It opens the Test Suite Operations page." }, { "code": null, "e": 58856, "s": 58709, "text": "You can see two options − Test Spec document (HTML) on the new window and another option Download Test spec document (Pseudo word) as shown below." }, { "code": null, "e": 58939, "s": 58856, "text": "After clicking the option, you will get the Test specification details as follows." }, { "code": null, "e": 59108, "s": 58939, "text": "Requirements are high-level descriptions about particular system services, constraints, or a detailed specification generated during the requirements gathering process." }, { "code": null, "e": 59262, "s": 59108, "text": "TestLink supports Requirement Specification where you can create a Requirement and take various actions such as Edit, Delete, or Freeze the version, etc." }, { "code": null, "e": 59338, "s": 59262, "text": "To create a requirement, you should have the Create Requirement permission." }, { "code": null, "e": 59388, "s": 59338, "text": "Following are the steps to create a requirement −" }, { "code": null, "e": 59492, "s": 59388, "text": "Step 1 − Go to Requirement Specification → Requirement Specification from the dashboard as shown below." }, { "code": null, "e": 59584, "s": 59492, "text": "Step 2 − On the left side, Search the folder structure where you want to add a requirement." }, { "code": null, "e": 59665, "s": 59584, "text": "Step 3 − Click the Create button present on the right side panel as shown below." }, { "code": null, "e": 59783, "s": 59665, "text": "It opens the create requirement page where you can specify the Document ID, Title, Scope and the type of requirement." }, { "code": null, "e": 59865, "s": 59783, "text": "Step 4 − Click the Save button to add the requirement in the list as shown below." }, { "code": null, "e": 59921, "s": 59865, "text": "It adds the parent folder as Requirement Specification." }, { "code": null, "e": 60076, "s": 59921, "text": "Step 5 − Click the parent folder and then click the Settings icon known as Actions displayed on the right side panel as shown in the following screenshot." }, { "code": null, "e": 60114, "s": 60076, "text": "It shows Requirement Operations page." }, { "code": null, "e": 60189, "s": 60114, "text": "Step 6 − Click the Create button as displayed in the following screenshot." }, { "code": null, "e": 60230, "s": 60189, "text": "It displays the Create Requirement form." }, { "code": null, "e": 60299, "s": 60230, "text": "Step 7 − Enter the following fields before clicking the Save button." }, { "code": null, "e": 60336, "s": 60299, "text": "Document ID − Unique ID to identify." }, { "code": null, "e": 60373, "s": 60336, "text": "Document ID − Unique ID to identify." }, { "code": null, "e": 60431, "s": 60373, "text": "Title − A unique title and must be within 100 characters." }, { "code": null, "e": 60489, "s": 60431, "text": "Title − A unique title and must be within 100 characters." }, { "code": null, "e": 60526, "s": 60489, "text": "Scope − It is text into HTML format." }, { "code": null, "e": 60563, "s": 60526, "text": "Scope − It is text into HTML format." }, { "code": null, "e": 60671, "s": 60563, "text": "Status − It can have value as Valid, Draft, Review, Rework, Finish, implemented, Not testable and Obsolete." }, { "code": null, "e": 60779, "s": 60671, "text": "Status − It can have value as Valid, Draft, Review, Rework, Finish, implemented, Not testable and Obsolete." }, { "code": null, "e": 60908, "s": 60779, "text": "Type − It could have a value as Informational, Feature, Use Case, User Interface, Non-Functional, Constraint or System Function." }, { "code": null, "e": 61037, "s": 60908, "text": "Type − It could have a value as Informational, Feature, Use Case, User Interface, Non-Functional, Constraint or System Function." }, { "code": null, "e": 61122, "s": 61037, "text": "Number of test cases needed − An estimated test case needs to cover the requirement." }, { "code": null, "e": 61207, "s": 61122, "text": "Number of test cases needed − An estimated test case needs to cover the requirement." }, { "code": null, "e": 61296, "s": 61207, "text": "After clicking Save, the requirement gets added and is displayed with additional fields." }, { "code": null, "e": 61342, "s": 61296, "text": "Step 8 − Add Coverage by clicking the + icon." }, { "code": null, "e": 61477, "s": 61342, "text": "Step 9 − Add the relation of the current requirement with any existing requirement as parent, child, related to, blocks or depends on." }, { "code": null, "e": 61593, "s": 61477, "text": "In addition, you can attach a file as well for more details about requirement as shown in the following screenshot." }, { "code": null, "e": 61780, "s": 61593, "text": "Requirement Overview is one of the useful features of TestLink. You can see all the listed requirements at one place along with all the available versions in case there is more than one." }, { "code": null, "e": 61870, "s": 61780, "text": "Go to Requirement Specification → Requirement Overview from the dashboard as shown below." }, { "code": null, "e": 61943, "s": 61870, "text": "It displays the Requirement Overview page with the list of requirements." }, { "code": null, "e": 62134, "s": 61943, "text": "This Overview shows all the requirements (last or all versions) and all the related attributes. In addition, all the defined custom fields for requirements is displayed in a separate column." }, { "code": null, "e": 62248, "s": 62134, "text": "The show all versions will be displayed if you check the checkbox at top “Show all versions of each requirement”." }, { "code": null, "e": 62485, "s": 62248, "text": "Coverage − A value of e.g. \"20% (4/20)\" means that 20 Test Cases have to be created for this Requirement to test it completely. 4 of those have already been created and linked to this Requirement, which makes the coverage of 20 percent." }, { "code": null, "e": 62546, "s": 62485, "text": "Following screenshot displays the Requirement Overview page." }, { "code": null, "e": 62716, "s": 62546, "text": "By clicking the pencil icon, you can edit the requirement details as shown in the above screenshot. It opens a new window along with the requirement detail in edit mode." }, { "code": null, "e": 63184, "s": 62716, "text": "TestLink supports the feature to assign Test Case for execution to different users. Assigning test cases affects both the execution and reports. On the execution page, you can sort the executable Test Cases to view whom they are assigned to. In the reports section, you can see the remaining test cases grouped by the tester’s name. If there are no test cases assigned to a tester, it defaults to none. A Tester can also see the metrics of his/her own executed tests." }, { "code": null, "e": 63232, "s": 63184, "text": "Following are the steps to assign a test case −" }, { "code": null, "e": 63331, "s": 63232, "text": "Step 1 − Go to Test Plan contents → Assign test cases execution from the dashboard as shown below." }, { "code": null, "e": 63474, "s": 63331, "text": "Step 2 − On the left side of the screen, search the test suite and click it. It displays the details and test cases present on the right side." }, { "code": null, "e": 63626, "s": 63474, "text": "Step 3 − Select the test case to be assigned. Verify if any existing user is present. The ‘Assigned To’ field displays the user name if it is assigned." }, { "code": null, "e": 63780, "s": 63626, "text": "Step 4 − Go to Assign text box and start typing the name of the user. It will display the list of matched users, from which you can select the user name." }, { "code": null, "e": 63845, "s": 63780, "text": "Step 5 − Click the Save button present at the top of the screen." }, { "code": null, "e": 63950, "s": 63845, "text": "After assigning the test case, the user name appears in the Assigned to section along with a red symbol." }, { "code": null, "e": 64065, "s": 63950, "text": "Step 6 − If the assigned user needs to be removed, simply click the red symbol , it will remove the assigned user." }, { "code": null, "e": 64239, "s": 64065, "text": "Bulk user assignment is almost similar to a normal assignment. The only difference being multiple users can be assigned at a time to a single as well as multiple test cases." }, { "code": null, "e": 64290, "s": 64239, "text": "Following are the steps for bulk user assignment −" }, { "code": null, "e": 64411, "s": 64290, "text": "Step 1 − Go to Test Plan contents → Assign test cases execution from the dashboard as shown in the following screenshot." }, { "code": null, "e": 64545, "s": 64411, "text": "Step 2 − On the left side search the test suite and click it. It displays the details and test cases present on the right side panel." }, { "code": null, "e": 64725, "s": 64545, "text": "Step 3 − Select the multiple test cases to be assigned to multiple users. Verify if any existing user is present. The ‘Assigned To’ field displays the user name if it is assigned." }, { "code": null, "e": 64937, "s": 64725, "text": "Step 4 − Go to Bulk User Assignment test box at the top. Start typing the name of the user. It will display the list of matched users from where the user name can be selected. Add multiple users in the text box." }, { "code": null, "e": 65009, "s": 64937, "text": "Step 5 − Click the Do button present on the right side of the text box." }, { "code": null, "e": 65088, "s": 65009, "text": "It displays the users name in the Assign To field of each selected test cases." }, { "code": null, "e": 65160, "s": 65088, "text": "Step 6 − Click the Save button to assign the test cases to these users." }, { "code": null, "e": 65265, "s": 65160, "text": "After assigning the test case, the user name appears in the Assigned to section along with a red symbol." }, { "code": null, "e": 65380, "s": 65265, "text": "Step 7 − If the assigned user needs to be removed , simply click the red symbol, it will remove the assigned user." }, { "code": null, "e": 65481, "s": 65380, "text": "For bulk user removal, first select the test cases from which the assigned users need to be removed." }, { "code": null, "e": 65550, "s": 65481, "text": "Click “Do bulk user remove” button present on the top of the screen." }, { "code": null, "e": 65598, "s": 65550, "text": "It removes the assigned user of that test case." }, { "code": null, "e": 65837, "s": 65598, "text": "Platform means a place or configuration of system where a test case has to be executed. A platform can be different web browsers such as Chrome, Safari, IE, Mozilla, etc. or different operating systems, hardware devices or configurations." }, { "code": null, "e": 66076, "s": 65837, "text": "The chosen platforms should be associated with Test Plan where test cases are executed. A test project might need several platforms to test before releasing a product. Test cases must be connected with Platforms as well as Test Plans too." }, { "code": null, "e": 66223, "s": 66076, "text": "To use the Platform feature, it should be created first under Platform Management. You should have Platform Management right to create a platform." }, { "code": null, "e": 66269, "s": 66223, "text": "Following are the steps to create a platform." }, { "code": null, "e": 66354, "s": 66269, "text": "Step 1 − Go to Test Project → Platform Management from the dashboard as shown below." }, { "code": null, "e": 66396, "s": 66354, "text": "It displays the Platform Management page." }, { "code": null, "e": 66454, "s": 66396, "text": "Step 2 − Click the Create Platform button as shown below." }, { "code": null, "e": 66489, "s": 66454, "text": "It opens the Create platform form." }, { "code": null, "e": 66539, "s": 66489, "text": "Step 3 − Enter the Platform Name and Description." }, { "code": null, "e": 66571, "s": 66539, "text": "Step 4 − Click the Save button." }, { "code": null, "e": 66645, "s": 66571, "text": "After clicking Save, the platform gets listed in the Platform Management." }, { "code": null, "e": 66790, "s": 66645, "text": "Step 1 − Navigate to Test Project → Platform Management. It displays a list of all available platforms along with the delete symbol in red as X." }, { "code": null, "e": 66839, "s": 66790, "text": "Step 2 − Click the Delete symbol as shown below." }, { "code": null, "e": 66878, "s": 66839, "text": "A delete confirmation pop-up displays." }, { "code": null, "e": 66909, "s": 66878, "text": "Step 3 − Click the Yes button." }, { "code": null, "e": 66977, "s": 66909, "text": "The page gets refreshed and the platform is delisted from the page." }, { "code": null, "e": 67292, "s": 66977, "text": "Milestones are associated with the project and is one of the best ways to track the progress and timeline. It is similar to the small targets in a project. A milestone can be an important target such as a planned public software release, an internal test version, a new beta release for an important customer, etc." }, { "code": null, "e": 67572, "s": 67292, "text": "Once stakeholders add milestones to TestLink, the users can assign test runs to specific milestones. It helps to track the milestone’s progress separately. Especially, if multiple milestones are in progress in parallel or if the users have many test runs active at the same time." }, { "code": null, "e": 67616, "s": 67572, "text": "Following are the steps to add a milestone." }, { "code": null, "e": 67697, "s": 67616, "text": "Step 1 − Go to Test Plan → Milestone Overview from the dashboard as shown below." }, { "code": null, "e": 67755, "s": 67697, "text": "It opens the Milestone page along with the Create button." }, { "code": null, "e": 67804, "s": 67755, "text": "Step 2 − Click the Create button as shown below." }, { "code": null, "e": 67841, "s": 67804, "text": "It opens the Create Milestone forms." }, { "code": null, "e": 67894, "s": 67841, "text": "Step 3 − Enter the Name, Target Date and Start Date." }, { "code": null, "e": 68028, "s": 67894, "text": "There are sub-milestones as Complete test with high priority, Complete test with medium priority and Complete test with low priority." }, { "code": null, "e": 68091, "s": 68028, "text": "Step 4 − After entering the percentage, click the Save button." }, { "code": null, "e": 68182, "s": 68091, "text": "You can see the status and progress of the milestone as shown in the following screenshot." }, { "code": null, "e": 68324, "s": 68182, "text": "Step 1 − Navigate to Test Plan → Milestone Overview. It displays a list of all available milestones along with the delete symbol in red as X." }, { "code": null, "e": 68373, "s": 68324, "text": "Step 2 − Click the Delete symbol as shown below." }, { "code": null, "e": 68416, "s": 68373, "text": "A delete confirmation pop-up is displayed." }, { "code": null, "e": 68462, "s": 68416, "text": "Step 3 − Click the Yes button as shown below." }, { "code": null, "e": 68531, "s": 68462, "text": "The page gets refreshed and the Milestone is delisted from the page." }, { "code": null, "e": 68716, "s": 68531, "text": "Before starting the actual execution, setup of the execution suite is the required step to track the progress and the status of execution. This stage is called as test execution setup." }, { "code": null, "e": 68780, "s": 68716, "text": "Before execution, make sure the following documents are ready −" }, { "code": null, "e": 68840, "s": 68780, "text": "Test specification is written and mentioned in the project." }, { "code": null, "e": 68875, "s": 68840, "text": "Test Plan is created and reviewed." }, { "code": null, "e": 68942, "s": 68875, "text": "Test cases are created and mapped into the test plan for coverage." }, { "code": null, "e": 68989, "s": 68942, "text": "At least one build is created for the project." }, { "code": null, "e": 69068, "s": 68989, "text": "You should have proper permission for execution and to work in this test plan." }, { "code": null, "e": 69153, "s": 69068, "text": "Following are the steps to set the navigation and settings for executing test cases." }, { "code": null, "e": 69234, "s": 69153, "text": "Step 1 − Go to Test Execution → Execute Tests from the dashboard as shown below." }, { "code": null, "e": 69319, "s": 69234, "text": "It opens Execute Test page where Settings and Filters are present on the left panel." }, { "code": null, "e": 69371, "s": 69319, "text": "Along with these two, there is a tree menu as well." }, { "code": null, "e": 69431, "s": 69371, "text": "Step 2 − Select Test Plan and build at the setting section." }, { "code": null, "e": 69528, "s": 69431, "text": "Step 3 − In the filter section, you can narrow down the tree structure present below the filter." }, { "code": null, "e": 69605, "s": 69528, "text": "Following screenshots displays Navigation & Settings in execute tests page −" }, { "code": null, "e": 69744, "s": 69605, "text": "You should specify one of the active Builds to add test case execution results. If you do not specify, the latest build is set by default." }, { "code": null, "e": 69975, "s": 69744, "text": "Build label specifies the exact package of application under test for tracking purposes. Each Test Case may be run one or more times per Build. However, it's recommended that only one test cycle should be executed against a Build." }, { "code": null, "e": 70045, "s": 69975, "text": "Builds can be created by Test Leader using the Create New Build page." }, { "code": null, "e": 70166, "s": 70045, "text": "The tree menu in the navigation pane below the Filter section displays the filtered list of Test Cases in the Test Plan." }, { "code": null, "e": 70276, "s": 70166, "text": "By selecting the test case, it allows to open an appropriate Test Case for test execution on the right panel." }, { "code": null, "e": 70387, "s": 70276, "text": "Test Suites in the tree menu display Test Plan details and build details as shown in the following screenshot." }, { "code": null, "e": 70486, "s": 70387, "text": "Test execution is the process of executing the code and comparing the expected and actual results." }, { "code": null, "e": 70617, "s": 70486, "text": "By default, a test case remains in No Run status. Once a status is assigned to a test case, it cannot revert to the no Run status." }, { "code": null, "e": 70843, "s": 70617, "text": "A test case can be assigned a result as Passed, Failed or Blocked. TestLink supports to assign a result to individual test steps as well. You can assign Passed, Failed or Blocked status at each individual step of a test case." }, { "code": null, "e": 70930, "s": 70843, "text": "Passed − When a test case or step matches the expected result, it is marked as Passed." }, { "code": null, "e": 71017, "s": 70930, "text": "Passed − When a test case or step matches the expected result, it is marked as Passed." }, { "code": null, "e": 71110, "s": 71017, "text": "Failed − When a test case or step deviates from the expected result, it is marked as Failed." }, { "code": null, "e": 71203, "s": 71110, "text": "Failed − When a test case or step deviates from the expected result, it is marked as Failed." }, { "code": null, "e": 71311, "s": 71203, "text": "Blocked − When a test case or step cannot be executed due to an outstanding issue, it is marked as Blocked." }, { "code": null, "e": 71419, "s": 71311, "text": "Blocked − When a test case or step cannot be executed due to an outstanding issue, it is marked as Blocked." }, { "code": null, "e": 71502, "s": 71419, "text": "Once a test case or test step is executed, the result should be assigned to those." }, { "code": null, "e": 71569, "s": 71502, "text": "Following steps should be performed while insering a test result −" }, { "code": null, "e": 71662, "s": 71569, "text": "Step 1 − Go to Test Execution → Execution Tests or Test Cases Assigned to Me as shown below." }, { "code": null, "e": 71770, "s": 71662, "text": "Step 2 − Select the test case from the left panel. It displays all the details and steps of the test cases." }, { "code": null, "e": 71902, "s": 71770, "text": "Step 3 − In the test step, there are Execution Notes and Result column. After execution, you can enter comments as Execution Notes." }, { "code": null, "e": 71956, "s": 71902, "text": "Step 4 − Select Results as Passed, Failed or Blocked." }, { "code": null, "e": 72051, "s": 71956, "text": "You can also attach an image or screenshot file as an artefact in support of result selection." }, { "code": null, "e": 72159, "s": 72051, "text": "Step 5 − In the Notes/Description section present below, enter overall comment for the test case execution." }, { "code": null, "e": 72311, "s": 72159, "text": "Step 6 − On the right side of Notes/Description, Execution duration (min) is present. Enter the number of minutes spent while executing this test case." }, { "code": null, "e": 72495, "s": 72311, "text": "Step 7 − Below the Execution Duration text box, three icons are present to select the overall result status for the test case. Icons are Passed, Failed and Blocked from left to right." }, { "code": null, "e": 72575, "s": 72495, "text": "After selection, the overall result gets updated with all execution iterations." }, { "code": null, "e": 72718, "s": 72575, "text": "Step 8 − Click the Print icon to view detailed execution result. The symbol is present in Run Mode column at the extreme right as shown below." }, { "code": null, "e": 72804, "s": 72718, "text": "It opens a new window with details of execution and comment step-wise as shown below." }, { "code": null, "e": 72908, "s": 72804, "text": "You can delete the execution result by clicking the delete red symbol as X, present in Run Mode column." }, { "code": null, "e": 72971, "s": 72908, "text": "It opens a confirmation pop-up to delete. Click the OK button." }, { "code": null, "e": 73084, "s": 72971, "text": "Reports and Metrics group the results of execution at one place that helps to track the progress of the project." }, { "code": null, "e": 73210, "s": 73084, "text": "To access the Report and Metrics section, select Test Execution → Test Reports and Metrics from the dashboard as shown below." }, { "code": null, "e": 73408, "s": 73210, "text": "The left pane is used to navigate to each report and operate controls of reports behavior and display. The button “Print” initializes the printing of the right pane (no navigation will be printed)." }, { "code": null, "e": 73545, "s": 73408, "text": "You can print as HTML or Pseudo MS Word. You can also email the report in HTML format. The right pane displays a summary of each report." }, { "code": null, "e": 73681, "s": 73545, "text": "These metrics display the current status of a Test Plan by the following criteria - test suite, owner, milestone, priority and keyword." }, { "code": null, "e": 73845, "s": 73681, "text": "In addition to this, it also displays the basic metrics for all enabled builds. The current status is determined by the recent Build where Test Cases are executed." }, { "code": null, "e": 74024, "s": 73845, "text": "For instance, if a Test Case is executed in multiple builds, only the latest result is counted. Last Test Result is a concept used in many reports, and is determined as follows −" }, { "code": null, "e": 74177, "s": 74024, "text": "The order of Builds is created into a Test Plan. For example, if a test fails in Build 1, and is marked as pass in Build 2, the latest result will pass." }, { "code": null, "e": 74330, "s": 74177, "text": "The order of Builds is created into a Test Plan. For example, if a test fails in Build 1, and is marked as pass in Build 2, the latest result will pass." }, { "code": null, "e": 74559, "s": 74330, "text": "If a Test Case is executed multiple times on the same Build, the most recent execution will be considered. For example, if Build 3 is released and marked as “pass” at 1PM and marked as “fail” at 5PM – will be considered as fail." }, { "code": null, "e": 74788, "s": 74559, "text": "If a Test Case is executed multiple times on the same Build, the most recent execution will be considered. For example, if Build 3 is released and marked as “pass” at 1PM and marked as “fail” at 5PM – will be considered as fail." }, { "code": null, "e": 74983, "s": 74788, "text": "Test Cases listed as “No Run” in a Build is not considered. For example, if a test case is marked as “pass” in Build 1 and don't execute in Build 2, the last result will be considered as “pass”." }, { "code": null, "e": 75178, "s": 74983, "text": "Test Cases listed as “No Run” in a Build is not considered. For example, if a test case is marked as “pass” in Build 1 and don't execute in Build 2, the last result will be considered as “pass”." }, { "code": null, "e": 75295, "s": 75178, "text": "When you click General Test Plan Metrics on the left side of the screen, it displays all the results as shown below." }, { "code": null, "e": 75539, "s": 75295, "text": "Results by Top Level Test Suites − It lists the results of each top level suite. It displays the number of test cases with status as Passed, Failed, Blocked, Not run, and Completed (%). Results for top level suites include all children suites." }, { "code": null, "e": 75858, "s": 75539, "text": "Results by Build − It lists the execution results for every Build. For each Build, it displays the total Test Cases, total pass, % passed, total failed, % failed, blocked, % blocked, not run, and % not run. If a Test Case has been executed twice on the same Build, the most recent execution will be taken into account." }, { "code": null, "e": 76128, "s": 75858, "text": "Results by Keyword − It lists all the keywords assigned to cases in the current Test Plan, and the results associated with them. For each keyword, it displays the total Test Cases, total pass, % passed, total failed, % failed, blocked, % blocked, not run and % not run." }, { "code": null, "e": 76469, "s": 76128, "text": "In the Reports module, you can create, view, and export reports supported by TestLink. TestLink supports a wide range of reports at all phases of STLC to better track the progress such as test execution, requirements coverage, and test case creation details. These reports fetch the most important information to prepare any of the metrics." }, { "code": null, "e": 76704, "s": 76469, "text": "When you navigate to Test Reports and Metrics from the dashboard, it displays the list of available reports for different activities on the left panel. On the right panel, it displays the details of the selected report as shown below." }, { "code": null, "e": 76953, "s": 76704, "text": "This report displays all of the currently blocked, failed, passed or not run Test Cases. It shows the last test case execution result for each build. In addition, the last column shows the last test case execution result for the last created build." }, { "code": null, "e": 77129, "s": 76953, "text": "“Last Test Result” logic (which is described above under General Test Plan Metrics) is used to determine if a Test Case should be considered blocked, failed, passed or no run." }, { "code": null, "e": 77276, "s": 77129, "text": "Blocked and failed Test Case reports will display the associated bugs if the user is an associate of integrated bug tracking system with TestLink." }, { "code": null, "e": 77436, "s": 77276, "text": "To access the Test Result Matrix, click the Test Result Matrix on the left pane. it displays the report on the right side as shown in the following screenshot." }, { "code": null, "e": 77565, "s": 77436, "text": "This report is available in Test Report and Metrics, if the requirements are linked with test cases of the current Test Project." }, { "code": null, "e": 77677, "s": 77565, "text": "The Report is generated against one Requirement Specification document selected from Build and Status dropdown." }, { "code": null, "e": 77766, "s": 77677, "text": "There are two sections − metrics and results overview. Following metrics are available −" }, { "code": null, "e": 77795, "s": 77766, "text": "Total number of requirements" }, { "code": null, "e": 77824, "s": 77795, "text": "Requirements within TestLink" }, { "code": null, "e": 77859, "s": 77824, "text": "Requirements covered by Test Cases" }, { "code": null, "e": 77898, "s": 77859, "text": "Requirements not covered by Test Cases" }, { "code": null, "e": 77937, "s": 77898, "text": "Requirements not covered or not tested" }, { "code": null, "e": 77961, "s": 77937, "text": "Requirements not tested" }, { "code": null, "e": 78112, "s": 77961, "text": "Requirements are divided into four sections. Each requirement is listed together with all related Test Cases (colored according to Test Case result) −" }, { "code": null, "e": 78132, "s": 78112, "text": "Passed Requirements" }, { "code": null, "e": 78152, "s": 78132, "text": "Failed Requirements" }, { "code": null, "e": 78173, "s": 78152, "text": "Blocked Requirements" }, { "code": null, "e": 78199, "s": 78173, "text": "Not-executed Requirements" }, { "code": null, "e": 78250, "s": 78199, "text": "Following screenshot displays Requirement Report −" }, { "code": null, "e": 78370, "s": 78250, "text": "This report requires graphic library installed on the web server. “Last Test Result” logic is used for all four charts." }, { "code": null, "e": 78442, "s": 78370, "text": "To access the Charts, click the Charts on the left pane as shown below." }, { "code": null, "e": 78481, "s": 78442, "text": "Report contains the following charts −" }, { "code": null, "e": 78569, "s": 78481, "text": "Pie chart of overall passed / failed / blocked / and not run Test Cases as shown above." }, { "code": null, "e": 78617, "s": 78569, "text": "Bar chart of Results by Keyword as shown below." }, { "code": null, "e": 78673, "s": 78617, "text": "Bar chart of Results by Top Level Suite as shown below." }, { "code": null, "e": 78814, "s": 78673, "text": "The bars in the bar charts are colored such that the user can identify the approximate number of passed, failed, blocked, and not run cases." }, { "code": null, "e": 78821, "s": 78814, "text": " Print" }, { "code": null, "e": 78832, "s": 78821, "text": " Add Notes" } ]
YEAR() Function in SQL Server - GeeksforGeeks
11 Jan, 2021 YEAR() function :This function in SQL Server is used to return the year for a date stated. Features : This function is used to find the year for a date specified. This function comes under Date Functions. This function accepts only one parameter i.e, date. This function can also include time with the stated date. Syntax : YEAR(date) Parameter :This method accepts only one parameter as given below : date : Specified date from which the year is to be returned. Returns :It returns the year for a date specified. Example-1 :Using YEAR() function and getting the year from the date specified. SELECT YEAR('2020/01/02'); Output : 2020 Example-2 :Using YEAR() function with a variable and getting the year from the date specified. DECLARE @date VARCHAR(50); SET @date = '2017/07/05'; SELECT YEAR(@date); Output : 2017 Example-3 :Using YEAR() function with date as parameter which includes time as well. SELECT YEAR('2018/11/22 07:44'); Output : 2018 Example-4 :Using YEAR() function with a variable and a date as parameter which includes time as well. DECLARE @date VARCHAR(50); SET @date = '1995/05/13 23:59'; SELECT YEAR(@date); Output : 1995 Application :This function is used to find the year from a date specified. DBMS-SQL SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments SQL | DROP, TRUNCATE How to Select Data Between Two Dates and Times in SQL Server? SQL vs NoSQL: Which one is better to use? Advanced SQL Interview Questions SQL | OFFSET-FETCH Clause Insert multiple values into multiple tables using a single statement in SQL Server How to Update Multiple Columns in Single Update Statement in SQL? SQL | Comments SQL | CREATE Adding multiple constraints in a single table
[ { "code": null, "e": 23877, "s": 23849, "text": "\n11 Jan, 2021" }, { "code": null, "e": 23968, "s": 23877, "text": "YEAR() function :This function in SQL Server is used to return the year for a date stated." }, { "code": null, "e": 23979, "s": 23968, "text": "Features :" }, { "code": null, "e": 24040, "s": 23979, "text": "This function is used to find the year for a date specified." }, { "code": null, "e": 24082, "s": 24040, "text": "This function comes under Date Functions." }, { "code": null, "e": 24134, "s": 24082, "text": "This function accepts only one parameter i.e, date." }, { "code": null, "e": 24192, "s": 24134, "text": "This function can also include time with the stated date." }, { "code": null, "e": 24201, "s": 24192, "text": "Syntax :" }, { "code": null, "e": 24212, "s": 24201, "text": "YEAR(date)" }, { "code": null, "e": 24279, "s": 24212, "text": "Parameter :This method accepts only one parameter as given below :" }, { "code": null, "e": 24340, "s": 24279, "text": "date : Specified date from which the year is to be returned." }, { "code": null, "e": 24391, "s": 24340, "text": "Returns :It returns the year for a date specified." }, { "code": null, "e": 24470, "s": 24391, "text": "Example-1 :Using YEAR() function and getting the year from the date specified." }, { "code": null, "e": 24497, "s": 24470, "text": "SELECT YEAR('2020/01/02');" }, { "code": null, "e": 24506, "s": 24497, "text": "Output :" }, { "code": null, "e": 24511, "s": 24506, "text": "2020" }, { "code": null, "e": 24606, "s": 24511, "text": "Example-2 :Using YEAR() function with a variable and getting the year from the date specified." }, { "code": null, "e": 24679, "s": 24606, "text": "DECLARE @date VARCHAR(50);\nSET @date = '2017/07/05';\nSELECT YEAR(@date);" }, { "code": null, "e": 24688, "s": 24679, "text": "Output :" }, { "code": null, "e": 24693, "s": 24688, "text": "2017" }, { "code": null, "e": 24778, "s": 24693, "text": "Example-3 :Using YEAR() function with date as parameter which includes time as well." }, { "code": null, "e": 24811, "s": 24778, "text": "SELECT YEAR('2018/11/22 07:44');" }, { "code": null, "e": 24820, "s": 24811, "text": "Output :" }, { "code": null, "e": 24825, "s": 24820, "text": "2018" }, { "code": null, "e": 24927, "s": 24825, "text": "Example-4 :Using YEAR() function with a variable and a date as parameter which includes time as well." }, { "code": null, "e": 25006, "s": 24927, "text": "DECLARE @date VARCHAR(50);\nSET @date = '1995/05/13 23:59';\nSELECT YEAR(@date);" }, { "code": null, "e": 25015, "s": 25006, "text": "Output :" }, { "code": null, "e": 25020, "s": 25015, "text": "1995" }, { "code": null, "e": 25095, "s": 25020, "text": "Application :This function is used to find the year from a date specified." }, { "code": null, "e": 25104, "s": 25095, "text": "DBMS-SQL" }, { "code": null, "e": 25115, "s": 25104, "text": "SQL-Server" }, { "code": null, "e": 25119, "s": 25115, "text": "SQL" }, { "code": null, "e": 25123, "s": 25119, "text": "SQL" }, { "code": null, "e": 25221, "s": 25123, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25230, "s": 25221, "text": "Comments" }, { "code": null, "e": 25243, "s": 25230, "text": "Old Comments" }, { "code": null, "e": 25264, "s": 25243, "text": "SQL | DROP, TRUNCATE" }, { "code": null, "e": 25326, "s": 25264, "text": "How to Select Data Between Two Dates and Times in SQL Server?" }, { "code": null, "e": 25368, "s": 25326, "text": "SQL vs NoSQL: Which one is better to use?" }, { "code": null, "e": 25401, "s": 25368, "text": "Advanced SQL Interview Questions" }, { "code": null, "e": 25427, "s": 25401, "text": "SQL | OFFSET-FETCH Clause" }, { "code": null, "e": 25510, "s": 25427, "text": "Insert multiple values into multiple tables using a single statement in SQL Server" }, { "code": null, "e": 25576, "s": 25510, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 25591, "s": 25576, "text": "SQL | Comments" }, { "code": null, "e": 25604, "s": 25591, "text": "SQL | CREATE" } ]
Apache Bench - Quick Guide
Performance testing has proved itself to be crucial for the success of a business. Not only does a poor performing site face financial losses, it can also lead to legal repercussions at times. No one wants to put up with a slow performing, unreliable site in important online interactions such as purchasing, online test taking, bill payment, etc. With the Internet being so widely available, the range of alternatives is immense. It is easier to lose clientele than gain them and performance is a key game changer. If we can understand what is the need for a load testing tool, it will give us the reason and motivation to use it. Some famous business sites have suffered serious downtimes when they get large number of visitors. E-commerce websites invest heavily in advertising campaigns, but not in Load Testing. Therefore, they fail to ensure optimal system performance, when that marketing brings in traffic. Another familiar example of ignoring load testing is that of “error establishing connection” in WordPress websites. Therefore, it is a good idea to load test a website or application before its deployment in production. It is nice to quickly establish a best-case scenario for a project before running more detailed tests down the road. Apache Bench (ab) is a tool from the Apache organization for benchmarking a Hypertext Transfer Protocol (HTTP) web server. Although it is designed to measure the performance of Apache web server, yet it can also be used to test any other web server that is equally good. With this tool, you can quickly know how many requests per second your web server is capable of serving. Let us see the important features and limitations of Apache Bench. The features and limitations are listed below − Being an open source software, it is freely available. Being an open source software, it is freely available. It is a simple command line computer program. It is a simple command line computer program. It is a platform-independent tool. It means that it can be invoked on Linux/Unix or on Windows server equally well. It is a platform-independent tool. It means that it can be invoked on Linux/Unix or on Windows server equally well. It can conduct load and performance test for only web server - HTTP or HTTPS. It can conduct load and performance test for only web server - HTTP or HTTPS. It is not extensible. It is not extensible. Apache Bench uses only one operating system thread irrespective of the concurrency level (specified by the -c flag). Therefore, when benchmarking high-capacity servers, a single instance of Apache Bench can itself be a bottleneck. To completely saturate the target URL, it is better to use additional instances of Apache Bench in parallel, if your server has multiple processor cores. You need to be aware that there is no directive in the Apache Bench to increase concurrency in particular intervals while running tests. Therefore, running load tests using ab is equivalent to a denial-of-service (DOS) attack. It is recommended that you inform and take prior permission from your VPS service provider if you are going to do heavy load testing for a long period of time. They will allot you an appropriate time interval or shift your node for the load testing task. Second, if you are testing a third person’s website continuously and for a long time just for learning Apache Bench from your VPS (which becomes the testing node), there is a remote possibility that your VPS public IP can be blocked by the third person’s website permanently. In that case, you will not be able to connect to that website with the same IP. But if you really want to connect to the website in future, the only solution will be to talk to the system administrator of the target website, or create a new instance of the server with a different IP with the help of your VPS service provider. Having warned you, let me assure you that all tests in this tutorial are safe enough and out of what system administrators generally call "system abuse" practices. In this chapter, we will guide you how to set up your environment for Apache Bench on your VPS. Memory − 128 MB Memory − 128 MB Disk Space − No minimum requirement Disk Space − No minimum requirement Operating System − No minimum requirement Operating System − No minimum requirement Apache Bench is a stand-alone application, and has no dependencies on the Apache web server installation. The following is a two-step process to install Apache Bench. Step 1 − Update package database. # apt-get update Please note that symbol # before a terminal command means that root user is issuing that command. Step 2 − Install apache2 utils package to get access to Apache Bench. # apt-get install apache2-utils Apache Bench is now installed. If you want to test a web application hosted on the same VPS, then it is enough to install the Apache web server only − # apt-get install apache2 Being an Apache utility, Apache Bench is automatically installed on installation of the Apache web server. Let us now see how to verify Apache Bench Installation. The following code will help verify the installation − # ab -V Output This is ApacheBench, Version 2.3 <$Revision: 1604373 $> Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ Licensed to The Apache Software Foundation, http://www.apache.org/ When you see the above terminal output, it means you have successfully installed Apache Bench. From the safety point of view, it is considered a good practice for system administrator to create a sudo user instead of working as root. We will create a test user, named test, for the purpose − # useradd -m -d /home/test -g sudo test Let us set the password for the new user − # passwd test System will prompt for a new password for the user test. You can enter a simple password as we are just testing, and not deploying to the production server. Usually the sudo command will prompt you to provide the sudo user password; it is recommended not to use complicated password as the process becomes cumbersome. Output Enter new UNIX password: Retype new UNIX password: passwd: password updated successfully In this section, we will test the Apache.org Website. Let us first switch to the sudo user test − # su test To begin with, we will test the website of Apache organization, https://www.apache.org/. We will first run the command, and then understand the output − $ ab -n 100 -c 10 https://www.apache.org/ Here -n is the number of requests to perform for the benchmarking session. The default is to just perform a single request which usually leads to non-representative benchmarking results. And -c is the concurrency and denotes the number of multiple requests to perform at a time. Default is one request at a time. So in this test, Apache Bench will make 100 requests with concurrency 10 to the Apache organization server. Output This is ApacheBench, Version 2.3 <$Revision: 1604373 $> Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ Licensed to The Apache Software Foundation, http://www.apache.org/ Benchmarking www.apache.org (be patient).....done Server Software: Apache/2.4.7 Server Hostname: www.apache.org Server Port: 443 SSL/TLS Protocol: TLSv1.2,ECDHE-RSA-AES256-GCM-SHA384,2048,256 Document Path: / Document Length: 58769 bytes Concurrency Level: 10 Time taken for tests: 1.004 seconds Complete requests: 100 Failed requests: 0 Total transferred: 5911100 bytes HTML transferred: 5876900 bytes Requests per second: 99.56 [#/sec] (mean) Time per request: 100.444 [ms] (mean) Time per request: 10.044 [ms] (mean, across all concurrent requests) Transfer rate: 5747.06 [Kbytes/sec] received Connection Times (ms) min mean[+/-sd] median max Connect: 39 46 30.9 41 263 Processing: 37 40 21.7 38 255 Waiting: 12 15 21.7 13 230 Total: 77 86 37.5 79 301 Percentage of the requests served within a certain time (ms) 50% 79 66% 79 75% 80 80% 80 90% 82 95% 84 98% 296 99% 301 100% 301 (longest request) Having run our first test, it will be easy to recognize the pattern of use for this command which is as follows − # ab [options .....] URL where, ab − Apache Bench command ab − Apache Bench command options − flags for particular task we want to perform options − flags for particular task we want to perform URL − path url we want to test URL − path url we want to test We need to understand the different metrics to understand the various output values returned by ab. Here goes the list − Server Software − It is the name of the web server returned in the HTTP header of the first successful return. Server Software − It is the name of the web server returned in the HTTP header of the first successful return. Server Hostname − It is the DNS or IP address given on the command line. Server Hostname − It is the DNS or IP address given on the command line. Server Port − It is the port to which ab is connecting. If no port is given on the command line, this will default to 80 for http and 443 for https. Server Port − It is the port to which ab is connecting. If no port is given on the command line, this will default to 80 for http and 443 for https. SSL/TLS Protocol − This is the protocol parameter negotiated between the client and server. This will only be printed if SSL is used. SSL/TLS Protocol − This is the protocol parameter negotiated between the client and server. This will only be printed if SSL is used. Document Path − This is the request URI parsed from the command line string. Document Path − This is the request URI parsed from the command line string. Document Length − It is the size in bytes of the first successfully returned document. If the document length changes during testing, the response is considered an error. Document Length − It is the size in bytes of the first successfully returned document. If the document length changes during testing, the response is considered an error. Concurrency Level − This is the number of concurrent clients (equivalent to web browsers) used during the test. Concurrency Level − This is the number of concurrent clients (equivalent to web browsers) used during the test. Time Taken for Tests − This is the time taken from the moment the first socket connection is created to the moment the last response is received. Time Taken for Tests − This is the time taken from the moment the first socket connection is created to the moment the last response is received. Complete Requests − The number of successful responses received. Complete Requests − The number of successful responses received. Failed Requests − The number of requests that were considered a failure. If the number is greater than zero, another line will be printed showing the number of requests that failed due to connecting, reading, incorrect content length, or exceptions. Failed Requests − The number of requests that were considered a failure. If the number is greater than zero, another line will be printed showing the number of requests that failed due to connecting, reading, incorrect content length, or exceptions. Total Transferred − The total number of bytes received from the server. This number is essentially the number of bytes sent over the wire. Total Transferred − The total number of bytes received from the server. This number is essentially the number of bytes sent over the wire. HTML Transferred − The total number of document bytes received from the server. This number excludes bytes received in HTTP headers HTML Transferred − The total number of document bytes received from the server. This number excludes bytes received in HTTP headers Requests per second − This is the number of requests per second. This value is the result of dividing the number of requests by the total time taken. Requests per second − This is the number of requests per second. This value is the result of dividing the number of requests by the total time taken. Time per request − The average time spent per request. The first value is calculated with the formula concurrency * timetaken * 1000 / done while the second value is calculated with the formula timetaken * 1000 / done Time per request − The average time spent per request. The first value is calculated with the formula concurrency * timetaken * 1000 / done while the second value is calculated with the formula timetaken * 1000 / done Transfer rate − The rate of transfer as calculated by the formula totalread / 1024 / timetaken. Transfer rate − The rate of transfer as calculated by the formula totalread / 1024 / timetaken. Having learned about the headings of the output values from the ab command, let us try to analyze and understand the output values for our initial test − Apache organisation is using their own web Server Software − Apache (version 2.4.7) Apache organisation is using their own web Server Software − Apache (version 2.4.7) Server is listening on Port 443 because of https. Had it been http, it would have been 80 (default). Server is listening on Port 443 because of https. Had it been http, it would have been 80 (default). Total data transferred is 58769 bytes for 100 requests. Total data transferred is 58769 bytes for 100 requests. Test completed in 1.004 seconds. There are no failed requests. Test completed in 1.004 seconds. There are no failed requests. Requests per seconds − 99.56. This is considered a pretty good number. Requests per seconds − 99.56. This is considered a pretty good number. Time per request − 100.444 ms (for 10 concurrent requests). So across all requests, it is 100.444 ms/10 = 10.044 ms. Time per request − 100.444 ms (for 10 concurrent requests). So across all requests, it is 100.444 ms/10 = 10.044 ms. Transfer rate − 1338.39 [Kbytes/sec] received. Transfer rate − 1338.39 [Kbytes/sec] received. In connection time statistics, you can observe that many requests had to wait for few seconds. This may be due to apache web server putting requests in wait queue. In connection time statistics, you can observe that many requests had to wait for few seconds. This may be due to apache web server putting requests in wait queue. In our first test, we had tested an application (i.e., www.apache.org) hosted on a different server. In the later part of the tutorial, we will be testing our sample web-applications hosted on the same server from which we will be running the ab tests. This is for the ease of learning and demonstration purpose. Ideally, the host node and testing node should be different for accurate measurement. To better learn ab, you should compare and observe how the output values vary for different cases as we move forward in this tutorial. Here we will plot the relevant outcome to see how much time the server takes as the number of requests increases. For that, we will add the -g option in the previous command followed by the file name (here out.data) in which the ab output data will be saved − $ ab -n 100 -c 10 -g out.data https://www.apache.org/ Let us now see the out.data before we create a plot − $ less out.data Output starttime seconds ctime dtime ttime wait Tue May 30 12:11:37 2017 1496160697 40 38 77 13 Tue May 30 12:11:37 2017 1496160697 42 38 79 13 Tue May 30 12:11:37 2017 1496160697 41 38 80 13 ... Let us now understand the column headers in the out.data file − starttime − This is the date and time at which the call started. starttime − This is the date and time at which the call started. seconds − Same as starttime but in the Unix timestamp format (date -d @1496160697 returns starttime output). seconds − Same as starttime but in the Unix timestamp format (date -d @1496160697 returns starttime output). ctime − This is the Connection Time. ctime − This is the Connection Time. dtime − This is the Processing Time. dtime − This is the Processing Time. ttime − This is the Total Time (it is the sum of ctime and dtime, mathematically ttime = ctime + dtime). ttime − This is the Total Time (it is the sum of ctime and dtime, mathematically ttime = ctime + dtime). wait − This is the Waiting Time. wait − This is the Waiting Time. For a pictorial visualization of how these multiple items are related to each other, take a look at the following image − If we are working over terminal or where graphics are not available, gnuplot is a great option. We will quickly understand it by going through the following steps. Let us install and launch gnuplot − $ sudo apt-get install gnuplot $ gnuplot Output G N U P L O T Version 4.6 patchlevel 6 last modified September 2014 Build System: Linux x86_64 Copyright (C) 1986-1993, 1998, 2004, 2007-2014 Thomas Williams, Colin Kelley and many others gnuplot home: http://www.gnuplot.info faq, bugs, etc: type "help FAQ" immediate help: type "help" (plot window: hit 'h') Terminal type set to 'qt' gnuplot> As we are working over terminal and supposing that graphics are not available, we can choose the dumb terminal which will give output in ASCII over the terminal itself. This helps us get an idea what our plot looks like with this quick tool. Let us now prepare the terminal for ASCII plot. gnuplot> set terminal dumb Output Terminal type set to 'dumb' Options are 'feed size 79, 24' As, our gnuplot terminal is now ready for ASCII plot, let us plot the data from the out.data file − gnuplot> plot "out.data" using 9 w l Output 1400 ++-----+------+-----+------+------+------+------+-----+------+-----++ + + + + + + +"out.data" using 9 ****** + | | 1200 ++ ******************************************** | ******************* | 1000 ++ * ++ | * | | * | 800 ++ * ++ | * | | * | 600 ++ * ++ | * | | * | 400 ++ * ++ | * | 200 ++ * ++ | * | +**** + + + + + + + + + + 0 ++-----+------+-----+------+------+------+------+-----+------+-----++ 0 10 20 30 40 50 60 70 80 90 100 We have plotted the ttime, total time (in ms) from column 9, with respect to the number of requests. We can notice that for the initial ten requests, the total time was in the nearly 100 ms, for next 30 requests (from 10th to 40th), it increased to 1100 ms, and so on. Your plot must be different depending on your out.data. In the previous chapter, we understood the basic use of the Apache Bench to test a third party website. In this section, we will use this tool to test a web application on our own server. To keep the tutorial self-contained to the extent possible, we have chosen to install a python application for the demonstration purpose; you can choose any other language like PHP or Ruby depending on your expertise level. Generally, Python is installed by default on Linux servers. Bottle is a micro-framework written in python for creating web applications, and pip is a python package manager. Type the following command in terminal to install Bottle − $ sudo apt-get install python-pip $ sudo pip install bottle Let us now create a small Bottle application. For that, create a directory and move inside it − $ mkdir webapp $ cd webapp We will create a new python script, app.py, inside the webapp directory − $ vim app.py Now, write the following code in the app.py file − from bottle import Bottle, run app = Bottle() @app.route('/') @app.route('/hello') def hello(): return "Hello World!" run(app, host = 'localhost', port = 8080) When you have added the above lines, save and close the file. Having saved the file, we can run the python script to launch the application − $ python app.py Output Bottle v0.12.7 server starting up (using WSGIRefServer())... Listening on http://localhost:8080/ Hit Ctrl-C to quit. This output shows that our application is running on the local machine at the host http://localhost and listening on the port 8080. Let us check if our app is responding properly to the HTTP requests. As this terminal cannot take any input without quitting serving the Bottle application, we need to login to our VPS with another terminal. After logging into the VPS with another terminal, you can navigate to your application by typing the following code in the new terminal. $ lynx http://localhost:8080/ Lynx is a command line browser and is usually installed by default in various Linux distributions like Debian and Ubuntu. If you see the following output, it means your app is working fine. Output If you see the above output, that means our application is live and ready for testing. Please note that there is a bug in ab, and it is not able to test the application on the localhost. So we will change the host from localhost to 127.0.0.1 in the app.py file. So the file will change to the following − from bottle import Bottle, run app = Bottle() @app.route('/') @app.route('/hello') def hello(): return "Hello World!" run(app, host = '127.0.0.1', port = 8080) Let us now test our app by typing the following command on the same terminal on which ran the lynx command − $ ab -n 100 -c 10 http://127.0.0.1:8080/hello Output This is ApacheBench, Version 2.3 <$Revision: 1604373 $> Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ Licensed to The Apache Software Foundation, http://www.apache.org/ Benchmarking 127.0.0.1 (be patient).....done Server Software: WSGIServer/0.1 Server Hostname: 127.0.0.1 Server Port: 8080 Document Path: /hello Document Length: 12 bytes Concurrency Level: 10 Time taken for tests: 0.203 seconds Complete requests: 100 Failed requests: 0 Total transferred: 16500 bytes HTML transferred: 1200 bytes Requests per second: 493.78 [#/sec] (mean) Time per request: 20.252 [ms] (mean) Time per request: 2.025 [ms] (mean, across all concurrent requests) Transfer rate: 79.56 [Kbytes/sec] received Connection Times (ms) min mean[+/-sd] median max Connect: 0 0 0.1 0 0 Processing: 1 6 28.2 2 202 Waiting: 1 6 28.2 2 202 Total: 1 6 28.2 2 202 Percentage of the requests served within a certain time (ms) 50% 2 66% 2 75% 2 80% 2 90% 2 95% 2 98% 202 99% 202 100% 202 (longest request) While the output on the first terminal will be (100 times) as follows − ... 127.0.0.1 - - [10/Jun/2017 04:30:26] "GET /hello HTTP/1.0" 200 12 127.0.0.1 - - [10/Jun/2017 04:30:26] "GET /hello HTTP/1.0" 200 12 127.0.0.1 - - [10/Jun/2017 04:30:26] "GET /hello HTTP/1.0" 200 12 ... You can observe how the various values of the ab outcome have changed as compared to the initial test. In the previous tests of ab, we have used the default web server bundled in the Bottle framework. Now we will change the single-threaded default web server with a multi-threaded one. Therefore, let us install a multi-threaded web server library like cherrypy or gunicorn and tell Bottle to use it. We have chosen gunicorn for the demonstration purpose here (you can choose some other one too) − $ sudo apt-get install gunicorn And modify the file, that is change from the default web server to gunicorn − ... run(server = 'gunicorn'...) ... Let us test the app in the second terminal. $ ab -n 100 -c 10 http://127.0.0.1:8080/hello Output This is ApacheBench, Version 2.3 <$Revision: 1604373 $> Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ Licensed to The Apache Software Foundation, http://www.apache.org/ Benchmarking 127.0.0.1 (be patient).....done Server Software: gunicorn/19.0.0 Server Hostname: 127.0.0.1 Server Port: 8080 Document Path: /hello Document Length: 12 bytes Concurrency Level: 10 Time taken for tests: 0.031 seconds Complete requests: 100 Failed requests: 0 Total transferred: 17200 bytes HTML transferred: 1200 bytes Requests per second: 3252.77 [#/sec] (mean) Time per request: 3.074 [ms] (mean) Time per request: 0.307 [ms] (mean, across all concurrent requests) Transfer rate: 546.36 [Kbytes/sec] received Connection Times (ms) min mean[+/-sd] median max Connect: 0 1 0.9 0 4 Processing: 1 2 0.7 3 4 Waiting: 0 2 0.8 2 3 Total: 2 3 0.6 3 5 WARNING: The median and mean for the initial connection time are not within a normal deviation These results are probably not that reliable. WARNING: The median and mean for the processing time are not within a normal deviation These results are probably not that reliable. Percentage of the requests served within a certain time (ms) 50% 3 66% 3 75% 3 80% 3 90% 4 95% 5 98% 5 99% 5 100% 5 (longest request) Observe how the Requests per second increased from 493 to 3252. It means gunicorn is suitable as a production server for python apps. In this chapter, we will learn how to test multiple URLs concurrently. For that, we will need to edit our application file, app.py to include two URLs − from bottle import Bottle, run app = Bottle() @app.route('/') @app.route('/hello1') def hello(): return "Hello World! It is first URL." @app.route('/hello2') def hello(): return "Hello World! It is second URL." run(app,server = 'gunicorn',host = '127.0.0.1', port = 8080) You can do this by creating a shell script, with multiple ab calls. Create a file test.sh and add the following lines to it − ab -n 100 -c 10 http://127.0.0.1:8080/hello1 ab -n 100 -c 10 http://127.0.0.1:8080/hello2 When you have added the above lines, Save and Close the file. Make the file executable − chmod u+x test.sh Let us now run the script − ./test.sh To avoid repetition and purpose of clarity, we will show only the relevant of the ab output, indicating by dots what portion has been omitted, as in the following. . . . Document Path: /hello1 Document Length: 732 bytes Concurrency Level: 10 Time taken for tests: 0.040 seconds Complete requests: 100 Failed requests: 0 Non-2xx responses: 100 Total transferred: 90000 bytes HTML transferred: 73200 bytes Requests per second: 2496.13 [#/sec] (mean) Time per request: 4.006 [ms] (mean) Time per request: 0.401 [ms] (mean, across all concurrent requests) Transfer rate: 2193.87 [Kbytes/sec] received Connection Times (ms) min mean[+/-sd] median max Connect: 0 0 0.8 0 3 Processing: 1 3 1.0 4 5 Waiting: 0 3 1.2 4 4 Total: 1 4 0.6 4 5 WARNING: The median and mean for the processing time are not within a normal deviation These results are probably not that reliable. . . . You can save the Apache Bench Output to file by creating a shell script, with multiple ab calls. At the end of each line, place an &; this makes the command run in the background, and lets the next command start its execution. You will also want to redirect the output to a file for each url using <filename>. For example, our file test.sh will look like the following after modification − $ ab -n 100 -c 10 http://127.0.0.1:8080/hello1 > test1.txt & $ ab -n 100 -c 10 http://127.0.0.1:8080/hello2 > test2.txt & Here, test1.txt and test2.txt are the files to save the output data. You can check that the above script has created two files, test1.txt and test2.txt which contains the ab output for the respective URLs − $ ls -l ... -rw-r--r-- 1 root root 5225 May 30 12:11 out.data -rwxr--r-- 1 root root 118 Jun 10 12:24 test.sh -rw-r--r-- 1 root root 1291 Jun 10 12:31 test1.txt -rwxr--r-- 1 root root 91 Jun 10 13:22 test2.sh -rw-r--r-- 1 root root 1291 Jun 10 12:31 test2.txt ... While using ab, you should be alert to the failed test without warning. For example, if you check a wrong URL, you may get something similar to the following (we have deliberately changed the port here). $ ab -l -r -n 100 -c 10 -k -H "Accept-Encoding: gzip, deflate" http://127.0.0.1:805/ This is ApacheBench, Version 2.3 <$Revision: 1604373 $> Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ Licensed to The Apache Software Foundation, http://www.apache.org/ Benchmarking 127.0.0.1 (be patient).....done Server Software: Server Hostname: 127.0.0.1 Server Port: 805 Document Path: / Document Length: Variable Concurrency Level: 10 Time taken for tests: 0.002 seconds Complete requests: 100 Failed requests: 150 (Connect: 0, Receive: 100, Length: 0, Exceptions: 50) Keep-Alive requests: 0 Total transferred: 0 bytes HTML transferred: 0 bytes Requests per second: 44984.26 [#/sec] (mean) Time per request: 0.222 [ms] (mean) Time per request: 0.022 [ms] (mean, across all concurrent requests) Transfer rate: 0.00 [Kbytes/sec] received Connection Times (ms) min mean[+/-sd] median max Connect: 0 0 0.0 0 0 Processing: 0 0 0.2 0 0 Waiting: 0 0 0.0 0 0 Total: 0 0 0.2 0 0 Percentage of the requests served within a certain time (ms) 50% 0 66% 0 75% 0 80% 0 90% 0 95% 0 98% 0 99% 0 100% 0 (longest request) In this chapter, we will understand the preparation required for testing dynamic pages. A server-side dynamic web page is a web page the construction of which is controlled by an application server processing server-side scripts. The apache bench can only load test the server-side dynamic web page. Concurrency level should be lower than the total number of requests. $ ab -l -r -n 30 -c 80 -k -H "Accept-Encoding: gzip, deflate" http://127.0.0.1:8000/ Output ab: Cannot use concurrency level greater than total number of requests Usage: ab [options] [http[s]://]hostname[:port]/path In this section, we will describe the use of some important flags with the ab command. We will use the terms, options and flags, interchangeably. The verbose option can be used to analyze and debug if there exist multiple number of failed requests. A common indication of failure of the load test is that the test finishes very fast and it gives a good number for request per second value. But it will be a wrong benchmark. To identify the success or failure, you can use the -v 2 option which will dump each response’s body and header to the terminal output. Following command depicts a use case − $ ab -n 1 -v 2 http://www.generic-example-URL.com/ Output LOG: header received: HTTP/1.0 200 OK ... Content-Length: 2548687 Of course, if you are testing variable responses or returning non-200 HTTP codes in the event of any error, you should simply ignore length checking with the -l option. We will soon see non-200 HTTP when we will launch a web2py application in the subsequent chapters. When the client sends HTTP request, the connection is made to the server, the server sends the response, and the connection is closed after it has sent the request. This cycle continues with each request. However, with the keep-alive setting (also known as persistent connections), the client maintains an underlying TCP connection open to facilitate multiple requests and response; this eliminates the slow and costly connection initialization time that would otherwise be present. If the web page is of variable length, then you should make use of the option -l. Apache Bench does not report errors if the length of the responses is not constant. This can be useful for dynamic pages. How to force ab not to exit on receiving errors? You should use the option -r. Without this option, your test may break as soon as any request hits the socket error. However, with this option, errors will be reported in the failed errors heading, but the test will continue till the end. This option is used to add arbitrary header line. The argument is typically in the form of a valid header line, containing a colon-separated field-value pair (i.e., “Accept-Encoding: zip/zop;8bit”). In the following section, we will learn in detail how to use the above options in combination with the option to use the cookie value, i.e., the -C option. The -C option is typically in the form of a name = value pair. This field can be repeated. To understand how to use the cookie with Apache Bench, we need a web page that tries to set a cookie. A very good example is the web2py application which is a python web framework. We are going to quickly install another python app web2py. You can read more on how to use it on Web2py Framework Overview. Python is generally installed by default on the Ubuntu and Debian server. Therefore, one requirement is already met to run web2py successfully. However, we need to install the unzip package to extract the source files of web2py from the zip file which we will be downloading − $ sudo apt-get update $ sudo apt-get install unzip Let us get the web2py framework from the project’s website. We will download this to our home folder − $cd ~ $ wget http://www.web2py.com/examples/static/web2py_src.zip Now, we can unzip the file we just downloaded and move inside − $ unzip web2py_src.zip $ cd web2py To run the web2py, you do not need to install it. Once you are inside the web2py directory, you can run it by typing the following command − $python web2py.py If everything is successful, you will see the following output where you will be asked to choose a password for the administrative UI − web2py Web Framework Created by Massimo Di Pierro, Copyright 2007-2017 Version 2.14.6-stable+timestamp.2016.05.10.00.21.47 Database drivers available: sqlite3, imaplib, pymysql, pg8000 WARNING:web2py:GUI not available because Tk library is not installed choose a password: please visit: http://127.0.0.1:8000/ use "kill -SIGTERM 23904" to shutdown the web2py server However, you need to be aware of the fact that the launched web interface is accessible on the local machine only. From the output, you can understand that to stop the web server, you will have to type “CTRL-C” in the instant terminal. On the other hand, to stop the web2py server on the other terminal related to the same VPS, you can insert the command kill -SIGTERM <PID>, where <PID> is the process ID for the web2py server, which in this case is 23904. If a page is only accessible by a logged in user, not directly accessible from the login page, in that case you can use the -C flag. This flag defines a cookie for the ab command. But you have to get the value of the session identifier cookie from a valid session. How to get that? Various online tutorials will guide you towards Chrome (or Mozilla) browser developer tools. But in our test case, as the application is available only on the command line, we will use the lynx browser to obtain the value. Let us get the cookie value of a session first. Open another terminal and type the following command − $ lynx http://127.0.0.1:8000/ In response to the above command, lynx will ask your permission to accept the cookie from the web2py server as shown in the image below. Note down the cookie value before typing y to accept the cookie. Now the terminal will look similar to the following image – website on the terminal! Having obtained the cookie value, we will now run the ab test. For that, we will have to open the third terminal (see the image below) − Now, let us use the -C flag in the third terminal − $ ab -n 100 -c 10 -C session_name = 127.0.0.1-643dad04-3c34 http://127.0.0.1:8000/ This is ApacheBench, Version 2.3 <$Revision: 1604373 $> Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ Licensed to The Apache Software Foundation, http://www.apache.org/ Benchmarking 127.0.0.1 (be patient).....done Server Software: Rocket Server Hostname: 127.0.0.1 Server Port: 8000 Document Path: / Document Length: 66 bytes Concurrency Level: 10 Time taken for tests: 0.051 seconds Complete requests: 100 Failed requests: 0 Non-2xx responses: 100 Total transferred: 27700 bytes HTML transferred: 6600 bytes Requests per second: 1968.12 [#/sec] (mean) Time per request: 5.081 [ms] (mean) Time per request: 0.508 [ms] (mean, across all concurrent requests) Transfer rate: 532.39 [Kbytes/sec] received Connection Times (ms) min mean[+/-sd] median max Connect: 1 2 0.9 2 4 Processing: 0 3 0.9 3 5 Waiting: 0 2 1.1 2 4 Total: 4 5 0.7 5 7 Percentage of the requests served within a certain time (ms) 50% 5 66% 5 75% 5 80% 6 90% 6 95% 6 98% 7 99% 7 100% 7 (longest request) From the output above, we note several points. First, web2py uses Rocket web server. We also note that we are getting ‘Non-2xx responses’ in addition to previously discussed headings in the output. In general, Http protocol responds to a request using a response code, and anything within the 200s range means ‘okay’, and the rest corresponds to some problem. For example, 400s are resource related errors such as 404 File Not Found. 500s correspond to server errors. In our instant case, there is no error anywhere except when we are using the -C option. It can be suppressed using the -l option as already described. In this section, we will understand how to check the admin page. For the purpose of comparison, let us test another URL of the web2py application − $ ab -n 100 -c 10 session_name = 127.0.0.1-643dad04-3c34 http://127.0.0.1:8000/admin This is ApacheBench, Version 2.3 <$Revision: 1604373 $> Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ Licensed to The Apache Software Foundation, http://www.apache.org/ Benchmarking 127.0.0.1 (be patient).....done Server Software: Rocket Server Hostname: 127.0.0.1 Server Port: 8000 Document Path: /admin Document Length: 8840 bytes Concurrency Level: 10 Time taken for tests: 2.077 seconds Complete requests: 100 Failed requests: 0 Total transferred: 926700 bytes HTML transferred: 884000 bytes Requests per second: 48.14 [#/sec] (mean) Time per request: 207.749 [ms] (mean) Time per request: 20.775 [ms] (mean, across all concurrent requests) Transfer rate: 435.61 [Kbytes/sec] received Connection Times (ms) min mean[+/-sd] median max Connect: 0 1 3.2 0 12 Processing: 62 204 52.2 199 400 Waiting: 61 203 52.0 199 400 Total: 62 205 54.3 199 411 Percentage of the requests served within a certain time (ms) 50% 199 66% 211 75% 220 80% 226 90% 264 95% 349 98% 381 99% 411 100% 411 (longest request) You should in particular note the respective statistics in section “Connection Times” and “Percentage of the requests served ...” of http://127.0.0.1:8000/ and http://127.0.0.1:8000/admin. There is a huge difference. Generally, Timelimit option is a tricky one. Let us understand this from the manual of ab, which is quite explanatory − -t timelimit Maximum number of seconds to spend for benchmarking. This implies a -n 50000 internally. Use this to benchmark the server within a fixed total amount of time. Per default there is no timelimit. Let us run a test with this option. We will note our observations after the going through the output − $ ab -n 100 -c 10 -t 60 http://127.0.0.1:8000/ This is ApacheBench, Version 2.3 <$Revision: 1604373 $> Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ Licensed to The Apache Software Foundation, http://www.apache.org/ Benchmarking 127.0.0.1 (be patient) Completed 5000 requests Completed 10000 requests Completed 15000 requests Completed 20000 requests Completed 25000 requests Completed 30000 requests Completed 35000 requests Completed 40000 requests Completed 45000 requests Completed 50000 requests Finished 50000 requests Server Software: Rocket Server Hostname: 127.0.0.1 Server Port: 8000 Document Path: / Document Length: 66 bytes Concurrency Level: 10 Time taken for tests: 22.547 seconds Complete requests: 50000 Failed requests: 0 Non-2xx responses: 50000 Total transferred: 13850000 bytes HTML transferred: 3300000 bytes Requests per second: 2217.61 [#/sec] (mean) Time per request: 4.509 [ms] (mean) Time per request: 0.451 [ms] (mean, across all concurrent requests) Transfer rate: 599.88 [Kbytes/sec] received Connection Times (ms) min mean[+/-sd] median max Connect: 0 2 0.8 2 8 Processing: 0 2 3.2 2 218 Waiting: 0 2 3.2 2 218 Total: 2 4 3.1 4 220 Percentage of the requests served within a certain time (ms) 50% 4 66% 4 75% 4 80% 5 90% 5 95% 5 98% 7 99% 8 100% 220 (longest request) Notice that the output shows this option overrides the number of requests specified by the -n option and continues upto the 50K requests. However, as the requests were handled very fast, ab has terminated as soon as 50k mark was achieved – within 22 seconds (see heading Time taken for tests) in the instant case. You can test the same command replacing http://127.0.0.1:8000/ with http://127.0.0.1:8000/admin (assuming it is our web2py application) or a third party website like https://www.apache.org/, notice the difference in statistics. There are a few checks which will help you successfully run the test, and measure the performance accurately. Consider the following conditions before performing the load test − Ensure that no extra python module is loaded. Ensure that no extra python module is loaded. To avoid TCP/IP Port Exhaustion, you should typically wait 2-3 minutes before you move to another ab test. To avoid TCP/IP Port Exhaustion, you should typically wait 2-3 minutes before you move to another ab test. Ensure that the number of concurrent connections are lower than Apache Worker Threads. Ensure that the number of concurrent connections are lower than Apache Worker Threads. You should reboot the server before performing another test, if Apache or python crashes. You should reboot the server before performing another test, if Apache or python crashes. In this chapter, we will describe the various combinations of -n and -c with the important flags to gradually increase the load on your webserver. You should mainly focus on how the following metrics change as you increase the load − Requests per second Connection Times (ms) Percentage of the requests served within a certain time (ms) You should also notice for the threshold value when server starts getting stuck and you start getting failed requests. Let us do 100 sequential page-loads by a single user − $ ab -l -r -n 100 -c 1 -k -H "Accept-Encoding: gzip, deflate" http://127.0.0.1:8000/ This is ApacheBench, Version 2.3 <$Revision: 1604373 $> Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ Licensed to The Apache Software Foundation, http://www.apache.org/ Benchmarking 127.0.0.1 (be patient).....done Server Software: Rocket Server Hostname: 127.0.0.1 Server Port: 8000 Document Path: / Document Length: Variable Concurrency Level: 1 Time taken for tests: 0.045 seconds Complete requests: 100 Failed requests: 0 Non-2xx responses: 100 Keep-Alive requests: 0 Total transferred: 27700 bytes HTML transferred: 6600 bytes Requests per second: 2206.24 [#/sec] (mean) Time per request: 0.453 [ms] (mean) Time per request: 0.453 [ms] (mean, across all concurrent requests) Transfer rate: 596.80 [Kbytes/sec] received Connection Times (ms) min mean[+/-sd] median max Connect: 0 0 0.0 0 0 Processing: 0 0 0.0 0 0 Waiting: 0 0 0.0 0 0 Total: 0 0 0.0 0 1 Percentage of the requests served within a certain time (ms) 50% 0 66% 0 75% 0 80% 0 90% 1 95% 1 98% 1 99% 1 100% 1 (longest request) This case corresponds to a peak load on a website that gets around 50,000+ hits a month. $ ab -l -r -n 10 -c 5 -k -H "Accept-Encoding: gzip, deflate" http://127.0.0.1:8000/ In the following subsequent outputs, we will be omitting the common header for clarity purpose. ... Requests per second: 2009.24 [#/sec] (mean) Time per request: 2.488 [ms] (mean) Time per request: 0.498 [ms] (mean, across all concurrent requests) Transfer rate: 543.52 [Kbytes/sec] received Connection Times (ms) min mean[+/-sd] median max Connect: 0 1 0.5 1 2 Processing: 0 1 0.5 1 2 Waiting: 0 1 0.5 1 1 Total: 2 2 0.4 3 3 ERROR: The median and mean for the total time are more than twice the standard deviation apart. These results are NOT reliable. Percentage of the requests served within a certain time (ms) 50% 3 66% 3 75% 3 80% 3 90% 3 95% 3 98% 3 99% 3 100% 3 (longest request) This test corresponds to 100 page loads by 10 different concurrent users, each user is doing 10 sequential pages loads. $ ab -r -n 10 -c 10 -k -H "Accept-Encoding: gzip, deflate" http://127.0.0.1:8000/ ... Requests per second: 2225.68 [#/sec] (mean) Time per request: 4.493 [ms] (mean) Time per request: 0.449 [ms] (mean, across all concurrent requests) Transfer rate: 602.07 [Kbytes/sec] received Connection Times (ms) min mean[+/-sd] median max Connect: 1 2 0.7 2 3 Processing: 0 2 1.0 2 3 Waiting: 0 1 1.0 2 3 Total: 4 4 0.3 4 4 WARNING: The median and mean for the waiting time are not within a normal deviation These results are probably not that reliable. Percentage of the requests served within a certain time (ms) 50% 4 66% 4 75% 4 80% 4 90% 4 95% 4 98% 4 99% 4 100% 4 (longest request) This test corresponds to 400 page loads by 20 different concurrent users, each user is doing 20 sequential pages loads. $ ab -r -n 20 -c 20 -k -H “Accept-Encoding: gzip, deflate” http://127.0.0.1:8000/ ... Requests per second: 1619.96 [#/sec] (mean) Time per request: 12.346 [ms] (mean) Time per request: 0.617 [ms] (mean, across all concurrent requests) Transfer rate: 438.21 [Kbytes/sec] received Connection Times (ms) min mean[+/-sd] median max Connect: 2 6 2.3 6 10 Processing: 1 5 2.9 5 10 Waiting: 0 5 2.9 5 9 Total: 10 11 0.6 11 12 Percentage of the requests served within a certain time (ms) 50% 11 66% 11 75% 12 80% 12 90% 12 95% 12 98% 12 99% 12 100% 12 (longest request) This test corresponds to 900 page loads by 30 different concurrent users, each user is doing 30 sequential pages loads. $ ab -r -n 30 -c 30 -k -H "Accept-Encoding: gzip, deflate" http://127.0.0.1:8000/ ... Requests per second: 2283.45 [#/sec] (mean) Time per request: 13.138 [ms] (mean) Time per request: 0.438 [ms] (mean, across all concurrent requests) Transfer rate: 617.69 [Kbytes/sec] received Connection Times (ms) min mean[+/-sd] median max Connect: 2 6 2.7 6 11 Processing: 1 6 3.1 6 11 Waiting: 0 5 3.2 5 10 Total: 11 12 0.5 12 13 Percentage of the requests served within a certain time (ms) 50% 12 66% 12 75% 12 80% 12 90% 13 95% 13 98% 13 99% 13 100% 13 (longest request) We have now learned how to increase the load gradually on the website and test its performance. In this chapter, we will compare the outputs with and without flags. Let us see how the use of appropriate flags can increase the performance of your web application. Before that, we need to understand how if your application is simple then you may not notice the difference. As is the case with our simple application, with flags and without flags. Then we will perform the same test with https://www.apache.org/ URL, and see the difference. In this section, we will understand how to test our application without flags. $ ab -n 100 -c 10 http://127.0.0.1:8000/ This is ApacheBench, Version 2.3 <$Revision: 1604373 $> Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ Licensed to The Apache Software Foundation, http://www.apache.org/ Benchmarking 127.0.0.1 (be patient).....done Server Software: Rocket Server Hostname: 127.0.0.1 Server Port: 8000 Document Path: / Document Length: Variable Concurrency Level: 10 Time taken for tests: 0.244 seconds Complete requests: 100 Failed requests: 0 Non-2xx responses: 100 Keep-Alive requests: 0 Total transferred: 27700 bytes HTML transferred: 6600 bytes Requests per second: 2208.77 [#/sec] (mean) Time per request: 4.527 [ms] (mean) Time per request: 0.453 [ms] (mean, across all concurrent requests) Transfer rate: 597.49 [Kbytes/sec] received Connection Times (ms) min mean[+/-sd] median max Connect: 1 2 0.7 2 3 Processing: 0 2 0.7 2 4 Waiting: 0 2 1.0 2 3 Total: 4 4 0.3 4 5 Percentage of the requests served within a certain time (ms) 50% 4 66% 4 75% 5 80% 5 90% 5 95% 5 98% 5 99% 5 100% 5 (longest request) In this section, we will understand how to test our application with flags. $ ab -l -r -n 100 -c 10 -k -H "Accept-Encoding: gzip, deflate" http://127.0.0.1:8000/ ... Requests per second: 2277.07 [#/sec] (mean) Time per request: 4.392 [ms] (mean) Time per request: 0.439 [ms] (mean, across all concurrent requests) Transfer rate: 615.97 [Kbytes/sec] received Connection Times (ms) min mean[+/-sd] median max Connect: 1 2 0.7 2 3 Processing: 0 2 0.7 2 4 Waiting: 0 2 1.0 2 3 Total: 4 4 0.2 4 5 Percentage of the requests served within a certain time (ms) 50% 4 66% 4 75% 4 80% 4 90% 5 95% 5 98% 5 99% 5 100% 5 (longest request) We can simply note that there is not much difference between the output statistics. Let us now see how to test the Apache Organisation Website without flags. $ ab -n 100 -c 10 http://www.apache.org/ This is ApacheBench, Version 2.3 <$Revision: 1604373 $> Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ Licensed to The Apache Software Foundation, http://www.apache.org/ Benchmarking www.apache.org (be patient).....done Server Software: Apache/2.4.7 Server Hostname: www.apache.org Server Port: 80 Document Path: / Document Length: 58433 bytes Concurrency Level: 10 Time taken for tests: 1.498 seconds Complete requests: 100 Failed requests: 0 Total transferred: 5877500 bytes HTML transferred: 5843300 bytes Requests per second: 66.74 [#/sec] (mean) Time per request: 149.840 [ms] (mean) Time per request: 14.984 [ms] (mean, across all concurrent requests) Transfer rate: 3830.58 [Kbytes/sec] received Connection Times (ms) min mean[+/-sd] median max Connect: 12 110 295.2 12 1012 Processing: 37 38 0.5 38 39 Waiting: 12 13 0.3 13 15 Total: 49 147 295.4 50 1051 Percentage of the requests served within a certain time (ms) 50% 50 66% 50 75% 50 80% 50 90% 816 95% 1050 98% 1051 99% 1051 100% 1051 (longest request) Let us now test the Apache Organisation Website with Flags. $ ab -l -r -n 100 -c 10 -k -H "Accept-Encoding: gzip, deflate" http://www.apache.org/ ... Document Length: Variable Concurrency Level: 10 Time taken for tests: 0.357 seconds Complete requests: 100 Failed requests: 0 Keep-Alive requests: 100 Total transferred: 1358510 bytes HTML transferred: 1317700 bytes Requests per second: 280.28 [#/sec] (mean) Time per request: 35.678 [ms] (mean) Time per request: 3.568 [ms] (mean, across all concurrent requests) Transfer rate: 3718.41 [Kbytes/sec] received Connection Times (ms) min mean[+/-sd] median max Connect: 0 1 3.7 0 12 Processing: 14 17 21.3 15 227 Waiting: 14 17 21.3 14 227 Total: 14 18 21.5 15 227 Percentage of the requests served within a certain time (ms) 50% 15 66% 15 75% 15 80% 15 90% 27 95% 28 98% 29 99% 227 100% 227 (longest request) You can simply note how the request per second increased with the use of flags. In the instant case, it is particularly due to use of -H "Accept-Encoding: gzip, deflate because this flag tells the Apache server to serve requests in gzipped format. A few important points need to be considered when it comes to the Apache Bench results. This will help us design our overall strategy to remove the bottlenecks in our application and improve its performance. We need to Requests Per Second. This gives us an idea of how well our web server set-up is working; the larger the number, the better the performance. Then comes the Connection Times (ms) and the Percentage of the requests served. You may have to tweak the settings of your web server to change these metrics to your desired performance. Check if there are errors in the Apache’s or the used web server error logs or (general) logs. As you will increase your load, things will start to choke: memory issues will start coming up. A lot of python scripts will begin to crash if they are not written with concurrency in mind. You need to find out what is the critical concurrency value above which your web server crashes and/or times-out? Normally this should happen at a fairly high concurrency level. If this value is low, something is wrong and you need to adjust these settings lower/higher. In this tutorial we learned how Apache Bench can be used to load test any web site or web application. Apache Bench can be a very valuable tool for determining how your web application server setup should be improved, to reduce bottlenecks and increase performance. Now that you are familiar with the basic usage of Apache Bench, you can start by creating new test plans to measure the performance of your applications in various scenarios. 46 Lectures 3.5 hours Arnab Chakraborty 23 Lectures 1.5 hours Mukund Kumar Mishra 16 Lectures 1 hours Nilay Mehta 52 Lectures 1.5 hours Bigdata Engineer 14 Lectures 1 hours Bigdata Engineer 23 Lectures 1 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2027, "s": 1834, "text": "Performance testing has proved itself to be crucial for the success of a business. Not only does a poor performing site face financial losses, it can also lead to legal repercussions at times." }, { "code": null, "e": 2350, "s": 2027, "text": "No one wants to put up with a slow performing, unreliable site in important online interactions such as purchasing, online test taking, bill payment, etc. With the Internet being so widely available, the range of alternatives is immense. It is easier to lose clientele than gain them and performance is a key game changer." }, { "code": null, "e": 2749, "s": 2350, "text": "If we can understand what is the need for a load testing tool, it will give us the reason and motivation to use it. Some famous business sites have suffered serious downtimes when they get large number of visitors. E-commerce websites invest heavily in advertising campaigns, but not in Load Testing. Therefore, they fail to ensure optimal system performance, when that marketing brings in traffic." }, { "code": null, "e": 3086, "s": 2749, "text": "Another familiar example of ignoring load testing is that of “error establishing connection” in WordPress websites. Therefore, it is a good idea to load test a website or application before its deployment in production. It is nice to quickly establish a best-case scenario for a project before running more detailed tests down the road." }, { "code": null, "e": 3462, "s": 3086, "text": "Apache Bench (ab) is a tool from the Apache organization for benchmarking a Hypertext Transfer Protocol (HTTP) web server. Although it is designed to measure the performance of Apache web server, yet it can also be used to test any other web server that is equally good. With this tool, you can quickly know how many requests per second your web server is capable of serving." }, { "code": null, "e": 3577, "s": 3462, "text": "Let us see the important features and limitations of Apache Bench. The features and limitations are listed below −" }, { "code": null, "e": 3632, "s": 3577, "text": "Being an open source software, it is freely available." }, { "code": null, "e": 3687, "s": 3632, "text": "Being an open source software, it is freely available." }, { "code": null, "e": 3733, "s": 3687, "text": "It is a simple command line computer program." }, { "code": null, "e": 3779, "s": 3733, "text": "It is a simple command line computer program." }, { "code": null, "e": 3895, "s": 3779, "text": "It is a platform-independent tool. It means that it can be invoked on Linux/Unix or on Windows server equally well." }, { "code": null, "e": 4011, "s": 3895, "text": "It is a platform-independent tool. It means that it can be invoked on Linux/Unix or on Windows server equally well." }, { "code": null, "e": 4089, "s": 4011, "text": "It can conduct load and performance test for only web server - HTTP or HTTPS." }, { "code": null, "e": 4167, "s": 4089, "text": "It can conduct load and performance test for only web server - HTTP or HTTPS." }, { "code": null, "e": 4189, "s": 4167, "text": "It is not extensible." }, { "code": null, "e": 4211, "s": 4189, "text": "It is not extensible." }, { "code": null, "e": 4596, "s": 4211, "text": "Apache Bench uses only one operating system thread irrespective of the concurrency level (specified by the -c flag). Therefore, when benchmarking high-capacity servers, a single instance of Apache Bench can itself be a bottleneck. To completely saturate the target URL, it is better to use additional instances of Apache Bench in parallel, if your server has multiple processor cores." }, { "code": null, "e": 5078, "s": 4596, "text": "You need to be aware that there is no directive in the Apache Bench to increase concurrency in particular intervals while running tests. Therefore, running load tests using ab is equivalent to a denial-of-service (DOS) attack. It is recommended that you inform and take prior permission from your VPS service provider if you are going to do heavy load testing for a long period of time. They will allot you an appropriate time interval or shift your node for the load testing task." }, { "code": null, "e": 5682, "s": 5078, "text": "Second, if you are testing a third person’s website continuously and for a long time just for learning Apache Bench from your VPS (which becomes the testing node), there is a remote possibility that your VPS public IP can be blocked by the third person’s website permanently. In that case, you will not be able to connect to that website with the same IP. But if you really want to connect to the website in future, the only solution will be to talk to the system administrator of the target website, or create a new instance of the server with a different IP with the help of your VPS service provider." }, { "code": null, "e": 5846, "s": 5682, "text": "Having warned you, let me assure you that all tests in this tutorial are safe enough and out of what system administrators generally call \"system abuse\" practices." }, { "code": null, "e": 5942, "s": 5846, "text": "In this chapter, we will guide you how to set up your environment for Apache Bench on your VPS." }, { "code": null, "e": 5958, "s": 5942, "text": "Memory − 128 MB" }, { "code": null, "e": 5974, "s": 5958, "text": "Memory − 128 MB" }, { "code": null, "e": 6010, "s": 5974, "text": "Disk Space − No minimum requirement" }, { "code": null, "e": 6046, "s": 6010, "text": "Disk Space − No minimum requirement" }, { "code": null, "e": 6088, "s": 6046, "text": "Operating System − No minimum requirement" }, { "code": null, "e": 6130, "s": 6088, "text": "Operating System − No minimum requirement" }, { "code": null, "e": 6297, "s": 6130, "text": "Apache Bench is a stand-alone application, and has no dependencies on the Apache web server installation. The following is a two-step process to install Apache Bench." }, { "code": null, "e": 6331, "s": 6297, "text": "Step 1 − Update package database." }, { "code": null, "e": 6349, "s": 6331, "text": "# apt-get update\n" }, { "code": null, "e": 6447, "s": 6349, "text": "Please note that symbol # before a terminal command means that root user is issuing that command." }, { "code": null, "e": 6517, "s": 6447, "text": "Step 2 − Install apache2 utils package to get access to Apache Bench." }, { "code": null, "e": 6550, "s": 6517, "text": "# apt-get install apache2-utils\n" }, { "code": null, "e": 6701, "s": 6550, "text": "Apache Bench is now installed. If you want to test a web application hosted on the same VPS, then it is enough to install the Apache web server only −" }, { "code": null, "e": 6728, "s": 6701, "text": "# apt-get install apache2\n" }, { "code": null, "e": 6835, "s": 6728, "text": "Being an Apache utility, Apache Bench is automatically installed on installation of the Apache web server." }, { "code": null, "e": 6946, "s": 6835, "text": "Let us now see how to verify Apache Bench Installation. The following code will help verify the installation −" }, { "code": null, "e": 6955, "s": 6946, "text": "# ab -V\n" }, { "code": null, "e": 6962, "s": 6955, "text": "Output" }, { "code": null, "e": 7159, "s": 6962, "text": "This is ApacheBench, Version 2.3 <$Revision: 1604373 $>\nCopyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/\nLicensed to The Apache Software Foundation, http://www.apache.org/\n" }, { "code": null, "e": 7254, "s": 7159, "text": "When you see the above terminal output, it means you have successfully installed Apache Bench." }, { "code": null, "e": 7451, "s": 7254, "text": "From the safety point of view, it is considered a good practice for system administrator to create a sudo user instead of working as root. We will create a test user, named test, for the purpose −" }, { "code": null, "e": 7492, "s": 7451, "text": "# useradd -m -d /home/test -g sudo test\n" }, { "code": null, "e": 7535, "s": 7492, "text": "Let us set the password for the new user −" }, { "code": null, "e": 7550, "s": 7535, "text": "# passwd test\n" }, { "code": null, "e": 7868, "s": 7550, "text": "System will prompt for a new password for the user test. You can enter a simple password as we are just testing, and not deploying to the production server. Usually the sudo command will prompt you to provide the sudo user password; it is recommended not to use complicated password as the process becomes cumbersome." }, { "code": null, "e": 7875, "s": 7868, "text": "Output" }, { "code": null, "e": 7968, "s": 7875, "text": "Enter new UNIX password:\nRetype new UNIX password: \npasswd: password updated successfully\n" }, { "code": null, "e": 8066, "s": 7968, "text": "In this section, we will test the Apache.org Website. Let us first switch to the sudo user test −" }, { "code": null, "e": 8077, "s": 8066, "text": "# su test\n" }, { "code": null, "e": 8230, "s": 8077, "text": "To begin with, we will test the website of Apache organization, https://www.apache.org/. We will first run the command, and then understand the output −" }, { "code": null, "e": 8273, "s": 8230, "text": "$ ab -n 100 -c 10 https://www.apache.org/\n" }, { "code": null, "e": 8460, "s": 8273, "text": "Here -n is the number of requests to perform for the benchmarking session. The default is to just perform a single request which usually leads to non-representative benchmarking results." }, { "code": null, "e": 8586, "s": 8460, "text": "And -c is the concurrency and denotes the number of multiple requests to perform at a time. Default is one request at a time." }, { "code": null, "e": 8694, "s": 8586, "text": "So in this test, Apache Bench will make 100 requests with concurrency 10 to the Apache organization server." }, { "code": null, "e": 8701, "s": 8694, "text": "Output" }, { "code": null, "e": 10040, "s": 8701, "text": "This is ApacheBench, Version 2.3 <$Revision: 1604373 $>\nCopyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/\nLicensed to The Apache Software Foundation, http://www.apache.org/\n\nBenchmarking www.apache.org (be patient).....done\n\nServer Software: Apache/2.4.7\nServer Hostname: www.apache.org\nServer Port: 443\nSSL/TLS Protocol: TLSv1.2,ECDHE-RSA-AES256-GCM-SHA384,2048,256\n\nDocument Path: /\nDocument Length: 58769 bytes\n\nConcurrency Level: 10\nTime taken for tests: 1.004 seconds\nComplete requests: 100\nFailed requests: 0\nTotal transferred: 5911100 bytes\nHTML transferred: 5876900 bytes\nRequests per second: 99.56 [#/sec] (mean)\nTime per request: 100.444 [ms] (mean)\nTime per request: 10.044 [ms] (mean, across all concurrent requests)\nTransfer rate: 5747.06 [Kbytes/sec] received\n\nConnection Times (ms)\n min mean[+/-sd] median max\nConnect: 39 46 30.9 41 263\nProcessing: 37 40 21.7 38 255\nWaiting: 12 15 21.7 13 230\nTotal: 77 86 37.5 79 301\n\nPercentage of the requests served within a certain time (ms)\n 50% 79\n 66% 79\n 75% 80\n 80% 80\n 90% 82\n 95% 84\n 98% 296\n 99% 301\n 100% 301 (longest request)\n" }, { "code": null, "e": 10154, "s": 10040, "text": "Having run our first test, it will be easy to recognize the pattern of use for this command which is as follows −" }, { "code": null, "e": 10181, "s": 10154, "text": "# ab [options .....] URL\n" }, { "code": null, "e": 10188, "s": 10181, "text": "where," }, { "code": null, "e": 10214, "s": 10188, "text": "ab − Apache Bench command" }, { "code": null, "e": 10240, "s": 10214, "text": "ab − Apache Bench command" }, { "code": null, "e": 10295, "s": 10240, "text": "options − flags for particular task we want to perform" }, { "code": null, "e": 10350, "s": 10295, "text": "options − flags for particular task we want to perform" }, { "code": null, "e": 10381, "s": 10350, "text": "URL − path url we want to test" }, { "code": null, "e": 10412, "s": 10381, "text": "URL − path url we want to test" }, { "code": null, "e": 10533, "s": 10412, "text": "We need to understand the different metrics to understand the various output values returned by ab. Here goes the list −" }, { "code": null, "e": 10644, "s": 10533, "text": "Server Software − It is the name of the web server returned in the HTTP header of the first successful return." }, { "code": null, "e": 10755, "s": 10644, "text": "Server Software − It is the name of the web server returned in the HTTP header of the first successful return." }, { "code": null, "e": 10828, "s": 10755, "text": "Server Hostname − It is the DNS or IP address given on the command line." }, { "code": null, "e": 10901, "s": 10828, "text": "Server Hostname − It is the DNS or IP address given on the command line." }, { "code": null, "e": 11050, "s": 10901, "text": "Server Port − It is the port to which ab is connecting. If no port is given on the command line, this will default to 80 for http and 443 for https." }, { "code": null, "e": 11199, "s": 11050, "text": "Server Port − It is the port to which ab is connecting. If no port is given on the command line, this will default to 80 for http and 443 for https." }, { "code": null, "e": 11333, "s": 11199, "text": "SSL/TLS Protocol − This is the protocol parameter negotiated between the client and server. This will only be printed if SSL is used." }, { "code": null, "e": 11467, "s": 11333, "text": "SSL/TLS Protocol − This is the protocol parameter negotiated between the client and server. This will only be printed if SSL is used." }, { "code": null, "e": 11544, "s": 11467, "text": "Document Path − This is the request URI parsed from the command line string." }, { "code": null, "e": 11621, "s": 11544, "text": "Document Path − This is the request URI parsed from the command line string." }, { "code": null, "e": 11792, "s": 11621, "text": "Document Length − It is the size in bytes of the first successfully returned document. If the document length changes during testing, the response is considered an error." }, { "code": null, "e": 11963, "s": 11792, "text": "Document Length − It is the size in bytes of the first successfully returned document. If the document length changes during testing, the response is considered an error." }, { "code": null, "e": 12075, "s": 11963, "text": "Concurrency Level − This is the number of concurrent clients (equivalent to web browsers) used during the test." }, { "code": null, "e": 12187, "s": 12075, "text": "Concurrency Level − This is the number of concurrent clients (equivalent to web browsers) used during the test." }, { "code": null, "e": 12333, "s": 12187, "text": "Time Taken for Tests − This is the time taken from the moment the first socket connection is created to the moment the last response is received." }, { "code": null, "e": 12479, "s": 12333, "text": "Time Taken for Tests − This is the time taken from the moment the first socket connection is created to the moment the last response is received." }, { "code": null, "e": 12544, "s": 12479, "text": "Complete Requests − The number of successful responses received." }, { "code": null, "e": 12609, "s": 12544, "text": "Complete Requests − The number of successful responses received." }, { "code": null, "e": 12859, "s": 12609, "text": "Failed Requests − The number of requests that were considered a failure. If the number is greater than zero, another line will be printed showing the number of requests that failed due to connecting, reading, incorrect content length, or exceptions." }, { "code": null, "e": 13109, "s": 12859, "text": "Failed Requests − The number of requests that were considered a failure. If the number is greater than zero, another line will be printed showing the number of requests that failed due to connecting, reading, incorrect content length, or exceptions." }, { "code": null, "e": 13248, "s": 13109, "text": "Total Transferred − The total number of bytes received from the server. This number is essentially the number of bytes sent over the wire." }, { "code": null, "e": 13387, "s": 13248, "text": "Total Transferred − The total number of bytes received from the server. This number is essentially the number of bytes sent over the wire." }, { "code": null, "e": 13519, "s": 13387, "text": "HTML Transferred − The total number of document bytes received from the server. This number excludes bytes received in HTTP headers" }, { "code": null, "e": 13651, "s": 13519, "text": "HTML Transferred − The total number of document bytes received from the server. This number excludes bytes received in HTTP headers" }, { "code": null, "e": 13801, "s": 13651, "text": "Requests per second − This is the number of requests per second. This value is the result of dividing the number of requests by the total time taken." }, { "code": null, "e": 13951, "s": 13801, "text": "Requests per second − This is the number of requests per second. This value is the result of dividing the number of requests by the total time taken." }, { "code": null, "e": 14169, "s": 13951, "text": "Time per request − The average time spent per request. The first value is calculated with the formula concurrency * timetaken * 1000 / done while the second value is calculated with the formula timetaken * 1000 / done" }, { "code": null, "e": 14387, "s": 14169, "text": "Time per request − The average time spent per request. The first value is calculated with the formula concurrency * timetaken * 1000 / done while the second value is calculated with the formula timetaken * 1000 / done" }, { "code": null, "e": 14483, "s": 14387, "text": "Transfer rate − The rate of transfer as calculated by the formula totalread / 1024 / timetaken." }, { "code": null, "e": 14579, "s": 14483, "text": "Transfer rate − The rate of transfer as calculated by the formula totalread / 1024 / timetaken." }, { "code": null, "e": 14733, "s": 14579, "text": "Having learned about the headings of the output values from the ab command, let us try to analyze and understand the output values for our initial test −" }, { "code": null, "e": 14817, "s": 14733, "text": "Apache organisation is using their own web Server Software − Apache (version 2.4.7)" }, { "code": null, "e": 14901, "s": 14817, "text": "Apache organisation is using their own web Server Software − Apache (version 2.4.7)" }, { "code": null, "e": 15002, "s": 14901, "text": "Server is listening on Port 443 because of https. Had it been http, it would have been 80 (default)." }, { "code": null, "e": 15103, "s": 15002, "text": "Server is listening on Port 443 because of https. Had it been http, it would have been 80 (default)." }, { "code": null, "e": 15159, "s": 15103, "text": "Total data transferred is 58769 bytes for 100 requests." }, { "code": null, "e": 15215, "s": 15159, "text": "Total data transferred is 58769 bytes for 100 requests." }, { "code": null, "e": 15278, "s": 15215, "text": "Test completed in 1.004 seconds. There are no failed requests." }, { "code": null, "e": 15341, "s": 15278, "text": "Test completed in 1.004 seconds. There are no failed requests." }, { "code": null, "e": 15412, "s": 15341, "text": "Requests per seconds − 99.56. This is considered a pretty good number." }, { "code": null, "e": 15483, "s": 15412, "text": "Requests per seconds − 99.56. This is considered a pretty good number." }, { "code": null, "e": 15600, "s": 15483, "text": "Time per request − 100.444 ms (for 10 concurrent requests). So across all requests, it is 100.444 ms/10 = 10.044 ms." }, { "code": null, "e": 15717, "s": 15600, "text": "Time per request − 100.444 ms (for 10 concurrent requests). So across all requests, it is 100.444 ms/10 = 10.044 ms." }, { "code": null, "e": 15764, "s": 15717, "text": "Transfer rate − 1338.39 [Kbytes/sec] received." }, { "code": null, "e": 15811, "s": 15764, "text": "Transfer rate − 1338.39 [Kbytes/sec] received." }, { "code": null, "e": 15975, "s": 15811, "text": "In connection time statistics, you can observe that many requests had to wait for few seconds. This may be due to apache web server putting requests in wait queue." }, { "code": null, "e": 16139, "s": 15975, "text": "In connection time statistics, you can observe that many requests had to wait for few seconds. This may be due to apache web server putting requests in wait queue." }, { "code": null, "e": 16538, "s": 16139, "text": "In our first test, we had tested an application (i.e., www.apache.org) hosted on a different server. In the later part of the tutorial, we will be testing our sample web-applications hosted on the same server from which we will be running the ab tests. This is for the ease of learning and demonstration purpose. Ideally, the host node and testing node should be different for accurate measurement." }, { "code": null, "e": 16673, "s": 16538, "text": "To better learn ab, you should compare and observe how the output values vary for different cases as we move forward in this tutorial." }, { "code": null, "e": 16933, "s": 16673, "text": "Here we will plot the relevant outcome to see how much time the server takes as the number of requests increases. For that, we will add the -g option in the previous command followed by the file name (here out.data) in which the ab output data will be saved −" }, { "code": null, "e": 16988, "s": 16933, "text": "$ ab -n 100 -c 10 -g out.data https://www.apache.org/\n" }, { "code": null, "e": 17042, "s": 16988, "text": "Let us now see the out.data before we create a plot −" }, { "code": null, "e": 17059, "s": 17042, "text": "$ less out.data\n" }, { "code": null, "e": 17066, "s": 17059, "text": "Output" }, { "code": null, "e": 17349, "s": 17066, "text": "starttime seconds ctime dtime ttime wait\nTue May 30 12:11:37 2017 1496160697 40 38 77 13\nTue May 30 12:11:37 2017 1496160697 42 38 79 13\nTue May 30 12:11:37 2017 1496160697 41 38 80 13\n...\n" }, { "code": null, "e": 17413, "s": 17349, "text": "Let us now understand the column headers in the out.data file −" }, { "code": null, "e": 17478, "s": 17413, "text": "starttime − This is the date and time at which the call started." }, { "code": null, "e": 17543, "s": 17478, "text": "starttime − This is the date and time at which the call started." }, { "code": null, "e": 17652, "s": 17543, "text": "seconds − Same as starttime but in the Unix timestamp format (date -d @1496160697 returns starttime output)." }, { "code": null, "e": 17761, "s": 17652, "text": "seconds − Same as starttime but in the Unix timestamp format (date -d @1496160697 returns starttime output)." }, { "code": null, "e": 17798, "s": 17761, "text": "ctime − This is the Connection Time." }, { "code": null, "e": 17835, "s": 17798, "text": "ctime − This is the Connection Time." }, { "code": null, "e": 17872, "s": 17835, "text": "dtime − This is the Processing Time." }, { "code": null, "e": 17909, "s": 17872, "text": "dtime − This is the Processing Time." }, { "code": null, "e": 18014, "s": 17909, "text": "ttime − This is the Total Time (it is the sum of ctime and dtime, mathematically ttime = ctime + dtime)." }, { "code": null, "e": 18119, "s": 18014, "text": "ttime − This is the Total Time (it is the sum of ctime and dtime, mathematically ttime = ctime + dtime)." }, { "code": null, "e": 18152, "s": 18119, "text": "wait − This is the Waiting Time." }, { "code": null, "e": 18185, "s": 18152, "text": "wait − This is the Waiting Time." }, { "code": null, "e": 18307, "s": 18185, "text": "For a pictorial visualization of how these multiple items are related to each other, take a look at the following image −" }, { "code": null, "e": 18471, "s": 18307, "text": "If we are working over terminal or where graphics are not available, gnuplot is a great option. We will quickly understand it by going through the following steps." }, { "code": null, "e": 18507, "s": 18471, "text": "Let us install and launch gnuplot −" }, { "code": null, "e": 18551, "s": 18507, "text": "$ sudo apt-get install gnuplot \n$ gnuplot\n" }, { "code": null, "e": 18558, "s": 18551, "text": "Output" }, { "code": null, "e": 18918, "s": 18558, "text": "G N U P L O T\nVersion 4.6 patchlevel 6 last modified September 2014\nBuild System: Linux x86_64\n\nCopyright (C) 1986-1993, 1998, 2004, 2007-2014\nThomas Williams, Colin Kelley and many others\n\ngnuplot home: http://www.gnuplot.info\nfaq, bugs, etc: type \"help FAQ\"\nimmediate help: type \"help\" (plot window: hit 'h')\n\nTerminal type set to 'qt'\ngnuplot>\n" }, { "code": null, "e": 19208, "s": 18918, "text": "As we are working over terminal and supposing that graphics are not available, we can choose the dumb terminal which will give output in ASCII over the terminal itself. This helps us get an idea what our plot looks like with this quick tool. Let us now prepare the terminal for ASCII plot." }, { "code": null, "e": 19236, "s": 19208, "text": "gnuplot> set terminal dumb\n" }, { "code": null, "e": 19243, "s": 19236, "text": "Output" }, { "code": null, "e": 19304, "s": 19243, "text": "Terminal type set to 'dumb'\nOptions are 'feed size 79, 24'\n" }, { "code": null, "e": 19404, "s": 19304, "text": "As, our gnuplot terminal is now ready for ASCII plot, let us plot the data from the out.data file −" }, { "code": null, "e": 19443, "s": 19404, "text": "gnuplot> plot \"out.data\" using 9 w l\n" }, { "code": null, "e": 19450, "s": 19443, "text": "Output" }, { "code": null, "e": 21069, "s": 19450, "text": " 1400 ++-----+------+-----+------+------+------+------+-----+------+-----++\n + + + + + + +\"out.data\" using 9 ****** +\n | |\n 1200 ++ ********************************************\n | ******************* |\n 1000 ++ * ++\n | * |\n | * |\n 800 ++ * ++\n | * |\n | * |\n 600 ++ * ++\n | * |\n | * |\n 400 ++ * ++\n | * |\n 200 ++ * ++\n | * |\n +**** + + + + + + + + + +\n 0 ++-----+------+-----+------+------+------+------+-----+------+-----++\n 0 10 20 30 40 50 60 70 80 90 100\n" }, { "code": null, "e": 21394, "s": 21069, "text": "We have plotted the ttime, total time (in ms) from column 9, with respect to the number of requests. We can notice that for the initial ten requests, the total time was in the nearly 100 ms, for next 30 requests (from 10th to 40th), it increased to 1100 ms, and so on. Your plot must be different depending on your out.data." }, { "code": null, "e": 21806, "s": 21394, "text": "In the previous chapter, we understood the basic use of the Apache Bench to test a third party website. In this section, we will use this tool to test a web application on our own server. To keep the tutorial self-contained to the extent possible, we have chosen to install a python application for the demonstration purpose; you can choose any other language like PHP or Ruby depending on your expertise level." }, { "code": null, "e": 21866, "s": 21806, "text": "Generally, Python is installed by default on Linux servers." }, { "code": null, "e": 22039, "s": 21866, "text": "Bottle is a micro-framework written in python for creating web applications, and pip is a python package manager. Type the following command in terminal to install Bottle −" }, { "code": null, "e": 22100, "s": 22039, "text": "$ sudo apt-get install python-pip\n$ sudo pip install bottle\n" }, { "code": null, "e": 22196, "s": 22100, "text": "Let us now create a small Bottle application. For that, create a directory and move inside it −" }, { "code": null, "e": 22224, "s": 22196, "text": "$ mkdir webapp\n$ cd webapp\n" }, { "code": null, "e": 22298, "s": 22224, "text": "We will create a new python script, app.py, inside the webapp directory −" }, { "code": null, "e": 22312, "s": 22298, "text": "$ vim app.py\n" }, { "code": null, "e": 22363, "s": 22312, "text": "Now, write the following code in the app.py file −" }, { "code": null, "e": 22529, "s": 22363, "text": "from bottle import Bottle, run\n\napp = Bottle()\n\n@app.route('/')\n@app.route('/hello')\ndef hello():\n return \"Hello World!\"\n\nrun(app, host = 'localhost', port = 8080)" }, { "code": null, "e": 22671, "s": 22529, "text": "When you have added the above lines, save and close the file. Having saved the file, we can run the python script to launch the application −" }, { "code": null, "e": 22688, "s": 22671, "text": "$ python app.py\n" }, { "code": null, "e": 22695, "s": 22688, "text": "Output" }, { "code": null, "e": 22813, "s": 22695, "text": "Bottle v0.12.7 server starting up (using WSGIRefServer())...\nListening on http://localhost:8080/\nHit Ctrl-C to quit.\n" }, { "code": null, "e": 22945, "s": 22813, "text": "This output shows that our application is running on the local machine at the host http://localhost and listening on the port 8080." }, { "code": null, "e": 23290, "s": 22945, "text": "Let us check if our app is responding properly to the HTTP requests. As this terminal cannot take any input without quitting serving the Bottle application, we need to login to our VPS with another terminal. After logging into the VPS with another terminal, you can navigate to your application by typing the following code in the new terminal." }, { "code": null, "e": 23321, "s": 23290, "text": "$ lynx http://localhost:8080/\n" }, { "code": null, "e": 23511, "s": 23321, "text": "Lynx is a command line browser and is usually installed by default in various Linux distributions like Debian and Ubuntu. If you see the following output, it means your app is working fine." }, { "code": null, "e": 23518, "s": 23511, "text": "Output" }, { "code": null, "e": 23605, "s": 23518, "text": "If you see the above output, that means our application is live and ready for testing." }, { "code": null, "e": 23823, "s": 23605, "text": "Please note that there is a bug in ab, and it is not able to test the application on the localhost. So we will change the host from localhost to 127.0.0.1 in the app.py file. So the file will change to the following −" }, { "code": null, "e": 23989, "s": 23823, "text": "from bottle import Bottle, run\n\napp = Bottle()\n\n@app.route('/')\n@app.route('/hello')\ndef hello():\n return \"Hello World!\"\n\nrun(app, host = '127.0.0.1', port = 8080)" }, { "code": null, "e": 24098, "s": 23989, "text": "Let us now test our app by typing the following command on the same terminal on which ran the lynx command −" }, { "code": null, "e": 24146, "s": 24098, "text": "$ ab -n 100 -c 10 http://127.0.0.1:8080/hello\n" }, { "code": null, "e": 24153, "s": 24146, "text": "Output" }, { "code": null, "e": 25411, "s": 24153, "text": "This is ApacheBench, Version 2.3 <$Revision: 1604373 $>\nCopyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/\nLicensed to The Apache Software Foundation, http://www.apache.org/\n\nBenchmarking 127.0.0.1 (be patient).....done\n\n\nServer Software: WSGIServer/0.1\nServer Hostname: 127.0.0.1\nServer Port: 8080\n\nDocument Path: /hello\nDocument Length: 12 bytes\n\nConcurrency Level: 10\nTime taken for tests: 0.203 seconds\nComplete requests: 100\nFailed requests: 0\nTotal transferred: 16500 bytes\nHTML transferred: 1200 bytes\nRequests per second: 493.78 [#/sec] (mean)\nTime per request: 20.252 [ms] (mean)\nTime per request: 2.025 [ms] (mean, across all concurrent requests)\nTransfer rate: 79.56 [Kbytes/sec] received\n\nConnection Times (ms)\n min mean[+/-sd] median max\nConnect: 0 0 0.1 0 0\nProcessing: 1 6 28.2 2 202\nWaiting: 1 6 28.2 2 202\nTotal: 1 6 28.2 2 202\n\nPercentage of the requests served within a certain time (ms)\n 50% 2\n 66% 2\n 75% 2\n 80% 2\n 90% 2\n 95% 2\n 98% 202\n 99% 202\n 100% 202 (longest request)\n" }, { "code": null, "e": 25483, "s": 25411, "text": "While the output on the first terminal will be (100 times) as follows −" }, { "code": null, "e": 25693, "s": 25483, "text": "...\n127.0.0.1 - - [10/Jun/2017 04:30:26] \"GET /hello HTTP/1.0\" 200 12\n127.0.0.1 - - [10/Jun/2017 04:30:26] \"GET /hello HTTP/1.0\" 200 12\n127.0.0.1 - - [10/Jun/2017 04:30:26] \"GET /hello HTTP/1.0\" 200 12 \n...\n" }, { "code": null, "e": 25796, "s": 25693, "text": "You can observe how the various values of the ab outcome have changed as compared to the initial test." }, { "code": null, "e": 25894, "s": 25796, "text": "In the previous tests of ab, we have used the default web server bundled in the Bottle framework." }, { "code": null, "e": 26191, "s": 25894, "text": "Now we will change the single-threaded default web server with a multi-threaded one. Therefore, let us install a multi-threaded web server library like cherrypy or gunicorn and tell Bottle to use it. We have chosen gunicorn for the demonstration purpose here (you can choose some other one too) −" }, { "code": null, "e": 26225, "s": 26191, "text": "$ sudo apt-get install gunicorn\n" }, { "code": null, "e": 26303, "s": 26225, "text": "And modify the file, that is change from the default web server to gunicorn −" }, { "code": null, "e": 26340, "s": 26303, "text": "...\nrun(server = 'gunicorn'...)\n...\n" }, { "code": null, "e": 26384, "s": 26340, "text": "Let us test the app in the second terminal." }, { "code": null, "e": 26432, "s": 26384, "text": "$ ab -n 100 -c 10 http://127.0.0.1:8080/hello\n" }, { "code": null, "e": 26439, "s": 26432, "text": "Output" }, { "code": null, "e": 27989, "s": 26439, "text": "This is ApacheBench, Version 2.3 <$Revision: 1604373 $>\nCopyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/\nLicensed to The Apache Software Foundation, http://www.apache.org/\n\nBenchmarking 127.0.0.1 (be patient).....done\n\n\nServer Software: gunicorn/19.0.0\nServer Hostname: 127.0.0.1\nServer Port: 8080\n\nDocument Path: /hello\nDocument Length: 12 bytes\n\nConcurrency Level: 10\nTime taken for tests: 0.031 seconds\nComplete requests: 100\nFailed requests: 0\nTotal transferred: 17200 bytes\nHTML transferred: 1200 bytes\nRequests per second: 3252.77 [#/sec] (mean)\nTime per request: 3.074 [ms] (mean)\nTime per request: 0.307 [ms] (mean, across all concurrent requests)\nTransfer rate: 546.36 [Kbytes/sec] received\n\nConnection Times (ms)\n min mean[+/-sd] median max\nConnect: 0 1 0.9 0 4\nProcessing: 1 2 0.7 3 4\nWaiting: 0 2 0.8 2 3\nTotal: 2 3 0.6 3 5\nWARNING: The median and mean for the initial connection time are not within a normal\n deviation These results are probably not that reliable.\nWARNING: The median and mean for the processing time are not within a normal deviation\n These results are probably not that reliable.\n\nPercentage of the requests served within a certain time (ms)\n 50% 3\n 66% 3\n 75% 3\n 80% 3\n 90% 4\n 95% 5\n 98% 5\n 99% 5\n 100% 5 (longest request)\n" }, { "code": null, "e": 28123, "s": 27989, "text": "Observe how the Requests per second increased from 493 to 3252. It means gunicorn is suitable as a production server for python apps." }, { "code": null, "e": 28276, "s": 28123, "text": "In this chapter, we will learn how to test multiple URLs concurrently. For that, we will need to edit our application file, app.py to include two URLs −" }, { "code": null, "e": 28558, "s": 28276, "text": "from bottle import Bottle, run\n\napp = Bottle()\n\n@app.route('/')\n@app.route('/hello1')\ndef hello():\n return \"Hello World! It is first URL.\"\n\n@app.route('/hello2')\ndef hello():\n return \"Hello World! It is second URL.\"\n\nrun(app,server = 'gunicorn',host = '127.0.0.1', port = 8080)" }, { "code": null, "e": 28684, "s": 28558, "text": "You can do this by creating a shell script, with multiple ab calls. Create a file test.sh and add the following lines to it −" }, { "code": null, "e": 28776, "s": 28684, "text": "ab -n 100 -c 10 http://127.0.0.1:8080/hello1 \nab -n 100 -c 10 http://127.0.0.1:8080/hello2\n" }, { "code": null, "e": 28865, "s": 28776, "text": "When you have added the above lines, Save and Close the file. Make the file executable −" }, { "code": null, "e": 28884, "s": 28865, "text": "chmod u+x test.sh\n" }, { "code": null, "e": 28912, "s": 28884, "text": "Let us now run the script −" }, { "code": null, "e": 28923, "s": 28912, "text": "./test.sh\n" }, { "code": null, "e": 29087, "s": 28923, "text": "To avoid repetition and purpose of clarity, we will show only the relevant of the ab output, indicating by dots what portion has been omitted, as in the following." }, { "code": null, "e": 29987, "s": 29087, "text": ".\n.\n.\nDocument Path: /hello1\nDocument Length: 732 bytes\n\nConcurrency Level: 10\nTime taken for tests: 0.040 seconds\nComplete requests: 100\nFailed requests: 0\nNon-2xx responses: 100\nTotal transferred: 90000 bytes\nHTML transferred: 73200 bytes\nRequests per second: 2496.13 [#/sec] (mean)\nTime per request: 4.006 [ms] (mean)\nTime per request: 0.401 [ms] (mean, across all concurrent requests)\nTransfer rate: 2193.87 [Kbytes/sec] received\n\nConnection Times (ms)\n min mean[+/-sd] median max\nConnect: 0 0 0.8 0 3\nProcessing: 1 3 1.0 4 5\nWaiting: 0 3 1.2 4 4\nTotal: 1 4 0.6 4 5\nWARNING: The median and mean for the processing time are not within a normal deviation\n These results are probably not that reliable.\n.\n.\n.\n" }, { "code": null, "e": 30377, "s": 29987, "text": "You can save the Apache Bench Output to file by creating a shell script, with multiple ab calls. At the end of each line, place an &; this makes the command run in the background, and lets the next command start its execution. You will also want to redirect the output to a file for each url using <filename>. For example, our file test.sh will look like the following after modification −" }, { "code": null, "e": 30500, "s": 30377, "text": "$ ab -n 100 -c 10 http://127.0.0.1:8080/hello1 > test1.txt &\n$ ab -n 100 -c 10 http://127.0.0.1:8080/hello2 > test2.txt &\n" }, { "code": null, "e": 30569, "s": 30500, "text": "Here, test1.txt and test2.txt are the files to save the output data." }, { "code": null, "e": 30707, "s": 30569, "text": "You can check that the above script has created two files, test1.txt and test2.txt which contains the ab output for the respective URLs −" }, { "code": null, "e": 30716, "s": 30707, "text": "$ ls -l\n" }, { "code": null, "e": 30981, "s": 30716, "text": "...\n-rw-r--r-- 1 root root 5225 May 30 12:11 out.data\n-rwxr--r-- 1 root root 118 Jun 10 12:24 test.sh\n-rw-r--r-- 1 root root 1291 Jun 10 12:31 test1.txt\n-rwxr--r-- 1 root root 91 Jun 10 13:22 test2.sh\n-rw-r--r-- 1 root root 1291 Jun 10 12:31 test2.txt\n...\n" }, { "code": null, "e": 31185, "s": 30981, "text": "While using ab, you should be alert to the failed test without warning. For example, if you check a wrong URL, you may get something similar to the following (we have deliberately changed the port here)." }, { "code": null, "e": 31272, "s": 31185, "text": "$ ab -l -r -n 100 -c 10 -k -H \"Accept-Encoding: gzip, deflate\" http://127.0.0.1:805/\n" }, { "code": null, "e": 32579, "s": 31272, "text": "This is ApacheBench, Version 2.3 <$Revision: 1604373 $>\nCopyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/\nLicensed to The Apache Software Foundation, http://www.apache.org/\n\nBenchmarking 127.0.0.1 (be patient).....done\n\nServer Software:\nServer Hostname: 127.0.0.1\nServer Port: 805\n\nDocument Path: /\nDocument Length: Variable\n\nConcurrency Level: 10\nTime taken for tests: 0.002 seconds\nComplete requests: 100\nFailed requests: 150\n (Connect: 0, Receive: 100, Length: 0, Exceptions: 50)\nKeep-Alive requests: 0\nTotal transferred: 0 bytes\nHTML transferred: 0 bytes\nRequests per second: 44984.26 [#/sec] (mean)\nTime per request: 0.222 [ms] (mean)\nTime per request: 0.022 [ms] (mean, across all concurrent requests)\nTransfer rate: 0.00 [Kbytes/sec] received\n\nConnection Times (ms)\n min mean[+/-sd] median max\nConnect: 0 0 0.0 0 0\nProcessing: 0 0 0.2 0 0\nWaiting: 0 0 0.0 0 0\nTotal: 0 0 0.2 0 0\n\nPercentage of the requests served within a certain time (ms)\n 50% 0\n 66% 0\n 75% 0\n 80% 0\n 90% 0\n 95% 0\n 98% 0\n 99% 0\n 100% 0 (longest request)\n" }, { "code": null, "e": 32879, "s": 32579, "text": "In this chapter, we will understand the preparation required for testing dynamic pages. A server-side dynamic web page is a web page the construction of which is controlled by an application server processing server-side scripts. The apache bench can only load test the server-side dynamic web page." }, { "code": null, "e": 32948, "s": 32879, "text": "Concurrency level should be lower than the total number of requests." }, { "code": null, "e": 33035, "s": 32948, "text": "$ ab -l -r -n 30 -c 80 -k -H \"Accept-Encoding: gzip, deflate\" http://127.0.0.1:8000/\n" }, { "code": null, "e": 33042, "s": 33035, "text": "Output" }, { "code": null, "e": 33167, "s": 33042, "text": "ab: Cannot use concurrency level greater than total number of requests\nUsage: ab [options] [http[s]://]hostname[:port]/path\n" }, { "code": null, "e": 33313, "s": 33167, "text": "In this section, we will describe the use of some important flags with the ab command. We will use the terms, options and flags, interchangeably." }, { "code": null, "e": 33766, "s": 33313, "text": "The verbose option can be used to analyze and debug if there exist multiple number of failed requests. A common indication of failure of the load test is that the test finishes very fast and it gives a good number for request per second value. But it will be a wrong benchmark. To identify the success or failure, you can use the -v 2 option which will dump each response’s body and header to the terminal output. Following command depicts a use case −" }, { "code": null, "e": 33818, "s": 33766, "text": "$ ab -n 1 -v 2 http://www.generic-example-URL.com/\n" }, { "code": null, "e": 33825, "s": 33818, "text": "Output" }, { "code": null, "e": 33892, "s": 33825, "text": "LOG: header received:\nHTTP/1.0 200 OK\n...\nContent-Length: 2548687\n" }, { "code": null, "e": 34160, "s": 33892, "text": "Of course, if you are testing variable responses or returning non-200 HTTP codes in the event of any error, you should simply ignore length checking with the -l option. We will soon see non-200 HTTP when we will launch a web2py application in the subsequent chapters." }, { "code": null, "e": 34643, "s": 34160, "text": "When the client sends HTTP request, the connection is made to the server, the server sends the response, and the connection is closed after it has sent the request. This cycle continues with each request. However, with the keep-alive setting (also known as persistent connections), the client maintains an underlying TCP connection open to facilitate multiple requests and response; this eliminates the slow and costly connection initialization time that would otherwise be present." }, { "code": null, "e": 34847, "s": 34643, "text": "If the web page is of variable length, then you should make use of the option -l. Apache Bench does not report errors if the length of the responses is not constant. This can be useful for dynamic pages." }, { "code": null, "e": 35135, "s": 34847, "text": "How to force ab not to exit on receiving errors? You should use the option -r. Without this option, your test may break as soon as any request hits the socket error. However, with this option, errors will be reported in the failed errors heading, but the test will continue till the end." }, { "code": null, "e": 35334, "s": 35135, "text": "This option is used to add arbitrary header line. The argument is typically in the form of a valid header line, containing a colon-separated field-value pair (i.e., “Accept-Encoding: zip/zop;8bit”)." }, { "code": null, "e": 35581, "s": 35334, "text": "In the following section, we will learn in detail how to use the above options in combination with the option to use the cookie value, i.e., the -C option. The -C option is typically in the form of a name = value pair. This field can be repeated." }, { "code": null, "e": 35762, "s": 35581, "text": "To understand how to use the cookie with Apache Bench, we need a web page that tries to set a cookie. A very good example is the web2py application which is a python web framework." }, { "code": null, "e": 35886, "s": 35762, "text": "We are going to quickly install another python app web2py. You can read more on how to use it on Web2py Framework Overview." }, { "code": null, "e": 36030, "s": 35886, "text": "Python is generally installed by default on the Ubuntu and Debian server. Therefore, one requirement is already met to run web2py successfully." }, { "code": null, "e": 36163, "s": 36030, "text": "However, we need to install the unzip package to extract the source files of web2py from the zip file which we will be downloading −" }, { "code": null, "e": 36215, "s": 36163, "text": "$ sudo apt-get update\n$ sudo apt-get install unzip\n" }, { "code": null, "e": 36318, "s": 36215, "text": "Let us get the web2py framework from the project’s website. We will download this to our home folder −" }, { "code": null, "e": 36385, "s": 36318, "text": "$cd ~\n$ wget http://www.web2py.com/examples/static/web2py_src.zip\n" }, { "code": null, "e": 36449, "s": 36385, "text": "Now, we can unzip the file we just downloaded and move inside −" }, { "code": null, "e": 36485, "s": 36449, "text": "$ unzip web2py_src.zip\n$ cd web2py\n" }, { "code": null, "e": 36626, "s": 36485, "text": "To run the web2py, you do not need to install it. Once you are inside the web2py directory, you can run it by typing the following command −" }, { "code": null, "e": 36645, "s": 36626, "text": "$python web2py.py\n" }, { "code": null, "e": 36781, "s": 36645, "text": "If everything is successful, you will see the following output where you will be asked to choose a password for the administrative UI −" }, { "code": null, "e": 37157, "s": 36781, "text": "web2py Web Framework\nCreated by Massimo Di Pierro, Copyright 2007-2017\nVersion 2.14.6-stable+timestamp.2016.05.10.00.21.47\nDatabase drivers available: sqlite3, imaplib, pymysql, pg8000\nWARNING:web2py:GUI not available because Tk library is not installed\nchoose a password:\n\nplease visit:\n http://127.0.0.1:8000/\nuse \"kill -SIGTERM 23904\" to shutdown the web2py server\n" }, { "code": null, "e": 37272, "s": 37157, "text": "However, you need to be aware of the fact that the launched web interface is accessible on the local machine only." }, { "code": null, "e": 37615, "s": 37272, "text": "From the output, you can understand that to stop the web server, you will have to type “CTRL-C” in the instant terminal. On the other hand, to stop the web2py server on the other terminal related to the same VPS, you can insert the command kill -SIGTERM <PID>, where <PID> is the process ID for the web2py server, which in this case is 23904." }, { "code": null, "e": 38120, "s": 37615, "text": "If a page is only accessible by a logged in user, not directly accessible from the login page, in that case you can use the -C flag. This flag defines a cookie for the ab command. But you have to get the value of the session identifier cookie from a valid session. How to get that? Various online tutorials will guide you towards Chrome (or Mozilla) browser developer tools. But in our test case, as the application is available only on the command line, we will use the lynx browser to obtain the value." }, { "code": null, "e": 38223, "s": 38120, "text": "Let us get the cookie value of a session first. Open another terminal and type the following command −" }, { "code": null, "e": 38254, "s": 38223, "text": "$ lynx http://127.0.0.1:8000/\n" }, { "code": null, "e": 38391, "s": 38254, "text": "In response to the above command, lynx will ask your permission to accept the cookie from the web2py server as shown in the image below." }, { "code": null, "e": 38541, "s": 38391, "text": "Note down the cookie value before typing y to accept the cookie. Now the terminal will look similar to the following image – website on the terminal!" }, { "code": null, "e": 38678, "s": 38541, "text": "Having obtained the cookie value, we will now run the ab test. For that, we will have to open the third terminal (see the image below) −" }, { "code": null, "e": 38730, "s": 38678, "text": "Now, let us use the -C flag in the third terminal −" }, { "code": null, "e": 38815, "s": 38730, "text": "$ ab -n 100 -c 10 -C session_name = 127.0.0.1-643dad04-3c34 http://127.0.0.1:8000/\n" }, { "code": null, "e": 40089, "s": 38815, "text": "This is ApacheBench, Version 2.3 <$Revision: 1604373 $>\nCopyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/\nLicensed to The Apache Software Foundation, http://www.apache.org/\n\nBenchmarking 127.0.0.1 (be patient).....done\n\n\nServer Software: Rocket\nServer Hostname: 127.0.0.1\nServer Port: 8000\n\nDocument Path: /\nDocument Length: 66 bytes\n\nConcurrency Level: 10\nTime taken for tests: 0.051 seconds\nComplete requests: 100\nFailed requests: 0\nNon-2xx responses: 100\nTotal transferred: 27700 bytes\nHTML transferred: 6600 bytes\nRequests per second: 1968.12 [#/sec] (mean)\nTime per request: 5.081 [ms] (mean)\nTime per request: 0.508 [ms] (mean, across all concurrent requests)\nTransfer rate: 532.39 [Kbytes/sec] received\n\nConnection Times (ms)\n min mean[+/-sd] median max\nConnect: 1 2 0.9 2 4\nProcessing: 0 3 0.9 3 5\nWaiting: 0 2 1.1 2 4\nTotal: 4 5 0.7 5 7\n\nPercentage of the requests served within a certain time (ms)\n 50% 5\n 66% 5\n 75% 5\n 80% 6\n 90% 6\n 95% 6\n 98% 7\n 99% 7\n 100% 7 (longest request)\n" }, { "code": null, "e": 40708, "s": 40089, "text": "From the output above, we note several points. First, web2py uses Rocket web server. We also note that we are getting ‘Non-2xx responses’ in addition to previously discussed headings in the output. In general, Http protocol responds to a request using a response code, and anything within the 200s range means ‘okay’, and the rest corresponds to some problem. For example, 400s are resource related errors such as 404 File Not Found. 500s correspond to server errors. In our instant case, there is no error anywhere except when we are using the -C option. It can be suppressed using the -l option as already described." }, { "code": null, "e": 40856, "s": 40708, "text": "In this section, we will understand how to check the admin page. For the purpose of comparison, let us test another URL of the web2py application −" }, { "code": null, "e": 40943, "s": 40856, "text": "$ ab -n 100 -c 10 session_name = 127.0.0.1-643dad04-3c34 http://127.0.0.1:8000/admin\n" }, { "code": null, "e": 42197, "s": 40943, "text": "This is ApacheBench, Version 2.3 <$Revision: 1604373 $>\nCopyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/\nLicensed to The Apache Software Foundation, http://www.apache.org/\n\nBenchmarking 127.0.0.1 (be patient).....done\n\n\nServer Software: Rocket\nServer Hostname: 127.0.0.1\nServer Port: 8000\n\nDocument Path: /admin\nDocument Length: 8840 bytes\n\nConcurrency Level: 10\nTime taken for tests: 2.077 seconds\nComplete requests: 100\nFailed requests: 0\nTotal transferred: 926700 bytes\nHTML transferred: 884000 bytes\nRequests per second: 48.14 [#/sec] (mean)\nTime per request: 207.749 [ms] (mean)\nTime per request: 20.775 [ms] (mean, across all concurrent requests)\nTransfer rate: 435.61 [Kbytes/sec] received\n\nConnection Times (ms)\n min mean[+/-sd] median max\nConnect: 0 1 3.2 0 12\nProcessing: 62 204 52.2 199 400\nWaiting: 61 203 52.0 199 400\nTotal: 62 205 54.3 199 411\n\nPercentage of the requests served within a certain time (ms)\n 50% 199\n 66% 211\n 75% 220\n 80% 226\n 90% 264\n 95% 349\n 98% 381\n 99% 411\n 100% 411 (longest request)\n " }, { "code": null, "e": 42414, "s": 42197, "text": "You should in particular note the respective statistics in section “Connection Times” and “Percentage of the requests served ...” of http://127.0.0.1:8000/ and http://127.0.0.1:8000/admin. There is a huge difference." }, { "code": null, "e": 42534, "s": 42414, "text": "Generally, Timelimit option is a tricky one. Let us understand this from the manual of ab, which is quite explanatory −" }, { "code": null, "e": 42742, "s": 42534, "text": "-t timelimit\nMaximum number of seconds to spend for benchmarking. This implies a -n 50000 internally.\nUse this to benchmark the server within a fixed total amount of time.\nPer default there is no timelimit.\n" }, { "code": null, "e": 42845, "s": 42742, "text": "Let us run a test with this option. We will note our observations after the going through the output −" }, { "code": null, "e": 42895, "s": 42845, "text": "$ ab -n 100 -c 10 -t 60 http://127.0.0.1:8000/\n" }, { "code": null, "e": 44444, "s": 42895, "text": "This is ApacheBench, Version 2.3 <$Revision: 1604373 $>\nCopyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/\nLicensed to The Apache Software Foundation, http://www.apache.org/\n\nBenchmarking 127.0.0.1 (be patient)\nCompleted 5000 requests\nCompleted 10000 requests\nCompleted 15000 requests\nCompleted 20000 requests\nCompleted 25000 requests\nCompleted 30000 requests\nCompleted 35000 requests\nCompleted 40000 requests\nCompleted 45000 requests\nCompleted 50000 requests\nFinished 50000 requests\n\n\nServer Software: Rocket\nServer Hostname: 127.0.0.1\nServer Port: 8000\n\nDocument Path: /\nDocument Length: 66 bytes\n\nConcurrency Level: 10\nTime taken for tests: 22.547 seconds\nComplete requests: 50000\nFailed requests: 0\nNon-2xx responses: 50000\nTotal transferred: 13850000 bytes\nHTML transferred: 3300000 bytes\nRequests per second: 2217.61 [#/sec] (mean)\nTime per request: 4.509 [ms] (mean)\nTime per request: 0.451 [ms] (mean, across all concurrent requests)\nTransfer rate: 599.88 [Kbytes/sec] received\n\nConnection Times (ms)\n min mean[+/-sd] median max\nConnect: 0 2 0.8 2 8\nProcessing: 0 2 3.2 2 218\nWaiting: 0 2 3.2 2 218\nTotal: 2 4 3.1 4 220\n\nPercentage of the requests served within a certain time (ms)\n 50% 4\n 66% 4\n 75% 4\n 80% 5\n 90% 5\n 95% 5\n 98% 7\n 99% 8\n 100% 220 (longest request)\n" }, { "code": null, "e": 44758, "s": 44444, "text": "Notice that the output shows this option overrides the number of requests specified by the -n option and continues upto the 50K requests. However, as the requests were handled very fast, ab has terminated as soon as 50k mark was achieved – within 22 seconds (see heading Time taken for tests) in the instant case." }, { "code": null, "e": 44986, "s": 44758, "text": "You can test the same command replacing http://127.0.0.1:8000/ with http://127.0.0.1:8000/admin (assuming it is our web2py application) or a third party website like https://www.apache.org/, notice the difference in statistics." }, { "code": null, "e": 45164, "s": 44986, "text": "There are a few checks which will help you successfully run the test, and measure the performance accurately. Consider the following conditions before performing the load test −" }, { "code": null, "e": 45210, "s": 45164, "text": "Ensure that no extra python module is loaded." }, { "code": null, "e": 45256, "s": 45210, "text": "Ensure that no extra python module is loaded." }, { "code": null, "e": 45363, "s": 45256, "text": "To avoid TCP/IP Port Exhaustion, you should typically wait 2-3 minutes before you move to another ab test." }, { "code": null, "e": 45470, "s": 45363, "text": "To avoid TCP/IP Port Exhaustion, you should typically wait 2-3 minutes before you move to another ab test." }, { "code": null, "e": 45557, "s": 45470, "text": "Ensure that the number of concurrent connections are lower than Apache Worker Threads." }, { "code": null, "e": 45644, "s": 45557, "text": "Ensure that the number of concurrent connections are lower than Apache Worker Threads." }, { "code": null, "e": 45734, "s": 45644, "text": "You should reboot the server before performing another test, if Apache or python crashes." }, { "code": null, "e": 45824, "s": 45734, "text": "You should reboot the server before performing another test, if Apache or python crashes." }, { "code": null, "e": 45971, "s": 45824, "text": "In this chapter, we will describe the various combinations of -n and -c with the important flags to gradually increase the load on your webserver." }, { "code": null, "e": 46058, "s": 45971, "text": "You should mainly focus on how the following metrics change as you increase the load −" }, { "code": null, "e": 46078, "s": 46058, "text": "Requests per second" }, { "code": null, "e": 46100, "s": 46078, "text": "Connection Times (ms)" }, { "code": null, "e": 46161, "s": 46100, "text": "Percentage of the requests served within a certain time (ms)" }, { "code": null, "e": 46280, "s": 46161, "text": "You should also notice for the threshold value when server starts getting stuck and you start getting failed requests." }, { "code": null, "e": 46335, "s": 46280, "text": "Let us do 100 sequential page-loads by a single user −" }, { "code": null, "e": 46422, "s": 46335, "text": "$ ab -l -r -n 100 -c 1 -k -H \"Accept-Encoding: gzip, deflate\" http://127.0.0.1:8000/\n" }, { "code": null, "e": 47721, "s": 46422, "text": "This is ApacheBench, Version 2.3 <$Revision: 1604373 $>\nCopyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/\nLicensed to The Apache Software Foundation, http://www.apache.org/\n\nBenchmarking 127.0.0.1 (be patient).....done\n\n\nServer Software: Rocket\nServer Hostname: 127.0.0.1\nServer Port: 8000\n\nDocument Path: /\nDocument Length: Variable\n\nConcurrency Level: 1\nTime taken for tests: 0.045 seconds\nComplete requests: 100\nFailed requests: 0\nNon-2xx responses: 100\nKeep-Alive requests: 0\nTotal transferred: 27700 bytes\nHTML transferred: 6600 bytes\nRequests per second: 2206.24 [#/sec] (mean)\nTime per request: 0.453 [ms] (mean)\nTime per request: 0.453 [ms] (mean, across all concurrent requests)\nTransfer rate: 596.80 [Kbytes/sec] received\n\nConnection Times (ms)\n min mean[+/-sd] median max\nConnect: 0 0 0.0 0 0\nProcessing: 0 0 0.0 0 0\nWaiting: 0 0 0.0 0 0\nTotal: 0 0 0.0 0 1\n\nPercentage of the requests served within a certain time (ms)\n 50% 0\n 66% 0\n 75% 0\n 80% 0\n 90% 1\n 95% 1\n 98% 1\n 99% 1\n 100% 1 (longest request)\n" }, { "code": null, "e": 47810, "s": 47721, "text": "This case corresponds to a peak load on a website that gets around 50,000+ hits a month." }, { "code": null, "e": 47896, "s": 47810, "text": "$ ab -l -r -n 10 -c 5 -k -H \"Accept-Encoding: gzip, deflate\" http://127.0.0.1:8000/\n" }, { "code": null, "e": 47992, "s": 47896, "text": "In the following subsequent outputs, we will be omitting the common header for clarity purpose." }, { "code": null, "e": 48788, "s": 47992, "text": "...\nRequests per second: 2009.24 [#/sec] (mean)\nTime per request: 2.488 [ms] (mean)\nTime per request: 0.498 [ms] (mean, across all concurrent requests)\nTransfer rate: 543.52 [Kbytes/sec] received\n\nConnection Times (ms)\n min mean[+/-sd] median max\nConnect: 0 1 0.5 1 2\nProcessing: 0 1 0.5 1 2\nWaiting: 0 1 0.5 1 1\nTotal: 2 2 0.4 3 3\nERROR: The median and mean for the total time are more than twice the standard\n deviation apart. These results are NOT reliable.\n\nPercentage of the requests served within a certain time (ms)\n 50% 3\n 66% 3\n 75% 3\n 80% 3\n 90% 3\n 95% 3\n 98% 3\n 99% 3\n 100% 3 (longest request)\n" }, { "code": null, "e": 48908, "s": 48788, "text": "This test corresponds to 100 page loads by 10 different concurrent users, each user is doing 10 sequential pages loads." }, { "code": null, "e": 48993, "s": 48908, "text": "$ ab -r -n 10 -c 10 -k -H \"Accept-Encoding: gzip, deflate\" http://127.0.0.1:8000/\n" }, { "code": null, "e": 49792, "s": 48993, "text": "...\nRequests per second: 2225.68 [#/sec] (mean)\nTime per request: 4.493 [ms] (mean)\nTime per request: 0.449 [ms] (mean, across all concurrent requests)\nTransfer rate: 602.07 [Kbytes/sec] received\n\nConnection Times (ms)\n min mean[+/-sd] median max\nConnect: 1 2 0.7 2 3\nProcessing: 0 2 1.0 2 3\nWaiting: 0 1 1.0 2 3\nTotal: 4 4 0.3 4 4\nWARNING: The median and mean for the waiting time are not within a normal deviation\n These results are probably not that reliable.\n\nPercentage of the requests served within a certain time (ms)\n 50% 4\n 66% 4\n 75% 4\n 80% 4\n 90% 4\n 95% 4\n 98% 4\n 99% 4\n 100% 4 (longest request)\n" }, { "code": null, "e": 49912, "s": 49792, "text": "This test corresponds to 400 page loads by 20 different concurrent users, each user is doing 20 sequential pages loads." }, { "code": null, "e": 49995, "s": 49912, "text": "$ ab -r -n 20 -c 20 -k -H “Accept-Encoding: gzip, deflate” http://127.0.0.1:8000/\n" }, { "code": null, "e": 50658, "s": 49995, "text": "...\nRequests per second: 1619.96 [#/sec] (mean)\nTime per request: 12.346 [ms] (mean)\nTime per request: 0.617 [ms] (mean, across all concurrent requests)\nTransfer rate: 438.21 [Kbytes/sec] received\n\nConnection Times (ms)\n min mean[+/-sd] median max\nConnect: 2 6 2.3 6 10\nProcessing: 1 5 2.9 5 10\nWaiting: 0 5 2.9 5 9\nTotal: 10 11 0.6 11 12\n\nPercentage of the requests served within a certain time (ms)\n 50% 11\n 66% 11\n 75% 12\n 80% 12\n 90% 12\n 95% 12\n 98% 12\n 99% 12\n 100% 12 (longest request)\n " }, { "code": null, "e": 50778, "s": 50658, "text": "This test corresponds to 900 page loads by 30 different concurrent users, each user is doing 30 sequential pages loads." }, { "code": null, "e": 50863, "s": 50778, "text": "$ ab -r -n 30 -c 30 -k -H \"Accept-Encoding: gzip, deflate\" http://127.0.0.1:8000/\n" }, { "code": null, "e": 51525, "s": 50863, "text": "...\nRequests per second: 2283.45 [#/sec] (mean)\nTime per request: 13.138 [ms] (mean)\nTime per request: 0.438 [ms] (mean, across all concurrent requests)\nTransfer rate: 617.69 [Kbytes/sec] received\n\nConnection Times (ms)\n min mean[+/-sd] median max\nConnect: 2 6 2.7 6 11\nProcessing: 1 6 3.1 6 11\nWaiting: 0 5 3.2 5 10\nTotal: 11 12 0.5 12 13\n\nPercentage of the requests served within a certain time (ms)\n 50% 12\n 66% 12\n 75% 12\n 80% 12\n 90% 13\n 95% 13\n 98% 13\n 99% 13\n 100% 13 (longest request)\n" }, { "code": null, "e": 51621, "s": 51525, "text": "We have now learned how to increase the load gradually on the website and test its performance." }, { "code": null, "e": 52064, "s": 51621, "text": "In this chapter, we will compare the outputs with and without flags. Let us see how the use of appropriate flags can increase the performance of your web application. Before that, we need to understand how if your application is simple then you may not notice the difference. As is the case with our simple application, with flags and without flags. Then we will perform the same test with https://www.apache.org/ URL, and see the difference." }, { "code": null, "e": 52143, "s": 52064, "text": "In this section, we will understand how to test our application without flags." }, { "code": null, "e": 52185, "s": 52143, "text": "$ ab -n 100 -c 10 http://127.0.0.1:8000/\n" }, { "code": null, "e": 53485, "s": 52185, "text": "This is ApacheBench, Version 2.3 <$Revision: 1604373 $>\nCopyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/\nLicensed to The Apache Software Foundation, http://www.apache.org/\n\nBenchmarking 127.0.0.1 (be patient).....done\n\n\nServer Software: Rocket\nServer Hostname: 127.0.0.1\nServer Port: 8000\n\nDocument Path: /\nDocument Length: Variable\n\nConcurrency Level: 10\nTime taken for tests: 0.244 seconds\nComplete requests: 100\nFailed requests: 0\nNon-2xx responses: 100\nKeep-Alive requests: 0\nTotal transferred: 27700 bytes\nHTML transferred: 6600 bytes\nRequests per second: 2208.77 [#/sec] (mean)\nTime per request: 4.527 [ms] (mean)\nTime per request: 0.453 [ms] (mean, across all concurrent requests)\nTransfer rate: 597.49 [Kbytes/sec] received\n\nConnection Times (ms)\n min mean[+/-sd] median max\nConnect: 1 2 0.7 2 3\nProcessing: 0 2 0.7 2 4\nWaiting: 0 2 1.0 2 3\nTotal: 4 4 0.3 4 5\n\nPercentage of the requests served within a certain time (ms)\n 50% 4\n 66% 4\n 75% 5\n 80% 5\n 90% 5\n 95% 5\n 98% 5\n 99% 5\n 100% 5 (longest request)\n" }, { "code": null, "e": 53561, "s": 53485, "text": "In this section, we will understand how to test our application with flags." }, { "code": null, "e": 53649, "s": 53561, "text": "$ ab -l -r -n 100 -c 10 -k -H \"Accept-Encoding: gzip, deflate\" http://127.0.0.1:8000/\n" }, { "code": null, "e": 54310, "s": 53649, "text": "...\nRequests per second: 2277.07 [#/sec] (mean)\nTime per request: 4.392 [ms] (mean)\nTime per request: 0.439 [ms] (mean, across all concurrent requests)\nTransfer rate: 615.97 [Kbytes/sec] received\n\nConnection Times (ms)\n min mean[+/-sd] median max\nConnect: 1 2 0.7 2 3\nProcessing: 0 2 0.7 2 4\nWaiting: 0 2 1.0 2 3\nTotal: 4 4 0.2 4 5\n\nPercentage of the requests served within a certain time (ms)\n 50% 4\n 66% 4\n 75% 4\n 80% 4\n 90% 5\n 95% 5\n 98% 5\n 99% 5\n 100% 5 (longest request)\n" }, { "code": null, "e": 54394, "s": 54310, "text": "We can simply note that there is not much difference between the output statistics." }, { "code": null, "e": 54468, "s": 54394, "text": "Let us now see how to test the Apache Organisation Website without flags." }, { "code": null, "e": 54510, "s": 54468, "text": "$ ab -n 100 -c 10 http://www.apache.org/\n" }, { "code": null, "e": 55779, "s": 54510, "text": "This is ApacheBench, Version 2.3 <$Revision: 1604373 $>\nCopyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/\nLicensed to The Apache Software Foundation, http://www.apache.org/\n\nBenchmarking www.apache.org (be patient).....done\n\nServer Software: Apache/2.4.7\nServer Hostname: www.apache.org\nServer Port: 80\n\nDocument Path: /\nDocument Length: 58433 bytes\n\nConcurrency Level: 10\nTime taken for tests: 1.498 seconds\nComplete requests: 100\nFailed requests: 0\nTotal transferred: 5877500 bytes\nHTML transferred: 5843300 bytes\nRequests per second: 66.74 [#/sec] (mean)\nTime per request: 149.840 [ms] (mean)\nTime per request: 14.984 [ms] (mean, across all concurrent requests)\nTransfer rate: 3830.58 [Kbytes/sec] received\n\nConnection Times (ms)\n min mean[+/-sd] median max\nConnect: 12 110 295.2 12 1012\nProcessing: 37 38 0.5 38 39\nWaiting: 12 13 0.3 13 15\nTotal: 49 147 295.4 50 1051\n\nPercentage of the requests served within a certain time (ms)\n 50% 50\n 66% 50\n 75% 50\n 80% 50\n 90% 816\n 95% 1050\n 98% 1051\n 99% 1051\n 100% 1051 (longest request)\n" }, { "code": null, "e": 55839, "s": 55779, "text": "Let us now test the Apache Organisation Website with Flags." }, { "code": null, "e": 55927, "s": 55839, "text": "$ ab -l -r -n 100 -c 10 -k -H \"Accept-Encoding: gzip, deflate\" http://www.apache.org/\n" }, { "code": null, "e": 56846, "s": 55927, "text": "...\nDocument Length: Variable\n\nConcurrency Level: 10\nTime taken for tests: 0.357 seconds\nComplete requests: 100\nFailed requests: 0\nKeep-Alive requests: 100\nTotal transferred: 1358510 bytes\nHTML transferred: 1317700 bytes\nRequests per second: 280.28 [#/sec] (mean)\nTime per request: 35.678 [ms] (mean)\nTime per request: 3.568 [ms] (mean, across all concurrent requests)\nTransfer rate: 3718.41 [Kbytes/sec] received\n\nConnection Times (ms)\n min mean[+/-sd] median max\nConnect: 0 1 3.7 0 12\nProcessing: 14 17 21.3 15 227\nWaiting: 14 17 21.3 14 227\nTotal: 14 18 21.5 15 227\n\nPercentage of the requests served within a certain time (ms)\n 50% 15\n 66% 15\n 75% 15\n 80% 15\n 90% 27\n 95% 28\n 98% 29\n 99% 227\n 100% 227 (longest request)\n" }, { "code": null, "e": 57094, "s": 56846, "text": "You can simply note how the request per second increased with the use of flags. In the instant case, it is particularly due to use of -H \"Accept-Encoding: gzip, deflate because this flag tells the Apache server to serve requests in gzipped format." }, { "code": null, "e": 57302, "s": 57094, "text": "A few important points need to be considered when it comes to the Apache Bench results. This will help us design our overall strategy to remove the bottlenecks in our application and improve its performance." }, { "code": null, "e": 57640, "s": 57302, "text": "We need to Requests Per Second. This gives us an idea of how well our web server set-up is working; the larger the number, the better the performance. Then comes the Connection Times (ms) and the Percentage of the requests served. You may have to tweak the settings of your web server to change these metrics to your desired performance." }, { "code": null, "e": 57925, "s": 57640, "text": "Check if there are errors in the Apache’s or the used web server error logs or (general) logs. As you will increase your load, things will start to choke: memory issues will start coming up. A lot of python scripts will begin to crash if they are not written with concurrency in mind." }, { "code": null, "e": 58196, "s": 57925, "text": "You need to find out what is the critical concurrency value above which your web server crashes and/or times-out? Normally this should happen at a fairly high concurrency level. If this value is low, something is wrong and you need to adjust these settings lower/higher." }, { "code": null, "e": 58637, "s": 58196, "text": "In this tutorial we learned how Apache Bench can be used to load test any web site or web application. Apache Bench can be a very valuable tool for determining how your web application server setup should be improved, to reduce bottlenecks and increase performance. Now that you are familiar with the basic usage of Apache Bench, you can start by creating new test plans to measure the performance of your applications in various scenarios." }, { "code": null, "e": 58672, "s": 58637, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 58691, "s": 58672, "text": " Arnab Chakraborty" }, { "code": null, "e": 58726, "s": 58691, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 58747, "s": 58726, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 58780, "s": 58747, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 58793, "s": 58780, "text": " Nilay Mehta" }, { "code": null, "e": 58828, "s": 58793, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 58846, "s": 58828, "text": " Bigdata Engineer" }, { "code": null, "e": 58879, "s": 58846, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 58897, "s": 58879, "text": " Bigdata Engineer" }, { "code": null, "e": 58930, "s": 58897, "text": "\n 23 Lectures \n 1 hours \n" }, { "code": null, "e": 58948, "s": 58930, "text": " Bigdata Engineer" }, { "code": null, "e": 58955, "s": 58948, "text": " Print" }, { "code": null, "e": 58966, "s": 58955, "text": " Add Notes" } ]
How to implement MAX(distinct...) in MySQL and what is the difference without using DISTINCT?
Let us see the first syntax, which uses DISTINCT in MAX() − select max(DISTINCT yourColumnName) from yourTableName; The second syntax is as follows. It isn’t using DISTINCT − select max( yourColumnName) from yourTableName; NOTE − Both the above queries give the same result with or without a DISTINCT keyword. MySQL internally converts MAX(yourColumnName) to DISTINCT keyword. Let us now see an example and create a table − mysql> create table DemoTable ( Number int ); Query OK, 0 rows affected (1.50 sec) Insert some records in the table using insert command − mysql> insert into DemoTable values(80); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable values(88); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values(78); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values(88); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values(68); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable values(88); Query OK, 1 row affected (0.10 sec) Display all records from the table using select statement − mysql> select *from DemoTable; This will produce the following output − +--------+ | Number | +--------+ | 80 | | 88 | | 78 | | 88 | | 68 | | 88 | +--------+ 6 rows in set (0.00 sec) CASE 1 − Following is the query to implement MAX(DISTINCT..) − mysql> select max(DISTINCT Number) from DemoTable; This will produce the following output − +----------------------+ | max(DISTINCT Number) | +----------------------+ | 88 | +----------------------+ 1 row in set (0.00 sec) CASE 2 − Following is the query to implement MAX() without DISTINCT − mysql> select max(Number) from DemoTable; This will produce the following output − +-------------+ | max(Number) | +-------------+ | 88 | +-------------+ 1 row in set (0.07 sec) As you can see above, both of them give the same result.
[ { "code": null, "e": 1122, "s": 1062, "text": "Let us see the first syntax, which uses DISTINCT in MAX() −" }, { "code": null, "e": 1178, "s": 1122, "text": "select max(DISTINCT yourColumnName) from yourTableName;" }, { "code": null, "e": 1237, "s": 1178, "text": "The second syntax is as follows. It isn’t using DISTINCT −" }, { "code": null, "e": 1285, "s": 1237, "text": "select max( yourColumnName) from yourTableName;" }, { "code": null, "e": 1439, "s": 1285, "text": "NOTE − Both the above queries give the same result with or without a DISTINCT keyword. MySQL internally converts MAX(yourColumnName) to DISTINCT keyword." }, { "code": null, "e": 1486, "s": 1439, "text": "Let us now see an example and create a table −" }, { "code": null, "e": 1572, "s": 1486, "text": "mysql> create table DemoTable\n(\n Number int\n);\nQuery OK, 0 rows affected (1.50 sec)" }, { "code": null, "e": 1628, "s": 1572, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 2090, "s": 1628, "text": "mysql> insert into DemoTable values(80);\nQuery OK, 1 row affected (0.09 sec)\nmysql> insert into DemoTable values(88);\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable values(78);\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into DemoTable values(88);\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into DemoTable values(68);\nQuery OK, 1 row affected (0.09 sec)\nmysql> insert into DemoTable values(88);\nQuery OK, 1 row affected (0.10 sec)" }, { "code": null, "e": 2150, "s": 2090, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 2181, "s": 2150, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 2222, "s": 2181, "text": "This will produce the following output −" }, { "code": null, "e": 2357, "s": 2222, "text": "+--------+\n| Number |\n+--------+\n| 80 |\n| 88 |\n| 78 |\n| 88 |\n| 68 |\n| 88 |\n+--------+\n6 rows in set (0.00 sec)" }, { "code": null, "e": 2420, "s": 2357, "text": "CASE 1 − Following is the query to implement MAX(DISTINCT..) −" }, { "code": null, "e": 2471, "s": 2420, "text": "mysql> select max(DISTINCT Number) from DemoTable;" }, { "code": null, "e": 2512, "s": 2471, "text": "This will produce the following output −" }, { "code": null, "e": 2661, "s": 2512, "text": "+----------------------+\n| max(DISTINCT Number) |\n+----------------------+\n| 88 |\n+----------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 2731, "s": 2661, "text": "CASE 2 − Following is the query to implement MAX() without DISTINCT −" }, { "code": null, "e": 2773, "s": 2731, "text": "mysql> select max(Number) from DemoTable;" }, { "code": null, "e": 2814, "s": 2773, "text": "This will produce the following output −" }, { "code": null, "e": 2918, "s": 2814, "text": "+-------------+\n| max(Number) |\n+-------------+\n| 88 |\n+-------------+\n1 row in set (0.07 sec)" }, { "code": null, "e": 2975, "s": 2918, "text": "As you can see above, both of them give the same result." } ]
groupadd- Unix, Linux Command
groupadd - Creates a new group. groupadd [options] group groupadd command creates a new group account using the values specified on the command line and the default values from the system. The new group will be entered into the system files as needed. The numeric identifiers of new system groups are choosen in the SYS_GID_MIN-SYS_GID_MAX range, defined in login.defs, instead of GID_MIN-GID_MAX. Example: -K GID_MIN=100 -K GID_MAX=499 Note: -K GID_MIN=10,GID_MAX=499 doesn't work yet. Example-1: This example would create a new group called "newgroup". # groupadd newgroup output: to verify greoup created , search in /etc/group # grep test /etc/grouptest:x:1002: Example-2: To create new group with specific groupid # groupadd -g 9090 newgroup output: # grep newgroup /etc/groupnewgroup:x:9090: Example-3: To create group in user defined range ( not range from system i.e /etc/login.defs) # groupadd newgroup -K GID_MIN=8888 -K GID_MAX=9999 output: # grep newgroup /etc/groupnewgroup:x:9091: 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": 10609, "s": 10577, "text": "groupadd - Creates a new group." }, { "code": null, "e": 10634, "s": 10609, "text": "groupadd [options] group" }, { "code": null, "e": 10830, "s": 10634, "text": " groupadd command creates a new group account using the values specified on the command line and the default values from the system. The new group will be entered into the system files as needed." }, { "code": null, "e": 10976, "s": 10830, "text": "The numeric identifiers of new system groups are choosen in the SYS_GID_MIN-SYS_GID_MAX range, defined in login.defs, instead of GID_MIN-GID_MAX." }, { "code": null, "e": 11017, "s": 10976, "text": "Example: -K GID_MIN=100 -K GID_MAX=499\n\n" }, { "code": null, "e": 11067, "s": 11017, "text": "Note: -K GID_MIN=10,GID_MAX=499 doesn't work yet." }, { "code": null, "e": 11078, "s": 11067, "text": "Example-1:" }, { "code": null, "e": 11135, "s": 11078, "text": "This example would create a new group called \"newgroup\"." }, { "code": null, "e": 11155, "s": 11135, "text": "# groupadd newgroup" }, { "code": null, "e": 11163, "s": 11155, "text": "output:" }, { "code": null, "e": 11211, "s": 11163, "text": "to verify greoup created , search in /etc/group" }, { "code": null, "e": 11246, "s": 11211, "text": "# grep test /etc/grouptest:x:1002:" }, { "code": null, "e": 11257, "s": 11246, "text": "Example-2:" }, { "code": null, "e": 11299, "s": 11257, "text": "To create new group with specific groupid" }, { "code": null, "e": 11328, "s": 11299, "text": "# groupadd -g 9090 newgroup" }, { "code": null, "e": 11336, "s": 11328, "text": "output:" }, { "code": null, "e": 11379, "s": 11336, "text": "# grep newgroup /etc/groupnewgroup:x:9090:" }, { "code": null, "e": 11390, "s": 11379, "text": "Example-3:" }, { "code": null, "e": 11473, "s": 11390, "text": "To create group in user defined range ( not range from system i.e /etc/login.defs)" }, { "code": null, "e": 11525, "s": 11473, "text": "# groupadd newgroup -K GID_MIN=8888 -K GID_MAX=9999" }, { "code": null, "e": 11533, "s": 11525, "text": "output:" }, { "code": null, "e": 11576, "s": 11533, "text": "# grep newgroup /etc/groupnewgroup:x:9091:" }, { "code": null, "e": 11611, "s": 11576, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 11639, "s": 11611, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 11673, "s": 11639, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 11690, "s": 11673, "text": " Frahaan Hussain" }, { "code": null, "e": 11723, "s": 11690, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 11734, "s": 11723, "text": " Pradeep D" }, { "code": null, "e": 11769, "s": 11734, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 11785, "s": 11769, "text": " Musab Zayadneh" }, { "code": null, "e": 11818, "s": 11785, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 11830, "s": 11818, "text": " GUHARAJANM" }, { "code": null, "e": 11862, "s": 11830, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 11870, "s": 11862, "text": " Uplatz" }, { "code": null, "e": 11877, "s": 11870, "text": " Print" }, { "code": null, "e": 11888, "s": 11877, "text": " Add Notes" } ]
Priority of AND and OR operator in MySQL select query?
The AND has the highest priority than the OR operator in MySQL select query. Let us check how MySQL gives the highest priority to AND operator. The query is as follows mysql> select 0 AND 0 OR 1 as Result; The following is the output +--------+ | Result | +--------+ | 1 | +--------+ 1 row in set (0.00 sec) If you are considering the OR operator has the highest priority then MySQL will wrap up the above query like this. The query is as follows select 0 AND (0 OR 1) as Result First, solve the 0 OR 1, this will give result 1. After that 0 and 1 will give the result 0. But the above case is not fine because we are getting 0 and the output is 1. So, in the above query, AND gets the highest priority than OR to get result 1. The query is as follows select 0 AND 0 OR 1 as Result First, solve AND operator first. 0 AND 0 give result 0. After that 0 OR 1 gives result 1. Now we are getting the exact output.
[ { "code": null, "e": 1139, "s": 1062, "text": "The AND has the highest priority than the OR operator in MySQL select query." }, { "code": null, "e": 1206, "s": 1139, "text": "Let us check how MySQL gives the highest priority to AND operator." }, { "code": null, "e": 1230, "s": 1206, "text": "The query is as follows" }, { "code": null, "e": 1268, "s": 1230, "text": "mysql> select 0 AND 0 OR 1 as Result;" }, { "code": null, "e": 1296, "s": 1268, "text": "The following is the output" }, { "code": null, "e": 1374, "s": 1296, "text": "+--------+\n| Result |\n+--------+\n| 1 |\n+--------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 1489, "s": 1374, "text": "If you are considering the OR operator has the highest priority then MySQL will wrap up the above query like this." }, { "code": null, "e": 1513, "s": 1489, "text": "The query is as follows" }, { "code": null, "e": 1545, "s": 1513, "text": "select 0 AND (0 OR 1) as Result" }, { "code": null, "e": 1638, "s": 1545, "text": "First, solve the 0 OR 1, this will give result 1. After that 0 and 1 will give the result 0." }, { "code": null, "e": 1794, "s": 1638, "text": "But the above case is not fine because we are getting 0 and the output is 1. So, in the above query, AND gets the highest priority than OR to get result 1." }, { "code": null, "e": 1818, "s": 1794, "text": "The query is as follows" }, { "code": null, "e": 1848, "s": 1818, "text": "select 0 AND 0 OR 1 as Result" }, { "code": null, "e": 1904, "s": 1848, "text": "First, solve AND operator first. 0 AND 0 give result 0." }, { "code": null, "e": 1938, "s": 1904, "text": "After that 0 OR 1 gives result 1." }, { "code": null, "e": 1975, "s": 1938, "text": "Now we are getting the exact output." } ]