title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Scala String charAt() method with example
15 Oct, 2019 The charAt() method is utilized to return the character of the index passed in the argument. Method Definition: char charAt(int index)Return Type: It returns char for the index given in the argument. Example #1: // Scala program of charAt()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a String val m1 = "Nidhi" // Applying charAt() method val result = m1.charAt(2) // Displays output println(result) }} d Example #2: // Scala program of charAt()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a String val m1 = "Nidhi" // Applying charAt() method val result = m1.charAt(0) // Displays output println(result) }} N shubham_singh Scala Scala-Method Scala-Strings Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Scala Tutorial – Learn Scala with Step By Step Guide Scala Map Scala Lists Scala | Arrays Enumeration in Scala Lambda Expression in Scala How to get the first element of List in Scala How to Install Scala with VSCode? Scala String replace() method with example HashMap in Scala
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Oct, 2019" }, { "code": null, "e": 121, "s": 28, "text": "The charAt() method is utilized to return the character of the index passed in the argument." }, { "code": null, "e": 228, "s": 121, "text": "Method Definition: char charAt(int index)Return Type: It returns char for the index given in the argument." }, { "code": null, "e": 240, "s": 228, "text": "Example #1:" }, { "code": "// Scala program of charAt()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a String val m1 = \"Nidhi\" // Applying charAt() method val result = m1.charAt(2) // Displays output println(result) }} ", "e": 573, "s": 240, "text": null }, { "code": null, "e": 576, "s": 573, "text": "d\n" }, { "code": null, "e": 588, "s": 576, "text": "Example #2:" }, { "code": "// Scala program of charAt()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a String val m1 = \"Nidhi\" // Applying charAt() method val result = m1.charAt(0) // Displays output println(result) }} ", "e": 921, "s": 588, "text": null }, { "code": null, "e": 924, "s": 921, "text": "N\n" }, { "code": null, "e": 938, "s": 924, "text": "shubham_singh" }, { "code": null, "e": 944, "s": 938, "text": "Scala" }, { "code": null, "e": 957, "s": 944, "text": "Scala-Method" }, { "code": null, "e": 971, "s": 957, "text": "Scala-Strings" }, { "code": null, "e": 977, "s": 971, "text": "Scala" }, { "code": null, "e": 1075, "s": 977, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1128, "s": 1075, "text": "Scala Tutorial – Learn Scala with Step By Step Guide" }, { "code": null, "e": 1138, "s": 1128, "text": "Scala Map" }, { "code": null, "e": 1150, "s": 1138, "text": "Scala Lists" }, { "code": null, "e": 1165, "s": 1150, "text": "Scala | Arrays" }, { "code": null, "e": 1186, "s": 1165, "text": "Enumeration in Scala" }, { "code": null, "e": 1213, "s": 1186, "text": "Lambda Expression in Scala" }, { "code": null, "e": 1259, "s": 1213, "text": "How to get the first element of List in Scala" }, { "code": null, "e": 1293, "s": 1259, "text": "How to Install Scala with VSCode?" }, { "code": null, "e": 1336, "s": 1293, "text": "Scala String replace() method with example" } ]
Mouse Programming in C/C++
19 Jul, 2021 Till now we have seen only static output on the black window in C/C++ without any peripheral device interaction(like mouse). Here static means that interaction with the output screen through the mouse to run a dynamic event or task. The goal will be to make the pointer of the mouse visible on our output screen, through which it can see any new event when the mouse is clicked on the same output window. Requirement: Turbo C++ IDE or DOS BOX Fundamental Knowledge: The idea is to tell a mouse to do anything on the output screen. In actual the communication with the mouse directly is not possible but through the driver provided. The idea is to use interrupts to get access to this driver. Each device provided by a computer has a unique port which is a hexadecimal value that is designed to be machine-independent enhancing the portability of the program. Mouse has port 0X33 attached to it. Use of address registers is also required to access these port. These are basically UNION of type REGS defined in “dos.h“. Use two registers to communicate to a device driver one for input and one for output and send value to device driver through the input register and receive information in it embedded in the output register. Now there are two ways to display mouse pointer on C/C++ screen. First is the non-graphic mode and the second is Graphic mode, Here we use graphic mode. To switch our output window in Graphic mode steps are listed below:Enable Graphic mode: For enabling the graphics mode use initgraph() function which is used to initialize the graphics mode. This function is present in “graphics.h“ header file. Syntax of initgraph(): void initgraph(int *gdriver, int *gmode, char *pathtodriver); gdriver: It is an integer that specifies which graphics driver is to be used. Use DETECT it means compiler auto select the suitable driver according to requirement. gmode: It is also an integer that specifies the initial graphics mode. when gdriver = DETECT In this case, initgraph() sets gmode to the highest resolution available for the detected driver. pathtodriver: It denotes the directory path where initgraph must look for graphic drivers. Program 1: C C++ // C program to show how to// enable Graphics mode#include <conio.h>#include <graphics.h> // Driver Codeint main(){ int gdriver = DETECT, gmode, errorcode; initgraph(&gdriver, &gmode, "C:\\TC\\BGI"); errorcode = graphresult(); // If error occurs if (errorcode == grOk) printf("Graphics enabled: %s\n", grapherrormsg(errorcode)); else printf("Graphics error: %s\n", grapherrormsg(errorcode)); getch(); // Close the graph init() closegraph(); return 0;} // C++ program to show how to// enable Graphics mode#include <bits/stdc++.h>#include <conio.h>#include <graphics.h> // Driver Codeint main(){ int gdriver = DETECT, gmode, errorcode; initgraph(&gdriver, &gmode, "C:\\TC\\BGI"); errorcode = graphresult(); // If error occurs if (errorcode == grOk) cout << "Graphics enabled: \n" << grapherrormsg(errorcode); else cout << "Graphics error: \n" << grapherrormsg(errorcode); getch(); // Close the graph init() closegraph(); return 0;} Output: AX Register: The various mouse functions can be access using different values of AX input Register and passing those values to mouse port using an interrupt. Functions are listed below in the table: Here AX, BX, CX, and DX are members of UNION REGS. 0X33 OR 51 0 Reset mouse and get status. Call with AX = 0 Returns AX = FFFFh , if mouse support is available, otherwise, returns Ax = 0. 1 Show mouse pointer. Call with AX = 1. Returns Nothing 2 Hide mouse pointer. Call with AX = 2. Returns Nothing. 3 Get mouse position and button status. Call with AX = 3. Returns BX = mouse button status. BX Bit Significance:0 button not pressed1 left button is pressed2 right button is pressed3 center button is pressedCX = x coordinateDX = y coordinate 0 button not pressed 1 left button is pressed 2 right button is pressed 3 center button is pressed CX = x coordinate DX = y coordinate 4 Set mouse pointer position. Call with AX = 4. CX = x coordinate DX = y coordinate Returns Nothing. 7 Set horizontal limits for pointer. Call with AX = 7. CX = minimum x coordinate. DX = maximum x coordinate. Returns Nothing. 8 Set vertical limits for pointer. Call with AX = 8. CX = minimum y coordinate. DX = maximum y coordinate. Returns Nothing. int86() function: The int86() is a C library function that facilitates access to bare bone DOS and BIOS service interrupts. It is a wrapper over inline assembly interrupt call. It takes CPU register values with object to a structure where member variables are equivalent to CPU registers. It takes three arguments. // Declaration syntax int int86(int intno, union REGS* inregs, union REGS* outregs);// intno – Interrupt vector /service number // inregs – Input argument registers as REGS // outregs – Output argument registers as REGS There are various use cases of the Mouse Programming that are listed below: Detecting MouseDisplay mouse pointer in graphics modeHide pointerDetermine Current positionIdentified which mouse button is clickedRestrict mouse pointerFree hand drawing (Use of all function) Detecting Mouse Display mouse pointer in graphics mode Hide pointer Determine Current position Identified which mouse button is clicked Restrict mouse pointer Free hand drawing (Use of all function) Program 2: Below is the program to check if a mouse driver is loaded or not: C C++ // C program to check mouse status#include <conio.h>#include <dos.h>#include <graphics.h>#include <stdio.h>union REGS in, out; // Function to implement the functionality// of detecting Mousevoid detectMouse(){ in.x.ax = 0; // Invoke interrupt (in86 method // description mentioned above) int86(0X33, &in, &out); if (out.x.ax == 0) printf("\nMouse Failed To Initialize"); else printf("\nMouse was Successfully Initialized");} // Driver Codeint main(){ clrscr(); int gdriver = DETECT, gmode; // Method to enable graphics initgraph(&gdriver, &gmode, "c:\tc\bgi"); // Function Call detectMouse(); getch(); // Close graphics mode closegraph(); return 0;} // C++ program to check mouse status#include <bits/stdc++.h>#include <conio.h>#include <dos.h>#include <graphics.h>#include <stdio.h>union REGS in, out; // Function to implement the functionality// of detecting Mousevoid detectMouse(){ in.x.ax = 0; // Invoke interrupt (in86 method // description mentioned above) int86(0X33, &in, &out); if (out.x.ax == 0) cout << "\nMouse Failed To" << " Initialize"; else cout << "\nMouse was Successfully" << " Initialized";} // Driver Codeint main(){ clrscr(); int gdriver = DETECT, gmode; // Method to enable graphics initgraph(&gdriver, &gmode, "c:\tc\bgi"); // Function Call detectMouse(); getch(); // Close graphics mode closegraph(); return 0;} Output: sooda367 simranarora5sos Articles C Language C Programs C++ C++ Programs CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n19 Jul, 2021" }, { "code": null, "e": 459, "s": 54, "text": "Till now we have seen only static output on the black window in C/C++ without any peripheral device interaction(like mouse). Here static means that interaction with the output screen through the mouse to run a dynamic event or task. The goal will be to make the pointer of the mouse visible on our output screen, through which it can see any new event when the mouse is clicked on the same output window." }, { "code": null, "e": 497, "s": 459, "text": "Requirement: Turbo C++ IDE or DOS BOX" }, { "code": null, "e": 1280, "s": 497, "text": "Fundamental Knowledge: The idea is to tell a mouse to do anything on the output screen. In actual the communication with the mouse directly is not possible but through the driver provided. The idea is to use interrupts to get access to this driver. Each device provided by a computer has a unique port which is a hexadecimal value that is designed to be machine-independent enhancing the portability of the program. Mouse has port 0X33 attached to it. Use of address registers is also required to access these port. These are basically UNION of type REGS defined in “dos.h“. Use two registers to communicate to a device driver one for input and one for output and send value to device driver through the input register and receive information in it embedded in the output register. " }, { "code": null, "e": 1678, "s": 1280, "text": "Now there are two ways to display mouse pointer on C/C++ screen. First is the non-graphic mode and the second is Graphic mode, Here we use graphic mode. To switch our output window in Graphic mode steps are listed below:Enable Graphic mode: For enabling the graphics mode use initgraph() function which is used to initialize the graphics mode. This function is present in “graphics.h“ header file." }, { "code": null, "e": 1703, "s": 1678, "text": "Syntax of initgraph(): " }, { "code": null, "e": 1765, "s": 1703, "text": "void initgraph(int *gdriver, int *gmode, char *pathtodriver);" }, { "code": null, "e": 1930, "s": 1765, "text": "gdriver: It is an integer that specifies which graphics driver is to be used. Use DETECT it means compiler auto select the suitable driver according to requirement." }, { "code": null, "e": 2121, "s": 1930, "text": "gmode: It is also an integer that specifies the initial graphics mode. when gdriver = DETECT In this case, initgraph() sets gmode to the highest resolution available for the detected driver." }, { "code": null, "e": 2212, "s": 2121, "text": "pathtodriver: It denotes the directory path where initgraph must look for graphic drivers." }, { "code": null, "e": 2224, "s": 2212, "text": "Program 1: " }, { "code": null, "e": 2226, "s": 2224, "text": "C" }, { "code": null, "e": 2230, "s": 2226, "text": "C++" }, { "code": "// C program to show how to// enable Graphics mode#include <conio.h>#include <graphics.h> // Driver Codeint main(){ int gdriver = DETECT, gmode, errorcode; initgraph(&gdriver, &gmode, \"C:\\\\TC\\\\BGI\"); errorcode = graphresult(); // If error occurs if (errorcode == grOk) printf(\"Graphics enabled: %s\\n\", grapherrormsg(errorcode)); else printf(\"Graphics error: %s\\n\", grapherrormsg(errorcode)); getch(); // Close the graph init() closegraph(); return 0;}", "e": 2758, "s": 2230, "text": null }, { "code": "// C++ program to show how to// enable Graphics mode#include <bits/stdc++.h>#include <conio.h>#include <graphics.h> // Driver Codeint main(){ int gdriver = DETECT, gmode, errorcode; initgraph(&gdriver, &gmode, \"C:\\\\TC\\\\BGI\"); errorcode = graphresult(); // If error occurs if (errorcode == grOk) cout << \"Graphics enabled: \\n\" << grapherrormsg(errorcode); else cout << \"Graphics error: \\n\" << grapherrormsg(errorcode); getch(); // Close the graph init() closegraph(); return 0;}", "e": 3308, "s": 2758, "text": null }, { "code": null, "e": 3317, "s": 3308, "text": "Output: " }, { "code": null, "e": 3517, "s": 3317, "text": "AX Register: The various mouse functions can be access using different values of AX input Register and passing those values to mouse port using an interrupt. Functions are listed below in the table: " }, { "code": null, "e": 3568, "s": 3517, "text": "Here AX, BX, CX, and DX are members of UNION REGS." }, { "code": null, "e": 3573, "s": 3568, "text": "0X33" }, { "code": null, "e": 3576, "s": 3573, "text": "OR" }, { "code": null, "e": 3579, "s": 3576, "text": "51" }, { "code": null, "e": 3581, "s": 3579, "text": "0" }, { "code": null, "e": 3609, "s": 3581, "text": "Reset mouse and get status." }, { "code": null, "e": 3626, "s": 3609, "text": "Call with AX = 0" }, { "code": null, "e": 3705, "s": 3626, "text": "Returns AX = FFFFh , if mouse support is available, otherwise, returns Ax = 0." }, { "code": null, "e": 3707, "s": 3705, "text": "1" }, { "code": null, "e": 3727, "s": 3707, "text": "Show mouse pointer." }, { "code": null, "e": 3745, "s": 3727, "text": "Call with AX = 1." }, { "code": null, "e": 3761, "s": 3745, "text": "Returns Nothing" }, { "code": null, "e": 3763, "s": 3761, "text": "2" }, { "code": null, "e": 3783, "s": 3763, "text": "Hide mouse pointer." }, { "code": null, "e": 3801, "s": 3783, "text": "Call with AX = 2." }, { "code": null, "e": 3818, "s": 3801, "text": "Returns Nothing." }, { "code": null, "e": 3820, "s": 3818, "text": "3" }, { "code": null, "e": 3858, "s": 3820, "text": "Get mouse position and button status." }, { "code": null, "e": 3876, "s": 3858, "text": "Call with AX = 3." }, { "code": null, "e": 3910, "s": 3876, "text": "Returns BX = mouse button status." }, { "code": null, "e": 4061, "s": 3910, "text": "BX Bit Significance:0 button not pressed1 left button is pressed2 right button is pressed3 center button is pressedCX = x coordinateDX = y coordinate" }, { "code": null, "e": 4082, "s": 4061, "text": "0 button not pressed" }, { "code": null, "e": 4107, "s": 4082, "text": "1 left button is pressed" }, { "code": null, "e": 4134, "s": 4107, "text": "2 right button is pressed" }, { "code": null, "e": 4161, "s": 4134, "text": "3 center button is pressed" }, { "code": null, "e": 4179, "s": 4161, "text": "CX = x coordinate" }, { "code": null, "e": 4197, "s": 4179, "text": "DX = y coordinate" }, { "code": null, "e": 4199, "s": 4197, "text": "4" }, { "code": null, "e": 4227, "s": 4199, "text": "Set mouse pointer position." }, { "code": null, "e": 4245, "s": 4227, "text": "Call with AX = 4." }, { "code": null, "e": 4263, "s": 4245, "text": "CX = x coordinate" }, { "code": null, "e": 4281, "s": 4263, "text": "DX = y coordinate" }, { "code": null, "e": 4298, "s": 4281, "text": "Returns Nothing." }, { "code": null, "e": 4300, "s": 4298, "text": "7" }, { "code": null, "e": 4335, "s": 4300, "text": "Set horizontal limits for pointer." }, { "code": null, "e": 4353, "s": 4335, "text": "Call with AX = 7." }, { "code": null, "e": 4380, "s": 4353, "text": "CX = minimum x coordinate." }, { "code": null, "e": 4407, "s": 4380, "text": "DX = maximum x coordinate." }, { "code": null, "e": 4424, "s": 4407, "text": "Returns Nothing." }, { "code": null, "e": 4426, "s": 4424, "text": "8" }, { "code": null, "e": 4459, "s": 4426, "text": "Set vertical limits for pointer." }, { "code": null, "e": 4477, "s": 4459, "text": "Call with AX = 8." }, { "code": null, "e": 4504, "s": 4477, "text": "CX = minimum y coordinate." }, { "code": null, "e": 4531, "s": 4504, "text": "DX = maximum y coordinate." }, { "code": null, "e": 4548, "s": 4531, "text": "Returns Nothing." }, { "code": null, "e": 4864, "s": 4548, "text": "int86() function: The int86() is a C library function that facilitates access to bare bone DOS and BIOS service interrupts. It is a wrapper over inline assembly interrupt call. It takes CPU register values with object to a structure where member variables are equivalent to CPU registers. It takes three arguments. " }, { "code": null, "e": 5085, "s": 4864, "text": "// Declaration syntax int int86(int intno, union REGS* inregs, union REGS* outregs);// intno – Interrupt vector /service number // inregs – Input argument registers as REGS // outregs – Output argument registers as REGS " }, { "code": null, "e": 5161, "s": 5085, "text": "There are various use cases of the Mouse Programming that are listed below:" }, { "code": null, "e": 5354, "s": 5161, "text": "Detecting MouseDisplay mouse pointer in graphics modeHide pointerDetermine Current positionIdentified which mouse button is clickedRestrict mouse pointerFree hand drawing (Use of all function)" }, { "code": null, "e": 5370, "s": 5354, "text": "Detecting Mouse" }, { "code": null, "e": 5409, "s": 5370, "text": "Display mouse pointer in graphics mode" }, { "code": null, "e": 5422, "s": 5409, "text": "Hide pointer" }, { "code": null, "e": 5449, "s": 5422, "text": "Determine Current position" }, { "code": null, "e": 5490, "s": 5449, "text": "Identified which mouse button is clicked" }, { "code": null, "e": 5513, "s": 5490, "text": "Restrict mouse pointer" }, { "code": null, "e": 5553, "s": 5513, "text": "Free hand drawing (Use of all function)" }, { "code": null, "e": 5630, "s": 5553, "text": "Program 2: Below is the program to check if a mouse driver is loaded or not:" }, { "code": null, "e": 5632, "s": 5630, "text": "C" }, { "code": null, "e": 5636, "s": 5632, "text": "C++" }, { "code": "// C program to check mouse status#include <conio.h>#include <dos.h>#include <graphics.h>#include <stdio.h>union REGS in, out; // Function to implement the functionality// of detecting Mousevoid detectMouse(){ in.x.ax = 0; // Invoke interrupt (in86 method // description mentioned above) int86(0X33, &in, &out); if (out.x.ax == 0) printf(\"\\nMouse Failed To Initialize\"); else printf(\"\\nMouse was Successfully Initialized\");} // Driver Codeint main(){ clrscr(); int gdriver = DETECT, gmode; // Method to enable graphics initgraph(&gdriver, &gmode, \"c:\\tc\\bgi\"); // Function Call detectMouse(); getch(); // Close graphics mode closegraph(); return 0;}", "e": 6355, "s": 5636, "text": null }, { "code": "// C++ program to check mouse status#include <bits/stdc++.h>#include <conio.h>#include <dos.h>#include <graphics.h>#include <stdio.h>union REGS in, out; // Function to implement the functionality// of detecting Mousevoid detectMouse(){ in.x.ax = 0; // Invoke interrupt (in86 method // description mentioned above) int86(0X33, &in, &out); if (out.x.ax == 0) cout << \"\\nMouse Failed To\" << \" Initialize\"; else cout << \"\\nMouse was Successfully\" << \" Initialized\";} // Driver Codeint main(){ clrscr(); int gdriver = DETECT, gmode; // Method to enable graphics initgraph(&gdriver, &gmode, \"c:\\tc\\bgi\"); // Function Call detectMouse(); getch(); // Close graphics mode closegraph(); return 0;}", "e": 7137, "s": 6355, "text": null }, { "code": null, "e": 7146, "s": 7137, "text": "Output: " }, { "code": null, "e": 7157, "s": 7148, "text": "sooda367" }, { "code": null, "e": 7173, "s": 7157, "text": "simranarora5sos" }, { "code": null, "e": 7182, "s": 7173, "text": "Articles" }, { "code": null, "e": 7193, "s": 7182, "text": "C Language" }, { "code": null, "e": 7204, "s": 7193, "text": "C Programs" }, { "code": null, "e": 7208, "s": 7204, "text": "C++" }, { "code": null, "e": 7221, "s": 7208, "text": "C++ Programs" }, { "code": null, "e": 7225, "s": 7221, "text": "CPP" } ]
Search a node in BST | Practice | GeeksforGeeks
Given a Binary Search Tree and a node value X, find if the node with value X is present in the BST or not. Example 1: Input: 2 \ 81 / \ 42 87 \ \ 66 90 / 45 X = 87 Output: 1 Explanation: As 87 is present in the given nodes , so the output will be 1. Example 2: Input: 6 \ 8 / \ 7 9 X = 11 Output: 0 Explanation: As 11 is not present in the given nodes , so the output will be 0. Your Task: You don't need to read input or print anything. Complete the function search()which returns true if the node with value x is present in the BSTelse returns false. Expected Time Complexity: O(Height of the BST) Expected Auxiliary Space: O(1). Constraints: 1 <= Number of nodes <= 105 0 shanu146 days ago C++ Solution :- bool search(Node* root, int x) { if(root==NULL) return 0; else if(root->data==x) return 1; else if(x>root->data) search(root->right,x); else search(root->left,x); } -1 sibajit1176be201 week ago static int search(Node root,int key) { Node temp=root; if (temp==null) { return -1; } if(root.data == key) return 1; if (root.data<key ){ return search(root.right,key); } else if(root.data>key ) { return search(root.left,key); } return -1; } 0 sarthakacharya3 weeks ago class BST: #Function to search a node in BST. def search(self, node, x): if node is None: return 0 if node.data == x: return node if node.data < x: return self.search(node.right,x) else: return self.search(node.left,x) 0 amishasahu3283 weeks ago bool search(Node* root, int x) { // Your code here if(root == NULL) return root; if(root->data == x) return root; if(root->data > x) return search(root->left, x); if(root->data < x) return search(root->right, x); return NULL; } 0 jaydhurat3 weeks ago class BST { // Function to search a node in BST. boolean search(Node root, int x){ if(root==null) { return false; } if(root.data==x) { return true; } if(root.data>x) { return search(root.left,x); } return search(root.right,x); } } 0 pyushkumar9993 weeks ago bool search(Node* root, int x) { if(root == NULL) return false; if(root->data == x) return true; if(root->data < x) return search(root->right,x); if(root->data > x) return search(root->left,x); } Simple C++ solution using recursion. 0 kritikasinha2564 weeks ago PYTHON SOLUTION class BST: def search(self, node, x): if node is None: return None if x > node.data: return self.search(node.right, x) elif x< node.data: return self.search(node.left, x) else: return True return False 0 pritamtech19984 weeks ago One line code: xD bool search(Node* root, int x) { return (root)?(root->data == x)?true:(root->data < x)?search(root->right, x):search(root->left,x):false;} +1 19003001001681 month ago bool flag=false; void find(Node* root, int x){ if(root==NULL){ return; } if(root->data==x){ flag=true; return; } else if(root->data>x){ return find(root->left,x); } else if(root->data<x){ return find(root->right,x); }} bool search(Node* root, int x) { // Your code here find(root,x); return flag;} what is wrong in my code??? +1 wilkygandyj1 month ago //Simple Java Solution class BST { // Function to search a node in BST. boolean search(Node root, int x) { // Your code here Node currentNode = root; while(currentNode != null){ if(currentNode.data == x){ return true; } else if (currentNode.data < x) { currentNode = currentNode.right; } else { currentNode = currentNode.left; } } return false; }} 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": 345, "s": 238, "text": "Given a Binary Search Tree and a node value X, find if the node with value X is present in the BST or not." }, { "code": null, "e": 357, "s": 345, "text": "\nExample 1:" }, { "code": null, "e": 638, "s": 357, "text": "Input: 2\n \\\n 81 \n / \\ \n 42 87 \n \\ \\ \n 66 90 \n / \n 45\nX = 87\nOutput: 1\nExplanation: As 87 is present in the\ngiven nodes , so the output will be\n1." }, { "code": null, "e": 649, "s": 638, "text": "Example 2:" }, { "code": null, "e": 830, "s": 649, "text": "Input: 6\n \\ \n 8 \n / \\ \n 7 9\nX = 11\nOutput: 0\nExplanation: As 11 is not present in \nthe given nodes , so the output will\nbe 0." }, { "code": null, "e": 1005, "s": 830, "text": "\nYour Task:\nYou don't need to read input or print anything. Complete the function search()which returns true if the node with value x is present in the BSTelse returns false." }, { "code": null, "e": 1085, "s": 1005, "text": "\nExpected Time Complexity: O(Height of the BST)\nExpected Auxiliary Space: O(1)." }, { "code": null, "e": 1127, "s": 1085, "text": "\nConstraints:\n1 <= Number of nodes <= 105" }, { "code": null, "e": 1129, "s": 1127, "text": "0" }, { "code": null, "e": 1147, "s": 1129, "text": "shanu146 days ago" }, { "code": null, "e": 1163, "s": 1147, "text": "C++ Solution :-" }, { "code": null, "e": 1359, "s": 1163, "text": "bool search(Node* root, int x) {\n if(root==NULL) return 0;\n \n else if(root->data==x) return 1;\n \n else if(x>root->data) search(root->right,x);\n \n else search(root->left,x);\n}" }, { "code": null, "e": 1362, "s": 1359, "text": "-1" }, { "code": null, "e": 1388, "s": 1362, "text": "sibajit1176be201 week ago" }, { "code": null, "e": 1660, "s": 1388, "text": " static int search(Node root,int key) { Node temp=root; if (temp==null) { return -1; } if(root.data == key) return 1; if (root.data<key ){ return search(root.right,key); } else if(root.data>key ) { return search(root.left,key); } return -1; }" }, { "code": null, "e": 1662, "s": 1660, "text": "0" }, { "code": null, "e": 1688, "s": 1662, "text": "sarthakacharya3 weeks ago" }, { "code": null, "e": 2009, "s": 1688, "text": "class BST:\n \n #Function to search a node in BST.\n def search(self, node, x):\n if node is None:\n return 0\n if node.data == x:\n return node\n \n if node.data < x:\n return self.search(node.right,x)\n else:\n return self.search(node.left,x)" }, { "code": null, "e": 2011, "s": 2009, "text": "0" }, { "code": null, "e": 2036, "s": 2011, "text": "amishasahu3283 weeks ago" }, { "code": null, "e": 2332, "s": 2036, "text": "bool search(Node* root, int x) {\n // Your code here\n if(root == NULL) return root;\n if(root->data == x) return root;\n if(root->data > x)\n return search(root->left, x);\n if(root->data < x)\n return search(root->right, x);\n return NULL;\n}" }, { "code": null, "e": 2334, "s": 2332, "text": "0" }, { "code": null, "e": 2355, "s": 2334, "text": "jaydhurat3 weeks ago" }, { "code": null, "e": 2708, "s": 2355, "text": "class BST {\n // Function to search a node in BST.\n boolean search(Node root, int x){\n if(root==null)\n {\n return false;\n }\n if(root.data==x)\n {\n return true;\n }\n if(root.data>x)\n {\n return search(root.left,x); \n }\n \n return search(root.right,x);\n }\n }" }, { "code": null, "e": 2710, "s": 2708, "text": "0" }, { "code": null, "e": 2735, "s": 2710, "text": "pyushkumar9993 weeks ago" }, { "code": null, "e": 2947, "s": 2735, "text": "bool search(Node* root, int x) {\n if(root == NULL) return false;\n if(root->data == x) return true;\n if(root->data < x) return search(root->right,x);\n if(root->data > x) return search(root->left,x);\n}" }, { "code": null, "e": 2984, "s": 2947, "text": "Simple C++ solution using recursion." }, { "code": null, "e": 2986, "s": 2984, "text": "0" }, { "code": null, "e": 3013, "s": 2986, "text": "kritikasinha2564 weeks ago" }, { "code": null, "e": 3029, "s": 3013, "text": "PYTHON SOLUTION" }, { "code": null, "e": 3304, "s": 3029, "text": "class BST: def search(self, node, x): if node is None: return None if x > node.data: return self.search(node.right, x) elif x< node.data: return self.search(node.left, x) else: return True return False " }, { "code": null, "e": 3306, "s": 3304, "text": "0" }, { "code": null, "e": 3332, "s": 3306, "text": "pritamtech19984 weeks ago" }, { "code": null, "e": 3350, "s": 3332, "text": "One line code: xD" }, { "code": null, "e": 3493, "s": 3352, "text": "bool search(Node* root, int x) { return (root)?(root->data == x)?true:(root->data < x)?search(root->right, x):search(root->left,x):false;}" }, { "code": null, "e": 3496, "s": 3493, "text": "+1" }, { "code": null, "e": 3521, "s": 3496, "text": "19003001001681 month ago" }, { "code": null, "e": 3538, "s": 3521, "text": "bool flag=false;" }, { "code": null, "e": 3792, "s": 3538, "text": "void find(Node* root, int x){ if(root==NULL){ return; } if(root->data==x){ flag=true; return; } else if(root->data>x){ return find(root->left,x); } else if(root->data<x){ return find(root->right,x); }}" }, { "code": null, "e": 3878, "s": 3792, "text": "bool search(Node* root, int x) { // Your code here find(root,x); return flag;} " }, { "code": null, "e": 3908, "s": 3880, "text": "what is wrong in my code???" }, { "code": null, "e": 3911, "s": 3908, "text": "+1" }, { "code": null, "e": 3934, "s": 3911, "text": "wilkygandyj1 month ago" }, { "code": null, "e": 3957, "s": 3934, "text": "//Simple Java Solution" }, { "code": null, "e": 4399, "s": 3957, "text": "class BST { // Function to search a node in BST. boolean search(Node root, int x) { // Your code here Node currentNode = root; while(currentNode != null){ if(currentNode.data == x){ return true; } else if (currentNode.data < x) { currentNode = currentNode.right; } else { currentNode = currentNode.left; } } return false; }}" }, { "code": null, "e": 4545, "s": 4399, "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": 4581, "s": 4545, "text": " Login to access your submissions. " }, { "code": null, "e": 4591, "s": 4581, "text": "\nProblem\n" }, { "code": null, "e": 4601, "s": 4591, "text": "\nContest\n" }, { "code": null, "e": 4664, "s": 4601, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4812, "s": 4664, "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": 5020, "s": 4812, "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": 5126, "s": 5020, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Logistic regression: the basics. Understanding the foundations of... | by Arthur Mello | Towards Data Science
Logistic regression is a technique for modelling the probability of an event. Just like linear regression, it helps you understand the relationship between one or more variables and a target variable, except that, in this case, our target variable is binary: its value is either 0 or 1. For example, it can allow us to say that “smoking can increase your risk of having lung cancer by 20%”, since having lung cancer is a binary variable: you either have it or not (hopefully not). From that, we can infer answers to classification problems. For example, it can help us make an educated guess of whether someone will have lung cancer given that he/she does not smoke, lives in a polluted city and has a family history of lung cancer. With that said, the structure of a logistic regression is also similar to that of a linear regression model: you have a set of explanatory variables (X1, X2...) and our target binary variable (Y). The function behind it, however, is a bit more complicated: P(Y=1) represents the probability of your Y being equal to 1, while b0 is a parameter not linked to X and B is a vector of coefficients that represent the relationship between Y and each one of X1, X2 and so on. The logistic regression will then estimate the values for the b parameters that better fit your data, usually using the maximum likelihood method. Once we have those estimators, we can calculate P(Y=1) for new data points and either stick with that probability or use it to classify those observations based on a threshold (ex.: if the probability of someone having lung cancer is greater than 50%, we can make an educated guess that they will have it). To better understand the difference between a linear and a logistic regression, imagine we plotted the lung cancer variable in the Y-axis (Y = 1 if patient has lung cancer and 0 otherwise) and the patient’s age in the X-axis. Below we have the resulting lines from each regression. Which one seems more fit to our data? One of the most famous datasets for working with classification problems is the Titanic dataset, where we have the list of the Titanic passengers, some of their characteristics, such as age, sex and name, and whether they have survived the disaster or not (for some reason, many classification problems tend to be related to bad things such as lung cancer and dying in a disaster). We’ll be working in R, but you can do the same thing in Python if you want. Let’s first take a look at the available variables: IN:path = 'insert you file path here'data = read.csv(paste(path,'train.csv', sep = ""))colnames(data)OUT: [1] "PassengerId" "Survived" "Pclass" "Name" "Sex" "Age" "SibSp" [8] "Parch" "Ticket" "Fare" "Cabin" "Embarked" So, besides the Id, we have some possibly useful information about them, such as their class in the ship (1st, 2nd or 3rd) and their sex. Before we start modelling, we have to clean our data. Keep in mind, however, that the goal of this article is to introduce logistic regressions, not data cleaning, so we are not going too deep in here. IN:data$Age[is.na(data$Age)] = median(data$Age,na.rm=T)data$Pclass = as.factor(data$Pclass) We have to first replace missing ages by the median of the ages. Then, we turned the passenger class feature into a factor: this means that, instead of reading it as integers, R will read it as a category, which makes more sense in this case. Next step is to split our dataset into train and test, so we can build our model and then calculate some accuracy metrics in another dataset, that has not been used by our model. We have chosen an arbitrary size for the training set, but it usually is something around 70% and 80% of the original dataset. IN:train = data[1:700,]test = data[701:889,] For our first model, let’s choose variables that we intuitively believe could have some link with the probability of surviving the Titanic disaster. Personally, I would guess that the passenger’s class, age and sex can help us predict if they survived or not: IN:model = glm(Survived ~ Pclass + Sex + Age, family = binomial(link = 'logit'), data = train)summary(model)OUT:Call:glm(formula = Survived ~ Pclass + Sex + Age, family = binomial(link = "logit"), data = train)Deviance Residuals: Min 1Q Median 3Q Max -2.5352 -0.7055 -0.4390 0.6186 2.3728Coefficients: Estimate Std. Error z value Pr(>|z|) (Intercept) 3.226908 0.398636 8.095 5.73e-16 ***Pclass2 -0.908714 0.288174 -3.153 0.001614 ** Pclass3 -2.153203 0.268262 -8.026 1.00e-15 ***Sexmale -2.603025 0.209018 -12.454 < 2e-16 ***Age -0.027199 0.008157 -3.334 0.000855 ***---Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1(Dispersion parameter for binomial family taken to be 1)Null deviance: 934.43 on 699 degrees of freedomResidual deviance: 645.20 on 695 degrees of freedomAIC: 655.2Number of Fisher Scoring iterations: 4 Wow, that’s a lot of information at once, right? But let’s focus on the basics for now, starting by how we build our model: glm(Survived ~ Pclass + Sex + Age, family = binomial(link = 'logit'), data = train) We started by calling out a function called glm, that is used for fitting generalised linear models. To make it work specifically as a logistic regression, we set family = binomial and link = ‘logit’. For our problem, we could also have set link to ‘probit’ or ‘cochit’, but we’ll stick to the logit function. The difference between them is mainly theoretical and their results are usually fairly similar. Coefficients: Estimate Std. Error z value Pr(>|z|) (Intercept) 3.226908 0.398636 8.095 5.73e-16 ***Pclass2 -0.908714 0.288174 -3.153 0.001614 ** Pclass3 -2.153203 0.268262 -8.026 1.00e-15 ***Sexmale -2.603025 0.209018 -12.454 < 2e-16 ***Age -0.027199 0.008157 -3.334 0.000855 *** Now, moving on to the coefficients, we can see that all of them are negative (look at the Estimate column), meaning that all these variables are negatively correlated with the probability of survival. That is: being a man or being in classes 2 or 3 (instead of being a woman or in class 1) made you less likely to survive the Titanic disaster. The age coefficient is also negative, so, the older you were the less likely you were to survive. To interpret the precise values of the coefficients, let’s go back to our probability function: Here the Intercept coefficient is the b0 and the other coefficients are the vector B. Our model would look like this (I have rounded the coefficients for better readability): Where Pclass2 = 1 if the passenger was in class 2 and 0 otherwise (similarly for the other variables, except for Age, which is equal to the passenger’s actual age). In addition to being part of our probability equation, they also help us interpret the odds: the coefficient of -2.6 for Sexmale means that the odds of surviving when you are a man are exp(-2.6) = 0.07 times the odds of surviving when you are a woman. The other important column in that table is Pr(>|z|), which we call p-value. It shows us how confident we are that the estimated coefficient is significant (the closer it is to zero, the more confident we are). If we had some coefficients with high p-values, we should probably not include the related variables in our model. Finally, the last item we’ll talk about is the Akaike Information Criterion (AIC), shown at the end of the model summary. In simple terms, the AIC is an estimation of what our error would be if we applied our model to a test sample, and it helps us compare models (the smaller the AIC, the better). Now, let’s try a second model, adding the Fare variable (how much the passenger paid for the ticket): IN:model2 = glm(Survived ~ Pclass + Sex + Age + Fare, family = binomial(link = ‘logit’), data = train)summary(model2)OUT:Call:glm(formula = Survived ~ Pclass + Sex + Age + Fare, family = binomial(link = "logit"), data = train)Deviance Residuals: Min 1Q Median 3Q Max -2.5225 -0.7060 -0.4382 0.6187 2.3749Coefficients: Estimate Std. Error z value Pr(>|z|) (Intercept) 3.2957397 0.4738515 6.955 3.52e-12 ***Pclass2 -0.9500899 0.3265572 -2.909 0.003621 ** Pclass3 -2.2016346 0.3229743 -6.817 9.31e-12 ***Sexmale -2.6085804 0.2100784 -12.417 < 2e-16 ***Age -0.0275303 0.0082521 -3.336 0.000849 ***Fare -0.0006707 0.0024848 -0.270 0.787211 ---Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1(Dispersion parameter for binomial family taken to be 1)Null deviance: 934.43 on 699 degrees of freedomResidual deviance: 645.13 on 694 degrees of freedomAIC: 657.13Number of Fisher Scoring iterations: 4 Notice how the p-value for Fare is high, meaning that it is not a significant variable, and that the AIC has increased, meaning a slightly worse model. One possibility is that, since we already consider the passenger’s class, the ticket fare doesn’t add much new information. To test this, let’s run a third model, with the fare but removing Pclass: IN:model3 = glm(Survived ~ Sex + Age + Fare, family = binomial(link = 'logit'), data = train)summary(model3)OUT:Call:glm(formula = Survived ~ Sex + Age + Fare, family = binomial(link = “logit”), data = train)Deviance Residuals: Min 1Q Median 3Q Max -2.2015 -0.6174 -0.5889 0.8093 1.9786Coefficients: Estimate Std. Error z value Pr(>|z|) (Intercept) 0.835415 0.250798 3.331 0.000865 ***Sexmale -2.429141 0.192294 -12.632 < 2e-16 ***Age -0.005092 0.007294 -0.698 0.485142 Fare 0.009933 0.002412 4.119 3.81e-05 *** — -Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1(Dispersion parameter for binomial family taken to be 1)Null deviance: 934.43 on 699 degrees of freedomResidual deviance: 701.47 on 696 degrees of freedomAIC: 709.47Number of Fisher Scoring iterations: 4 This time, our AIC is dramatically worse and Fare has a significant coefficient but Age is no longer significant. Any idea why that is? Comment your hypothesis here :) Let’s now apply our first model, which performed better than the following two, to the test sample to see how it goes: IN:predictions = ifelse(predict(model, newdata = test) > 0.5, 1, 0)accuracy = mean(predictions == test$Survived)print(paste(‘Accuracy :’, accuracy))OUT:"Accuracy : 0.825396825396825" We started by applying our model to the test set, and stating that the passenger survived if the calculated probability is greater than 0.5. The first metric we calculated was accuracy, which represents our ratio of right predictions. An accuracy of 0.82 means that we got our predictions right 82% of the time. Not bad, right? Well, it depends. Imagine that 99% of the passengers had died. We could then predict that all passengers died, and our accuracy would be of 99% without needing a model for that. Therefore, we should somehow take into account the ratio of survivors in our metrics. That’s where the ROC curve and the AUC come in. ROC stands for Receiver Operating Characteristic, and it’s a plot of the True Positive Rate (probability of predicting 1 when the actual value is 1), against the False Positive Rate (probability of predicting 1 when the actual value is 0). When we plot that curve and calculate the area underneath it, we get the AUC, that stands for Area Under the Curve. That area is always between 0.5 and 1, which gives us a good scale to measure our model performance taking into account the sample distribution of 1's and 0's. To perform these calculations in R, we need the ROCR package: IN:library(ROCR)probabilities = predict(model, newdata = test)prediction_object = prediction(probabilities, test$Survived)roc = performance(prediction_object, measure = "tpr", x.measure = "fpr")plot(roc)OUT: The bigger the area underneath the curve, the better our model, so we want a curve that goes as close as possible to the top-left corner of the plot. Note in our code how we created it using the performance() function and used “fpr” for x.measure and “tpr” for measure. FPR stands for False Positive Rate and TPR for True Positive Rate. To calculate the AUC, we use the performance() function again, but we input “auc” as measure this time: IN:perf_auc = performance(prediction_object, measure = “auc”)auc = perf_auc@y.values[[1]]print(paste(‘AUC :’, auc))OUT:"AUC : 0.863385354141657" We have an AUC of 0.86, which is quite good for a classification problem. Logistic models are used for classification problems, and one of their advantages when compared to more complex alternatives is their interpretability: their results are easy to translate to layman’s terms. We have seen how to run a logistic regression in R, understand its results, how to compare different models and evaluate their performance. As the title suggests, this is an introductory article, and I encourage you to dig deeper in all the possibilities that arise from it. You can start by trying to improve this model, by setting a different link for the glm() function or adding/removing variables. Maybe there’s an automated way of doing it, like for linear regressions? You can access the full R script here.
[ { "code": null, "e": 905, "s": 172, "text": "Logistic regression is a technique for modelling the probability of an event. Just like linear regression, it helps you understand the relationship between one or more variables and a target variable, except that, in this case, our target variable is binary: its value is either 0 or 1. For example, it can allow us to say that “smoking can increase your risk of having lung cancer by 20%”, since having lung cancer is a binary variable: you either have it or not (hopefully not). From that, we can infer answers to classification problems. For example, it can help us make an educated guess of whether someone will have lung cancer given that he/she does not smoke, lives in a polluted city and has a family history of lung cancer." }, { "code": null, "e": 1162, "s": 905, "text": "With that said, the structure of a logistic regression is also similar to that of a linear regression model: you have a set of explanatory variables (X1, X2...) and our target binary variable (Y). The function behind it, however, is a bit more complicated:" }, { "code": null, "e": 1374, "s": 1162, "text": "P(Y=1) represents the probability of your Y being equal to 1, while b0 is a parameter not linked to X and B is a vector of coefficients that represent the relationship between Y and each one of X1, X2 and so on." }, { "code": null, "e": 1828, "s": 1374, "text": "The logistic regression will then estimate the values for the b parameters that better fit your data, usually using the maximum likelihood method. Once we have those estimators, we can calculate P(Y=1) for new data points and either stick with that probability or use it to classify those observations based on a threshold (ex.: if the probability of someone having lung cancer is greater than 50%, we can make an educated guess that they will have it)." }, { "code": null, "e": 2148, "s": 1828, "text": "To better understand the difference between a linear and a logistic regression, imagine we plotted the lung cancer variable in the Y-axis (Y = 1 if patient has lung cancer and 0 otherwise) and the patient’s age in the X-axis. Below we have the resulting lines from each regression. Which one seems more fit to our data?" }, { "code": null, "e": 2606, "s": 2148, "text": "One of the most famous datasets for working with classification problems is the Titanic dataset, where we have the list of the Titanic passengers, some of their characteristics, such as age, sex and name, and whether they have survived the disaster or not (for some reason, many classification problems tend to be related to bad things such as lung cancer and dying in a disaster). We’ll be working in R, but you can do the same thing in Python if you want." }, { "code": null, "e": 2658, "s": 2606, "text": "Let’s first take a look at the available variables:" }, { "code": null, "e": 2937, "s": 2658, "text": "IN:path = 'insert you file path here'data = read.csv(paste(path,'train.csv', sep = \"\"))colnames(data)OUT: [1] \"PassengerId\" \"Survived\" \"Pclass\" \"Name\" \"Sex\" \"Age\" \"SibSp\" [8] \"Parch\" \"Ticket\" \"Fare\" \"Cabin\" \"Embarked\"" }, { "code": null, "e": 3075, "s": 2937, "text": "So, besides the Id, we have some possibly useful information about them, such as their class in the ship (1st, 2nd or 3rd) and their sex." }, { "code": null, "e": 3277, "s": 3075, "text": "Before we start modelling, we have to clean our data. Keep in mind, however, that the goal of this article is to introduce logistic regressions, not data cleaning, so we are not going too deep in here." }, { "code": null, "e": 3369, "s": 3277, "text": "IN:data$Age[is.na(data$Age)] = median(data$Age,na.rm=T)data$Pclass = as.factor(data$Pclass)" }, { "code": null, "e": 3612, "s": 3369, "text": "We have to first replace missing ages by the median of the ages. Then, we turned the passenger class feature into a factor: this means that, instead of reading it as integers, R will read it as a category, which makes more sense in this case." }, { "code": null, "e": 3918, "s": 3612, "text": "Next step is to split our dataset into train and test, so we can build our model and then calculate some accuracy metrics in another dataset, that has not been used by our model. We have chosen an arbitrary size for the training set, but it usually is something around 70% and 80% of the original dataset." }, { "code": null, "e": 3963, "s": 3918, "text": "IN:train = data[1:700,]test = data[701:889,]" }, { "code": null, "e": 4223, "s": 3963, "text": "For our first model, let’s choose variables that we intuitively believe could have some link with the probability of surviving the Titanic disaster. Personally, I would guess that the passenger’s class, age and sex can help us predict if they survived or not:" }, { "code": null, "e": 5160, "s": 4223, "text": "IN:model = glm(Survived ~ Pclass + Sex + Age, family = binomial(link = 'logit'), data = train)summary(model)OUT:Call:glm(formula = Survived ~ Pclass + Sex + Age, family = binomial(link = \"logit\"), data = train)Deviance Residuals: Min 1Q Median 3Q Max -2.5352 -0.7055 -0.4390 0.6186 2.3728Coefficients: Estimate Std. Error z value Pr(>|z|) (Intercept) 3.226908 0.398636 8.095 5.73e-16 ***Pclass2 -0.908714 0.288174 -3.153 0.001614 ** Pclass3 -2.153203 0.268262 -8.026 1.00e-15 ***Sexmale -2.603025 0.209018 -12.454 < 2e-16 ***Age -0.027199 0.008157 -3.334 0.000855 ***---Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1(Dispersion parameter for binomial family taken to be 1)Null deviance: 934.43 on 699 degrees of freedomResidual deviance: 645.20 on 695 degrees of freedomAIC: 655.2Number of Fisher Scoring iterations: 4" }, { "code": null, "e": 5284, "s": 5160, "text": "Wow, that’s a lot of information at once, right? But let’s focus on the basics for now, starting by how we build our model:" }, { "code": null, "e": 5368, "s": 5284, "text": "glm(Survived ~ Pclass + Sex + Age, family = binomial(link = 'logit'), data = train)" }, { "code": null, "e": 5774, "s": 5368, "text": "We started by calling out a function called glm, that is used for fitting generalised linear models. To make it work specifically as a logistic regression, we set family = binomial and link = ‘logit’. For our problem, we could also have set link to ‘probit’ or ‘cochit’, but we’ll stick to the logit function. The difference between them is mainly theoretical and their results are usually fairly similar." }, { "code": null, "e": 6106, "s": 5774, "text": "Coefficients: Estimate Std. Error z value Pr(>|z|) (Intercept) 3.226908 0.398636 8.095 5.73e-16 ***Pclass2 -0.908714 0.288174 -3.153 0.001614 ** Pclass3 -2.153203 0.268262 -8.026 1.00e-15 ***Sexmale -2.603025 0.209018 -12.454 < 2e-16 ***Age -0.027199 0.008157 -3.334 0.000855 ***" }, { "code": null, "e": 6644, "s": 6106, "text": "Now, moving on to the coefficients, we can see that all of them are negative (look at the Estimate column), meaning that all these variables are negatively correlated with the probability of survival. That is: being a man or being in classes 2 or 3 (instead of being a woman or in class 1) made you less likely to survive the Titanic disaster. The age coefficient is also negative, so, the older you were the less likely you were to survive. To interpret the precise values of the coefficients, let’s go back to our probability function:" }, { "code": null, "e": 6819, "s": 6644, "text": "Here the Intercept coefficient is the b0 and the other coefficients are the vector B. Our model would look like this (I have rounded the coefficients for better readability):" }, { "code": null, "e": 7236, "s": 6819, "text": "Where Pclass2 = 1 if the passenger was in class 2 and 0 otherwise (similarly for the other variables, except for Age, which is equal to the passenger’s actual age). In addition to being part of our probability equation, they also help us interpret the odds: the coefficient of -2.6 for Sexmale means that the odds of surviving when you are a man are exp(-2.6) = 0.07 times the odds of surviving when you are a woman." }, { "code": null, "e": 7562, "s": 7236, "text": "The other important column in that table is Pr(>|z|), which we call p-value. It shows us how confident we are that the estimated coefficient is significant (the closer it is to zero, the more confident we are). If we had some coefficients with high p-values, we should probably not include the related variables in our model." }, { "code": null, "e": 7861, "s": 7562, "text": "Finally, the last item we’ll talk about is the Akaike Information Criterion (AIC), shown at the end of the model summary. In simple terms, the AIC is an estimation of what our error would be if we applied our model to a test sample, and it helps us compare models (the smaller the AIC, the better)." }, { "code": null, "e": 7963, "s": 7861, "text": "Now, let’s try a second model, adding the Fare variable (how much the passenger paid for the ticket):" }, { "code": null, "e": 8965, "s": 7963, "text": "IN:model2 = glm(Survived ~ Pclass + Sex + Age + Fare, family = binomial(link = ‘logit’), data = train)summary(model2)OUT:Call:glm(formula = Survived ~ Pclass + Sex + Age + Fare, family = binomial(link = \"logit\"), data = train)Deviance Residuals: Min 1Q Median 3Q Max -2.5225 -0.7060 -0.4382 0.6187 2.3749Coefficients: Estimate Std. Error z value Pr(>|z|) (Intercept) 3.2957397 0.4738515 6.955 3.52e-12 ***Pclass2 -0.9500899 0.3265572 -2.909 0.003621 ** Pclass3 -2.2016346 0.3229743 -6.817 9.31e-12 ***Sexmale -2.6085804 0.2100784 -12.417 < 2e-16 ***Age -0.0275303 0.0082521 -3.336 0.000849 ***Fare -0.0006707 0.0024848 -0.270 0.787211 ---Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1(Dispersion parameter for binomial family taken to be 1)Null deviance: 934.43 on 699 degrees of freedomResidual deviance: 645.13 on 694 degrees of freedomAIC: 657.13Number of Fisher Scoring iterations: 4" }, { "code": null, "e": 9315, "s": 8965, "text": "Notice how the p-value for Fare is high, meaning that it is not a significant variable, and that the AIC has increased, meaning a slightly worse model. One possibility is that, since we already consider the passenger’s class, the ticket fare doesn’t add much new information. To test this, let’s run a third model, with the fare but removing Pclass:" }, { "code": null, "e": 10110, "s": 9315, "text": "IN:model3 = glm(Survived ~ Sex + Age + Fare, family = binomial(link = 'logit'), data = train)summary(model3)OUT:Call:glm(formula = Survived ~ Sex + Age + Fare, family = binomial(link = “logit”), data = train)Deviance Residuals: Min 1Q Median 3Q Max -2.2015 -0.6174 -0.5889 0.8093 1.9786Coefficients: Estimate Std. Error z value Pr(>|z|) (Intercept) 0.835415 0.250798 3.331 0.000865 ***Sexmale -2.429141 0.192294 -12.632 < 2e-16 ***Age -0.005092 0.007294 -0.698 0.485142 Fare 0.009933 0.002412 4.119 3.81e-05 *** — -Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1(Dispersion parameter for binomial family taken to be 1)Null deviance: 934.43 on 699 degrees of freedomResidual deviance: 701.47 on 696 degrees of freedomAIC: 709.47Number of Fisher Scoring iterations: 4" }, { "code": null, "e": 10278, "s": 10110, "text": "This time, our AIC is dramatically worse and Fare has a significant coefficient but Age is no longer significant. Any idea why that is? Comment your hypothesis here :)" }, { "code": null, "e": 10397, "s": 10278, "text": "Let’s now apply our first model, which performed better than the following two, to the test sample to see how it goes:" }, { "code": null, "e": 10580, "s": 10397, "text": "IN:predictions = ifelse(predict(model, newdata = test) > 0.5, 1, 0)accuracy = mean(predictions == test$Survived)print(paste(‘Accuracy :’, accuracy))OUT:\"Accuracy : 0.825396825396825\"" }, { "code": null, "e": 11220, "s": 10580, "text": "We started by applying our model to the test set, and stating that the passenger survived if the calculated probability is greater than 0.5. The first metric we calculated was accuracy, which represents our ratio of right predictions. An accuracy of 0.82 means that we got our predictions right 82% of the time. Not bad, right? Well, it depends. Imagine that 99% of the passengers had died. We could then predict that all passengers died, and our accuracy would be of 99% without needing a model for that. Therefore, we should somehow take into account the ratio of survivors in our metrics. That’s where the ROC curve and the AUC come in." }, { "code": null, "e": 11736, "s": 11220, "text": "ROC stands for Receiver Operating Characteristic, and it’s a plot of the True Positive Rate (probability of predicting 1 when the actual value is 1), against the False Positive Rate (probability of predicting 1 when the actual value is 0). When we plot that curve and calculate the area underneath it, we get the AUC, that stands for Area Under the Curve. That area is always between 0.5 and 1, which gives us a good scale to measure our model performance taking into account the sample distribution of 1's and 0's." }, { "code": null, "e": 11798, "s": 11736, "text": "To perform these calculations in R, we need the ROCR package:" }, { "code": null, "e": 12006, "s": 11798, "text": "IN:library(ROCR)probabilities = predict(model, newdata = test)prediction_object = prediction(probabilities, test$Survived)roc = performance(prediction_object, measure = \"tpr\", x.measure = \"fpr\")plot(roc)OUT:" }, { "code": null, "e": 12447, "s": 12006, "text": "The bigger the area underneath the curve, the better our model, so we want a curve that goes as close as possible to the top-left corner of the plot. Note in our code how we created it using the performance() function and used “fpr” for x.measure and “tpr” for measure. FPR stands for False Positive Rate and TPR for True Positive Rate. To calculate the AUC, we use the performance() function again, but we input “auc” as measure this time:" }, { "code": null, "e": 12592, "s": 12447, "text": "IN:perf_auc = performance(prediction_object, measure = “auc”)auc = perf_auc@y.values[[1]]print(paste(‘AUC :’, auc))OUT:\"AUC : 0.863385354141657\"" }, { "code": null, "e": 12666, "s": 12592, "text": "We have an AUC of 0.86, which is quite good for a classification problem." }, { "code": null, "e": 13349, "s": 12666, "text": "Logistic models are used for classification problems, and one of their advantages when compared to more complex alternatives is their interpretability: their results are easy to translate to layman’s terms. We have seen how to run a logistic regression in R, understand its results, how to compare different models and evaluate their performance. As the title suggests, this is an introductory article, and I encourage you to dig deeper in all the possibilities that arise from it. You can start by trying to improve this model, by setting a different link for the glm() function or adding/removing variables. Maybe there’s an automated way of doing it, like for linear regressions?" } ]
Java program to find the largest number in an array
To find the largest element of the given array, first of all, sort the array. Compare the first two elements of the array If the first element is greater than the second swap them. Then, compare 2nd and 3rd elements if the second element is greater than the 3rd swap them. Repeat this till the end of the array. After sorting an array print the 1st element from the end of the array. Live Demo public class ThirdLargestNumberInAnArray { public static void main(String args[]){ int temp, size; int array[] = {10, 20, 25, 63, 96, 57}; size = array.length; for(int i = 0; i<size; i++ ){ for(int j = i+1; j<size; j++){ if(array[i]>array[j]){ temp = array[i]; array[i] = array[j]; array[j] = temp; } } } System.out.println("Third largest element is:: "+array[size-1]); } } Third largest element is:: 96 You can also sort the elements of the given array using the sort method of the java.util.Arrays class then, print the 1st element from the end of the array. Live Demo import java.util.Arrays; public class LargestNumberSample { public static void main(String args[]){ int array[] = {10, 20, 25, 63, 96, 57}; int size = array.length; Arrays.sort(array); System.out.println("sorted Array ::"+Arrays.toString(array)); int res = array[size-1]; System.out.println("largest element is ::"+res); } } sorted Array ::[10, 20, 25, 57, 63, 96] largest element is ::96
[ { "code": null, "e": 1140, "s": 1062, "text": "To find the largest element of the given array, first of all, sort the array." }, { "code": null, "e": 1184, "s": 1140, "text": "Compare the first two elements of the array" }, { "code": null, "e": 1243, "s": 1184, "text": "If the first element is greater than the second swap them." }, { "code": null, "e": 1335, "s": 1243, "text": "Then, compare 2nd and 3rd elements if the second element is greater than the 3rd swap them." }, { "code": null, "e": 1374, "s": 1335, "text": "Repeat this till the end of the array." }, { "code": null, "e": 1446, "s": 1374, "text": "After sorting an array print the 1st element from the end of the array." }, { "code": null, "e": 1456, "s": 1446, "text": "Live Demo" }, { "code": null, "e": 1960, "s": 1456, "text": "public class ThirdLargestNumberInAnArray {\n public static void main(String args[]){\n int temp, size;\n int array[] = {10, 20, 25, 63, 96, 57};\n size = array.length;\n\n for(int i = 0; i<size; i++ ){\n for(int j = i+1; j<size; j++){\n if(array[i]>array[j]){\n temp = array[i];\n array[i] = array[j];\n array[j] = temp;\n }\n }\n }\n System.out.println(\"Third largest element is:: \"+array[size-1]);\n }\n}" }, { "code": null, "e": 1990, "s": 1960, "text": "Third largest element is:: 96" }, { "code": null, "e": 2147, "s": 1990, "text": "You can also sort the elements of the given array using the sort method of the java.util.Arrays class then, print the 1st element from the end of the array." }, { "code": null, "e": 2157, "s": 2147, "text": "Live Demo" }, { "code": null, "e": 2524, "s": 2157, "text": "import java.util.Arrays;\npublic class LargestNumberSample {\n public static void main(String args[]){\n int array[] = {10, 20, 25, 63, 96, 57};\n int size = array.length;\n Arrays.sort(array);\n System.out.println(\"sorted Array ::\"+Arrays.toString(array));\n int res = array[size-1];\n System.out.println(\"largest element is ::\"+res);\n }\n}" }, { "code": null, "e": 2588, "s": 2524, "text": "sorted Array ::[10, 20, 25, 57, 63, 96]\nlargest element is ::96" } ]
5 Powerful Scikit-Learn Examples. Herein lies just enough information to... | by Posey | Towards Data Science
Below are 5 models. For each model we observe the model’s prediction that an Iris is/isn’t a Virginica. We then perform classification. It’s fascinating to observe how these models differ. We will not spend much time going into detailed math for each example. Our whole goal is to highlight some useful models you can add to your toolbox and highlight some of their differences. In a subsequent article we will discuss pros and cons. No point in ranting, let’s jump right in. Note: Full code for all examples is here. To explain Logistic Regression we can start by explaining the Sigmoid function. Sigmoid is at the core of Logistic Regression. Fundamentally, we take input and output a value between 0 and 1. Our output P(x) is the probability that our dependent variable equals a case. In the following output we get the probability that a certain set of observations is or isn’t a Virginica. We can see that as our petal width feature increases the probability of being a Virginica increases. log_reg = LogisticRegression(penalty="l2")log_reg.fit(X,y) X_new = np.linspace(0,3,1000).reshape(-1,1)y_proba = log_reg.predict_proba(X_new) We can extend Logistic Regression to multiple classes and it turns out to be very powerful. In this example we can see a very low classification error amongst the three classes. softmax_reg = LogisticRegression(multi_class="multinomial", solver="lbfgs", C=5)softmax_reg.fit(X,y)pred = softmax_reg.predict(X_test) Support Vector Machines work by attempting to pass a hyperplane through the dataset, capable of classifying the data. This can be done on various dimensions. Check out this article if you’re interested in diving deep into the various details. clf = svm.SVC(gamma='scale', decision_function_shape='ovo')clf.fit(X,y) X_new = np.linspace(0,3,1000).reshape(-1,1)y_proba = clf.predict_proba(X_new) clf = svm.SVC(gamma='scale', decision_function_shape='ovo')clf.fit(X,y)pred = clf.predict(X_test) Perhaps the simplest of all the models discussed in this article, we make it now to Naive Bayes. Naive Bayes is great for the small amount of data necessary to estimate parameters. Naive Bayes applies Bayes’ theorem and is called naive because of the assumption of conditional independence between each feature. In this example I apply Gaussian Naive Bayes: clf = GaussianNB()clf.fit(X,y) X_new = np.linspace(0,3,1000).reshape(-1,1)y_proba = clf.predict_proba(X_new) clf = GaussianNB()clf.fit(X,y)pred = clf.predict(X) Random Forest is a popular ensemble model used quite frequently. You can see ensemble models popping up all over the place, especially in Kaggle competitions. Random forest works by fitting decision tree classifiers on subsamples of the dataset. It then averages classification performance to garner superior accuracy whilst avoiding overfitting. We set n_estimators to 100 which sets the number of trees in the forest to 100. Max depth sets the maximum depth of the tree. clf = RandomForestClassifier(n_estimators=100, max_depth=2, random_state=0)clf.fit(X,y) X_new = np.linspace(0,3,1000).reshape(-1,1)y_proba = clf.predict_proba(X_new) clf = RandomForestClassifier(n_estimators=100, max_depth=2, random_state=0)clf.fit(X,y)pred = clf.predict(X) Another popular ensemble model...AdaBoost works to fit many classifiers on the dataset with different weights for incorrectly classified instances. AdaBoost training selects the features known to increase the classification power of the model. This of course acts as dimension reduction, which is a plus as long as classification capabilities are preserved. clf = AdaBoostClassifier(n_estimators=100)clf.fit(X,y) X_new = np.linspace(0,3,1000).reshape(-1,1)y_proba = clf.predict_proba(X_new) clf = AdaBoostClassifier(n_estimators=100)clf.fit(X,y)pred = clf.predict(X) Hooray! You made it to the end. Now it’s your job to ask questions and try to understand these models on a deeper level. In the next article I will dive into the pros and cons of each model. Until next time... Some more Scikit-Learn examples: https://scikit-learn.org/stable/auto_examples/classification/plot_classifier_comparison.html As a reminder, all of the models are available on Github if you want to learn more: https://github.com/Poseyy/Articles/tree/master/5SkLearnModels I started Dataset Daily where we share datasets and analysis every Monday, Wednesday, and Friday.
[ { "code": null, "e": 648, "s": 172, "text": "Below are 5 models. For each model we observe the model’s prediction that an Iris is/isn’t a Virginica. We then perform classification. It’s fascinating to observe how these models differ. We will not spend much time going into detailed math for each example. Our whole goal is to highlight some useful models you can add to your toolbox and highlight some of their differences. In a subsequent article we will discuss pros and cons. No point in ranting, let’s jump right in." }, { "code": null, "e": 690, "s": 648, "text": "Note: Full code for all examples is here." }, { "code": null, "e": 1168, "s": 690, "text": "To explain Logistic Regression we can start by explaining the Sigmoid function. Sigmoid is at the core of Logistic Regression. Fundamentally, we take input and output a value between 0 and 1. Our output P(x) is the probability that our dependent variable equals a case. In the following output we get the probability that a certain set of observations is or isn’t a Virginica. We can see that as our petal width feature increases the probability of being a Virginica increases." }, { "code": null, "e": 1309, "s": 1168, "text": "log_reg = LogisticRegression(penalty=\"l2\")log_reg.fit(X,y) X_new = np.linspace(0,3,1000).reshape(-1,1)y_proba = log_reg.predict_proba(X_new)" }, { "code": null, "e": 1487, "s": 1309, "text": "We can extend Logistic Regression to multiple classes and it turns out to be very powerful. In this example we can see a very low classification error amongst the three classes." }, { "code": null, "e": 1622, "s": 1487, "text": "softmax_reg = LogisticRegression(multi_class=\"multinomial\", solver=\"lbfgs\", C=5)softmax_reg.fit(X,y)pred = softmax_reg.predict(X_test)" }, { "code": null, "e": 1865, "s": 1622, "text": "Support Vector Machines work by attempting to pass a hyperplane through the dataset, capable of classifying the data. This can be done on various dimensions. Check out this article if you’re interested in diving deep into the various details." }, { "code": null, "e": 2015, "s": 1865, "text": "clf = svm.SVC(gamma='scale', decision_function_shape='ovo')clf.fit(X,y) X_new = np.linspace(0,3,1000).reshape(-1,1)y_proba = clf.predict_proba(X_new)" }, { "code": null, "e": 2113, "s": 2015, "text": "clf = svm.SVC(gamma='scale', decision_function_shape='ovo')clf.fit(X,y)pred = clf.predict(X_test)" }, { "code": null, "e": 2471, "s": 2113, "text": "Perhaps the simplest of all the models discussed in this article, we make it now to Naive Bayes. Naive Bayes is great for the small amount of data necessary to estimate parameters. Naive Bayes applies Bayes’ theorem and is called naive because of the assumption of conditional independence between each feature. In this example I apply Gaussian Naive Bayes:" }, { "code": null, "e": 2580, "s": 2471, "text": "clf = GaussianNB()clf.fit(X,y) X_new = np.linspace(0,3,1000).reshape(-1,1)y_proba = clf.predict_proba(X_new)" }, { "code": null, "e": 2632, "s": 2580, "text": "clf = GaussianNB()clf.fit(X,y)pred = clf.predict(X)" }, { "code": null, "e": 3105, "s": 2632, "text": "Random Forest is a popular ensemble model used quite frequently. You can see ensemble models popping up all over the place, especially in Kaggle competitions. Random forest works by fitting decision tree classifiers on subsamples of the dataset. It then averages classification performance to garner superior accuracy whilst avoiding overfitting. We set n_estimators to 100 which sets the number of trees in the forest to 100. Max depth sets the maximum depth of the tree." }, { "code": null, "e": 3271, "s": 3105, "text": "clf = RandomForestClassifier(n_estimators=100, max_depth=2, random_state=0)clf.fit(X,y) X_new = np.linspace(0,3,1000).reshape(-1,1)y_proba = clf.predict_proba(X_new)" }, { "code": null, "e": 3380, "s": 3271, "text": "clf = RandomForestClassifier(n_estimators=100, max_depth=2, random_state=0)clf.fit(X,y)pred = clf.predict(X)" }, { "code": null, "e": 3738, "s": 3380, "text": "Another popular ensemble model...AdaBoost works to fit many classifiers on the dataset with different weights for incorrectly classified instances. AdaBoost training selects the features known to increase the classification power of the model. This of course acts as dimension reduction, which is a plus as long as classification capabilities are preserved." }, { "code": null, "e": 3871, "s": 3738, "text": "clf = AdaBoostClassifier(n_estimators=100)clf.fit(X,y) X_new = np.linspace(0,3,1000).reshape(-1,1)y_proba = clf.predict_proba(X_new)" }, { "code": null, "e": 3947, "s": 3871, "text": "clf = AdaBoostClassifier(n_estimators=100)clf.fit(X,y)pred = clf.predict(X)" }, { "code": null, "e": 4157, "s": 3947, "text": "Hooray! You made it to the end. Now it’s your job to ask questions and try to understand these models on a deeper level. In the next article I will dive into the pros and cons of each model. Until next time..." }, { "code": null, "e": 4283, "s": 4157, "text": "Some more Scikit-Learn examples: https://scikit-learn.org/stable/auto_examples/classification/plot_classifier_comparison.html" }, { "code": null, "e": 4429, "s": 4283, "text": "As a reminder, all of the models are available on Github if you want to learn more: https://github.com/Poseyy/Articles/tree/master/5SkLearnModels" } ]
How to make a Python program wait? - GeeksforGeeks
02 Dec, 2020 Prerequisites: time module keyboard module os module Some requirements require a Python program to wait before it goes on. We might need another function to complete or a file to load to give the user a better experience. Discussed below are some ways by which this can be achieved. 1(A) General sleep function Python has a module named time. This module gives several useful functions to control time-related tasks. sleep() is one such function that suspends the execution of the calling thread for a given number of seconds and returns void. The argument may be a floating-point number to indicate more precise sleep time. This is the most common method used because of its ease of use and the fact that it is platform independent. The implementation is given below: Example: Python3 # First import time module.import time # immediately prints the following.print("GFG printed immediately.")time.sleep(5.5) # delays the execution# for 5.5 secs.print("GFG printed after 5.5 secs.") Output: 1(B) Sleep in multithreaded programming For multithreaded python programs, the sleep() function suspends the current thread for a given number of seconds rather than the whole process. But for single-threaded programs sleep() function suspends the thread and the whole process. The implementation is given below: Example: Python3 # import threading and time module.import threadingimport time def print_GFG(): for i in range(5): # suspend the current thread. time.sleep(1) print("GFG") def print_Geeksforgeeks(): for i in range(5): # suspend the current thread. time.sleep(1.5) print("Geeksforgeeks") # two threads are available in this program.t1 = threading.Thread(target=print_GFG)t2 = threading.Thread(target=print_Geeksforgeeks)t1.start()t2.start() Output: We all know that the input() function helps to take data from users. But with the help of this function, we can also pause a python script until a certain key is pressed, like in the following code: Example: Python3 print("GFG immediately")i = input("Press Enter to continue: ") # pauses the script here# until the user press any key.print("GFG after the input.") Output: Using this module, we can resume the program by pressing the key that is specified in the python script (In this program the key is the ‘space‘ key). Keyboard module doesn’t come in-built with python, thus needs to be installed explicitly using the following command: pip install keyboard The implementation is given below: Example: Python3 # import keyboard module.import keyboard # pause() function definition.def pause(): while True: if keyboard.read_key() == 'space': # If you put 'space' key # the program will resume. break print("GeeksforGeeks printed before pause function")pause()print("GeeksforGeeks printed after pause function") Output: This module contains a function called interact(). Some non-programmers may like this simple method. This creates an interpreter that acts almost exactly like a real interpreter. This creates a new instance of Interactive Console and sets readfunc to be used as the InteractiveConsole.raw_input() method if provided. Example: For the program given below press (Ctrl+D) to resume. Python3 # import codeimport code print("GeeksforGeeks printed immediately.") # implementation of code.interact().code.interact(banner='Paused. Press ^D (Ctrl+D) to continue.', local=globals())print("GeeksforGeeks.") Output: Os module contains a method called system(“pause”). Using this method we can make a python program wait until some key is pressed. But this method is platform dependent i.e. only works on windows. So, it is not widely used. Example: Python3 import os print("GeeksforGeeks printed immediately.")os.system("pause")print("GeeksforGeeks.") Output: python-utility 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 Python OOPs Concepts How to Install PIP on Windows ? Bar Plot in Matplotlib Defaultdict in Python Python Classes and Objects Deque in Python Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python - Ways to remove duplicates from list Class method vs Static method in Python
[ { "code": null, "e": 24237, "s": 24209, "text": "\n02 Dec, 2020" }, { "code": null, "e": 24254, "s": 24237, "text": "Prerequisites: " }, { "code": null, "e": 24266, "s": 24254, "text": "time module" }, { "code": null, "e": 24282, "s": 24266, "text": "keyboard module" }, { "code": null, "e": 24292, "s": 24282, "text": "os module" }, { "code": null, "e": 24522, "s": 24292, "text": "Some requirements require a Python program to wait before it goes on. We might need another function to complete or a file to load to give the user a better experience. Discussed below are some ways by which this can be achieved." }, { "code": null, "e": 24550, "s": 24522, "text": "1(A) General sleep function" }, { "code": null, "e": 25008, "s": 24550, "text": "Python has a module named time. This module gives several useful functions to control time-related tasks. sleep() is one such function that suspends the execution of the calling thread for a given number of seconds and returns void. The argument may be a floating-point number to indicate more precise sleep time. This is the most common method used because of its ease of use and the fact that it is platform independent. The implementation is given below:" }, { "code": null, "e": 25017, "s": 25008, "text": "Example:" }, { "code": null, "e": 25025, "s": 25017, "text": "Python3" }, { "code": "# First import time module.import time # immediately prints the following.print(\"GFG printed immediately.\")time.sleep(5.5) # delays the execution# for 5.5 secs.print(\"GFG printed after 5.5 secs.\")", "e": 25224, "s": 25025, "text": null }, { "code": null, "e": 25232, "s": 25224, "text": "Output:" }, { "code": null, "e": 25272, "s": 25232, "text": "1(B) Sleep in multithreaded programming" }, { "code": null, "e": 25545, "s": 25272, "text": "For multithreaded python programs, the sleep() function suspends the current thread for a given number of seconds rather than the whole process. But for single-threaded programs sleep() function suspends the thread and the whole process. The implementation is given below:" }, { "code": null, "e": 25554, "s": 25545, "text": "Example:" }, { "code": null, "e": 25562, "s": 25554, "text": "Python3" }, { "code": "# import threading and time module.import threadingimport time def print_GFG(): for i in range(5): # suspend the current thread. time.sleep(1) print(\"GFG\") def print_Geeksforgeeks(): for i in range(5): # suspend the current thread. time.sleep(1.5) print(\"Geeksforgeeks\") # two threads are available in this program.t1 = threading.Thread(target=print_GFG)t2 = threading.Thread(target=print_Geeksforgeeks)t1.start()t2.start()", "e": 26037, "s": 25562, "text": null }, { "code": null, "e": 26045, "s": 26037, "text": "Output:" }, { "code": null, "e": 26244, "s": 26045, "text": "We all know that the input() function helps to take data from users. But with the help of this function, we can also pause a python script until a certain key is pressed, like in the following code:" }, { "code": null, "e": 26253, "s": 26244, "text": "Example:" }, { "code": null, "e": 26261, "s": 26253, "text": "Python3" }, { "code": "print(\"GFG immediately\")i = input(\"Press Enter to continue: \") # pauses the script here# until the user press any key.print(\"GFG after the input.\")", "e": 26410, "s": 26261, "text": null }, { "code": null, "e": 26418, "s": 26410, "text": "Output:" }, { "code": null, "e": 26686, "s": 26418, "text": "Using this module, we can resume the program by pressing the key that is specified in the python script (In this program the key is the ‘space‘ key). Keyboard module doesn’t come in-built with python, thus needs to be installed explicitly using the following command:" }, { "code": null, "e": 26707, "s": 26686, "text": "pip install keyboard" }, { "code": null, "e": 26742, "s": 26707, "text": "The implementation is given below:" }, { "code": null, "e": 26751, "s": 26742, "text": "Example:" }, { "code": null, "e": 26759, "s": 26751, "text": "Python3" }, { "code": "# import keyboard module.import keyboard # pause() function definition.def pause(): while True: if keyboard.read_key() == 'space': # If you put 'space' key # the program will resume. break print(\"GeeksforGeeks printed before pause function\")pause()print(\"GeeksforGeeks printed after pause function\")", "e": 27106, "s": 26759, "text": null }, { "code": null, "e": 27114, "s": 27106, "text": "Output:" }, { "code": null, "e": 27431, "s": 27114, "text": "This module contains a function called interact(). Some non-programmers may like this simple method. This creates an interpreter that acts almost exactly like a real interpreter. This creates a new instance of Interactive Console and sets readfunc to be used as the InteractiveConsole.raw_input() method if provided." }, { "code": null, "e": 27440, "s": 27431, "text": "Example:" }, { "code": null, "e": 27494, "s": 27440, "text": "For the program given below press (Ctrl+D) to resume." }, { "code": null, "e": 27502, "s": 27494, "text": "Python3" }, { "code": "# import codeimport code print(\"GeeksforGeeks printed immediately.\") # implementation of code.interact().code.interact(banner='Paused. Press ^D (Ctrl+D) to continue.', local=globals())print(\"GeeksforGeeks.\")", "e": 27712, "s": 27502, "text": null }, { "code": null, "e": 27720, "s": 27712, "text": "Output:" }, { "code": null, "e": 27944, "s": 27720, "text": "Os module contains a method called system(“pause”). Using this method we can make a python program wait until some key is pressed. But this method is platform dependent i.e. only works on windows. So, it is not widely used." }, { "code": null, "e": 27953, "s": 27944, "text": "Example:" }, { "code": null, "e": 27961, "s": 27953, "text": "Python3" }, { "code": "import os print(\"GeeksforGeeks printed immediately.\")os.system(\"pause\")print(\"GeeksforGeeks.\")", "e": 28057, "s": 27961, "text": null }, { "code": null, "e": 28065, "s": 28057, "text": "Output:" }, { "code": null, "e": 28080, "s": 28065, "text": "python-utility" }, { "code": null, "e": 28104, "s": 28080, "text": "Technical Scripter 2020" }, { "code": null, "e": 28111, "s": 28104, "text": "Python" }, { "code": null, "e": 28130, "s": 28111, "text": "Technical Scripter" }, { "code": null, "e": 28228, "s": 28130, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28237, "s": 28228, "text": "Comments" }, { "code": null, "e": 28250, "s": 28237, "text": "Old Comments" }, { "code": null, "e": 28271, "s": 28250, "text": "Python OOPs Concepts" }, { "code": null, "e": 28303, "s": 28271, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28326, "s": 28303, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 28348, "s": 28326, "text": "Defaultdict in Python" }, { "code": null, "e": 28375, "s": 28348, "text": "Python Classes and Objects" }, { "code": null, "e": 28391, "s": 28375, "text": "Deque in Python" }, { "code": null, "e": 28433, "s": 28391, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28489, "s": 28433, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28534, "s": 28489, "text": "Python - Ways to remove duplicates from list" } ]
Machine Learning Explainability using Permutation Importance - GeeksforGeeks
18 Jul, 2021 Machine learning models often act as black boxes, meaning that they can make good predictions but it is difficult to fully comprehend the decisions that drive those predictions. Gaining insights from a model is not an easy task, despite the fact that they can help with debugging, feature engineering, directing future data collection, informing human decision-making, and finally, building trust in a model’s predictions. One of the most trivial queries regarding a model might be determining which features have the biggest impact on predictions, called feature importance. One way to evaluate this metric is permutation importance. Permutation importance is computed once a model has been trained on the training set. It inquires: If the data points of a single attribute are randomly shuffled (in the validation set), leaving all remaining data as is, what would be the ramifications on accuracy, using this new data? Ideally, random reordering of a column ought to result in reduced accuracy, since the new data has little or no correlation with real-world statistics. Model accuracy suffers most when an important feature, that the model was quite dependent on, is shuffled. With this insight, the process is as follows: Get a trained model.Shuffle the values for a single attribute and use this data to get new predictions. Next, evaluate change in loss function using these new values and predictions, to determine the effect of shuffling. The drop in performance quantifies the importance of the feature that has been shuffled.Reverse the shuffling done in the previous step to get the original data back. Redo step 2 using the next attribute, until the importance for every feature is determined. Get a trained model. Shuffle the values for a single attribute and use this data to get new predictions. Next, evaluate change in loss function using these new values and predictions, to determine the effect of shuffling. The drop in performance quantifies the importance of the feature that has been shuffled. Reverse the shuffling done in the previous step to get the original data back. Redo step 2 using the next attribute, until the importance for every feature is determined. Python’s ELI5 library provides a convenient way to calculate Permutation Importance. It works in Python 2.7 and Python 3.4+. Currently it requires scikit-learn 0.18+. You can install ELI5 using pip: pip install eli5 or using: conda install -c conda-forge eli5 We’ll train a Random Forest Regressor using scikitlearn’s Boston Housing Prices dataset, and use that trained model to calculate Permutation Importance. Python3 from sklearn.datasets import load_boston boston = load_boston()print(boston.DESCR[20:1420]) Output: Python3 from sklearn.model_selection import train_test_split # separate data into target & independent variablesx = boston.datay = boston.target # split data into train and test setx_train, x_test, y_train, y_test = train_test_split(x, y, train_size=0.8)print('Size of: ')print('Training Set x: ', x_train.shape)print('Training Set y: ', y_train.shape)print('Test Set x: ', x_test.shape)print('Test Set y: ', y_test.shape) Output: Size of: Training Set x: (404, 13) Training Set y: (404,) Test Set x: (102, 13) Test Set y: (102,) Python3 from sklearn.ensemble import RandomForestRegressor # train model on training setrf = RandomForestRegressor() # fit model on training setrf.fit(x_train, y_train) # calculate score on test setprint('R2 score for test set: ')print(rf.score(x_test, y_test)) Output: R2 score for test set: 0.857883705095584 Python3 import eli5from eli5.sklearn import PermutationImportance # create permutation importance object using model# and fit on test setperm = PermutationImportance(rf, random_state=1).fit(x_test, y_test) # display weights using PermutationImportance objecteli5.show_weights(perm, feature_names = boston.feature_names) Output: The values at the top of the table are the most important features in our model, while those at the bottom matter least. The first number in each row indicates how much model performance decreased with random shuffling, using the same performance metric as the model (in this case, R2 score). The number after the ± measures how performance varied from one-reshuffling to the next, i.e., degree of randomness across multiple shuffles. Negative values for permutation importance indicate that the predictions on the shuffled (or noisy) data are more accurate than the real data. This means that the feature does not contribute much to predictions (importance close to 0), but random chance caused the predictions on shuffled data to be more accurate. This is more common with small datasets. In our example, the top 3 features are LSTAT, RM and DIS, while the 3 least significant are RAD, CHAS and ZN. This article is a brief introduction to Machine Learning Explainability using Permutation Importance in Python. Gaining intuition into the impact of features on a model’s performance can help with debugging and provide insights into the dataset, making it a useful tool for data scientists. ELI5 documentationKaggle’s Machine Learning Explainability Coursesklearn’s RandomForestRegressorBoston Housing Prices Dataset ELI5 documentation Kaggle’s Machine Learning Explainability Course sklearn’s RandomForestRegressor Boston Housing Prices Dataset Artificial Intelligence data-science Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Support Vector Machine Algorithm Singular Value Decomposition (SVD) k-nearest neighbor algorithm in Python DBSCAN Clustering in ML | Density based clustering ML | Stochastic Gradient Descent (SGD) Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 24264, "s": 24236, "text": "\n18 Jul, 2021" }, { "code": null, "e": 24687, "s": 24264, "text": "Machine learning models often act as black boxes, meaning that they can make good predictions but it is difficult to fully comprehend the decisions that drive those predictions. Gaining insights from a model is not an easy task, despite the fact that they can help with debugging, feature engineering, directing future data collection, informing human decision-making, and finally, building trust in a model’s predictions." }, { "code": null, "e": 24900, "s": 24687, "text": "One of the most trivial queries regarding a model might be determining which features have the biggest impact on predictions, called feature importance. One way to evaluate this metric is permutation importance. " }, { "code": null, "e": 25187, "s": 24900, "text": "Permutation importance is computed once a model has been trained on the training set. It inquires: If the data points of a single attribute are randomly shuffled (in the validation set), leaving all remaining data as is, what would be the ramifications on accuracy, using this new data?" }, { "code": null, "e": 25492, "s": 25187, "text": "Ideally, random reordering of a column ought to result in reduced accuracy, since the new data has little or no correlation with real-world statistics. Model accuracy suffers most when an important feature, that the model was quite dependent on, is shuffled. With this insight, the process is as follows:" }, { "code": null, "e": 25974, "s": 25492, "text": "Get a trained model.Shuffle the values for a single attribute and use this data to get new predictions. Next, evaluate change in loss function using these new values and predictions, to determine the effect of shuffling. The drop in performance quantifies the importance of the feature that has been shuffled.Reverse the shuffling done in the previous step to get the original data back. Redo step 2 using the next attribute, until the importance for every feature is determined." }, { "code": null, "e": 25995, "s": 25974, "text": "Get a trained model." }, { "code": null, "e": 26286, "s": 25995, "text": "Shuffle the values for a single attribute and use this data to get new predictions. Next, evaluate change in loss function using these new values and predictions, to determine the effect of shuffling. The drop in performance quantifies the importance of the feature that has been shuffled." }, { "code": null, "e": 26458, "s": 26286, "text": "Reverse the shuffling done in the previous step to get the original data back. Redo step 2 using the next attribute, until the importance for every feature is determined." }, { "code": null, "e": 26657, "s": 26458, "text": "Python’s ELI5 library provides a convenient way to calculate Permutation Importance. It works in Python 2.7 and Python 3.4+. Currently it requires scikit-learn 0.18+. You can install ELI5 using pip:" }, { "code": null, "e": 26674, "s": 26657, "text": "pip install eli5" }, { "code": null, "e": 26684, "s": 26674, "text": "or using:" }, { "code": null, "e": 26718, "s": 26684, "text": "conda install -c conda-forge eli5" }, { "code": null, "e": 26871, "s": 26718, "text": "We’ll train a Random Forest Regressor using scikitlearn’s Boston Housing Prices dataset, and use that trained model to calculate Permutation Importance." }, { "code": null, "e": 26879, "s": 26871, "text": "Python3" }, { "code": "from sklearn.datasets import load_boston boston = load_boston()print(boston.DESCR[20:1420])", "e": 26972, "s": 26879, "text": null }, { "code": null, "e": 26980, "s": 26972, "text": "Output:" }, { "code": null, "e": 26988, "s": 26980, "text": "Python3" }, { "code": "from sklearn.model_selection import train_test_split # separate data into target & independent variablesx = boston.datay = boston.target # split data into train and test setx_train, x_test, y_train, y_test = train_test_split(x, y, train_size=0.8)print('Size of: ')print('Training Set x: ', x_train.shape)print('Training Set y: ', y_train.shape)print('Test Set x: ', x_test.shape)print('Test Set y: ', y_test.shape)", "e": 27405, "s": 26988, "text": null }, { "code": null, "e": 27413, "s": 27405, "text": "Output:" }, { "code": null, "e": 27514, "s": 27413, "text": "Size of: \nTraining Set x: (404, 13)\nTraining Set y: (404,)\nTest Set x: (102, 13)\nTest Set y: (102,)\n" }, { "code": null, "e": 27522, "s": 27514, "text": "Python3" }, { "code": "from sklearn.ensemble import RandomForestRegressor # train model on training setrf = RandomForestRegressor() # fit model on training setrf.fit(x_train, y_train) # calculate score on test setprint('R2 score for test set: ')print(rf.score(x_test, y_test))", "e": 27779, "s": 27522, "text": null }, { "code": null, "e": 27787, "s": 27779, "text": "Output:" }, { "code": null, "e": 27829, "s": 27787, "text": "R2 score for test set: 0.857883705095584\n" }, { "code": null, "e": 27837, "s": 27829, "text": "Python3" }, { "code": "import eli5from eli5.sklearn import PermutationImportance # create permutation importance object using model# and fit on test setperm = PermutationImportance(rf, random_state=1).fit(x_test, y_test) # display weights using PermutationImportance objecteli5.show_weights(perm, feature_names = boston.feature_names)", "e": 28151, "s": 27837, "text": null }, { "code": null, "e": 28159, "s": 28151, "text": "Output:" }, { "code": null, "e": 28280, "s": 28159, "text": "The values at the top of the table are the most important features in our model, while those at the bottom matter least." }, { "code": null, "e": 28452, "s": 28280, "text": "The first number in each row indicates how much model performance decreased with random shuffling, using the same performance metric as the model (in this case, R2 score)." }, { "code": null, "e": 28594, "s": 28452, "text": "The number after the ± measures how performance varied from one-reshuffling to the next, i.e., degree of randomness across multiple shuffles." }, { "code": null, "e": 28950, "s": 28594, "text": "Negative values for permutation importance indicate that the predictions on the shuffled (or noisy) data are more accurate than the real data. This means that the feature does not contribute much to predictions (importance close to 0), but random chance caused the predictions on shuffled data to be more accurate. This is more common with small datasets." }, { "code": null, "e": 29060, "s": 28950, "text": "In our example, the top 3 features are LSTAT, RM and DIS, while the 3 least significant are RAD, CHAS and ZN." }, { "code": null, "e": 29351, "s": 29060, "text": "This article is a brief introduction to Machine Learning Explainability using Permutation Importance in Python. Gaining intuition into the impact of features on a model’s performance can help with debugging and provide insights into the dataset, making it a useful tool for data scientists." }, { "code": null, "e": 29477, "s": 29351, "text": "ELI5 documentationKaggle’s Machine Learning Explainability Coursesklearn’s RandomForestRegressorBoston Housing Prices Dataset" }, { "code": null, "e": 29496, "s": 29477, "text": "ELI5 documentation" }, { "code": null, "e": 29544, "s": 29496, "text": "Kaggle’s Machine Learning Explainability Course" }, { "code": null, "e": 29576, "s": 29544, "text": "sklearn’s RandomForestRegressor" }, { "code": null, "e": 29606, "s": 29576, "text": "Boston Housing Prices Dataset" }, { "code": null, "e": 29630, "s": 29606, "text": "Artificial Intelligence" }, { "code": null, "e": 29643, "s": 29630, "text": "data-science" }, { "code": null, "e": 29660, "s": 29643, "text": "Machine Learning" }, { "code": null, "e": 29667, "s": 29660, "text": "Python" }, { "code": null, "e": 29684, "s": 29667, "text": "Machine Learning" }, { "code": null, "e": 29782, "s": 29684, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29791, "s": 29782, "text": "Comments" }, { "code": null, "e": 29804, "s": 29791, "text": "Old Comments" }, { "code": null, "e": 29837, "s": 29804, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 29872, "s": 29837, "text": "Singular Value Decomposition (SVD)" }, { "code": null, "e": 29911, "s": 29872, "text": "k-nearest neighbor algorithm in Python" }, { "code": null, "e": 29962, "s": 29911, "text": "DBSCAN Clustering in ML | Density based clustering" }, { "code": null, "e": 30001, "s": 29962, "text": "ML | Stochastic Gradient Descent (SGD)" }, { "code": null, "e": 30029, "s": 30001, "text": "Read JSON file using Python" }, { "code": null, "e": 30079, "s": 30029, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 30101, "s": 30079, "text": "Python map() function" } ]
Dart Programming - truncate Method
Returns an integer after discarding any fractional digits. Number.truncate() Returns an int without decimal points. void main() { double n1 = 2.123; var value = n1.truncate(); print("The truncated value of 2.123 = ${value}"); } It will produce the following output −. The truncated value of 2.123 = 2 44 Lectures 4.5 hours Sriyank Siddhartha 34 Lectures 4 hours Sriyank Siddhartha 69 Lectures 4 hours Frahaan Hussain 117 Lectures 10 hours Frahaan Hussain 22 Lectures 1.5 hours Pranjal Srivastava 34 Lectures 3 hours Pranjal Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2584, "s": 2525, "text": "Returns an integer after discarding any fractional digits." }, { "code": null, "e": 2603, "s": 2584, "text": "Number.truncate()\n" }, { "code": null, "e": 2642, "s": 2603, "text": "Returns an int without decimal points." }, { "code": null, "e": 2768, "s": 2642, "text": "void main() { \n double n1 = 2.123; \n var value = n1.truncate(); \n print(\"The truncated value of 2.123 = ${value}\"); \n} " }, { "code": null, "e": 2808, "s": 2768, "text": "It will produce the following output −." }, { "code": null, "e": 2843, "s": 2808, "text": "The truncated value of 2.123 = 2 \n" }, { "code": null, "e": 2878, "s": 2843, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 2898, "s": 2878, "text": " Sriyank Siddhartha" }, { "code": null, "e": 2931, "s": 2898, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 2951, "s": 2931, "text": " Sriyank Siddhartha" }, { "code": null, "e": 2984, "s": 2951, "text": "\n 69 Lectures \n 4 hours \n" }, { "code": null, "e": 3001, "s": 2984, "text": " Frahaan Hussain" }, { "code": null, "e": 3036, "s": 3001, "text": "\n 117 Lectures \n 10 hours \n" }, { "code": null, "e": 3053, "s": 3036, "text": " Frahaan Hussain" }, { "code": null, "e": 3088, "s": 3053, "text": "\n 22 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3108, "s": 3088, "text": " Pranjal Srivastava" }, { "code": null, "e": 3141, "s": 3108, "text": "\n 34 Lectures \n 3 hours \n" }, { "code": null, "e": 3161, "s": 3141, "text": " Pranjal Srivastava" }, { "code": null, "e": 3168, "s": 3161, "text": " Print" }, { "code": null, "e": 3179, "s": 3168, "text": " Add Notes" } ]
How to append some text to all paragraphs using jQuery ? - GeeksforGeeks
31 Dec, 2020 In this article, we will append some text to all paragraph elements using jQuery. To append some text to all paragraph elements, we use append() and document.createTextNode() methods. jQuery append() method is used to insert some content at the end of the selected elements. Syntax: $(selector).append( content, function(index, html) ) Example: HTML <!DOCTYPE html><html lang="en"> <head> <!-- Import jQuery cdn library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script> $(document).ready(function () { $("button").click(function () { $("p").append(document .createTextNode(" GeeksforGeeks")); }); }); </script></head> <body style="text-align: center;"> <h1 style="color: green;"> GeeksforGeeks </h1> <h3> How to append some text to all paragraphs using jQuery? </h3> <p> Computer Science Portal </p> <p>Welcome</p> <button>Click Here!</button></body> </html> Output: Before Click the Button: After Click Button: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Misc HTML-Misc jQuery-Misc CSS HTML JQuery Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Design a web page using HTML and CSS Form validation using jQuery Search Bar using HTML, CSS and JavaScript How to set space between the flexbox ? How to Create Time-Table schedule using HTML ? How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? How to Insert Form Data into Database using PHP ? Hide or show elements in HTML using display property REST API (Introduction)
[ { "code": null, "e": 25381, "s": 25353, "text": "\n31 Dec, 2020" }, { "code": null, "e": 25565, "s": 25381, "text": "In this article, we will append some text to all paragraph elements using jQuery. To append some text to all paragraph elements, we use append() and document.createTextNode() methods." }, { "code": null, "e": 25656, "s": 25565, "text": "jQuery append() method is used to insert some content at the end of the selected elements." }, { "code": null, "e": 25664, "s": 25656, "text": "Syntax:" }, { "code": null, "e": 25717, "s": 25664, "text": "$(selector).append( content, function(index, html) )" }, { "code": null, "e": 25726, "s": 25717, "text": "Example:" }, { "code": null, "e": 25731, "s": 25726, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <!-- Import jQuery cdn library --> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script> $(document).ready(function () { $(\"button\").click(function () { $(\"p\").append(document .createTextNode(\" GeeksforGeeks\")); }); }); </script></head> <body style=\"text-align: center;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <h3> How to append some text to all paragraphs using jQuery? </h3> <p> Computer Science Portal </p> <p>Welcome</p> <button>Click Here!</button></body> </html>", "e": 26441, "s": 25731, "text": null }, { "code": null, "e": 26449, "s": 26441, "text": "Output:" }, { "code": null, "e": 26474, "s": 26449, "text": "Before Click the Button:" }, { "code": null, "e": 26494, "s": 26474, "text": "After Click Button:" }, { "code": null, "e": 26631, "s": 26494, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 26640, "s": 26631, "text": "CSS-Misc" }, { "code": null, "e": 26650, "s": 26640, "text": "HTML-Misc" }, { "code": null, "e": 26662, "s": 26650, "text": "jQuery-Misc" }, { "code": null, "e": 26666, "s": 26662, "text": "CSS" }, { "code": null, "e": 26671, "s": 26666, "text": "HTML" }, { "code": null, "e": 26678, "s": 26671, "text": "JQuery" }, { "code": null, "e": 26695, "s": 26678, "text": "Web Technologies" }, { "code": null, "e": 26700, "s": 26695, "text": "HTML" }, { "code": null, "e": 26798, "s": 26700, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26807, "s": 26798, "text": "Comments" }, { "code": null, "e": 26820, "s": 26807, "text": "Old Comments" }, { "code": null, "e": 26857, "s": 26820, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 26886, "s": 26857, "text": "Form validation using jQuery" }, { "code": null, "e": 26928, "s": 26886, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 26967, "s": 26928, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 27014, "s": 26967, "text": "How to Create Time-Table schedule using HTML ?" }, { "code": null, "e": 27074, "s": 27014, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 27135, "s": 27074, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 27185, "s": 27135, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 27238, "s": 27185, "text": "Hide or show elements in HTML using display property" } ]
Dictionary Operations in Data Structure
A dictionary is defined as a general-purpose data structure for storing a group of objects. A dictionary is associated with a set of keys and each key has a single associated value. When presented with a key, the dictionary will simply return the associated value. For example, the results of a classroom test could be represented as a dictionary with student's names as keys and their scores as the values: results = {'Anik' : 75, 'Aftab' :80, 'James' : 85, 'Manisha': 77, 'Suhana' :87, 'Margaret': 82} Dictionaries typically support so many operations − retrieve a value (based on language, attempting to retrieve a missing key may provide a default value or throw an exception) retrieve a value (based on language, attempting to retrieve a missing key may provide a default value or throw an exception) inserting or updating a value (typically, if the key does not exist in the dictionary, the key-value pair is inserted; if the key already exists, its corresponding value is overwritten with the new one) inserting or updating a value (typically, if the key does not exist in the dictionary, the key-value pair is inserted; if the key already exists, its corresponding value is overwritten with the new one) remove or delete a key-value pair remove or delete a key-value pair test or verify for existence of a key test or verify for existence of a key Most programming languages with dictionaries support iteration over the keys or values in a dictionary. Note that items in a dictionary are unordered, so loops over dictionaries will return items in random order.
[ { "code": null, "e": 1327, "s": 1062, "text": "A dictionary is defined as a general-purpose data structure for storing a group of objects. A dictionary is associated with a set of keys and each key has a single associated value. When\npresented with a key, the dictionary will simply return the associated value." }, { "code": null, "e": 1470, "s": 1327, "text": "For example, the results of a classroom test could be represented as a dictionary with student's names as keys and their scores as the values:" }, { "code": null, "e": 1566, "s": 1470, "text": "results = {'Anik' : 75,\n'Aftab' :80,\n'James' : 85,\n'Manisha': 77,\n'Suhana' :87,\n'Margaret': 82}" }, { "code": null, "e": 1618, "s": 1566, "text": "Dictionaries typically support so many operations −" }, { "code": null, "e": 1743, "s": 1618, "text": "retrieve a value (based on language, attempting to retrieve a missing key may provide a default value or throw an exception)" }, { "code": null, "e": 1868, "s": 1743, "text": "retrieve a value (based on language, attempting to retrieve a missing key may provide a default value or throw an exception)" }, { "code": null, "e": 2071, "s": 1868, "text": "inserting or updating a value (typically, if the key does not exist in the dictionary, the key-value pair is inserted; if the key already exists, its corresponding value is overwritten with the new one)" }, { "code": null, "e": 2274, "s": 2071, "text": "inserting or updating a value (typically, if the key does not exist in the dictionary, the key-value pair is inserted; if the key already exists, its corresponding value is overwritten with the new one)" }, { "code": null, "e": 2308, "s": 2274, "text": "remove or delete a key-value pair" }, { "code": null, "e": 2342, "s": 2308, "text": "remove or delete a key-value pair" }, { "code": null, "e": 2380, "s": 2342, "text": "test or verify for existence of a key" }, { "code": null, "e": 2418, "s": 2380, "text": "test or verify for existence of a key" }, { "code": null, "e": 2631, "s": 2418, "text": "Most programming languages with dictionaries support iteration over the keys or values in a dictionary. Note that items in a dictionary are unordered, so loops over dictionaries will return items in random order." } ]
MATLAB - Colon Notation
The colon(:) is one of the most useful operator in MATLAB. It is used to create vectors, subscript arrays, and specify for iterations. If you want to create a row vector, containing integers from 1 to 10, you write − 1:10 MATLAB executes the statement and returns a row vector containing the integers from 1 to 10 − ans = 1 2 3 4 5 6 7 8 9 10 If you want to specify an increment value other than one, for example − 100: -5: 50 MATLAB executes the statement and returns the following result − ans = 100 95 90 85 80 75 70 65 60 55 50 Let us take another example − 0:pi/8:pi MATLAB executes the statement and returns the following result − ans = Columns 1 through 7 0 0.3927 0.7854 1.1781 1.5708 1.9635 2.3562 Columns 8 through 9 2.7489 3.1416 You can use the colon operator to create a vector of indices to select rows, columns or elements of arrays. The following table describes its use for this purpose (let us have a matrix A) − Create a script file and type the following code in it − A = [1 2 3 4; 4 5 6 7; 7 8 9 10] A(:,2) % second column of A A(:,2:3) % second and third column of A A(2:3,2:3) % second and third rows and second and third columns When you run the file, it displays the following result − A = 1 2 3 4 4 5 6 7 7 8 9 10 ans = 2 5 8 ans = 2 3 5 6 8 9 ans = 5 6 8 9 30 Lectures 4 hours Nouman Azam 127 Lectures 12 hours Nouman Azam 17 Lectures 3 hours Sanjeev 37 Lectures 5 hours TELCOMA Global 22 Lectures 4 hours TELCOMA Global 18 Lectures 3 hours Phinite Academy Print Add Notes Bookmark this page
[ { "code": null, "e": 2276, "s": 2141, "text": "The colon(:) is one of the most useful operator in MATLAB. It is used to create vectors, subscript arrays, and specify for iterations." }, { "code": null, "e": 2358, "s": 2276, "text": "If you want to create a row vector, containing integers from 1 to 10, you write −" }, { "code": null, "e": 2363, "s": 2358, "text": "1:10" }, { "code": null, "e": 2457, "s": 2363, "text": "MATLAB executes the statement and returns a row vector containing the integers from 1 to 10 −" }, { "code": null, "e": 2671, "s": 2457, "text": "ans = \n \n 1 2 3 4 5 6 7 8 9 10 \n" }, { "code": null, "e": 2743, "s": 2671, "text": "If you want to specify an increment value other than one, for example −" }, { "code": null, "e": 2755, "s": 2743, "text": "100: -5: 50" }, { "code": null, "e": 2820, "s": 2755, "text": "MATLAB executes the statement and returns the following result −" }, { "code": null, "e": 2894, "s": 2820, "text": "ans =\n 100 95 90 85 80 75 70 65 60 55 50\n" }, { "code": null, "e": 2924, "s": 2894, "text": "Let us take another example −" }, { "code": null, "e": 2934, "s": 2924, "text": "0:pi/8:pi" }, { "code": null, "e": 2999, "s": 2934, "text": "MATLAB executes the statement and returns the following result −" }, { "code": null, "e": 3143, "s": 2999, "text": "ans =\n Columns 1 through 7\n 0 0.3927 0.7854 1.1781 1.5708 1.9635 2.3562\n Columns 8 through 9\n 2.7489 3.1416\n" }, { "code": null, "e": 3251, "s": 3143, "text": "You can use the colon operator to create a vector of indices to select rows, columns or elements of arrays." }, { "code": null, "e": 3333, "s": 3251, "text": "The following table describes its use for this purpose (let us have a matrix A) −" }, { "code": null, "e": 3390, "s": 3333, "text": "Create a script file and type the following code in it −" }, { "code": null, "e": 3564, "s": 3390, "text": "A = [1 2 3 4; 4 5 6 7; 7 8 9 10]\nA(:,2) % second column of A\nA(:,2:3) % second and third column of A\nA(2:3,2:3) % second and third rows and second and third columns" }, { "code": null, "e": 3622, "s": 3564, "text": "When you run the file, it displays the following result −" }, { "code": null, "e": 3820, "s": 3622, "text": "A =\n 1 2 3 4\n 4 5 6 7\n 7 8 9 10\n\nans =\n 2\n 5\n 8\n\nans =\n 2 3\n 5 6\n 8 9\n\nans =\n 5 6\n 8 9\n" }, { "code": null, "e": 3853, "s": 3820, "text": "\n 30 Lectures \n 4 hours \n" }, { "code": null, "e": 3866, "s": 3853, "text": " Nouman Azam" }, { "code": null, "e": 3901, "s": 3866, "text": "\n 127 Lectures \n 12 hours \n" }, { "code": null, "e": 3914, "s": 3901, "text": " Nouman Azam" }, { "code": null, "e": 3947, "s": 3914, "text": "\n 17 Lectures \n 3 hours \n" }, { "code": null, "e": 3956, "s": 3947, "text": " Sanjeev" }, { "code": null, "e": 3989, "s": 3956, "text": "\n 37 Lectures \n 5 hours \n" }, { "code": null, "e": 4005, "s": 3989, "text": " TELCOMA Global" }, { "code": null, "e": 4038, "s": 4005, "text": "\n 22 Lectures \n 4 hours \n" }, { "code": null, "e": 4054, "s": 4038, "text": " TELCOMA Global" }, { "code": null, "e": 4087, "s": 4054, "text": "\n 18 Lectures \n 3 hours \n" }, { "code": null, "e": 4104, "s": 4087, "text": " Phinite Academy" }, { "code": null, "e": 4111, "s": 4104, "text": " Print" }, { "code": null, "e": 4122, "s": 4111, "text": " Add Notes" } ]
Julia’s Package Manager Is AWESOME | by Emmett Boudreau | Towards Data Science
In the past, I’ve gone beyond praise for the amazing multi-paradigm statistical language, Julia. This is for good reason because Julia is an incredibly high-level language that stretches the limits of what we thought could come from such high-level syntax. Additionally, in terms of being ideal for machine-learning, from how much I’ve used the big four, Julia is perfectly able to out-perform Python, R, and even Scala. I even briefly joked about getting a Julia tattoo on my head, even going as far as to create a semi-realistic rendering of that exact thing: Looks great, doesn’t it? But with all of this flaunting of one of my absolute favorite programming languages of all time, I’ve much neglected one of the features that makes Julia even better: Pkg Pkg is Julia’s package manager, and it is not a typical package manager like the ones you would find in Python or R. In fact, for the most part, I firmly believe that Julia’s package manager outmatches every Linux package manager I've ever used, including Dnf, Apt, Man, and likely the most robust: Pacman. There are a few key benefits that make managing packages in Julia a breeze with the Pkg package manager, and it’s likely that you’ll say “ It can do that?” at some point. A massive benefit to Pkg is that it has its own read evaluate print loop, or REPL. This is beneficial for a few reasons, the first of which I would like to mention is that it can add packages quicker than the library equivalent. This is because it makes it possible to skip recompiling a stale cache file entirely simply by pressing a key, ] Additionally, this allows for non-syntactual package adding, making it super quick and easy to add a package with simply a command and a space: add "Lathe" In addition to having a REPL, however, Julia’s Pkg also comes in the form of a Julia package itself. This is useful because it means that you can not only add packages from within the REPL, but also the code itself. This was particularly useful whenever I created TopLoader, which is a Python package that allows you to create a virtual Pkg environment and then use the packages added to that environment. Julia’s package manager is entirely based off of Github, where packages are pushed into the Registrator.jl repository, which you can take a gander at here. Not only does this make it incredibly easy to push your Julia packages through Github, but also allows you to add unregistered packages with Git URLs. This makes unpublished software, which is usually stored in a Git-compatible repository always usable. Julia’s packages use Github as a foundation for development, and that is certainly not a bad idea, as even non-developers are well aware that Open-Source development essentially revolves around Github. There are a lot of questions in life that have yet to be answered, but the age-old question of “ Who did environments the best?” has certainly already been answered. Compared to Pip, Package get, Quick Lisp, and the thousands of other package managers that are also called “ Pkg,” Julia’s Pkg once again outshines the competition. From the get-go, out of the box you can activate a virtual environment with two simple commands from the REPL, or a method from the package. using PkgPkg.activate("venv")julia> ]pkg> activate "venv" This makes managing and utilizing these virtual environments shockingly easy. It’s hard to justify this methodology of activating virtual environments without comparing it to a similar option of one of Julia’s competitors, Python. The package manager for Python is Pip, and though certainly not quite as robust as Pkg, I think Pip certainly stands the test of time and gets the job done in Python. But to activate a virtual environment for Pip, you need to install an entirely new package, that being venv, or something similar (there are a few different options.) sudo pip3 install virtualenvpython3 python3 -m venv venvname This is certainly not terrible, but on the other hand: certainly not nearly as robust and simple as the Julia equivalent. Reiterating on my Python package for loading Julia modules in a virtual environment, development of said package was incredibly easy because I was able to use the activate() method. I love Julia’s Pkg, and I tip my hat to the developers that put in the hard work to develop it, only to make the Julia programming experience that much better. I think many other package managers have a lot to learn from Pkg, because to me personally, it has always felt like the perfect package manager. I encourage you to try it out, as it feels like a breath of fresh air in a world filled with CLI package managers. Overall, I think that Pkg.jl contributes a lot to Julia, and makes the language even more enjoyable than it already is (hard to do) to use.
[ { "code": null, "e": 733, "s": 171, "text": "In the past, I’ve gone beyond praise for the amazing multi-paradigm statistical language, Julia. This is for good reason because Julia is an incredibly high-level language that stretches the limits of what we thought could come from such high-level syntax. Additionally, in terms of being ideal for machine-learning, from how much I’ve used the big four, Julia is perfectly able to out-perform Python, R, and even Scala. I even briefly joked about getting a Julia tattoo on my head, even going as far as to create a semi-realistic rendering of that exact thing:" }, { "code": null, "e": 758, "s": 733, "text": "Looks great, doesn’t it?" }, { "code": null, "e": 925, "s": 758, "text": "But with all of this flaunting of one of my absolute favorite programming languages of all time, I’ve much neglected one of the features that makes Julia even better:" }, { "code": null, "e": 929, "s": 925, "text": "Pkg" }, { "code": null, "e": 1373, "s": 929, "text": "Pkg is Julia’s package manager, and it is not a typical package manager like the ones you would find in Python or R. In fact, for the most part, I firmly believe that Julia’s package manager outmatches every Linux package manager I've ever used, including Dnf, Apt, Man, and likely the most robust: Pacman. There are a few key benefits that make managing packages in Julia a breeze with the Pkg package manager, and it’s likely that you’ll say" }, { "code": null, "e": 1407, "s": 1373, "text": "“ It can do that?” at some point." }, { "code": null, "e": 1747, "s": 1407, "text": "A massive benefit to Pkg is that it has its own read evaluate print loop, or REPL. This is beneficial for a few reasons, the first of which I would like to mention is that it can add packages quicker than the library equivalent. This is because it makes it possible to skip recompiling a stale cache file entirely simply by pressing a key," }, { "code": null, "e": 1749, "s": 1747, "text": "]" }, { "code": null, "e": 1893, "s": 1749, "text": "Additionally, this allows for non-syntactual package adding, making it super quick and easy to add a package with simply a command and a space:" }, { "code": null, "e": 1905, "s": 1893, "text": "add \"Lathe\"" }, { "code": null, "e": 2311, "s": 1905, "text": "In addition to having a REPL, however, Julia’s Pkg also comes in the form of a Julia package itself. This is useful because it means that you can not only add packages from within the REPL, but also the code itself. This was particularly useful whenever I created TopLoader, which is a Python package that allows you to create a virtual Pkg environment and then use the packages added to that environment." }, { "code": null, "e": 2467, "s": 2311, "text": "Julia’s package manager is entirely based off of Github, where packages are pushed into the Registrator.jl repository, which you can take a gander at here." }, { "code": null, "e": 2923, "s": 2467, "text": "Not only does this make it incredibly easy to push your Julia packages through Github, but also allows you to add unregistered packages with Git URLs. This makes unpublished software, which is usually stored in a Git-compatible repository always usable. Julia’s packages use Github as a foundation for development, and that is certainly not a bad idea, as even non-developers are well aware that Open-Source development essentially revolves around Github." }, { "code": null, "e": 3018, "s": 2923, "text": "There are a lot of questions in life that have yet to be answered, but the age-old question of" }, { "code": null, "e": 3052, "s": 3018, "text": "“ Who did environments the best?”" }, { "code": null, "e": 3395, "s": 3052, "text": "has certainly already been answered. Compared to Pip, Package get, Quick Lisp, and the thousands of other package managers that are also called “ Pkg,” Julia’s Pkg once again outshines the competition. From the get-go, out of the box you can activate a virtual environment with two simple commands from the REPL, or a method from the package." }, { "code": null, "e": 3453, "s": 3395, "text": "using PkgPkg.activate(\"venv\")julia> ]pkg> activate \"venv\"" }, { "code": null, "e": 4018, "s": 3453, "text": "This makes managing and utilizing these virtual environments shockingly easy. It’s hard to justify this methodology of activating virtual environments without comparing it to a similar option of one of Julia’s competitors, Python. The package manager for Python is Pip, and though certainly not quite as robust as Pkg, I think Pip certainly stands the test of time and gets the job done in Python. But to activate a virtual environment for Pip, you need to install an entirely new package, that being venv, or something similar (there are a few different options.)" }, { "code": null, "e": 4079, "s": 4018, "text": "sudo pip3 install virtualenvpython3 python3 -m venv venvname" }, { "code": null, "e": 4383, "s": 4079, "text": "This is certainly not terrible, but on the other hand: certainly not nearly as robust and simple as the Julia equivalent. Reiterating on my Python package for loading Julia modules in a virtual environment, development of said package was incredibly easy because I was able to use the activate() method." } ]
Initialization vs Instantiation in C#
When you assign a value to a variable when it is declared, it is called Initialization. Here is an example − int val = 50; For array initialization, you may need a new keyword, whereas to initialize a variable, you do not need it. When you create a new object in C# for a class using the new keyword, then it is called instantiation. Use the new operator to instantiate a class in C#. Here is an example showing two objects of Student class created using new keyword − Student s1 = new Student(); Student s2 = new Student();
[ { "code": null, "e": 1150, "s": 1062, "text": "When you assign a value to a variable when it is declared, it is called Initialization." }, { "code": null, "e": 1171, "s": 1150, "text": "Here is an example −" }, { "code": null, "e": 1186, "s": 1171, "text": "int val = 50;\n" }, { "code": null, "e": 1294, "s": 1186, "text": "For array initialization, you may need a new keyword, whereas to initialize a variable, you do not need it." }, { "code": null, "e": 1397, "s": 1294, "text": "When you create a new object in C# for a class using the new keyword, then it is called instantiation." }, { "code": null, "e": 1448, "s": 1397, "text": "Use the new operator to instantiate a class in C#." }, { "code": null, "e": 1532, "s": 1448, "text": "Here is an example showing two objects of Student class created using new keyword −" }, { "code": null, "e": 1589, "s": 1532, "text": "Student s1 = new Student();\nStudent s2 = new Student();\n" } ]
Check whether the String contains only digit characters in Java
The following is our string. String str = "4434"; To check whether the above string has only digit characters, try the following if condition that uses matches() method and checks for every character. if(str.matches("[0-9]+") && str.length() > 2) { System.out.println("String contains only digits!"); } Live Demo public class Demo { public static void main(String []args) { String str = "4434"; if(str.matches("[0-9]+") && str.length() > 2) { System.out.println("String contains only digits!"); } } } String contains only digits! Let us see another example. Live Demo public class Demo { public static void main(String []args) { String str = "5demo9"; System.out.println("String: "+str); if(str.matches("[0-9]+") && str.length() > 2) { System.out.println("String contains only digits!"); } else { System.out.println("String contains digits as well as other characters!"); } } } String: 5demo9 String contains digits as well as other characters!
[ { "code": null, "e": 1091, "s": 1062, "text": "The following is our string." }, { "code": null, "e": 1112, "s": 1091, "text": "String str = \"4434\";" }, { "code": null, "e": 1263, "s": 1112, "text": "To check whether the above string has only digit characters, try the following if condition that uses matches() method and checks for every character." }, { "code": null, "e": 1365, "s": 1263, "text": "if(str.matches(\"[0-9]+\") && str.length() > 2) {\nSystem.out.println(\"String contains only digits!\");\n}" }, { "code": null, "e": 1376, "s": 1365, "text": " Live Demo" }, { "code": null, "e": 1597, "s": 1376, "text": "public class Demo {\n public static void main(String []args) {\n String str = \"4434\";\n if(str.matches(\"[0-9]+\") && str.length() > 2) {\n System.out.println(\"String contains only digits!\");\n }\n }\n}" }, { "code": null, "e": 1626, "s": 1597, "text": "String contains only digits!" }, { "code": null, "e": 1654, "s": 1626, "text": "Let us see another example." }, { "code": null, "e": 1665, "s": 1654, "text": " Live Demo" }, { "code": null, "e": 2029, "s": 1665, "text": "public class Demo {\n public static void main(String []args) {\n String str = \"5demo9\";\n System.out.println(\"String: \"+str);\n if(str.matches(\"[0-9]+\") && str.length() > 2) {\n System.out.println(\"String contains only digits!\");\n } else {\n System.out.println(\"String contains digits as well as other characters!\");\n }\n }\n}" }, { "code": null, "e": 2096, "s": 2029, "text": "String: 5demo9\nString contains digits as well as other characters!" } ]
Formatted string literals (f-strings) in Python?
Python now provides new way to format strings, called f-strings. This features is available from Python 3.6 under PEP-498. They are so called (f-string) because of the letter ‘f’ prefix with a string. The letter ‘f’ also indicates that these f-strings can be used for formatting. Below are some of the examples to demonstrates the use of f-strings. name = 'Rajesh' age = 13 * 3 fString = f'My name is {name} and my age is {age}' print(fString) #We can use Uppercase 'F' instead of lowercase 'f'. print(F'My name is {name} and my age is {age}') #As the fString valuation is done, giving another value to the variable will not change fstring value. name = 'Zack' age = 44 print(fString) My name is Rajesh and my age is 39 My name is Rajesh and my age is 39 My name is Rajesh and my age is 39 from datetime import datetime name = 'Rajesh' age = 13 * 3 dt = datetime.now() print(f' Age after ten years will be {age + 10}') print(f'Name with quotes = {name!r}') print(f'Default formatted Date = {dt}') print(f'Modified Date format = {dt: %d/%m/%Y}') Age after ten years will be 49 Name with quotes = 'Rajesh' Default formatted Date = 2019-02-11 14:52:05.307841 Modified Date format = 11/02/2019 class Vehicle: Model = 0 Brand = '' def __init__(self, Model, Brand): self.Model = Model self.Brand = Brand def __str__(self): return f'E[Model={self.Model}, Brand = {self.Brand}]' Car = Vehicle (2018, 'Maruti') print(Car) print(f'Vehicle: {Car}\nModel is {Car.Model} and Brand is {Car.Brand}') E[Model=2018, Brand = Maruti] Vehicle: E[Model=2018, Brand = Maruti] Model is 2018 and Brand is Maruti We can call functions in f-strings formatting too. def Multiply(x,y): return x*y print( f'Multiply(40,20) = {Multiply(40,20)}') Multiply(40,20) = 800 x = -40.9 print(f' Lambda absolute of (-40.9) is : {(lambda x: abs(x)) (x)}') print(f' Lambda Square of 2^4 is: {(lambda x: pow(x, 2)) (4)}') Lambda absolute of (-40.9) is : 40.9 Lambda Square of 24 is: 16
[ { "code": null, "e": 1342, "s": 1062, "text": "Python now provides new way to format strings, called f-strings. This features is available from Python 3.6 under PEP-498. They are so called (f-string) because of the letter ‘f’ prefix with a string. The letter ‘f’ also indicates that these f-strings can be used for formatting." }, { "code": null, "e": 1411, "s": 1342, "text": "Below are some of the examples to demonstrates the use of f-strings." }, { "code": null, "e": 1747, "s": 1411, "text": "name = 'Rajesh'\nage = 13 * 3\nfString = f'My name is {name} and my age is {age}'\nprint(fString)\n#We can use Uppercase 'F' instead of lowercase 'f'.\nprint(F'My name is {name} and my age is {age}')\n#As the fString valuation is done, giving another value to the variable will not change fstring value.\nname = 'Zack'\nage = 44\nprint(fString)" }, { "code": null, "e": 1852, "s": 1747, "text": "My name is Rajesh and my age is 39\nMy name is Rajesh and my age is 39\nMy name is Rajesh and my age is 39" }, { "code": null, "e": 1882, "s": 1852, "text": "from datetime import datetime" }, { "code": null, "e": 2107, "s": 1882, "text": "name = 'Rajesh'\nage = 13 * 3\ndt = datetime.now()\nprint(f' Age after ten years will be {age + 10}')\nprint(f'Name with quotes = {name!r}')\nprint(f'Default formatted Date = {dt}')\nprint(f'Modified Date format = {dt: %d/%m/%Y}')" }, { "code": null, "e": 2252, "s": 2107, "text": "Age after ten years will be 49\nName with quotes = 'Rajesh'\nDefault formatted Date = 2019-02-11 14:52:05.307841\nModified Date format = 11/02/2019" }, { "code": null, "e": 2562, "s": 2252, "text": "class Vehicle:\n Model = 0\n Brand = ''\ndef __init__(self, Model, Brand):\n self.Model = Model\n self.Brand = Brand\ndef __str__(self):\n return f'E[Model={self.Model}, Brand = {self.Brand}]'\nCar = Vehicle (2018, 'Maruti')\nprint(Car)\nprint(f'Vehicle: {Car}\\nModel is {Car.Model} and Brand is {Car.Brand}')" }, { "code": null, "e": 2665, "s": 2562, "text": "E[Model=2018, Brand = Maruti]\nVehicle: E[Model=2018, Brand = Maruti]\nModel is 2018 and Brand is Maruti" }, { "code": null, "e": 2716, "s": 2665, "text": "We can call functions in f-strings formatting too." }, { "code": null, "e": 2796, "s": 2716, "text": "def Multiply(x,y):\n return x*y\nprint( f'Multiply(40,20) = {Multiply(40,20)}')" }, { "code": null, "e": 2818, "s": 2796, "text": "Multiply(40,20) = 800" }, { "code": null, "e": 2960, "s": 2818, "text": "x = -40.9\nprint(f' Lambda absolute of (-40.9) is : {(lambda x: abs(x)) (x)}')\nprint(f' Lambda Square of 2^4 is: {(lambda x: pow(x, 2)) (4)}')" }, { "code": null, "e": 3024, "s": 2960, "text": "Lambda absolute of (-40.9) is : 40.9\nLambda Square of 24 is: 16" } ]
Print Single and Multiple variables in Java
To print single and multiple variables in Java, the code is as follows − Live Demo public class Demo { public static void main(String args[]){ String name_1 = "Hello"; String name_2 = "World"; System.out.println("Printing single variable"); System.out.printf("%s", name_1); System.out.println("\nPrinting multiple variables"); System.out.printf("First Name: %s\nLast Name: %s",name_1, name_2); } } Printing single variable Hello Printing multiple variables First Name: Hello Last Name: World A class named Demo contains the main function, which defines two strings. These strings are displayed using the ‘println’ function and using the ‘printf’ function.
[ { "code": null, "e": 1135, "s": 1062, "text": "To print single and multiple variables in Java, the code is as follows −" }, { "code": null, "e": 1146, "s": 1135, "text": " Live Demo" }, { "code": null, "e": 1503, "s": 1146, "text": "public class Demo {\n public static void main(String args[]){\n String name_1 = \"Hello\";\n String name_2 = \"World\";\n System.out.println(\"Printing single variable\");\n System.out.printf(\"%s\", name_1);\n System.out.println(\"\\nPrinting multiple variables\");\n System.out.printf(\"First Name: %s\\nLast Name: %s\",name_1, name_2);\n }\n}" }, { "code": null, "e": 1597, "s": 1503, "text": "Printing single variable\nHello\nPrinting multiple variables\nFirst Name: Hello\nLast Name: World" }, { "code": null, "e": 1761, "s": 1597, "text": "A class named Demo contains the main function, which defines two strings. These strings are\ndisplayed using the ‘println’ function and using the ‘printf’ function." } ]
ArrayList set() method in Java with Examples - GeeksforGeeks
26 Nov, 2018 The set() method of java.util.ArrayList class is used to replace the element at the specified position in this list with the specified element. Syntax: public E set(int index, E element) Parameters: This method takes the following argument as a parameter. index- index of the element to replace element- element to be stored at the specified position Returns Value: This method returns the element previously at the specified position. Exception: This method throws IndexOutOfBoundsException if the index is not within the size range of the ArrayList. Below are the examples to illustrate the set() method. Example 1: // Java program to demonstrate// set() method// for Integer value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // Creating object of ArrayList<Integer> ArrayList<Integer> arrlist = new ArrayList<Integer>(); // Populating arrlist1 arrlist.add(1); arrlist.add(2); arrlist.add(3); arrlist.add(4); arrlist.add(5); // print arrlist System.out.println("Before operation: " + arrlist); // Replacing element at the index 3 with 30 // using method set() int i = arrlist.set(3, 30); // Print the modified arrlist System.out.println("After operation: " + arrlist); // Print the Replaced element System.out.println("Replaced element: " + i); } catch (IndexOutOfBoundsException e) { System.out.println("Exception thrown: " + e); } }} Before operation : [1, 2, 3, 4, 5] After operation : [1, 2, 3, 30, 5] Replaced element : 4 Example 2: For IndexOutOfBoundsException // Java program to demonstrate// set() method// for IndexOutOfBoundsException import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // Creating object of ArrayList<Integer> ArrayList<Integer> arrlist = new ArrayList<Integer>(); // Populating arrlist1 arrlist.add(1); arrlist.add(2); arrlist.add(3); arrlist.add(4); arrlist.add(5); // print arrlist System.out.println("Before operation : " + arrlist); // Replacing element at the index 7 with 30 // using method set() System.out.println("\nTrying to Replace" + " the element at" + " (index > Capacity) "); int i = arrlist.set(7, 30); // Print the modified arrlist System.out.println("After operation: " + arrlist); // Print the Replaced element System.out.println("Replaced element: " + i); } catch (IndexOutOfBoundsException e) { System.out.println("Exception thrown : " + e); } }} Before operation : [1, 2, 3, 4, 5] Trying to Replace the element at (index > Capacity) Exception thrown : java.lang.IndexOutOfBoundsException: Index: 7, Size: 5 Java - util package Java-ArrayList Java-Collections Java-Functions Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Initialize an ArrayList in Java Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java How to iterate any Map in Java Multidimensional Arrays in Java Stream In Java Stack Class in Java Singleton Class in Java Set in Java
[ { "code": null, "e": 24524, "s": 24496, "text": "\n26 Nov, 2018" }, { "code": null, "e": 24668, "s": 24524, "text": "The set() method of java.util.ArrayList class is used to replace the element at the specified position in this list with the specified element." }, { "code": null, "e": 24676, "s": 24668, "text": "Syntax:" }, { "code": null, "e": 24711, "s": 24676, "text": "public E set(int index, E element)" }, { "code": null, "e": 24780, "s": 24711, "text": "Parameters: This method takes the following argument as a parameter." }, { "code": null, "e": 24819, "s": 24780, "text": "index- index of the element to replace" }, { "code": null, "e": 24875, "s": 24819, "text": "element- element to be stored at the specified position" }, { "code": null, "e": 24960, "s": 24875, "text": "Returns Value: This method returns the element previously at the specified position." }, { "code": null, "e": 25076, "s": 24960, "text": "Exception: This method throws IndexOutOfBoundsException if the index is not within the size range of the ArrayList." }, { "code": null, "e": 25131, "s": 25076, "text": "Below are the examples to illustrate the set() method." }, { "code": null, "e": 25142, "s": 25131, "text": "Example 1:" }, { "code": "// Java program to demonstrate// set() method// for Integer value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // Creating object of ArrayList<Integer> ArrayList<Integer> arrlist = new ArrayList<Integer>(); // Populating arrlist1 arrlist.add(1); arrlist.add(2); arrlist.add(3); arrlist.add(4); arrlist.add(5); // print arrlist System.out.println(\"Before operation: \" + arrlist); // Replacing element at the index 3 with 30 // using method set() int i = arrlist.set(3, 30); // Print the modified arrlist System.out.println(\"After operation: \" + arrlist); // Print the Replaced element System.out.println(\"Replaced element: \" + i); } catch (IndexOutOfBoundsException e) { System.out.println(\"Exception thrown: \" + e); } }}", "e": 26308, "s": 25142, "text": null }, { "code": null, "e": 26400, "s": 26308, "text": "Before operation : [1, 2, 3, 4, 5]\nAfter operation : [1, 2, 3, 30, 5]\nReplaced element : 4\n" }, { "code": null, "e": 26441, "s": 26400, "text": "Example 2: For IndexOutOfBoundsException" }, { "code": "// Java program to demonstrate// set() method// for IndexOutOfBoundsException import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // Creating object of ArrayList<Integer> ArrayList<Integer> arrlist = new ArrayList<Integer>(); // Populating arrlist1 arrlist.add(1); arrlist.add(2); arrlist.add(3); arrlist.add(4); arrlist.add(5); // print arrlist System.out.println(\"Before operation : \" + arrlist); // Replacing element at the index 7 with 30 // using method set() System.out.println(\"\\nTrying to Replace\" + \" the element at\" + \" (index > Capacity) \"); int i = arrlist.set(7, 30); // Print the modified arrlist System.out.println(\"After operation: \" + arrlist); // Print the Replaced element System.out.println(\"Replaced element: \" + i); } catch (IndexOutOfBoundsException e) { System.out.println(\"Exception thrown : \" + e); } }}", "e": 27750, "s": 26441, "text": null }, { "code": null, "e": 27914, "s": 27750, "text": "Before operation : [1, 2, 3, 4, 5]\n\nTrying to Replace the element at (index > Capacity) \nException thrown : java.lang.IndexOutOfBoundsException: Index: 7, Size: 5\n" }, { "code": null, "e": 27934, "s": 27914, "text": "Java - util package" }, { "code": null, "e": 27949, "s": 27934, "text": "Java-ArrayList" }, { "code": null, "e": 27966, "s": 27949, "text": "Java-Collections" }, { "code": null, "e": 27981, "s": 27966, "text": "Java-Functions" }, { "code": null, "e": 27986, "s": 27981, "text": "Java" }, { "code": null, "e": 27991, "s": 27986, "text": "Java" }, { "code": null, "e": 28008, "s": 27991, "text": "Java-Collections" }, { "code": null, "e": 28106, "s": 28008, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28138, "s": 28106, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 28189, "s": 28138, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 28219, "s": 28189, "text": "HashMap in Java with Examples" }, { "code": null, "e": 28238, "s": 28219, "text": "Interfaces in Java" }, { "code": null, "e": 28269, "s": 28238, "text": "How to iterate any Map in Java" }, { "code": null, "e": 28301, "s": 28269, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 28316, "s": 28301, "text": "Stream In Java" }, { "code": null, "e": 28336, "s": 28316, "text": "Stack Class in Java" }, { "code": null, "e": 28360, "s": 28336, "text": "Singleton Class in Java" } ]
MySQL - JSON_OBJECTAGG() Function
In general, aggregation is a consideration of a collection of objects that are bound together as a single entity. MySQL provides a set of aggregate functions that perform operations on all the entities of the column of a table considering them as a single unit. The MySQL JSON_OBJECTAGG() function accepts the names of two columns of a table as arguments and returns a JSON object as a result which have the entities of first argument as keys and the entities of the second argument as values. If the specified columns have no rows this function returns NULL. Following is the syntax of this function – JSON_OBJECTAGG(key, value); Following is an example demonstrating the usage of this function. Assume we have created a table with name MyPlayers in MySQL database using CREATE statement as shown below – mysql> CREATE TABLE MyPlayers( ID INT, First_Name VARCHAR(255), Last_Name VARCHAR(255), Socre_In_Exhibiiton_match INT, COUNTRY VARCHAR(100), PRIMARY KEY (ID) ); This table stores the first and last names, country, scores in an exhibition match of a player. Now, we will insert 7 records in MyPlayers table using INSERT statements − insert into MyPlayers values(1, 'Shikhar', 'Dhawan', 95, 'India'); insert into MyPlayers values(2, 'Jonathan', 'Trott', 50, 'SouthAfrica'); insert into MyPlayers values(3, 'Kumara', 'Sangakkara', 25, 'Sri Lanka'); insert into MyPlayers values(4, 'Virat', 'Kohli', 50, 'India'); insert into MyPlayers values(5, 'Rohit', 'Sharma', 25, 'India'); insert into MyPlayers values(6, 'Ravindra', 'Jadeja', 15, 'India'); MySQL JSON_OBJECTAGG() Function insert into MyPlayers values(7, 'James', 'Anderson', 15, 'England'); Following query lists scores of all the players in an exhibition match in the form of a single JSON OBJECT with key-value pairs with first name of the players as key and score as value – mysql> SELECT JSON_OBJECTAGG(First_Name, Socre_In_Exhibiiton_match) as Scores from MyPlayers; +------------------------------------------------------------------------------------------------------+ | Scores | +------------------------------------------------------------------------------------------------------+ | {"James": 15, "Rohit": 25, "Virat": 50, "Kumara": 25, "Shikhar": 95, "Jonathan": 50, "Ravindra": 15} | +------------------------------------------------------------------------------------------------------+ 1 row in set (0.00 sec) Following query groups the scores of the players, based on the country – mysql> SELECT Country, JSON_OBJECTAGG(First_Name, Socre_In_Exhibiiton_match) as Scores from MyPlayers GROUP BY country; +-------------+-----------------------------------------------------------+ | Country | Scores | +-------------+-----------------------------------------------------------+ | England | {"James": 15} | | India | {"Rohit": 25, "Virat": 50, "Shikhar": 95, "Ravindra": 15} | | SouthAfrica | {"Jonathan": 50} | | Sri Lanka | {"Kumara": 25} | +-------------+-----------------------------------------------------------+ 4 rows in set (0.00 sec) Following is another example of this function. Assume we have created another table named employee_tbl and inserted records in it as follows – mysql> CREATE TABLE employee_tbl ( id INT, name VARCHAR(255), Work_date INT, daily_typing_pages INT ); mysql> insert into employee_tbl values(1, John, DATE('2007-01-24'), 250); mysql> insert into employee_tbl values(2, 'Ram', DATE('2007-05-27'), 220); mysql> insert into employee_tbl values(3, 'Jack', DATE('2007-05-06'), 170); mysql> insert into employee_tbl values(3, 'Jack', DATE('2007-04-06'), 100); mysql> insert into employee_tbl values(4, 'Jill', DATE('2007-04-06'), 220); mysql> insert into employee_tbl values(5, 'Zara', DATE('2007-06-06'), 300); mysql> insert into employee_tbl values(5, 'Zara', DATE('2007-02-06'), 350); Now, suppose based on the above table you want to retrieve the daily typing pages of all the employees as a single JSON object you can do so as shown below − mysql> SELECT JSON_OBJECTAGG(name, daily_typing_pages) FROM employee_tbl; +------------------------------------------------------------------+ | JSON_OBJECTAGG(name, daily_typing_pages) | +------------------------------------------------------------------+ | {"Ram": 220, "Jack": 100, "Jill": 220, "John": 250, "Zara": 350} | +------------------------------------------------------------------+ 1 row in set (0.00 sec) You can also list the JASON array for a grouped columns as shown below – mysql> SELECT Name, JSON_OBJECTAGG(name, daily_typing_pages) FROM employee_tbl GROUP BY name; +------+------------------------------------------+ | Name | JSON_OBJECTAGG(name, daily_typing_pages) | +------+------------------------------------------+ | Jack | {"Jack": 100} | | Jill | {"Jill": 220} | | John | {"John": 250} | | Ram | {"Ram": 220} | | Zara | {"Zara": 350} | +------+------------------------------------------+ 5 rows in set (0.00 sec) Let us create a table named student and inserted records into it using CREATE and INSERT statements as shown below – mysql> CREATE TABLE student (name VARCHAR(15), marks INT, grade CHAR); mysql> INSERT INTO student VALUES ('Raju', 80, 'A'); mysql> INSERT INTO student VALUES ('Rahman', 60, 'B'); mysql> INSERT INTO student VALUES ('Robert', 45, 'C'); Following query prints the values of the marks column of the student table as a JSON object – mysql> SELECT JSON_OBJECTAGG(name, marks) from student; +------------------------------------------+ | JSON_OBJECTAGG(name, marks) | +------------------------------------------+ | {"Raju": 80, "Rahman": 60, "Robert": 45} | +------------------------------------------+ 1 row in set (0.00 sec) Using the GROUP BY clause – mysql> SELECT JSON_OBJECTAGG(name, marks) from student GROUP BY name; +-----------------------------+ | JSON_OBJECTAGG(name, marks) | +-----------------------------+ | {"Rahman": 60} | | {"Raju": 80} | | {"Robert": 45} | +-----------------------------+ 3 rows in set (0.00 sec) Assume we have created and populated a table with name Sales. mysql> CREATE TABLE sales( ID INT, ProductName VARCHAR(255), CustomerName VARCHAR(255), DispatchDate date, DeliveryTime time, Price INT, Location VARCHAR(255) ); Query OK, 0 rows affected (2.22 sec) INSERT INTO SALES values(1, 'Key-Board', 'Raja', DATE('2019-09-01'), TIME('11:00:00'), 7000, 'Hyderabad'); INSERT INTO SALES values(2, 'Earphones', 'Roja', DATE('2019-05-01'), TIME('11:00:00'), 2000, 'Vishakhapatnam'); INSERT INTO SALES values(3, 'Mouse', 'Puja', DATE('2019-03-01'), TIME('10:59:59'), 3000, 'Vijayawada'); INSERT INTO SALES values(4, 'Mobile', 'Vanaja', DATE('2019-03-01'), TIME('10:10:52'), 9000, 'Chennai'); INSERT INTO SALES values(5, 'Headset', 'Jalaja', DATE('2019-04-06'), TIME('11:08:59'), 6000, 'Goa'); Following query prints the JASON object consisting the price values – mysql> SELECT JSON_OBJECTAGG(ProductName, Price) FROM SALES; +----------------------------------------------------------------------------------------+ | JSON_OBJECTAGG(ProductName, Price) | +----------------------------------------------------------------------------------------+ | {"Mouse": 3000, "Mobile": 9000, "Headset": 6000, "Earphones": 2000, "Key-Board": 7000} | +----------------------------------------------------------------------------------------+ 1 row in set (0.00 sec) You can also re write the above query as shown below – mysql> SELECT JSON_OBJECTAGG(ProductName, Price) FROM SALES GROUP BY ProductName; +------------------------------------+ | JSON_OBJECTAGG(ProductName, Price) | +------------------------------------+ | {"Earphones": 2000} | | {"Headset": 6000} | | {"Key-Board": 7000} | | {"Mobile": 9000} | | {"Mouse": 3000} | +------------------------------------+ 5 rows in set (0.00 sec) 31 Lectures 6 hours Eduonix Learning Solutions 84 Lectures 5.5 hours Frahaan Hussain 6 Lectures 3.5 hours DATAhill Solutions Srinivas Reddy 60 Lectures 10 hours Vijay Kumar Parvatha Reddy 10 Lectures 1 hours Harshit Srivastava 25 Lectures 4 hours Trevoir Williams Print Add Notes Bookmark this page
[ { "code": null, "e": 2447, "s": 2333, "text": "In general, aggregation is a consideration of a collection of objects that are bound together as a single entity." }, { "code": null, "e": 2595, "s": 2447, "text": "MySQL provides a set of aggregate functions that perform operations on all the entities of the column of a table considering them as a single unit." }, { "code": null, "e": 2827, "s": 2595, "text": "The MySQL JSON_OBJECTAGG() function accepts the names of two columns of a table as arguments and returns a JSON object as a result which have the entities of first argument as keys and the entities of the second argument as values." }, { "code": null, "e": 2893, "s": 2827, "text": "If the specified columns have no rows this function returns NULL." }, { "code": null, "e": 2936, "s": 2893, "text": "Following is the syntax of this function –" }, { "code": null, "e": 2965, "s": 2936, "text": "JSON_OBJECTAGG(key, value);\n" }, { "code": null, "e": 3140, "s": 2965, "text": "Following is an example demonstrating the usage of this function. Assume we have created a table with name MyPlayers in MySQL database using CREATE statement as shown below –" }, { "code": null, "e": 3307, "s": 3140, "text": "mysql> CREATE TABLE MyPlayers(\n\tID INT,\n\tFirst_Name VARCHAR(255),\n\tLast_Name VARCHAR(255),\n\tSocre_In_Exhibiiton_match INT,\n\tCOUNTRY VARCHAR(100),\n\tPRIMARY KEY (ID)\n);" }, { "code": null, "e": 3478, "s": 3307, "text": "This table stores the first and last names, country, scores in an exhibition match of a player. Now, we will insert 7 records in MyPlayers table using INSERT statements −" }, { "code": null, "e": 3990, "s": 3478, "text": "insert into MyPlayers values(1, 'Shikhar', 'Dhawan', 95, 'India');\ninsert into MyPlayers values(2, 'Jonathan', 'Trott', 50, 'SouthAfrica');\ninsert into MyPlayers values(3, 'Kumara', 'Sangakkara', 25, 'Sri Lanka');\ninsert into MyPlayers values(4, 'Virat', 'Kohli', 50, 'India');\ninsert into MyPlayers values(5, 'Rohit', 'Sharma', 25, 'India');\ninsert into MyPlayers values(6, 'Ravindra', 'Jadeja', 15, 'India'); MySQL JSON_OBJECTAGG() Function\ninsert into MyPlayers values(7, 'James', 'Anderson', 15, 'England');" }, { "code": null, "e": 4177, "s": 3990, "text": "Following query lists scores of all the players in an exhibition match in the form of a single JSON OBJECT with key-value pairs with first name of the players as key and score as value –" }, { "code": null, "e": 4820, "s": 4177, "text": "mysql> SELECT JSON_OBJECTAGG(First_Name, Socre_In_Exhibiiton_match) as Scores from MyPlayers;\n+------------------------------------------------------------------------------------------------------+\n| Scores |\n+------------------------------------------------------------------------------------------------------+\n| {\"James\": 15, \"Rohit\": 25, \"Virat\": 50, \"Kumara\": 25, \"Shikhar\": 95, \"Jonathan\": 50, \"Ravindra\": 15} |\n+------------------------------------------------------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 4893, "s": 4820, "text": "Following query groups the scores of the players, based on the country –" }, { "code": null, "e": 5646, "s": 4893, "text": "mysql> SELECT Country, JSON_OBJECTAGG(First_Name, Socre_In_Exhibiiton_match) as Scores from MyPlayers GROUP BY country;\n+-------------+-----------------------------------------------------------+\n| Country | Scores |\n+-------------+-----------------------------------------------------------+\n| England | {\"James\": 15} |\n| India | {\"Rohit\": 25, \"Virat\": 50, \"Shikhar\": 95, \"Ravindra\": 15} |\n| SouthAfrica | {\"Jonathan\": 50} |\n| Sri Lanka | {\"Kumara\": 25} |\n+-------------+-----------------------------------------------------------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 5789, "s": 5646, "text": "Following is another example of this function. Assume we have created another table named employee_tbl and inserted records in it as follows –" }, { "code": null, "e": 6425, "s": 5789, "text": "mysql> CREATE TABLE employee_tbl (\n\tid INT,\n\tname VARCHAR(255),\n\tWork_date INT,\n\tdaily_typing_pages INT\n);\nmysql> insert into employee_tbl values(1, John, DATE('2007-01-24'), 250);\nmysql> insert into employee_tbl values(2, 'Ram', DATE('2007-05-27'), 220);\nmysql> insert into employee_tbl values(3, 'Jack', DATE('2007-05-06'), 170);\nmysql> insert into employee_tbl values(3, 'Jack', DATE('2007-04-06'), 100);\nmysql> insert into employee_tbl values(4, 'Jill', DATE('2007-04-06'), 220);\nmysql> insert into employee_tbl values(5, 'Zara', DATE('2007-06-06'), 300);\nmysql> insert into employee_tbl values(5, 'Zara', DATE('2007-02-06'), 350);" }, { "code": null, "e": 6583, "s": 6425, "text": "Now, suppose based on the above table you want to retrieve the daily typing pages of all the employees as a single JSON object you can do so as shown below −" }, { "code": null, "e": 7026, "s": 6583, "text": "mysql> SELECT JSON_OBJECTAGG(name, daily_typing_pages) FROM employee_tbl;\n+------------------------------------------------------------------+\n| JSON_OBJECTAGG(name, daily_typing_pages) |\n+------------------------------------------------------------------+\n| {\"Ram\": 220, \"Jack\": 100, \"Jill\": 220, \"John\": 250, \"Zara\": 350} |\n+------------------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 7099, "s": 7026, "text": "You can also list the JASON array for a grouped columns as shown below –" }, { "code": null, "e": 7686, "s": 7099, "text": "mysql> SELECT Name, JSON_OBJECTAGG(name, daily_typing_pages) FROM employee_tbl GROUP BY name;\n+------+------------------------------------------+\n| Name | JSON_OBJECTAGG(name, daily_typing_pages) |\n+------+------------------------------------------+\n| Jack | {\"Jack\": 100} |\n| Jill | {\"Jill\": 220} |\n| John | {\"John\": 250} |\n| Ram | {\"Ram\": 220} |\n| Zara | {\"Zara\": 350} |\n+------+------------------------------------------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 7803, "s": 7686, "text": "Let us create a table named student and inserted records into it using CREATE and INSERT statements as shown below –" }, { "code": null, "e": 8037, "s": 7803, "text": "mysql> CREATE TABLE student (name VARCHAR(15), marks INT, grade CHAR);\nmysql> INSERT INTO student VALUES ('Raju', 80, 'A');\nmysql> INSERT INTO student VALUES ('Rahman', 60, 'B');\nmysql> INSERT INTO student VALUES ('Robert', 45, 'C');" }, { "code": null, "e": 8131, "s": 8037, "text": "Following query prints the values of the marks column of the student table as a JSON object –" }, { "code": null, "e": 8436, "s": 8131, "text": "mysql> SELECT JSON_OBJECTAGG(name, marks) from student;\n+------------------------------------------+\n| JSON_OBJECTAGG(name, marks) |\n+------------------------------------------+\n| {\"Raju\": 80, \"Rahman\": 60, \"Robert\": 45} |\n+------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 8464, "s": 8436, "text": "Using the GROUP BY clause –" }, { "code": null, "e": 8783, "s": 8464, "text": "mysql> SELECT JSON_OBJECTAGG(name, marks) from student GROUP BY name;\n+-----------------------------+\n| JSON_OBJECTAGG(name, marks) |\n+-----------------------------+\n| {\"Rahman\": 60} |\n| {\"Raju\": 80} |\n| {\"Robert\": 45} |\n+-----------------------------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 8845, "s": 8783, "text": "Assume we have created and populated a table with name Sales." }, { "code": null, "e": 9579, "s": 8845, "text": "mysql> CREATE TABLE sales(\n\tID INT,\n\tProductName VARCHAR(255),\n\tCustomerName VARCHAR(255),\n\tDispatchDate date,\n\tDeliveryTime time,\n\tPrice INT,\n\tLocation VARCHAR(255)\n);\nQuery OK, 0 rows affected (2.22 sec)\nINSERT INTO SALES values(1, 'Key-Board', 'Raja', DATE('2019-09-01'), TIME('11:00:00'), 7000, 'Hyderabad');\nINSERT INTO SALES values(2, 'Earphones', 'Roja', DATE('2019-05-01'), TIME('11:00:00'), 2000, 'Vishakhapatnam');\nINSERT INTO SALES values(3, 'Mouse', 'Puja', DATE('2019-03-01'), TIME('10:59:59'), 3000, 'Vijayawada');\nINSERT INTO SALES values(4, 'Mobile', 'Vanaja', DATE('2019-03-01'), TIME('10:10:52'), 9000, 'Chennai');\nINSERT INTO SALES values(5, 'Headset', 'Jalaja', DATE('2019-04-06'), TIME('11:08:59'), 6000, 'Goa');" }, { "code": null, "e": 9649, "s": 9579, "text": "Following query prints the JASON object consisting the price values –" }, { "code": null, "e": 10189, "s": 9649, "text": "mysql> SELECT JSON_OBJECTAGG(ProductName, Price) FROM SALES;\n+----------------------------------------------------------------------------------------+\n| JSON_OBJECTAGG(ProductName, Price) |\n+----------------------------------------------------------------------------------------+\n| {\"Mouse\": 3000, \"Mobile\": 9000, \"Headset\": 6000, \"Earphones\": 2000, \"Key-Board\": 7000} |\n+----------------------------------------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 10244, "s": 10189, "text": "You can also re write the above query as shown below –" }, { "code": null, "e": 10702, "s": 10244, "text": "mysql> SELECT JSON_OBJECTAGG(ProductName, Price) FROM SALES GROUP BY ProductName;\n+------------------------------------+\n| JSON_OBJECTAGG(ProductName, Price) |\n+------------------------------------+\n| {\"Earphones\": 2000} |\n| {\"Headset\": 6000} |\n| {\"Key-Board\": 7000} |\n| {\"Mobile\": 9000} |\n| {\"Mouse\": 3000} |\n+------------------------------------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 10735, "s": 10702, "text": "\n 31 Lectures \n 6 hours \n" }, { "code": null, "e": 10763, "s": 10735, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 10798, "s": 10763, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 10815, "s": 10798, "text": " Frahaan Hussain" }, { "code": null, "e": 10849, "s": 10815, "text": "\n 6 Lectures \n 3.5 hours \n" }, { "code": null, "e": 10884, "s": 10849, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 10918, "s": 10884, "text": "\n 60 Lectures \n 10 hours \n" }, { "code": null, "e": 10946, "s": 10918, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 10979, "s": 10946, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 10999, "s": 10979, "text": " Harshit Srivastava" }, { "code": null, "e": 11032, "s": 10999, "text": "\n 25 Lectures \n 4 hours \n" }, { "code": null, "e": 11050, "s": 11032, "text": " Trevoir Williams" }, { "code": null, "e": 11057, "s": 11050, "text": " Print" }, { "code": null, "e": 11068, "s": 11057, "text": " Add Notes" } ]
atomic.AddUint32() Function in Golang With Examples - GeeksforGeeks
01 Apr, 2020 In Go language, atomic packages supply lower-level atomic memory that is helpful is implementing synchronization algorithms. The AddUint32() function in Go language is used to automically add delta to the *addr.This function is defined under the atomic package. Here, you need to import “sync/atomic” package in order to use these function. Syntax: func AddUint32(addr *uint32, delta uint32) (new uint32) Here, addr indicates address and delta indicates a small number of bits greater than zero. Moreover, if you want to subtract a signed positive constant value c from x, then you can do it by AddUint32(&x, ^uint32(c-1)). And if you want to decrement x particularly, then it can be done by AddUint32(&x, ^uint32(0)). Note: (*uint32) is the pointer to a uint32 value. And uint32 is an unsigned integer type of bit size 32. Moreover, uint32 contains the set of all unsigned 32-bit integers from 0 to 4294967295. Return value: It adds addr and delta automically and returns a new value. Example 1: // Golang Program to illustrate the usage// of AddUint32 function // Including main packagepackage main // importing fmt and sync/atomicimport ( "fmt" "sync/atomic") // Main functionfunc main() { // Assigning values to the uint32 var ( i uint32 = 45 j uint32 = 67 k uint32 = 4294967295 l uint32 = 0 z int = 5 ) // Assigning constant // values to uint32 const ( x uint32 = 6 y uint32 = 3 ) // Calling AddUint32 method // with its parameters a_1 := atomic.AddUint32(&i, -uint32(z)) a_2 := atomic.AddUint32(&j, ^(y - 1)) a_3 := atomic.AddUint32(&k, x-1) a_4 := atomic.AddUint32(&l, ^uint32(z-1)) // Displays the output after adding // addr and delta automically fmt.Println(a_1) fmt.Println(a_2) fmt.Println(a_3) fmt.Println(a_4)} Output: 40 64 4 4294967291 Example 2: // Golang program to illustrate the usage// of the AddUint32 function // Including main packagepackage main // importing fmt and sync/atomicimport ( "fmt" "sync/atomic") // Defining addr of type uint32type addr uint32 // function that adds addr and deltafunc (u *addr) add() uint32 { // Calling AddUint32() function // with its parameter return atomic.AddUint32((*uint32)(u), 4)} // Main functionfunc main() { // Defining u var u addr // For loop to increment the value of u for i := 0; i < 17; i += 2 { // Displays the new value // after adding delta and addr fmt.Println(u.add()) }} Output: 4 8 12 16 20 24 28 32 36 In the above example, we have defined a function add that returns the output returned from calling AddUint32 method. In the main function, we have defined a “for” loop that will increment the value of ‘u’ in each call. Here, the second parameter of the AddUint32() method is constant and only the value of the first parameter is variable. However, the output of the previous call will be the value of the first parameter of the AddUint32() method in the next call until the loop stops. Lets see how above example works: 1st parameter = 0, 2nd parameter = 4 // returns (0 + 4 = 4) // Now, the above output is 1st parameter in next call to AddUint32() method 1st parameter = 4, 2nd parameter = 4 // returns (4 + 4 = 8) 1st parameter = 8, 2nd parameter = 4 // returns (8 + 4 = 12) and so on. GoLang-atomic Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Parse JSON in Golang? Defer Keyword in Golang Time Durations in Golang Anonymous function in Go Language How to iterate over an Array using for loop in Golang? time.Parse() Function in Golang With Examples Loops in Go Language Strings in Golang Class and Object in Golang Structures in Golang
[ { "code": null, "e": 24460, "s": 24432, "text": "\n01 Apr, 2020" }, { "code": null, "e": 24801, "s": 24460, "text": "In Go language, atomic packages supply lower-level atomic memory that is helpful is implementing synchronization algorithms. The AddUint32() function in Go language is used to automically add delta to the *addr.This function is defined under the atomic package. Here, you need to import “sync/atomic” package in order to use these function." }, { "code": null, "e": 24809, "s": 24801, "text": "Syntax:" }, { "code": null, "e": 24866, "s": 24809, "text": "func AddUint32(addr *uint32, delta uint32) (new uint32)\n" }, { "code": null, "e": 25180, "s": 24866, "text": "Here, addr indicates address and delta indicates a small number of bits greater than zero. Moreover, if you want to subtract a signed positive constant value c from x, then you can do it by AddUint32(&x, ^uint32(c-1)). And if you want to decrement x particularly, then it can be done by AddUint32(&x, ^uint32(0))." }, { "code": null, "e": 25373, "s": 25180, "text": "Note: (*uint32) is the pointer to a uint32 value. And uint32 is an unsigned integer type of bit size 32. Moreover, uint32 contains the set of all unsigned 32-bit integers from 0 to 4294967295." }, { "code": null, "e": 25447, "s": 25373, "text": "Return value: It adds addr and delta automically and returns a new value." }, { "code": null, "e": 25458, "s": 25447, "text": "Example 1:" }, { "code": "// Golang Program to illustrate the usage// of AddUint32 function // Including main packagepackage main // importing fmt and sync/atomicimport ( \"fmt\" \"sync/atomic\") // Main functionfunc main() { // Assigning values to the uint32 var ( i uint32 = 45 j uint32 = 67 k uint32 = 4294967295 l uint32 = 0 z int = 5 ) // Assigning constant // values to uint32 const ( x uint32 = 6 y uint32 = 3 ) // Calling AddUint32 method // with its parameters a_1 := atomic.AddUint32(&i, -uint32(z)) a_2 := atomic.AddUint32(&j, ^(y - 1)) a_3 := atomic.AddUint32(&k, x-1) a_4 := atomic.AddUint32(&l, ^uint32(z-1)) // Displays the output after adding // addr and delta automically fmt.Println(a_1) fmt.Println(a_2) fmt.Println(a_3) fmt.Println(a_4)}", "e": 26313, "s": 25458, "text": null }, { "code": null, "e": 26321, "s": 26313, "text": "Output:" }, { "code": null, "e": 26341, "s": 26321, "text": "40\n64\n4\n4294967291\n" }, { "code": null, "e": 26352, "s": 26341, "text": "Example 2:" }, { "code": "// Golang program to illustrate the usage// of the AddUint32 function // Including main packagepackage main // importing fmt and sync/atomicimport ( \"fmt\" \"sync/atomic\") // Defining addr of type uint32type addr uint32 // function that adds addr and deltafunc (u *addr) add() uint32 { // Calling AddUint32() function // with its parameter return atomic.AddUint32((*uint32)(u), 4)} // Main functionfunc main() { // Defining u var u addr // For loop to increment the value of u for i := 0; i < 17; i += 2 { // Displays the new value // after adding delta and addr fmt.Println(u.add()) }}", "e": 27001, "s": 26352, "text": null }, { "code": null, "e": 27009, "s": 27001, "text": "Output:" }, { "code": null, "e": 27035, "s": 27009, "text": "4\n8\n12\n16\n20\n24\n28\n32\n36\n" }, { "code": null, "e": 27521, "s": 27035, "text": "In the above example, we have defined a function add that returns the output returned from calling AddUint32 method. In the main function, we have defined a “for” loop that will increment the value of ‘u’ in each call. Here, the second parameter of the AddUint32() method is constant and only the value of the first parameter is variable. However, the output of the previous call will be the value of the first parameter of the AddUint32() method in the next call until the loop stops." }, { "code": null, "e": 27555, "s": 27521, "text": "Lets see how above example works:" }, { "code": null, "e": 27831, "s": 27555, "text": "1st parameter = 0, 2nd parameter = 4 // returns (0 + 4 = 4)\n\n// Now, the above output is 1st parameter in next call to AddUint32() method\n1st parameter = 4, 2nd parameter = 4 // returns (4 + 4 = 8)\n1st parameter = 8, 2nd parameter = 4 // returns (8 + 4 = 12) and so on.\n" }, { "code": null, "e": 27845, "s": 27831, "text": "GoLang-atomic" }, { "code": null, "e": 27857, "s": 27845, "text": "Go Language" }, { "code": null, "e": 27955, "s": 27857, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27984, "s": 27955, "text": "How to Parse JSON in Golang?" }, { "code": null, "e": 28008, "s": 27984, "text": "Defer Keyword in Golang" }, { "code": null, "e": 28033, "s": 28008, "text": "Time Durations in Golang" }, { "code": null, "e": 28067, "s": 28033, "text": "Anonymous function in Go Language" }, { "code": null, "e": 28122, "s": 28067, "text": "How to iterate over an Array using for loop in Golang?" }, { "code": null, "e": 28168, "s": 28122, "text": "time.Parse() Function in Golang With Examples" }, { "code": null, "e": 28189, "s": 28168, "text": "Loops in Go Language" }, { "code": null, "e": 28207, "s": 28189, "text": "Strings in Golang" }, { "code": null, "e": 28234, "s": 28207, "text": "Class and Object in Golang" } ]
Bound methods python - GeeksforGeeks
11 Dec, 2019 A bound method is the one which is dependent on the instance of the class as the first argument. It passes the instance as the first argument which is used to access the variables and functions. In Python 3 and newer versions of python, all functions in the class are by default bound methods. Let’s understand this concept with an example: # Python code to demonstrate# use of bound methods class A: def func(self, arg): self.arg = arg print("Value of arg = ", arg) # Creating an instanceobj = A() # bound methodprint(obj.func) Output: < bound method A.func of <__main__.A object at 0x7fb81c5a09e8>> Here, obj.func(arg) is translated by python as A.func(obj, arg). The instance obj is automatically passed as the first argument to the function called and hence the first parameter of the function will be used to access the variables/functions of the object. Let’s see another example of the Bound method. # Python code to demonstrate# use of bound methods class Car: # Car class created gears = 5 # a class method to change the number of gears @classmethod def change_gears(cls, gears): cls.gears = gears # instance of class Car createdCar1 = Car() print("Car1 gears before calling change_gears() = ", Car1.gears)Car1.change_gears(6) print("Gears after calling change_gears() = ", Car1.gears) # bound methodprint(Car1.change_gears) Output: Car1 gears before calling change_gears() = 5 Gears after calling change_gears() = 6 <bound method Car.change_gears of <class '__main__.Car'>> The above code is an example of a classmethod. A class method is like a bound method except that the class of the instance is passed as an argument rather than the instance itself. Here in the above example when we call Car1.change_gears(6), the class ‘Car’ is passed as the first argument. Python-Functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Python program to convert a list to string Reading and Writing to text files in Python
[ { "code": null, "e": 24102, "s": 24074, "text": "\n11 Dec, 2019" }, { "code": null, "e": 24396, "s": 24102, "text": "A bound method is the one which is dependent on the instance of the class as the first argument. It passes the instance as the first argument which is used to access the variables and functions. In Python 3 and newer versions of python, all functions in the class are by default bound methods." }, { "code": null, "e": 24443, "s": 24396, "text": "Let’s understand this concept with an example:" }, { "code": "# Python code to demonstrate# use of bound methods class A: def func(self, arg): self.arg = arg print(\"Value of arg = \", arg) # Creating an instanceobj = A() # bound methodprint(obj.func)", "e": 24657, "s": 24443, "text": null }, { "code": null, "e": 24665, "s": 24657, "text": "Output:" }, { "code": null, "e": 24730, "s": 24665, "text": "< bound method A.func of <__main__.A object at 0x7fb81c5a09e8>>\n" }, { "code": null, "e": 24736, "s": 24730, "text": "Here," }, { "code": null, "e": 24796, "s": 24736, "text": " obj.func(arg) is translated by python as A.func(obj, arg)." }, { "code": null, "e": 24990, "s": 24796, "text": "The instance obj is automatically passed as the first argument to the function called and hence the first parameter of the function will be used to access the variables/functions of the object." }, { "code": null, "e": 25037, "s": 24990, "text": "Let’s see another example of the Bound method." }, { "code": "# Python code to demonstrate# use of bound methods class Car: # Car class created gears = 5 # a class method to change the number of gears @classmethod def change_gears(cls, gears): cls.gears = gears # instance of class Car createdCar1 = Car() print(\"Car1 gears before calling change_gears() = \", Car1.gears)Car1.change_gears(6) print(\"Gears after calling change_gears() = \", Car1.gears) # bound methodprint(Car1.change_gears)", "e": 25499, "s": 25037, "text": null }, { "code": null, "e": 25507, "s": 25499, "text": "Output:" }, { "code": null, "e": 25652, "s": 25507, "text": "Car1 gears before calling change_gears() = 5\nGears after calling change_gears() = 6\n<bound method Car.change_gears of <class '__main__.Car'>>\n" }, { "code": null, "e": 25943, "s": 25652, "text": "The above code is an example of a classmethod. A class method is like a bound method except that the class of the instance is passed as an argument rather than the instance itself. Here in the above example when we call Car1.change_gears(6), the class ‘Car’ is passed as the first argument." }, { "code": null, "e": 25960, "s": 25943, "text": "Python-Functions" }, { "code": null, "e": 25967, "s": 25960, "text": "Python" }, { "code": null, "e": 26065, "s": 25967, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26083, "s": 26065, "text": "Python Dictionary" }, { "code": null, "e": 26118, "s": 26083, "text": "Read a file line by line in Python" }, { "code": null, "e": 26140, "s": 26118, "text": "Enumerate() in Python" }, { "code": null, "e": 26172, "s": 26140, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26202, "s": 26172, "text": "Iterate over a list in Python" }, { "code": null, "e": 26244, "s": 26202, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26270, "s": 26244, "text": "Python String | replace()" }, { "code": null, "e": 26307, "s": 26270, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 26350, "s": 26307, "text": "Python program to convert a list to string" } ]
SimpleDateFormat('E, dd MMM yyyy HH:mm:ss Z') in Java
Using the SimpleDateFormat(“E, dd MMM yyyy HH:mm:ss Z”), wherein E is for Day of Week − // displaying current date and time Calendar cal = Calendar.getInstance(); SimpleDateFormat simpleformat = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z"); System.out.println("Today's date and time = "+simpleformat.format(cal.getTime())); Since we have used the Format and SimpleDateFormat class above, therefore import the following packages. With that, we have also used the Date − import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; The following is an example − Live Demo import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Calendar; public class Demo { public static void main(String[] args) throws Exception { // displaying current date and time Calendar cal = Calendar.getInstance(); SimpleDateFormat simpleformat = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z"); System.out.println("Today's date and time = "+simpleformat.format(cal.getTime())); // displaying date Format f = new SimpleDateFormat("dd/MMMM/yyyy"); String strDate = f.format(new Date()); System.out.println("Current Date = "+strDate); // displaying month number f = new SimpleDateFormat("M"); String strMonth = f.format(new Date()); System.out.println("Month Number = "+strMonth); // current time f = new SimpleDateFormat("HH.mm.ss Z"); String strTime = f.format(new Date()); System.out.println("Current Time = "+strTime); // displaying hour f = new SimpleDateFormat("H"); String strHour = f.format(new Date()); System.out.println("Current Hour = "+strHour); // displaying minutes f = new SimpleDateFormat("mm"); String strMinute = f.format(new Date()); System.out.println("Current Minutes = "+strMinute); // displaying seconds f = new SimpleDateFormat("ss"); String strSeconds = f.format(new Date()); System.out.println("Current Seconds = "+strSeconds); } } Today's date and time = Mon, 26 Nov 2018 09:18:28 +0000 Current Date = 26/November/2018 Month Number = 11 Current Time = 09.18.28 +0000 Current Hour = 9 Current Minutes = 18 Current Seconds = 28
[ { "code": null, "e": 1150, "s": 1062, "text": "Using the SimpleDateFormat(“E, dd MMM yyyy HH:mm:ss Z”), wherein E is for Day of Week −" }, { "code": null, "e": 1391, "s": 1150, "text": "// displaying current date and time\nCalendar cal = Calendar.getInstance();\nSimpleDateFormat simpleformat = new SimpleDateFormat(\"E, dd MMM yyyy HH:mm:ss Z\");\nSystem.out.println(\"Today's date and time = \"+simpleformat.format(cal.getTime()));" }, { "code": null, "e": 1536, "s": 1391, "text": "Since we have used the Format and SimpleDateFormat class above, therefore import the following packages. With that, we have also used the Date −" }, { "code": null, "e": 1619, "s": 1536, "text": "import java.text.Format;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;" }, { "code": null, "e": 1649, "s": 1619, "text": "The following is an example −" }, { "code": null, "e": 1660, "s": 1649, "text": " Live Demo" }, { "code": null, "e": 3141, "s": 1660, "text": "import java.text.Format;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\nimport java.util.Calendar;\npublic class Demo {\n public static void main(String[] args) throws Exception {\n // displaying current date and time\n Calendar cal = Calendar.getInstance();\n SimpleDateFormat simpleformat = new SimpleDateFormat(\"E, dd MMM yyyy HH:mm:ss Z\");\n System.out.println(\"Today's date and time = \"+simpleformat.format(cal.getTime()));\n // displaying date\n Format f = new SimpleDateFormat(\"dd/MMMM/yyyy\");\n String strDate = f.format(new Date());\n System.out.println(\"Current Date = \"+strDate);\n // displaying month number\n f = new SimpleDateFormat(\"M\");\n String strMonth = f.format(new Date());\n System.out.println(\"Month Number = \"+strMonth);\n // current time\n f = new SimpleDateFormat(\"HH.mm.ss Z\");\n String strTime = f.format(new Date());\n System.out.println(\"Current Time = \"+strTime);\n // displaying hour\n f = new SimpleDateFormat(\"H\");\n String strHour = f.format(new Date());\n System.out.println(\"Current Hour = \"+strHour);\n // displaying minutes\n f = new SimpleDateFormat(\"mm\");\n String strMinute = f.format(new Date());\n System.out.println(\"Current Minutes = \"+strMinute);\n // displaying seconds\n f = new SimpleDateFormat(\"ss\");\n String strSeconds = f.format(new Date());\n System.out.println(\"Current Seconds = \"+strSeconds);\n }\n}" }, { "code": null, "e": 3336, "s": 3141, "text": "Today's date and time = Mon, 26 Nov 2018 09:18:28 +0000\nCurrent Date = 26/November/2018\nMonth Number = 11\nCurrent Time = 09.18.28 +0000\nCurrent Hour = 9\nCurrent Minutes = 18\nCurrent Seconds = 28" } ]
Check if two BSTs contain same set of elements - GeeksforGeeks
01 Jul, 2021 Given two Binary Search Trees consisting of unique positive elements, we have to check whether the two BSTs contains same set or elements or not. Note: The structure of the two given BSTs can be different. For example, The above two BSTs contains same set of elements {5, 10, 12, 15, 20, 25} Method 1: The most simple method will be to traverse first tree and store its element in a list or array. Now, traverse 2nd tree and simultaneously check if the current element is present in the list or not. If yes, then mark the element in the list as negative and check for further elements otherwise if no, then immediately terminate the traversal and print No. If all the elements of 2nd tree is present in the list and are marked negative then finally traverse the list to check if there are any non-negative elements left. If Yes then it means that the first tree had some extra element otherwise the both tree consists same set of elements.Time Complexity: O( n * n ) , where n is the number of nodes in the BST. Auxiliary Space: O( n ).Method 2: This method is an optimization of above approach. If we observe carefully, we will see that in the above approach, search for element in the list takes linear time. We can optimize this operation to be done in constant time using a hashmap instead of list. We insert elements of both trees in different hash sets. Finally we compare if both hash sets contain same elements or not.Below is the complete implementation of above approach: C++ Java Python3 C# Javascript // CPP program to check if two BSTs contains// same set of elements#include<bits/stdc++.h>using namespace std; // BST Nodestruct Node{ int data; struct Node* left; struct Node* right;}; // Utility function to create new NodeNode* newNode(int val){ Node* temp = new Node; temp->data = val; temp->left = temp->right = NULL; return temp;} // function to insert elements of the// tree to map mvoid insertToHash(Node* root, unordered_set<int> &s){ if (!root) return; insertToHash(root->left, s); s.insert(root->data); insertToHash(root->right, s);} // function to check if the two BSTs contain// same set of elementsbool checkBSTs(Node* root1, Node* root2){ // Base cases if (!root1 && !root2) return true; if ((root1 && !root2) || (!root1 && root2)) return false; // Create two hash sets and store // elements both BSTs in them. unordered_set<int> s1, s2; insertToHash(root1, s1); insertToHash(root2, s2); // Return true if both hash sets // contain same elements. return (s1 == s2);} // Driver program to check above functionsint main(){ // First BST Node* root1 = newNode(15); root1->left = newNode(10); root1->right = newNode(20); root1->left->left = newNode(5); root1->left->right = newNode(12); root1->right->right = newNode(25); // Second BST Node* root2 = newNode(15); root2->left = newNode(12); root2->right = newNode(20); root2->left->left = newNode(5); root2->left->left->right = newNode(10); root2->right->right = newNode(25); // check if two BSTs have same set of elements if (checkBSTs(root1, root2)) cout << "YES"; else cout << "NO"; return 0; } // JAVA program to check if two BSTs contains// same set of elementsimport java.util.*; class GFG{ // BST Nodestatic class Node{ int data; Node left; Node right;}; // Utility function to create new Nodestatic Node newNode(int val){ Node temp = new Node(); temp.data = val; temp.left = temp.right = null; return temp;} // function to insert elements of the// tree to map mstatic void insertToHash(Node root, HashSet<Integer> s){ if (root == null) return; insertToHash(root.left, s); s.add(root.data); insertToHash(root.right, s);} // function to check if the two BSTs contain// same set of elementsstatic boolean checkBSTs(Node root1, Node root2){ // Base cases if (root1 != null && root2 != null) return true; if ((root1 == null && root2 != null) || (root1 != null && root2 == null)) return false; // Create two hash sets and store // elements both BSTs in them. HashSet<Integer> s1 = new HashSet<Integer>(); HashSet<Integer> s2 = new HashSet<Integer>(); insertToHash(root1, s1); insertToHash(root2, s2); // Return true if both hash sets // contain same elements. return (s1.equals(s2));} // Driver program to check above functionspublic static void main(String[] args){ // First BST Node root1 = newNode(15); root1.left = newNode(10); root1.right = newNode(20); root1.left.left = newNode(5); root1.left.right = newNode(12); root1.right.right = newNode(25); // Second BST Node root2 = newNode(15); root2.left = newNode(12); root2.right = newNode(20); root2.left.left = newNode(5); root2.left.left.right = newNode(10); root2.right.right = newNode(25); // check if two BSTs have same set of elements if (checkBSTs(root1, root2)) System.out.print("YES"); else System.out.print("NO");} } // This code is contributed by 29AjayKumar # Python3 program to check if two BSTs contains# same set of elements # BST Nodeclass Node: def __init__(self): self.val = 0 self.left = None self.right = None # Utility function to create Nodedef Node_(val1): temp = Node() temp.val = val1 temp.left = temp.right = None return temp s = {} # function to insert elements of the# tree to map mdef insertToHash(root): if (root == None): return insertToHash(root.left) s.add(root.data) insertToHash(root.right) # function to check if the two BSTs contain# same set of elementsdef checkBSTs(root1, root2): # Base cases if (root1 != None and root2 != None) : return True if ((root1 == None and root2 != None) or (root1 != None and root2 == None)): return False # Create two hash sets and store # elements both BSTs in them. s1 = {} s2 = {} s = s1 insertToHash(root1) s1 = s s = s2 insertToHash(root2) s2 = s # Return True if both hash sets # contain same elements. return (s1 == (s2)) # Driver code # First BSTroot1 = Node_(15)root1.left = Node_(10)root1.right = Node_(20)root1.left.left = Node_(5)root1.left.right = Node_(12)root1.right.right = Node_(25) # Second BSTroot2 = Node_(15)root2.left = Node_(12)root2.right = Node_(20)root2.left.left = Node_(5)root2.left.left.right = Node_(10)root2.right.right = Node_(25) # check if two BSTs have same set of elementsif (checkBSTs(root1, root2)): print("YES")else: print("NO") # This code is contributed by Arnab Kundu // C# program to check if two BSTs contains// same set of elementsusing System;using System.Collections.Generic; class GFG{ // BST Nodeclass Node{ public int data; public Node left; public Node right;}; // Utility function to create new Nodestatic Node newNode(int val){ Node temp = new Node(); temp.data = val; temp.left = temp.right = null; return temp;} // function to insert elements of the// tree to map mstatic void insertToHash(Node root, HashSet<int> s){ if (root == null) return; insertToHash(root.left, s); s.Add(root.data); insertToHash(root.right, s);} // function to check if the two BSTs contain// same set of elementsstatic bool checkBSTs(Node root1, Node root2){ // Base cases if (root1 != null && root2 != null) return true; if ((root1 == null && root2 != null) || (root1 != null && root2 == null)) return false; // Create two hash sets and store // elements both BSTs in them. HashSet<int> s1 = new HashSet<int>(); HashSet<int> s2 = new HashSet<int>(); insertToHash(root1, s1); insertToHash(root2, s2); // Return true if both hash sets // contain same elements. return (s1.Equals(s2));} // Driver Codepublic static void Main(String[] args){ // First BST Node root1 = newNode(15); root1.left = newNode(10); root1.right = newNode(20); root1.left.left = newNode(5); root1.left.right = newNode(12); root1.right.right = newNode(25); // Second BST Node root2 = newNode(15); root2.left = newNode(12); root2.right = newNode(20); root2.left.left = newNode(5); root2.left.left.right = newNode(10); root2.right.right = newNode(25); // check if two BSTs have same set of elements if (checkBSTs(root1, root2)) Console.Write("YES"); else Console.Write("NO");} } // This code is contributed by PrinciRaj1992 <script> // JavaScript program to check if two BSTs contains// same set of elements // BST Nodeclass Node{ constructor() { this.data = 0; this.left = null; this.right = null; }}; // Utility function to create new Nodefunction newNode(val){ var temp = new Node(); temp.data = val; temp.left = temp.right = null; return temp;} // function to insert elements of the// tree to map mfunction insertToHash(root, s){ if (root == null) return; insertToHash(root.left, s); s.add(root.data); insertToHash(root.right, s);} // function to check if the two BSTs contain// same set of elementsfunction checkBSTs(root1, root2){ // Base cases if (root1 != null && root2 != null) return true; if ((root1 == null && root2 != null) || (root1 != null && root2 == null)) return false; // Create two hash sets and store // elements both BSTs in them. var s1 = new Set(); var s2 = new Set(); insertToHash(root1, s1); insertToHash(root2, s2); // Return true if both hash sets // contain same elements. return (s1==s2);} // Driver Code// First BSTvar root1 = newNode(15);root1.left = newNode(10);root1.right = newNode(20);root1.left.left = newNode(5);root1.left.right = newNode(12);root1.right.right = newNode(25); // Second BSTvar root2 = newNode(15);root2.left = newNode(12);root2.right = newNode(20);root2.left.left = newNode(5);root2.left.left.right = newNode(10);root2.right.right = newNode(25); // check if two BSTs have same set of elementsif (checkBSTs(root1, root2)) document.write("YES");else document.write("NO"); </script> Output: YES Time Complexity: O( n ), where n is the number of nodes in the trees. Auxiliary Space: O( n ).Method 3: We know about an interesting property of BST that inorder traversal of a BST generates a sorted array. So we can do inorder traversals of both the BSTs and generate two arrays and finally we can compare these two arrays. If both of the arrays are same then the BSTs have same set of elements otherwise not. C++ Java Python3 C# Javascript // CPP program to check if two BSTs contains// same set of elements#include<bits/stdc++.h>using namespace std; // BST Nodestruct Node{ int data; struct Node* left; struct Node* right;}; // Utility function to create new NodeNode* newNode(int val){ Node* temp = new Node; temp->data = val; temp->left = temp->right = NULL; return temp;} // function to insert elements of the// tree to map mvoid storeInorder(Node* root, vector<int> &v){ if (!root) return; storeInorder(root->left, v); v.push_back(root->data); storeInorder(root->right, v);} // function to check if the two BSTs contain// same set of elementsbool checkBSTs(Node* root1, Node* root2){ // Base cases if (!root1 && !root2) return true; if ((root1 && !root2) || (!root1 && root2)) return false; // Create two vectors and store // inorder traversals of both BSTs // in them. vector<int> v1, v2; storeInorder(root1, v1); storeInorder(root2, v2); // Return true if both vectors are // identical return (v1 == v2);} // Driver program to check above functionsint main(){ // First BST Node* root1 = newNode(15); root1->left = newNode(10); root1->right = newNode(20); root1->left->left = newNode(5); root1->left->right = newNode(12); root1->right->right = newNode(25); // Second BST Node* root2 = newNode(15); root2->left = newNode(12); root2->right = newNode(20); root2->left->left = newNode(5); root2->left->left->right = newNode(10); root2->right->right = newNode(25); // check if two BSTs have same set of elements if (checkBSTs(root1, root2)) cout << "YES"; else cout << "NO"; return 0; } // Java program to check if two BSTs// contain same set of elementsimport java.util.*; class GFG{ // BST Nodestatic class Node{ int data; Node left; Node right;}; // Utility function to create new Nodestatic Node newNode(int val){ Node temp = new Node(); temp.data = val; temp.left = temp.right = null; return temp;} // function to insert elements // of the tree to map mstatic void storeInorder(Node root, Vector<Integer> v){ if (root == null) return; storeInorder(root.left, v); v.add(root.data); storeInorder(root.right, v);} // function to check if the two BSTs// contain same set of elementsstatic boolean checkBSTs(Node root1, Node root2){ // Base cases if (root1 != null && root2 != null) return true; if ((root1 == null && root2 != null) || (root1 != null && root2 == null)) return false; // Create two vectors and store // inorder traversals of both BSTs // in them. Vector<Integer> v1 = new Vector<Integer>(); Vector<Integer> v2 = new Vector<Integer>(); storeInorder(root1, v1); storeInorder(root2, v2); // Return true if both vectors are // identical return (v1 == v2);} // Driver Codepublic static void main(String[] args){ // First BST Node root1 = newNode(15); root1.left = newNode(10); root1.right = newNode(20); root1.left.left = newNode(5); root1.left.right = newNode(12); root1.right.right = newNode(25); // Second BST Node root2 = newNode(15); root2.left = newNode(12); root2.right = newNode(20); root2.left.left = newNode(5); root2.left.left.right = newNode(10); root2.right.right = newNode(25); // check if two BSTs have same set of elements if (checkBSTs(root1, root2)) System.out.print("YES"); else System.out.print("NO");} } // This code is contributed by Rajput-Ji # Python3 program to check if two BSTs contains# same set of elements # BST Nodeclass Node: def __init__(self): self.val = 0 self.left = None self.right = None # Utility function to create Nodedef Node_(val1): temp = Node() temp.val = val1 temp.left = temp.right = None return temp v = [] # function to insert elements of the# tree to map mdef storeInorder(root): if (root == None): return storeInorder(root.left) v.append(root.data) storeInorder(root.right) # function to check if the two BSTs contain# same set of elementsdef checkBSTs(root1, root2): # Base cases if (root1 != None and root2 != None) : return True if ((root1 == None and root2 != None) or \ (root1 != None and root2 == None)): return False # Create two hash sets and store # elements both BSTs in them. v1 = [] v2 = [] v = v1 storeInorder(root1) v1 = v v = v2 storeInorder(root2) v2 = v # Return True if both hash sets # contain same elements. return (v1 == v2) # Driver code # First BSTroot1 = Node_(15)root1.left = Node_(10)root1.right = Node_(20)root1.left.left = Node_(5)root1.left.right = Node_(12)root1.right.right = Node_(25) # Second BSTroot2 = Node_(15)root2.left = Node_(12)root2.right = Node_(20)root2.left.left = Node_(5)root2.left.left.right = Node_(10)root2.right.right = Node_(25) # check if two BSTs have same set of elementsif (checkBSTs(root1, root2)): print("YES")else: print("NO") # This code is contributed by SHUBHAMSINGH10 // C# program to check if two BSTs// contain same set of elementsusing System;using System.Collections.Generic; class GFG{ // BST Nodeclass Node{ public int data; public Node left; public Node right;}; // Utility function to create new Nodestatic Node newNode(int val){ Node temp = new Node(); temp.data = val; temp.left = temp.right = null; return temp;} // function to insert elements// of the tree to map mstatic void storeInorder(Node root, List<int> v){ if (root == null) return; storeInorder(root.left, v); v.Add(root.data); storeInorder(root.right, v);} // function to check if the two BSTs// contain same set of elementsstatic bool checkBSTs(Node root1, Node root2){ // Base cases if (root1 != null && root2 != null) return true; if ((root1 == null && root2 != null) || (root1 != null && root2 == null)) return false; // Create two vectors and store // inorder traversals of both BSTs // in them. List<int> v1 = new List<int>(); List<int> v2 = new List<int>(); storeInorder(root1, v1); storeInorder(root2, v2); // Return true if both vectors are // identical return (v1 == v2);} // Driver Codepublic static void Main(String[] args){ // First BST Node root1 = newNode(15); root1.left = newNode(10); root1.right = newNode(20); root1.left.left = newNode(5); root1.left.right = newNode(12); root1.right.right = newNode(25); // Second BST Node root2 = newNode(15); root2.left = newNode(12); root2.right = newNode(20); root2.left.left = newNode(5); root2.left.left.right = newNode(10); root2.right.right = newNode(25); // check if two BSTs have // same set of elements if (checkBSTs(root1, root2)) Console.Write("YES"); else Console.Write("NO");} } // This code is contributed by Rajput-Ji <script> // JavaScript program to check if two BSTs// contain same set of elements // BST Nodeclass Node { constructor() { this.data = 0; this.prev = null; this.next = null; }} // Utility function to create new Node function newNode(val) { var temp = new Node(); temp.data = val; temp.left = temp.right = null; return temp; } // function to insert elements // of the tree to map m function storeInorder(root, v) { if (root == null) return; storeInorder(root.left, v); v.push(root.data); storeInorder(root.right, v); } // function to check if the two BSTs // contain same set of elements function checkBSTs(root1, root2) { // Base cases if (root1 != null && root2 != null) return true; if ((root1 == null && root2 != null) || (root1 != null && root2 == null)) return false; // Create two vectors and store // inorder traversals of both BSTs // in them. var v1 = []; var v2 = []; storeInorder(root1, v1); storeInorder(root2, v2); // Return true if both vectors are // identical return (v1 == v2); } // Driver Code // First BST var root1 = newNode(15); root1.left = newNode(10); root1.right = newNode(20); root1.left.left = newNode(5); root1.left.right = newNode(12); root1.right.right = newNode(25); // Second BST var root2 = newNode(15); root2.left = newNode(12); root2.right = newNode(20); root2.left.left = newNode(5); root2.left.left.right = newNode(10); root2.right.right = newNode(25); // check if two BSTs have same set of elements if (checkBSTs(root1, root2)) document.write("YES"); else document.write("NO"); // This code is contributed by Rajput-Ji </script> Output: YES Time Complexity: O( n ). Auxiliary Space: O( n ). YouTubeGeeksforGeeks502K subscribersCheck if two BSTs contain same set of elements | 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:34•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=c-OSdbpOVDE" 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 Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to 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. 29AjayKumar princiraj1992 Rajput-Ji andrew1234 SHUBHAMSINGH10 rutvik_56 cpp-unordered_set cpp-vector Binary Search Tree Binary Search Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Advantages of BST over Hash Table Difference between Binary Tree and Binary Search Tree Inorder predecessor and successor for a given key in BST Sorted Linked List to Balanced BST Print BST keys in the given range Binary Tree to Binary Search Tree Conversion Insert a node in Binary Search Tree Iteratively C Program for Red Black Tree Insertion Find the node with maximum value in a Binary Search Tree Total number of possible Binary Search Trees and Binary Trees with n keys
[ { "code": null, "e": 25092, "s": 25064, "text": "\n01 Jul, 2021" }, { "code": null, "e": 25313, "s": 25092, "text": "Given two Binary Search Trees consisting of unique positive elements, we have to check whether the two BSTs contains same set or elements or not. Note: The structure of the two given BSTs can be different. For example, " }, { "code": null, "e": 25387, "s": 25313, "text": "The above two BSTs contains same set of elements {5, 10, 12, 15, 20, 25} " }, { "code": null, "e": 26579, "s": 25387, "text": "Method 1: The most simple method will be to traverse first tree and store its element in a list or array. Now, traverse 2nd tree and simultaneously check if the current element is present in the list or not. If yes, then mark the element in the list as negative and check for further elements otherwise if no, then immediately terminate the traversal and print No. If all the elements of 2nd tree is present in the list and are marked negative then finally traverse the list to check if there are any non-negative elements left. If Yes then it means that the first tree had some extra element otherwise the both tree consists same set of elements.Time Complexity: O( n * n ) , where n is the number of nodes in the BST. Auxiliary Space: O( n ).Method 2: This method is an optimization of above approach. If we observe carefully, we will see that in the above approach, search for element in the list takes linear time. We can optimize this operation to be done in constant time using a hashmap instead of list. We insert elements of both trees in different hash sets. Finally we compare if both hash sets contain same elements or not.Below is the complete implementation of above approach: " }, { "code": null, "e": 26583, "s": 26579, "text": "C++" }, { "code": null, "e": 26588, "s": 26583, "text": "Java" }, { "code": null, "e": 26596, "s": 26588, "text": "Python3" }, { "code": null, "e": 26599, "s": 26596, "text": "C#" }, { "code": null, "e": 26610, "s": 26599, "text": "Javascript" }, { "code": "// CPP program to check if two BSTs contains// same set of elements#include<bits/stdc++.h>using namespace std; // BST Nodestruct Node{ int data; struct Node* left; struct Node* right;}; // Utility function to create new NodeNode* newNode(int val){ Node* temp = new Node; temp->data = val; temp->left = temp->right = NULL; return temp;} // function to insert elements of the// tree to map mvoid insertToHash(Node* root, unordered_set<int> &s){ if (!root) return; insertToHash(root->left, s); s.insert(root->data); insertToHash(root->right, s);} // function to check if the two BSTs contain// same set of elementsbool checkBSTs(Node* root1, Node* root2){ // Base cases if (!root1 && !root2) return true; if ((root1 && !root2) || (!root1 && root2)) return false; // Create two hash sets and store // elements both BSTs in them. unordered_set<int> s1, s2; insertToHash(root1, s1); insertToHash(root2, s2); // Return true if both hash sets // contain same elements. return (s1 == s2);} // Driver program to check above functionsint main(){ // First BST Node* root1 = newNode(15); root1->left = newNode(10); root1->right = newNode(20); root1->left->left = newNode(5); root1->left->right = newNode(12); root1->right->right = newNode(25); // Second BST Node* root2 = newNode(15); root2->left = newNode(12); root2->right = newNode(20); root2->left->left = newNode(5); root2->left->left->right = newNode(10); root2->right->right = newNode(25); // check if two BSTs have same set of elements if (checkBSTs(root1, root2)) cout << \"YES\"; else cout << \"NO\"; return 0; }", "e": 28348, "s": 26610, "text": null }, { "code": "// JAVA program to check if two BSTs contains// same set of elementsimport java.util.*; class GFG{ // BST Nodestatic class Node{ int data; Node left; Node right;}; // Utility function to create new Nodestatic Node newNode(int val){ Node temp = new Node(); temp.data = val; temp.left = temp.right = null; return temp;} // function to insert elements of the// tree to map mstatic void insertToHash(Node root, HashSet<Integer> s){ if (root == null) return; insertToHash(root.left, s); s.add(root.data); insertToHash(root.right, s);} // function to check if the two BSTs contain// same set of elementsstatic boolean checkBSTs(Node root1, Node root2){ // Base cases if (root1 != null && root2 != null) return true; if ((root1 == null && root2 != null) || (root1 != null && root2 == null)) return false; // Create two hash sets and store // elements both BSTs in them. HashSet<Integer> s1 = new HashSet<Integer>(); HashSet<Integer> s2 = new HashSet<Integer>(); insertToHash(root1, s1); insertToHash(root2, s2); // Return true if both hash sets // contain same elements. return (s1.equals(s2));} // Driver program to check above functionspublic static void main(String[] args){ // First BST Node root1 = newNode(15); root1.left = newNode(10); root1.right = newNode(20); root1.left.left = newNode(5); root1.left.right = newNode(12); root1.right.right = newNode(25); // Second BST Node root2 = newNode(15); root2.left = newNode(12); root2.right = newNode(20); root2.left.left = newNode(5); root2.left.left.right = newNode(10); root2.right.right = newNode(25); // check if two BSTs have same set of elements if (checkBSTs(root1, root2)) System.out.print(\"YES\"); else System.out.print(\"NO\");} } // This code is contributed by 29AjayKumar", "e": 30257, "s": 28348, "text": null }, { "code": "# Python3 program to check if two BSTs contains# same set of elements # BST Nodeclass Node: def __init__(self): self.val = 0 self.left = None self.right = None # Utility function to create Nodedef Node_(val1): temp = Node() temp.val = val1 temp.left = temp.right = None return temp s = {} # function to insert elements of the# tree to map mdef insertToHash(root): if (root == None): return insertToHash(root.left) s.add(root.data) insertToHash(root.right) # function to check if the two BSTs contain# same set of elementsdef checkBSTs(root1, root2): # Base cases if (root1 != None and root2 != None) : return True if ((root1 == None and root2 != None) or (root1 != None and root2 == None)): return False # Create two hash sets and store # elements both BSTs in them. s1 = {} s2 = {} s = s1 insertToHash(root1) s1 = s s = s2 insertToHash(root2) s2 = s # Return True if both hash sets # contain same elements. return (s1 == (s2)) # Driver code # First BSTroot1 = Node_(15)root1.left = Node_(10)root1.right = Node_(20)root1.left.left = Node_(5)root1.left.right = Node_(12)root1.right.right = Node_(25) # Second BSTroot2 = Node_(15)root2.left = Node_(12)root2.right = Node_(20)root2.left.left = Node_(5)root2.left.left.right = Node_(10)root2.right.right = Node_(25) # check if two BSTs have same set of elementsif (checkBSTs(root1, root2)): print(\"YES\")else: print(\"NO\") # This code is contributed by Arnab Kundu", "e": 31825, "s": 30257, "text": null }, { "code": "// C# program to check if two BSTs contains// same set of elementsusing System;using System.Collections.Generic; class GFG{ // BST Nodeclass Node{ public int data; public Node left; public Node right;}; // Utility function to create new Nodestatic Node newNode(int val){ Node temp = new Node(); temp.data = val; temp.left = temp.right = null; return temp;} // function to insert elements of the// tree to map mstatic void insertToHash(Node root, HashSet<int> s){ if (root == null) return; insertToHash(root.left, s); s.Add(root.data); insertToHash(root.right, s);} // function to check if the two BSTs contain// same set of elementsstatic bool checkBSTs(Node root1, Node root2){ // Base cases if (root1 != null && root2 != null) return true; if ((root1 == null && root2 != null) || (root1 != null && root2 == null)) return false; // Create two hash sets and store // elements both BSTs in them. HashSet<int> s1 = new HashSet<int>(); HashSet<int> s2 = new HashSet<int>(); insertToHash(root1, s1); insertToHash(root2, s2); // Return true if both hash sets // contain same elements. return (s1.Equals(s2));} // Driver Codepublic static void Main(String[] args){ // First BST Node root1 = newNode(15); root1.left = newNode(10); root1.right = newNode(20); root1.left.left = newNode(5); root1.left.right = newNode(12); root1.right.right = newNode(25); // Second BST Node root2 = newNode(15); root2.left = newNode(12); root2.right = newNode(20); root2.left.left = newNode(5); root2.left.left.right = newNode(10); root2.right.right = newNode(25); // check if two BSTs have same set of elements if (checkBSTs(root1, root2)) Console.Write(\"YES\"); else Console.Write(\"NO\");} } // This code is contributed by PrinciRaj1992", "e": 33749, "s": 31825, "text": null }, { "code": "<script> // JavaScript program to check if two BSTs contains// same set of elements // BST Nodeclass Node{ constructor() { this.data = 0; this.left = null; this.right = null; }}; // Utility function to create new Nodefunction newNode(val){ var temp = new Node(); temp.data = val; temp.left = temp.right = null; return temp;} // function to insert elements of the// tree to map mfunction insertToHash(root, s){ if (root == null) return; insertToHash(root.left, s); s.add(root.data); insertToHash(root.right, s);} // function to check if the two BSTs contain// same set of elementsfunction checkBSTs(root1, root2){ // Base cases if (root1 != null && root2 != null) return true; if ((root1 == null && root2 != null) || (root1 != null && root2 == null)) return false; // Create two hash sets and store // elements both BSTs in them. var s1 = new Set(); var s2 = new Set(); insertToHash(root1, s1); insertToHash(root2, s2); // Return true if both hash sets // contain same elements. return (s1==s2);} // Driver Code// First BSTvar root1 = newNode(15);root1.left = newNode(10);root1.right = newNode(20);root1.left.left = newNode(5);root1.left.right = newNode(12);root1.right.right = newNode(25); // Second BSTvar root2 = newNode(15);root2.left = newNode(12);root2.right = newNode(20);root2.left.left = newNode(5);root2.left.left.right = newNode(10);root2.right.right = newNode(25); // check if two BSTs have same set of elementsif (checkBSTs(root1, root2)) document.write(\"YES\");else document.write(\"NO\"); </script>", "e": 35397, "s": 33749, "text": null }, { "code": null, "e": 35407, "s": 35397, "text": "Output: " }, { "code": null, "e": 35411, "s": 35407, "text": "YES" }, { "code": null, "e": 35823, "s": 35411, "text": "Time Complexity: O( n ), where n is the number of nodes in the trees. Auxiliary Space: O( n ).Method 3: We know about an interesting property of BST that inorder traversal of a BST generates a sorted array. So we can do inorder traversals of both the BSTs and generate two arrays and finally we can compare these two arrays. If both of the arrays are same then the BSTs have same set of elements otherwise not. " }, { "code": null, "e": 35827, "s": 35823, "text": "C++" }, { "code": null, "e": 35832, "s": 35827, "text": "Java" }, { "code": null, "e": 35840, "s": 35832, "text": "Python3" }, { "code": null, "e": 35843, "s": 35840, "text": "C#" }, { "code": null, "e": 35854, "s": 35843, "text": "Javascript" }, { "code": "// CPP program to check if two BSTs contains// same set of elements#include<bits/stdc++.h>using namespace std; // BST Nodestruct Node{ int data; struct Node* left; struct Node* right;}; // Utility function to create new NodeNode* newNode(int val){ Node* temp = new Node; temp->data = val; temp->left = temp->right = NULL; return temp;} // function to insert elements of the// tree to map mvoid storeInorder(Node* root, vector<int> &v){ if (!root) return; storeInorder(root->left, v); v.push_back(root->data); storeInorder(root->right, v);} // function to check if the two BSTs contain// same set of elementsbool checkBSTs(Node* root1, Node* root2){ // Base cases if (!root1 && !root2) return true; if ((root1 && !root2) || (!root1 && root2)) return false; // Create two vectors and store // inorder traversals of both BSTs // in them. vector<int> v1, v2; storeInorder(root1, v1); storeInorder(root2, v2); // Return true if both vectors are // identical return (v1 == v2);} // Driver program to check above functionsint main(){ // First BST Node* root1 = newNode(15); root1->left = newNode(10); root1->right = newNode(20); root1->left->left = newNode(5); root1->left->right = newNode(12); root1->right->right = newNode(25); // Second BST Node* root2 = newNode(15); root2->left = newNode(12); root2->right = newNode(20); root2->left->left = newNode(5); root2->left->left->right = newNode(10); root2->right->right = newNode(25); // check if two BSTs have same set of elements if (checkBSTs(root1, root2)) cout << \"YES\"; else cout << \"NO\"; return 0; }", "e": 37587, "s": 35854, "text": null }, { "code": "// Java program to check if two BSTs// contain same set of elementsimport java.util.*; class GFG{ // BST Nodestatic class Node{ int data; Node left; Node right;}; // Utility function to create new Nodestatic Node newNode(int val){ Node temp = new Node(); temp.data = val; temp.left = temp.right = null; return temp;} // function to insert elements // of the tree to map mstatic void storeInorder(Node root, Vector<Integer> v){ if (root == null) return; storeInorder(root.left, v); v.add(root.data); storeInorder(root.right, v);} // function to check if the two BSTs// contain same set of elementsstatic boolean checkBSTs(Node root1, Node root2){ // Base cases if (root1 != null && root2 != null) return true; if ((root1 == null && root2 != null) || (root1 != null && root2 == null)) return false; // Create two vectors and store // inorder traversals of both BSTs // in them. Vector<Integer> v1 = new Vector<Integer>(); Vector<Integer> v2 = new Vector<Integer>(); storeInorder(root1, v1); storeInorder(root2, v2); // Return true if both vectors are // identical return (v1 == v2);} // Driver Codepublic static void main(String[] args){ // First BST Node root1 = newNode(15); root1.left = newNode(10); root1.right = newNode(20); root1.left.left = newNode(5); root1.left.right = newNode(12); root1.right.right = newNode(25); // Second BST Node root2 = newNode(15); root2.left = newNode(12); root2.right = newNode(20); root2.left.left = newNode(5); root2.left.left.right = newNode(10); root2.right.right = newNode(25); // check if two BSTs have same set of elements if (checkBSTs(root1, root2)) System.out.print(\"YES\"); else System.out.print(\"NO\");} } // This code is contributed by Rajput-Ji", "e": 39489, "s": 37587, "text": null }, { "code": "# Python3 program to check if two BSTs contains# same set of elements # BST Nodeclass Node: def __init__(self): self.val = 0 self.left = None self.right = None # Utility function to create Nodedef Node_(val1): temp = Node() temp.val = val1 temp.left = temp.right = None return temp v = [] # function to insert elements of the# tree to map mdef storeInorder(root): if (root == None): return storeInorder(root.left) v.append(root.data) storeInorder(root.right) # function to check if the two BSTs contain# same set of elementsdef checkBSTs(root1, root2): # Base cases if (root1 != None and root2 != None) : return True if ((root1 == None and root2 != None) or \\ (root1 != None and root2 == None)): return False # Create two hash sets and store # elements both BSTs in them. v1 = [] v2 = [] v = v1 storeInorder(root1) v1 = v v = v2 storeInorder(root2) v2 = v # Return True if both hash sets # contain same elements. return (v1 == v2) # Driver code # First BSTroot1 = Node_(15)root1.left = Node_(10)root1.right = Node_(20)root1.left.left = Node_(5)root1.left.right = Node_(12)root1.right.right = Node_(25) # Second BSTroot2 = Node_(15)root2.left = Node_(12)root2.right = Node_(20)root2.left.left = Node_(5)root2.left.left.right = Node_(10)root2.right.right = Node_(25) # check if two BSTs have same set of elementsif (checkBSTs(root1, root2)): print(\"YES\")else: print(\"NO\") # This code is contributed by SHUBHAMSINGH10", "e": 41063, "s": 39489, "text": null }, { "code": "// C# program to check if two BSTs// contain same set of elementsusing System;using System.Collections.Generic; class GFG{ // BST Nodeclass Node{ public int data; public Node left; public Node right;}; // Utility function to create new Nodestatic Node newNode(int val){ Node temp = new Node(); temp.data = val; temp.left = temp.right = null; return temp;} // function to insert elements// of the tree to map mstatic void storeInorder(Node root, List<int> v){ if (root == null) return; storeInorder(root.left, v); v.Add(root.data); storeInorder(root.right, v);} // function to check if the two BSTs// contain same set of elementsstatic bool checkBSTs(Node root1, Node root2){ // Base cases if (root1 != null && root2 != null) return true; if ((root1 == null && root2 != null) || (root1 != null && root2 == null)) return false; // Create two vectors and store // inorder traversals of both BSTs // in them. List<int> v1 = new List<int>(); List<int> v2 = new List<int>(); storeInorder(root1, v1); storeInorder(root2, v2); // Return true if both vectors are // identical return (v1 == v2);} // Driver Codepublic static void Main(String[] args){ // First BST Node root1 = newNode(15); root1.left = newNode(10); root1.right = newNode(20); root1.left.left = newNode(5); root1.left.right = newNode(12); root1.right.right = newNode(25); // Second BST Node root2 = newNode(15); root2.left = newNode(12); root2.right = newNode(20); root2.left.left = newNode(5); root2.left.left.right = newNode(10); root2.right.right = newNode(25); // check if two BSTs have // same set of elements if (checkBSTs(root1, root2)) Console.Write(\"YES\"); else Console.Write(\"NO\");} } // This code is contributed by Rajput-Ji", "e": 42991, "s": 41063, "text": null }, { "code": "<script> // JavaScript program to check if two BSTs// contain same set of elements // BST Nodeclass Node { constructor() { this.data = 0; this.prev = null; this.next = null; }} // Utility function to create new Node function newNode(val) { var temp = new Node(); temp.data = val; temp.left = temp.right = null; return temp; } // function to insert elements // of the tree to map m function storeInorder(root, v) { if (root == null) return; storeInorder(root.left, v); v.push(root.data); storeInorder(root.right, v); } // function to check if the two BSTs // contain same set of elements function checkBSTs(root1, root2) { // Base cases if (root1 != null && root2 != null) return true; if ((root1 == null && root2 != null) || (root1 != null && root2 == null)) return false; // Create two vectors and store // inorder traversals of both BSTs // in them. var v1 = []; var v2 = []; storeInorder(root1, v1); storeInorder(root2, v2); // Return true if both vectors are // identical return (v1 == v2); } // Driver Code // First BST var root1 = newNode(15); root1.left = newNode(10); root1.right = newNode(20); root1.left.left = newNode(5); root1.left.right = newNode(12); root1.right.right = newNode(25); // Second BST var root2 = newNode(15); root2.left = newNode(12); root2.right = newNode(20); root2.left.left = newNode(5); root2.left.left.right = newNode(10); root2.right.right = newNode(25); // check if two BSTs have same set of elements if (checkBSTs(root1, root2)) document.write(\"YES\"); else document.write(\"NO\"); // This code is contributed by Rajput-Ji </script>", "e": 44977, "s": 42991, "text": null }, { "code": null, "e": 44987, "s": 44977, "text": "Output: " }, { "code": null, "e": 44991, "s": 44987, "text": "YES" }, { "code": null, "e": 45042, "s": 44991, "text": "Time Complexity: O( n ). Auxiliary Space: O( n ). " }, { "code": null, "e": 45887, "s": 45042, "text": "YouTubeGeeksforGeeks502K subscribersCheck if two BSTs contain same set of elements | 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:34•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=c-OSdbpOVDE\" 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": 46309, "s": 45887, "text": "This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to 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": 46323, "s": 46311, "text": "29AjayKumar" }, { "code": null, "e": 46337, "s": 46323, "text": "princiraj1992" }, { "code": null, "e": 46347, "s": 46337, "text": "Rajput-Ji" }, { "code": null, "e": 46358, "s": 46347, "text": "andrew1234" }, { "code": null, "e": 46373, "s": 46358, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 46383, "s": 46373, "text": "rutvik_56" }, { "code": null, "e": 46401, "s": 46383, "text": "cpp-unordered_set" }, { "code": null, "e": 46412, "s": 46401, "text": "cpp-vector" }, { "code": null, "e": 46431, "s": 46412, "text": "Binary Search Tree" }, { "code": null, "e": 46450, "s": 46431, "text": "Binary Search Tree" }, { "code": null, "e": 46548, "s": 46450, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 46582, "s": 46548, "text": "Advantages of BST over Hash Table" }, { "code": null, "e": 46636, "s": 46582, "text": "Difference between Binary Tree and Binary Search Tree" }, { "code": null, "e": 46693, "s": 46636, "text": "Inorder predecessor and successor for a given key in BST" }, { "code": null, "e": 46728, "s": 46693, "text": "Sorted Linked List to Balanced BST" }, { "code": null, "e": 46762, "s": 46728, "text": "Print BST keys in the given range" }, { "code": null, "e": 46807, "s": 46762, "text": "Binary Tree to Binary Search Tree Conversion" }, { "code": null, "e": 46855, "s": 46807, "text": "Insert a node in Binary Search Tree Iteratively" }, { "code": null, "e": 46894, "s": 46855, "text": "C Program for Red Black Tree Insertion" }, { "code": null, "e": 46951, "s": 46894, "text": "Find the node with maximum value in a Binary Search Tree" } ]
Tough Competitors | Practice | GeeksforGeeks
There are n competitors in an exam. Each competitor has his own skill value which is given by the array arr where arr1 is the skill of the first competitor, arr2 is the skill of second competitor and so on. Two competitors are said to be tough competitors if their skill difference is least i.e. they are very close in their skill values. Given n and an array arr as input, find the tough competitors among the n competitors and print the absolute of the difference of their skill values. Example 1: Input: n = 4 arr[] = {9, 4, 12, 6} Output: 2 Explanation: As |9-4|=5, |9-12|=3, |9-6|=3, |4-12|=8, |4-6|=2, |12-6|=6 so, the tough competitors are competitors having skill values 4, 6 having their skill difference as 2. Example 2: Input: n = 5 arr[] = {4, 9, 1, 32, 12} Output: 3 Explanation: Tough competitors are competitors having skill values (4,1) and (9,12) having their skill difference as 3. Your Task: You don't need to read input or print anything. Your task is to complete the function toughCompetitor() which takes the array of integers arr and n as parameters and returns an integer denoting the answer. Expected Time Complexity: O(n*logn) Expected Auxiliary Space: O(1) Constraints: 2 <= n <= 105 1 <= arr[i] <= 106 0 arvind16yadav2 weeks ago /*JAVA CODE*/ int toughCompetitor(int[] arr, int n) { // code here Arrays.sort(arr); int min = arr[1] - arr[0]; for(int i=1; i<n-1; i++){ int temp = arr[i+1] - arr[i]; if(min > temp){ min = temp; } } return min; } 0 codewithshoaib193 weeks ago int toughCompetitor(int[] arr, int n) { // code here Arrays.sort(arr); int x=Integer.MAX_VALUE; int abs=0; for(int i=0;i<n-1;i++){ abs=Math.abs(arr[i]-arr[i+1]); if(abs<x){ x=abs; } } return x; } 0 hasnainraza1998hr2 months ago C++, 0.3 int toughCompetitor(int *arr, int n) { sort(arr,arr+n); int min = INT_MAX; for(int i=1;i<n;i++){ if(arr[i]-arr[i-1]<min) min = arr[i]-arr[i-1]; } return min; } 0 ravichaunal309002 months ago l=[] for i in range(len(arr)): for j in range(1,len(arr)): if arr[i]==arr[j]: break else: p=abs(arr[i]-arr[j]) l.append(p) return min(l) test case fail please help 0 vidhigupta123 months ago int toughCompetitor(int *arr, int n) { // code here sort(arr,arr+n); int ans=INT_MAX; for(int i=0;i<n-1;i++) { int diff=abs(arr[i]-arr[i+1]); ans=min(diff,ans); } return ans; } 0 cshubham4396 months ago int min = Integer.MAX_VALUE; int dif = 0; Arrays.sort(arr); for(int i = 0; i<n-1; i++){ dif = Math.abs(arr[i] - arr[i+1]); if(dif<min) min = dif; } return min; +1 badgujarsachin836 months ago int toughCompetitor(int *arr, int n) { // code here sort(arr,arr+n); int min=abs(arr[0]-arr[1]); int di=0; for(int i=1;i<n;i++){ di=abs(arr[i]-arr[i+1]); if(di<min){ min=di; } } return min; } 0 Aashutosh Jha1 year ago Aashutosh Jha int i,j,min=0,diff=0; sort(arr,arr+n); min=abs(arr[1]-arr[0]); for(i=0;i<n;i++) {="" diff="abs(arr[i]-arr[i+1]);" if(diff<min)="" {="" min="diff;" }="" }="" return="" min;="" "execution="" time:0.50"=""> 0 Abhishek Gupta1 year ago Abhishek Gupta SIMPLE C++ SOL:https://practice.geeksforge... 0 Tulsi Dey2 years ago Tulsi Dey Solution in C++:Execution time : 0.01 https://uploads.disquscdn.c... 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": 715, "s": 226, "text": "There are n competitors in an exam. Each competitor has his own skill value which is given by the array arr where arr1 is the skill of the first competitor, arr2 is the skill of second competitor and so on. Two competitors are said to be tough competitors if their skill difference is least i.e. they are very close in their skill values. Given n and an array arr as input, find the tough competitors among the n competitors and print the absolute of the difference of their skill values." }, { "code": null, "e": 726, "s": 715, "text": "Example 1:" }, { "code": null, "e": 947, "s": 726, "text": "Input:\nn = 4\narr[] = {9, 4, 12, 6}\nOutput: 2\nExplanation: As |9-4|=5, |9-12|=3, |9-6|=3,\n|4-12|=8, |4-6|=2, |12-6|=6 so, the tough\ncompetitors are competitors having skill\nvalues 4, 6 having their skill difference\nas 2.\n" }, { "code": null, "e": 958, "s": 947, "text": "Example 2:" }, { "code": null, "e": 1128, "s": 958, "text": "Input:\nn = 5\narr[] = {4, 9, 1, 32, 12}\nOutput: 3\nExplanation: Tough competitors are\ncompetitors having skill values (4,1)\nand (9,12) having their skill difference\nas 3.\n" }, { "code": null, "e": 1345, "s": 1128, "text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function toughCompetitor() which takes the array of integers arr and n as parameters and returns an integer denoting the answer." }, { "code": null, "e": 1412, "s": 1345, "text": "Expected Time Complexity: O(n*logn)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 1458, "s": 1412, "text": "Constraints:\n2 <= n <= 105\n1 <= arr[i] <= 106" }, { "code": null, "e": 1460, "s": 1458, "text": "0" }, { "code": null, "e": 1485, "s": 1460, "text": "arvind16yadav2 weeks ago" }, { "code": null, "e": 1499, "s": 1485, "text": "/*JAVA CODE*/" }, { "code": null, "e": 1809, "s": 1499, "text": "int toughCompetitor(int[] arr, int n) { // code here Arrays.sort(arr); int min = arr[1] - arr[0]; for(int i=1; i<n-1; i++){ int temp = arr[i+1] - arr[i]; if(min > temp){ min = temp; } } return min; }" }, { "code": null, "e": 1811, "s": 1809, "text": "0" }, { "code": null, "e": 1839, "s": 1811, "text": "codewithshoaib193 weeks ago" }, { "code": null, "e": 2128, "s": 1839, "text": " int toughCompetitor(int[] arr, int n) { // code here Arrays.sort(arr); int x=Integer.MAX_VALUE; int abs=0; for(int i=0;i<n-1;i++){ abs=Math.abs(arr[i]-arr[i+1]); if(abs<x){ x=abs; } } return x; }" }, { "code": null, "e": 2130, "s": 2128, "text": "0" }, { "code": null, "e": 2160, "s": 2130, "text": "hasnainraza1998hr2 months ago" }, { "code": null, "e": 2169, "s": 2160, "text": "C++, 0.3" }, { "code": null, "e": 2385, "s": 2169, "text": "int toughCompetitor(int *arr, int n) { sort(arr,arr+n); int min = INT_MAX; for(int i=1;i<n;i++){ if(arr[i]-arr[i-1]<min) min = arr[i]-arr[i-1]; } return min; }" }, { "code": null, "e": 2387, "s": 2385, "text": "0" }, { "code": null, "e": 2416, "s": 2387, "text": "ravichaunal309002 months ago" }, { "code": null, "e": 2660, "s": 2416, "text": " l=[] for i in range(len(arr)): for j in range(1,len(arr)): if arr[i]==arr[j]: break else: p=abs(arr[i]-arr[j]) l.append(p) return min(l) " }, { "code": null, "e": 2687, "s": 2660, "text": "test case fail please help" }, { "code": null, "e": 2689, "s": 2687, "text": "0" }, { "code": null, "e": 2714, "s": 2689, "text": "vidhigupta123 months ago" }, { "code": null, "e": 2953, "s": 2714, "text": "int toughCompetitor(int *arr, int n) { // code here sort(arr,arr+n); int ans=INT_MAX; for(int i=0;i<n-1;i++) { int diff=abs(arr[i]-arr[i+1]); ans=min(diff,ans); } return ans; }" }, { "code": null, "e": 2955, "s": 2953, "text": "0" }, { "code": null, "e": 2979, "s": 2955, "text": "cshubham4396 months ago" }, { "code": null, "e": 3211, "s": 2979, "text": " int min = Integer.MAX_VALUE; int dif = 0; Arrays.sort(arr); for(int i = 0; i<n-1; i++){ dif = Math.abs(arr[i] - arr[i+1]); if(dif<min) min = dif; } return min;" }, { "code": null, "e": 3214, "s": 3211, "text": "+1" }, { "code": null, "e": 3243, "s": 3214, "text": "badgujarsachin836 months ago" }, { "code": null, "e": 3547, "s": 3243, "text": "int toughCompetitor(int *arr, int n) {\n // code here\n sort(arr,arr+n);\n int min=abs(arr[0]-arr[1]);\n int di=0;\n for(int i=1;i<n;i++){\n di=abs(arr[i]-arr[i+1]);\n if(di<min){\n min=di;\n }\n }\n return min;\n }" }, { "code": null, "e": 3549, "s": 3547, "text": "0" }, { "code": null, "e": 3573, "s": 3549, "text": "Aashutosh Jha1 year ago" }, { "code": null, "e": 3587, "s": 3573, "text": "Aashutosh Jha" }, { "code": null, "e": 3812, "s": 3587, "text": "int i,j,min=0,diff=0; sort(arr,arr+n); min=abs(arr[1]-arr[0]); for(i=0;i<n;i++) {=\"\" diff=\"abs(arr[i]-arr[i+1]);\" if(diff<min)=\"\" {=\"\" min=\"diff;\" }=\"\" }=\"\" return=\"\" min;=\"\" \"execution=\"\" time:0.50\"=\"\">" }, { "code": null, "e": 3814, "s": 3812, "text": "0" }, { "code": null, "e": 3839, "s": 3814, "text": "Abhishek Gupta1 year ago" }, { "code": null, "e": 3854, "s": 3839, "text": "Abhishek Gupta" }, { "code": null, "e": 3900, "s": 3854, "text": "SIMPLE C++ SOL:https://practice.geeksforge..." }, { "code": null, "e": 3902, "s": 3900, "text": "0" }, { "code": null, "e": 3923, "s": 3902, "text": "Tulsi Dey2 years ago" }, { "code": null, "e": 3933, "s": 3923, "text": "Tulsi Dey" }, { "code": null, "e": 4002, "s": 3933, "text": "Solution in C++:Execution time : 0.01 https://uploads.disquscdn.c..." }, { "code": null, "e": 4148, "s": 4002, "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": 4184, "s": 4148, "text": " Login to access your submissions. " }, { "code": null, "e": 4194, "s": 4184, "text": "\nProblem\n" }, { "code": null, "e": 4204, "s": 4194, "text": "\nContest\n" }, { "code": null, "e": 4267, "s": 4204, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4415, "s": 4267, "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": 4623, "s": 4415, "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": 4729, "s": 4623, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Amazon RDS - MySQL DB Export Import
Amazon RDS MySQL provides easy ways of importing data into the DB and exporting data from the DB. After we are able to successfully connect to the MySQL database we can use CLI tools to run the import and export commands to get the data from other sources in and out of the RDS database. Below are the scenarios to consider when deciding on the approach to the import the data into the Amazon RDS - MySQL database. An existing MySQL DB can be present on premise or in another EC2 instance. Diagrammatically what we do is shown below. As a first step we create a backup of the on-premise database using the below command. mysqldump -u user -p[user_password] [database_name] > backupfile.sql A file with name backupfile.sql is created which contains the table structure along with the data to be used. Upload the backup file created above to a pre-decided Amazon S3 bucket in the same region where the target RDS MySQL DB database is present. You can follow this link to learn about how to upload. You can use the following Amazon CLI command to import the data from S3 to MySQL DB. aws rds restore-db-instance-from-s3 \ --allocated-storage 125 \ --db-instance-identifier tddbidentifier \ --db-instance-class db.m4.small \ --engine mysql \ --master-user-name masterawsuser \ --master-user-password masteruserpassword \ --s3-bucket-name tpbucket \ --s3-ingestion-role-arn arn:aws:iam::account-number:role/rolename \ --s3-prefix bucketprefix \ --source-engine mysql \ --source-engine-version 5.6.27 There may be scenarios when you want data from an existing RDS MYSQL DB to be taken into another RDS MYSQL DB. For example, to cerate a Disaster recovery DB or create a DB only for business reporting etc. In such scenario, we create read replicas which are a copy of their source DB and then promote that read replica to a new DB instance. They are used to prevent direct heavy read from the original source DB when we want to copy the data. aws rds create-db-instance-read-replica \ --db-instance-identifier myreadreplica \ --source-db-instance-identifier mydbinstance Now as we have the replica, we can promote it to a standalone DB instance. This will serve our end need of importing data from o RDS – Mysql DB to a new one. The following command is used to complete the promotion of a read replica to a db instance. aws rds create-db-instance-read-replica \ --db-instance-identifier readreplica_name \ --region target_region_name --db-subnet-group-name subnet_name --source-db-instance-identifier arn:aws:rds:region_name:11323467889012:db:mysql_instance1 In order to import data from any other database to Amazon RDS – MySQL, we have to use the amazon Data Migration Service also called Amazon DMS. It uses Schema conversion tool to translate the existing data base to a the MYSQL platform. The below diagram explains the overall process. Also it works on the similar principle of replication as described in the previous section. Exporting of data from Amazon RDS Mysql DB is a straight forwards process where it works on the same replication principle we have seen above. Below are the steps to carry out the export process. Start the instance of MySQL running external to Amazon RDS. Designate the MySQL DB instance to be the replication source. Use mysqldump to transfer the database from the Amazon RDS instance to the instance external to Amazon RDS. Below is the code for the mysqldum command mysqldump -h RDS instance endpoint \ -u user \ -p password \ --port=3306 \ --single-transaction \ --routines \ --triggers \ --databases database database2 \ --compress \ --compact | mysql \ -h MySQL host \ -u master user \ -p password \ --port 3306 Print Add Notes Bookmark this page
[ { "code": null, "e": 3000, "s": 2585, "text": "Amazon RDS MySQL provides easy ways of importing data into the DB and exporting data from the DB. After we are able to successfully connect to the MySQL database we can use CLI tools to run the import and export commands to get the data from other sources in and out of the RDS database.\nBelow are the scenarios to consider when deciding on the approach to the import the data into the Amazon RDS - MySQL database." }, { "code": null, "e": 3119, "s": 3000, "text": "An existing MySQL DB can be present on premise or in another EC2 instance.\nDiagrammatically what we do is shown below." }, { "code": null, "e": 3207, "s": 3119, "text": "As a first step we create a backup of the on-premise database using the below command. " }, { "code": null, "e": 3278, "s": 3207, "text": "\nmysqldump -u user -p[user_password] [database_name] > backupfile.sql\n" }, { "code": null, "e": 3388, "s": 3278, "text": "A file with name backupfile.sql is created which contains the table structure along with the data to be used." }, { "code": null, "e": 3585, "s": 3388, "text": "Upload the backup file created above to a pre-decided Amazon S3 bucket in the same region where the target RDS MySQL DB database is present. You can follow this link to learn about how to upload." }, { "code": null, "e": 3670, "s": 3585, "text": "You can use the following Amazon CLI command to import the data from S3 to MySQL DB." }, { "code": null, "e": 4087, "s": 3670, "text": "aws rds restore-db-instance-from-s3 \\ \n--allocated-storage 125 \\ \n--db-instance-identifier tddbidentifier \\\n--db-instance-class db.m4.small \\\n--engine mysql \\\n--master-user-name masterawsuser \\\n--master-user-password masteruserpassword \\\n--s3-bucket-name tpbucket \\\n--s3-ingestion-role-arn arn:aws:iam::account-number:role/rolename \\\n--s3-prefix bucketprefix \\\n--source-engine mysql \\\n--source-engine-version 5.6.27" }, { "code": null, "e": 4530, "s": 4087, "text": "There may be scenarios when you want data from an existing RDS MYSQL DB to be taken into another RDS MYSQL DB. For example, to cerate a Disaster recovery DB or create a DB only for business reporting etc. In such scenario, we create read replicas which are a copy of their source DB and then promote that read replica to a new DB instance. They are used to prevent direct heavy read from the original source DB when we want to copy the data." }, { "code": null, "e": 4666, "s": 4530, "text": "aws rds create-db-instance-read-replica \\\n --db-instance-identifier myreadreplica \\\n --source-db-instance-identifier mydbinstance" }, { "code": null, "e": 4916, "s": 4666, "text": "Now as we have the replica, we can promote it to a standalone DB instance. This will serve our end need of importing data from o RDS – Mysql DB to a new one. The following command is used to complete the promotion of a read replica to a db instance." }, { "code": null, "e": 5173, "s": 4916, "text": "aws rds create-db-instance-read-replica \\\n --db-instance-identifier readreplica_name \\\n --region target_region_name\n --db-subnet-group-name subnet_name \n --source-db-instance-identifier arn:aws:rds:region_name:11323467889012:db:mysql_instance1 " }, { "code": null, "e": 5549, "s": 5173, "text": "In order to import data from any other database to Amazon RDS – MySQL, we have to use the amazon Data Migration Service also called Amazon DMS. It uses Schema conversion tool to translate the existing data base to a the MYSQL platform. The below diagram explains the overall process. Also it works on the similar principle of replication as described in the previous section." }, { "code": null, "e": 5745, "s": 5549, "text": "Exporting of data from Amazon RDS Mysql DB is a straight forwards process where it works on the same replication principle we have seen above. Below are the steps to carry out the export process." }, { "code": null, "e": 5805, "s": 5745, "text": "Start the instance of MySQL running external to Amazon RDS." }, { "code": null, "e": 5867, "s": 5805, "text": "Designate the MySQL DB instance to be the replication source." }, { "code": null, "e": 5976, "s": 5867, "text": "Use mysqldump to transfer the database from the Amazon RDS instance to the instance external to Amazon RDS. " }, { "code": null, "e": 6019, "s": 5976, "text": "Below is the code for the mysqldum command" }, { "code": null, "e": 6339, "s": 6019, "text": "mysqldump -h RDS instance endpoint \\\n -u user \\\n -p password \\\n --port=3306 \\\n --single-transaction \\\n --routines \\\n --triggers \\\n --databases database database2 \\\n --compress \\\n --compact | mysql \\\n -h MySQL host \\\n -u master user \\\n -p password \\\n --port 3306 " }, { "code": null, "e": 6346, "s": 6339, "text": " Print" }, { "code": null, "e": 6357, "s": 6346, "text": " Add Notes" } ]
C++ if statement
An if statement consists of a boolean expression followed by one or more statements. The syntax of an if statement in C++ is − if(boolean_expression) { // statement(s) will execute if the boolean expression is true } If the boolean expression evaluates to true, then the block of code inside the if statement will be executed. If boolean expression evaluates to false, then the first set of code after the end of the if statement (after the closing curly brace) will be executed. #include <iostream> using namespace std; int main () { // local variable declaration: int a = 10; // check the boolean condition if( a < 20 ) { // if condition is true then print the following cout << "a is less than 20;" << endl; } cout << "value of a is : " << a << endl; return 0; } When the above code is compiled and executed, it produces the following result − a is less than 20; value of a is : 10 154 Lectures 11.5 hours Arnab Chakraborty 14 Lectures 57 mins Kaushik Roy Chowdhury 30 Lectures 12.5 hours Frahaan Hussain 54 Lectures 3.5 hours Frahaan Hussain 77 Lectures 5.5 hours Frahaan Hussain 12 Lectures 3.5 hours Frahaan Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2403, "s": 2318, "text": "An if statement consists of a boolean expression followed by one or more statements." }, { "code": null, "e": 2445, "s": 2403, "text": "The syntax of an if statement in C++ is −" }, { "code": null, "e": 2539, "s": 2445, "text": "if(boolean_expression) {\n // statement(s) will execute if the boolean expression is true\n}\n" }, { "code": null, "e": 2803, "s": 2539, "text": "If the boolean expression evaluates to true, then the block of code inside the if statement will be executed. If boolean expression evaluates to false, then the first set of code after the end of the if statement (after the closing curly brace) will be executed." }, { "code": null, "e": 3128, "s": 2803, "text": "#include <iostream>\nusing namespace std;\n \nint main () {\n // local variable declaration:\n int a = 10;\n \n // check the boolean condition\n if( a < 20 ) {\n // if condition is true then print the following\n cout << \"a is less than 20;\" << endl;\n }\n cout << \"value of a is : \" << a << endl;\n \n return 0;\n}" }, { "code": null, "e": 3209, "s": 3128, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 3248, "s": 3209, "text": "a is less than 20;\nvalue of a is : 10\n" }, { "code": null, "e": 3285, "s": 3248, "text": "\n 154 Lectures \n 11.5 hours \n" }, { "code": null, "e": 3304, "s": 3285, "text": " Arnab Chakraborty" }, { "code": null, "e": 3336, "s": 3304, "text": "\n 14 Lectures \n 57 mins\n" }, { "code": null, "e": 3359, "s": 3336, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 3395, "s": 3359, "text": "\n 30 Lectures \n 12.5 hours \n" }, { "code": null, "e": 3412, "s": 3395, "text": " Frahaan Hussain" }, { "code": null, "e": 3447, "s": 3412, "text": "\n 54 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3464, "s": 3447, "text": " Frahaan Hussain" }, { "code": null, "e": 3499, "s": 3464, "text": "\n 77 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3516, "s": 3499, "text": " Frahaan Hussain" }, { "code": null, "e": 3551, "s": 3516, "text": "\n 12 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3568, "s": 3551, "text": " Frahaan Hussain" }, { "code": null, "e": 3575, "s": 3568, "text": " Print" }, { "code": null, "e": 3586, "s": 3575, "text": " Add Notes" } ]
Maximum Sequence Length | Collatz Conjecture - GeeksforGeeks
26 Apr, 2022 Given an integer N. The task is to find the number in the range from 1 to N-1 which is having the maximum number of terms in its Collatz Sequence and the number of terms in the sequence.The collatz sequence of a number N is defined as: If N is Odd then change N to 3*N + 1. If N is Even then change N to N / 2. For example let us have a look at the sequence when N = 13: 13 -> 40 -> 20 -> 10 -> 5 > 16 -> 8 -> 4 -> 2 -> 1Examples: Input: 10 Output: (9, 20)9 has 20 terms in its Collatz sequenceInput: 50 Output: (27, 112) 27 has 112 terms Approach: As in the above example discussed for N = 13, collatz sequence for N = 13 and N = 40 have similar terms except one, that ensures there may be an involvement of dynamic programming to store the answer for subproblems and reuse it.But here normal memoization will not work because at one step we are either making a number large from itself ( in above example N = 13 is depending upon the solution of N = 40 ) or dividing by 2 ( N = 40 solution depends upon the solution of N = 20 ).So instead of using a dp array we will use a Map/ dictionary data structure to store the solution of subproblems and will perform the normal operation as discussed in the collatz sequence.Below is the implementation of the above approach: C++ Python3 Javascript #include<bits/stdc++.h>using namespace std; int collatzLenUtil(int n, unordered_map<int,int>&collLenMap){ // If value already // computed, return it if(collLenMap.find(n) != collLenMap.end()) return collLenMap[n]; // Base case if(n == 1) collLenMap[n] = 1; // Even case else if(n % 2 == 0){ collLenMap[n] = 1 + collatzLenUtil(n/2 , collLenMap); } // Odd case else{ collLenMap[n] = 1 + collatzLenUtil(3 * n + 1, collLenMap); } return collLenMap[n];} pair<int,int> collatzLen(int n){ // Declare empty Map / Dict // to store collatz lengths unordered_map<int,int>collLenMap; collatzLenUtil(n, collLenMap); // Initialise ans and // its collatz length int num = -1, l = 0; for(int i=1;i<n;i++){ // If value not already computed, // pass Dict to Helper function // and calculate and store value if(collLenMap.find(i)==collLenMap.end()) collatzLenUtil(i, collLenMap); int cLen = collLenMap[i]; if(l < cLen){ l = cLen; num = i; } } // Return ans and // its collatz length return {num, l};} int main(){ cout<<"("<<collatzLen(10).first<<", "<<collatzLen(10).second<<")"<<endl; } // This code is contributed by shinjanpatra def collatzLenUtil(n, collLenMap): # If value already # computed, return it if n in collLenMap: return collLenMap[n] # Base case if(n == 1): collLenMap[n] = 1 # Even case elif(n % 2 == 0): collLenMap[n] \ = 1 \ + collatzLenUtil(n//2, collLenMap) # Odd case else: collLenMap[n] \ = 1 \ + collatzLenUtil(3 * n + 1, collLenMap) return collLenMap[n] def collatzLen(n): # Declare empty Map / Dict # to store collatz lengths collLenMap = {} collatzLenUtil(n, collLenMap) # Initialise ans and # its collatz length num, l =-1, 0 for i in range(1, n): # If value not already computed, # pass Dict to Helper function # and calculate and store value if i not in collLenMap: collatzLenUtil(i, collLenMap) cLen = collLenMap[i] if l < cLen: l = cLen num = i # Return ans and # its collatz length return (num, l) print(collatzLen(10)) <script> function collatzLenUtil(n, collLenMap){ // If value already // computed, return it if(collLenMap.has(n)) return collLenMap.get(n) // Base case if(n == 1) collLenMap.set(n, 1) // Even case else if(n % 2 == 0){ collLenMap.set(n , 1 + collatzLenUtil(Math.floor(n/2) , collLenMap)) } // Odd case else{ collLenMap.set(n , 1 + collatzLenUtil(3 * n + 1, collLenMap)) } return collLenMap.get(n);} function collatzLen(n){ // Declare empty Map / Dict // to store collatz lengths let collLenMap = new Map() collatzLenUtil(n, collLenMap) // Initialise ans and // its collatz length let num = -1, l = 0 for(let i=1;i<n;i++){ // If value not already computed, // pass Dict to Helper function // and calculate and store value if(collLenMap.has(i)==false) collatzLenUtil(i, collLenMap) let cLen = collLenMap.get(i) if(l < cLen){ l = cLen num = i } } // Return ans and // its collatz length return [num, l]} document.write(collatzLen(10)) // This code is contributed by shinjanpatra </script> (9, 20) sweetyty shinjanpatra Algorithms Dynamic Programming Mathematical Recursion Dynamic Programming Mathematical Recursion Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SDE SHEET - A Complete Guide for SDE Preparation DSA Sheet by Love Babbar Understanding Time Complexity with Simple Examples Introduction to Algorithms How to write a Pseudo Code? 0-1 Knapsack Problem | DP-10 Program for Fibonacci numbers Largest Sum Contiguous Subarray Longest Common Subsequence | DP-4 Bellman–Ford Algorithm | DP-23
[ { "code": null, "e": 24502, "s": 24474, "text": "\n26 Apr, 2022" }, { "code": null, "e": 24740, "s": 24502, "text": "Given an integer N. The task is to find the number in the range from 1 to N-1 which is having the maximum number of terms in its Collatz Sequence and the number of terms in the sequence.The collatz sequence of a number N is defined as: " }, { "code": null, "e": 24778, "s": 24740, "text": "If N is Odd then change N to 3*N + 1." }, { "code": null, "e": 24815, "s": 24778, "text": "If N is Even then change N to N / 2." }, { "code": null, "e": 24937, "s": 24815, "text": "For example let us have a look at the sequence when N = 13: 13 -> 40 -> 20 -> 10 -> 5 > 16 -> 8 -> 4 -> 2 -> 1Examples: " }, { "code": null, "e": 25047, "s": 24937, "text": "Input: 10 Output: (9, 20)9 has 20 terms in its Collatz sequenceInput: 50 Output: (27, 112) 27 has 112 terms " }, { "code": null, "e": 25780, "s": 25049, "text": "Approach: As in the above example discussed for N = 13, collatz sequence for N = 13 and N = 40 have similar terms except one, that ensures there may be an involvement of dynamic programming to store the answer for subproblems and reuse it.But here normal memoization will not work because at one step we are either making a number large from itself ( in above example N = 13 is depending upon the solution of N = 40 ) or dividing by 2 ( N = 40 solution depends upon the solution of N = 20 ).So instead of using a dp array we will use a Map/ dictionary data structure to store the solution of subproblems and will perform the normal operation as discussed in the collatz sequence.Below is the implementation of the above approach: " }, { "code": null, "e": 25784, "s": 25780, "text": "C++" }, { "code": null, "e": 25792, "s": 25784, "text": "Python3" }, { "code": null, "e": 25803, "s": 25792, "text": "Javascript" }, { "code": "#include<bits/stdc++.h>using namespace std; int collatzLenUtil(int n, unordered_map<int,int>&collLenMap){ // If value already // computed, return it if(collLenMap.find(n) != collLenMap.end()) return collLenMap[n]; // Base case if(n == 1) collLenMap[n] = 1; // Even case else if(n % 2 == 0){ collLenMap[n] = 1 + collatzLenUtil(n/2 , collLenMap); } // Odd case else{ collLenMap[n] = 1 + collatzLenUtil(3 * n + 1, collLenMap); } return collLenMap[n];} pair<int,int> collatzLen(int n){ // Declare empty Map / Dict // to store collatz lengths unordered_map<int,int>collLenMap; collatzLenUtil(n, collLenMap); // Initialise ans and // its collatz length int num = -1, l = 0; for(int i=1;i<n;i++){ // If value not already computed, // pass Dict to Helper function // and calculate and store value if(collLenMap.find(i)==collLenMap.end()) collatzLenUtil(i, collLenMap); int cLen = collLenMap[i]; if(l < cLen){ l = cLen; num = i; } } // Return ans and // its collatz length return {num, l};} int main(){ cout<<\"(\"<<collatzLen(10).first<<\", \"<<collatzLen(10).second<<\")\"<<endl; } // This code is contributed by shinjanpatra", "e": 27003, "s": 25803, "text": null }, { "code": "def collatzLenUtil(n, collLenMap): # If value already # computed, return it if n in collLenMap: return collLenMap[n] # Base case if(n == 1): collLenMap[n] = 1 # Even case elif(n % 2 == 0): collLenMap[n] \\ = 1 \\ + collatzLenUtil(n//2, collLenMap) # Odd case else: collLenMap[n] \\ = 1 \\ + collatzLenUtil(3 * n + 1, collLenMap) return collLenMap[n] def collatzLen(n): # Declare empty Map / Dict # to store collatz lengths collLenMap = {} collatzLenUtil(n, collLenMap) # Initialise ans and # its collatz length num, l =-1, 0 for i in range(1, n): # If value not already computed, # pass Dict to Helper function # and calculate and store value if i not in collLenMap: collatzLenUtil(i, collLenMap) cLen = collLenMap[i] if l < cLen: l = cLen num = i # Return ans and # its collatz length return (num, l) print(collatzLen(10))", "e": 28078, "s": 27003, "text": null }, { "code": "<script> function collatzLenUtil(n, collLenMap){ // If value already // computed, return it if(collLenMap.has(n)) return collLenMap.get(n) // Base case if(n == 1) collLenMap.set(n, 1) // Even case else if(n % 2 == 0){ collLenMap.set(n , 1 + collatzLenUtil(Math.floor(n/2) , collLenMap)) } // Odd case else{ collLenMap.set(n , 1 + collatzLenUtil(3 * n + 1, collLenMap)) } return collLenMap.get(n);} function collatzLen(n){ // Declare empty Map / Dict // to store collatz lengths let collLenMap = new Map() collatzLenUtil(n, collLenMap) // Initialise ans and // its collatz length let num = -1, l = 0 for(let i=1;i<n;i++){ // If value not already computed, // pass Dict to Helper function // and calculate and store value if(collLenMap.has(i)==false) collatzLenUtil(i, collLenMap) let cLen = collLenMap.get(i) if(l < cLen){ l = cLen num = i } } // Return ans and // its collatz length return [num, l]} document.write(collatzLen(10)) // This code is contributed by shinjanpatra </script>", "e": 29302, "s": 28078, "text": null }, { "code": null, "e": 29310, "s": 29302, "text": "(9, 20)" }, { "code": null, "e": 29321, "s": 29312, "text": "sweetyty" }, { "code": null, "e": 29334, "s": 29321, "text": "shinjanpatra" }, { "code": null, "e": 29345, "s": 29334, "text": "Algorithms" }, { "code": null, "e": 29365, "s": 29345, "text": "Dynamic Programming" }, { "code": null, "e": 29378, "s": 29365, "text": "Mathematical" }, { "code": null, "e": 29388, "s": 29378, "text": "Recursion" }, { "code": null, "e": 29408, "s": 29388, "text": "Dynamic Programming" }, { "code": null, "e": 29421, "s": 29408, "text": "Mathematical" }, { "code": null, "e": 29431, "s": 29421, "text": "Recursion" }, { "code": null, "e": 29442, "s": 29431, "text": "Algorithms" }, { "code": null, "e": 29540, "s": 29442, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29589, "s": 29540, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 29614, "s": 29589, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 29665, "s": 29614, "text": "Understanding Time Complexity with Simple Examples" }, { "code": null, "e": 29692, "s": 29665, "text": "Introduction to Algorithms" }, { "code": null, "e": 29720, "s": 29692, "text": "How to write a Pseudo Code?" }, { "code": null, "e": 29749, "s": 29720, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 29779, "s": 29749, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 29811, "s": 29779, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 29845, "s": 29811, "text": "Longest Common Subsequence | DP-4" } ]
PHP mysqli_stmt_fetch() Function
You can create a prepared statement, which has parameter markers ("?") in case of values using the mysqli_prepare() function. Once you prepare a statement, you need to bind values to the parameters of the created statement using the mysqli_stmt_bind_param() function. In the same way you can bound the columns of the result set of a statement to desired variables using the mysqli_stmt_bind_result() function. After you have bound the columns if you invoke the mysqli_stmt_fetch() function, it fetches the columns of the result into the specified variables. mysqli_stmt_fetch($stmt); stmt(Mandatory) This is an object representing a prepared statement. The PHP mysqli_stmt_fetch() function returns TRUE if the data is fetched, FALSE in case of an error and, NULL if there are no more rows in the result. This function was first introduced in PHP Version 5 and works works in all the later versions. Following example demonstrates the usage of the mysqli_stmt_fetch() function (in procedural style) − <?php $con = mysqli_connect("localhost", "root", "password", "mydb"); mysqli_query($con, "CREATE TABLE myplayers(ID INT, First_Name VARCHAR(255), Last_Name VARCHAR(255), Place_Of_Birth VARCHAR(255), Country VARCHAR(255))"); print("Table Created.....\n"); mysqli_query($con, "INSERT INTO myplayers values(1, 'Sikhar', 'Dhawan', 'Delhi', 'India')"); mysqli_query($con, "INSERT INTO myplayers values(2, 'Jonathan', 'Trott', 'CapeTown', 'SouthAfrica')"); print("Record Inserted.....\n"); //Retrieving the contents of the table $stmt = mysqli_prepare($con, "SELECT * FROM myplayers"); //Executing the statement mysqli_stmt_execute($stmt); //Binding values in result to variables mysqli_stmt_bind_result($stmt, $id, $fname, $lname, $pob, $country); while (mysqli_stmt_fetch($stmt)) { print("Id: ".$id."\n"); print("fname: ".$fname."\n"); print("lname: ".$lname."\n"); print("pob: ".$pob."\n"); print("country: ".$country."\n"); print("\n"); } //Closing the statement mysqli_stmt_close($stmt); //Closing the connection mysqli_close($con); ?> This will produce following result − Table Created..... Record Inserted..... Id: 1 fname: Sikhar lname: Dhawan pob: Delhi country: India Id: 2 fname: Jonathan lname: Trott pob: CapeTown country: SouthAfrica In object oriented style the syntax of this function is $stmt->fetch(); Following is the example of this function in object oriented style $minus; <?php //Creating a connection $con = new mysqli("localhost", "root", "password", "mydb"); $con -> query("CREATE TABLE Test(Name VARCHAR(255), AGE INT)"); $con -> query("insert into Test values('Raju', 25),('Rahman', 30),('Sarmista', 27)"); print("Table Created.....\n"); $stmt = $con -> prepare( "SELECT * FROM Test WHERE Name in(?, ?)"); $stmt -> bind_param("ss", $name1, $name2); $name1 = 'Raju'; $name2 = 'Rahman'; print("Records Deleted.....\n"); //Executing the statement $stmt->execute(); //Binding variables to resultset $stmt->bind_result($name, $age); while ($stmt->fetch()) { print("Name: ".$name."\n"); print("Age: ".$age."\n"); } //Closing the statement $stmt->close(); //Closing the connection $con->close(); ?> This will produce following result − Table Created..... Records Deleted..... Name: Raju Age: 25 Name: Rahman Age: 30 Following example fetches the results of the DESCRIBE query using mysqli_stmt_bind_result() and mysqli_stmt_fetch() functions − <?php $con = mysqli_connect("localhost", "root", "password", "mydb"); mysqli_query($con, "CREATE TABLE myplayers(ID INT, First_Name VARCHAR(255), Last_Name VARCHAR(255), Place_Of_Birth VARCHAR(255), Country VARCHAR(255))"); print("Table Created.....\n"); //Description of the table $stmt = mysqli_prepare($con, "DESC myplayers"); //Executing the statement mysqli_stmt_execute($stmt); //Binding values in result to variables mysqli_stmt_bind_result($stmt, $field, $type, $null, $key, $default, $extra); while (mysqli_stmt_fetch($stmt)) { print("Field: ".$field."\n"); print("Type: ".$type."\n"); print("Null: ".$null."\n"); print("Key: ".$key."\n"); print("Default: ".$default."\n"); print("Extra: ".$extra."\n"); print("\n"); } //Closing the statement mysqli_stmt_close($stmt); //Closing the connection mysqli_close($con); ?> This will produce following result − Table Created..... Field: ID Type: int(11) Null: YES Key: Default: Extra: Field: First_Name Type: varchar(255) Null: YES Key: Default: Extra: Field: Last_Name Type: varchar(255) Null: YES Key: Default: Extra: Field: Place_Of_Birth Type: varchar(255) Null: YES Key: Default: Extra: Field: Country Type: varchar(255) Null: YES Key: Default: Extra: Following example fetches the results of the SHOW TABLES query using mysqli_stmt_bind_result() and mysqli_stmt_fetch() functions − <?php $con = mysqli_connect("localhost", "root", "password"); //Selecting the database mysqli_query($con, "CREATE DATABASE NewDatabase"); mysqli_select_db($con, "NewDatabase"); //Creating tables mysqli_query($con, "CREATE TABLE test1(Name VARCHAR(255), Age INT)"); mysqli_query($con, "CREATE TABLE test2(Name VARCHAR(255), Age INT)"); mysqli_query($con, "CREATE TABLE test3(Name VARCHAR(255), Age INT)"); print("Tables Created.....\n"); //Description of the table $stmt = mysqli_prepare($con, "SHOW TABLES"); //Executing the statement mysqli_stmt_execute($stmt); //Binding values in result to variables mysqli_stmt_bind_result($stmt, $table_name); print("List of tables in the current database: \n"); while (mysqli_stmt_fetch($stmt)) { print($table_name."\n"); } //Closing the statement mysqli_stmt_close($stmt); //Closing the connection mysqli_close($con); ?> This will produce following result − Tables Created..... List of tables in the current database: test1 test2 test3 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": 3025, "s": 2757, "text": "You can create a prepared statement, which has parameter markers (\"?\") in case of values using the mysqli_prepare() function. Once you prepare a statement, you need to bind values to the parameters of the created statement using the mysqli_stmt_bind_param() function." }, { "code": null, "e": 3167, "s": 3025, "text": "In the same way you can bound the columns of the result set of a statement to desired variables using the mysqli_stmt_bind_result() function." }, { "code": null, "e": 3315, "s": 3167, "text": "After you have bound the columns if you invoke the mysqli_stmt_fetch() function, it fetches the columns of the result into the specified variables." }, { "code": null, "e": 3342, "s": 3315, "text": "mysqli_stmt_fetch($stmt);\n" }, { "code": null, "e": 3358, "s": 3342, "text": "stmt(Mandatory)" }, { "code": null, "e": 3411, "s": 3358, "text": "This is an object representing a prepared statement." }, { "code": null, "e": 3562, "s": 3411, "text": "The PHP mysqli_stmt_fetch() function returns TRUE if the data is fetched, FALSE in case of an error and, NULL if there are no more rows in the result." }, { "code": null, "e": 3657, "s": 3562, "text": "This function was first introduced in PHP Version 5 and works works in all the later versions." }, { "code": null, "e": 3758, "s": 3657, "text": "Following example demonstrates the usage of the mysqli_stmt_fetch() function (in procedural style) −" }, { "code": null, "e": 4890, "s": 3758, "text": "<?php\n $con = mysqli_connect(\"localhost\", \"root\", \"password\", \"mydb\");\n\n mysqli_query($con, \"CREATE TABLE myplayers(ID INT, First_Name VARCHAR(255), Last_Name VARCHAR(255), Place_Of_Birth VARCHAR(255), Country VARCHAR(255))\");\n print(\"Table Created.....\\n\");\n mysqli_query($con, \"INSERT INTO myplayers values(1, 'Sikhar', 'Dhawan', 'Delhi', 'India')\");\n mysqli_query($con, \"INSERT INTO myplayers values(2, 'Jonathan', 'Trott', 'CapeTown', 'SouthAfrica')\");\n print(\"Record Inserted.....\\n\");\n\n //Retrieving the contents of the table\n $stmt = mysqli_prepare($con, \"SELECT * FROM myplayers\");\n\n //Executing the statement\n mysqli_stmt_execute($stmt);\n\n //Binding values in result to variables\n mysqli_stmt_bind_result($stmt, $id, $fname, $lname, $pob, $country);\n\n while (mysqli_stmt_fetch($stmt)) {\n print(\"Id: \".$id.\"\\n\");\n print(\"fname: \".$fname.\"\\n\");\n print(\"lname: \".$lname.\"\\n\");\n print(\"pob: \".$pob.\"\\n\");\n print(\"country: \".$country.\"\\n\");\n print(\"\\n\");\n\n }\n //Closing the statement\n mysqli_stmt_close($stmt);\n\n //Closing the connection\n mysqli_close($con);\n?>" }, { "code": null, "e": 4927, "s": 4890, "text": "This will produce following result −" }, { "code": null, "e": 5099, "s": 4927, "text": "Table Created.....\nRecord Inserted.....\nId: 1\nfname: Sikhar\nlname: Dhawan\npob: Delhi\ncountry: India\n\nId: 2\nfname: Jonathan\nlname: Trott\npob: CapeTown\ncountry: SouthAfrica\n" }, { "code": null, "e": 5246, "s": 5099, "text": "In object oriented style the syntax of this function is $stmt->fetch(); Following is the example of this function in object oriented style $minus;" }, { "code": null, "e": 6049, "s": 5246, "text": "<?php\n //Creating a connection\n $con = new mysqli(\"localhost\", \"root\", \"password\", \"mydb\");\n\n $con -> query(\"CREATE TABLE Test(Name VARCHAR(255), AGE INT)\");\n $con -> query(\"insert into Test values('Raju', 25),('Rahman', 30),('Sarmista', 27)\");\n print(\"Table Created.....\\n\");\n\n $stmt = $con -> prepare( \"SELECT * FROM Test WHERE Name in(?, ?)\");\n $stmt -> bind_param(\"ss\", $name1, $name2);\n $name1 = 'Raju';\n $name2 = 'Rahman';\n print(\"Records Deleted.....\\n\");\n\n //Executing the statement\n $stmt->execute();\n\n //Binding variables to resultset\n $stmt->bind_result($name, $age);\n while ($stmt->fetch()) {\n print(\"Name: \".$name.\"\\n\");\n print(\"Age: \".$age.\"\\n\");\n }\n\n //Closing the statement\n $stmt->close();\n\n //Closing the connection\n $con->close();\n?>" }, { "code": null, "e": 6086, "s": 6049, "text": "This will produce following result −" }, { "code": null, "e": 6167, "s": 6086, "text": "Table Created.....\nRecords Deleted.....\nName: Raju\nAge: 25\nName: Rahman\nAge: 30\n" }, { "code": null, "e": 6296, "s": 6167, "text": "Following example fetches the results of the DESCRIBE query using mysqli_stmt_bind_result() and mysqli_stmt_fetch() functions −" }, { "code": null, "e": 7216, "s": 6296, "text": "<?php\n $con = mysqli_connect(\"localhost\", \"root\", \"password\", \"mydb\");\n\n mysqli_query($con, \"CREATE TABLE myplayers(ID INT, First_Name VARCHAR(255), Last_Name VARCHAR(255), Place_Of_Birth VARCHAR(255), Country VARCHAR(255))\");\n print(\"Table Created.....\\n\");\n\n //Description of the table\n $stmt = mysqli_prepare($con, \"DESC myplayers\");\n\n //Executing the statement\n mysqli_stmt_execute($stmt);\n\n //Binding values in result to variables\n mysqli_stmt_bind_result($stmt, $field, $type, $null, $key, $default, $extra);\n\n while (mysqli_stmt_fetch($stmt)) {\n print(\"Field: \".$field.\"\\n\");\n print(\"Type: \".$type.\"\\n\");\n print(\"Null: \".$null.\"\\n\");\n print(\"Key: \".$key.\"\\n\");\n print(\"Default: \".$default.\"\\n\");\n print(\"Extra: \".$extra.\"\\n\");\n print(\"\\n\");\n }\n\n //Closing the statement\n mysqli_stmt_close($stmt);\n\n //Closing the connection\n mysqli_close($con);\n?>" }, { "code": null, "e": 7253, "s": 7216, "text": "This will produce following result −" }, { "code": null, "e": 7604, "s": 7253, "text": "Table Created.....\nField: ID\nType: int(11)\nNull: YES\nKey:\nDefault:\nExtra:\n\nField: First_Name\nType: varchar(255)\nNull: YES\nKey:\nDefault:\nExtra:\n\nField: Last_Name\nType: varchar(255)\nNull: YES\nKey:\nDefault:\nExtra:\n\nField: Place_Of_Birth\nType: varchar(255)\nNull: YES\nKey:\nDefault:\nExtra:\n\nField: Country\nType: varchar(255)\nNull: YES\nKey:\nDefault:\nExtra:\n" }, { "code": null, "e": 7735, "s": 7604, "text": "Following example fetches the results of the SHOW TABLES query using mysqli_stmt_bind_result() and mysqli_stmt_fetch() functions −" }, { "code": null, "e": 8676, "s": 7735, "text": "<?php\n $con = mysqli_connect(\"localhost\", \"root\", \"password\");\n\n //Selecting the database\n mysqli_query($con, \"CREATE DATABASE NewDatabase\");\n mysqli_select_db($con, \"NewDatabase\");\n\n //Creating tables\n mysqli_query($con, \"CREATE TABLE test1(Name VARCHAR(255), Age INT)\");\n mysqli_query($con, \"CREATE TABLE test2(Name VARCHAR(255), Age INT)\");\n mysqli_query($con, \"CREATE TABLE test3(Name VARCHAR(255), Age INT)\");\n print(\"Tables Created.....\\n\");\n\n //Description of the table\n $stmt = mysqli_prepare($con, \"SHOW TABLES\");\n\n //Executing the statement\n mysqli_stmt_execute($stmt);\n\n //Binding values in result to variables\n mysqli_stmt_bind_result($stmt, $table_name);\n\n print(\"List of tables in the current database: \\n\");\n while (mysqli_stmt_fetch($stmt)) {\n print($table_name.\"\\n\");\n }\n\n //Closing the statement\n mysqli_stmt_close($stmt);\n\n //Closing the connection\n mysqli_close($con);\n?>" }, { "code": null, "e": 8713, "s": 8676, "text": "This will produce following result −" }, { "code": null, "e": 8792, "s": 8713, "text": "Tables Created.....\nList of tables in the current database:\ntest1\ntest2\ntest3\n" }, { "code": null, "e": 8825, "s": 8792, "text": "\n 45 Lectures \n 9 hours \n" }, { "code": null, "e": 8841, "s": 8825, "text": " Malhar Lathkar" }, { "code": null, "e": 8874, "s": 8841, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 8885, "s": 8874, "text": " Syed Raza" }, { "code": null, "e": 8920, "s": 8885, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 8937, "s": 8920, "text": " Frahaan Hussain" }, { "code": null, "e": 8970, "s": 8937, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 8985, "s": 8970, "text": " Nivedita Jain" }, { "code": null, "e": 9020, "s": 8985, "text": "\n 100 Lectures \n 34 hours \n" }, { "code": null, "e": 9032, "s": 9020, "text": " Azaz Patel" }, { "code": null, "e": 9067, "s": 9032, "text": "\n 43 Lectures \n 5.5 hours \n" }, { "code": null, "e": 9095, "s": 9067, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 9102, "s": 9095, "text": " Print" }, { "code": null, "e": 9113, "s": 9102, "text": " Add Notes" } ]
Instruction type ANI d8 in 8085 Microprocessor
In 8085 Instruction set, ANI is a mnemonic, which stands for “ANd Immediate with Accumulator” and “d8” stands for any 8-bit or 1-Bytedata. This instruction is used to AND 8-bit immediate data with the Accumulator’s content. The result of this ANDingoperation will be stored in the Accumulator itself over writing its previous content. As it is an arithmetic operation do S, P, and Z flags are affected based on the result. Cy is reset to 0, and AC is set to 1. It occupies 2-Bytes in the memory. Let us consider ANI CDH as a sample instruction of this type. It is a 2-Byte instruction. We are considering the initial content of Accumulator is ABH. So after this ANI operation result will be stored back on to the Accumulator itself. The result of execution of this instruction has been depicted in the following tracing table − (A) (F) The internal calculation has been done as follows − (A) ABH ---> 1010 1011 (d8) CDH ---> 1100 1101 --------- ANI CDH ---> 1000 1001 (89H) The timing diagram against this instruction ANI CDH execution is as follows. Summary − So this instruction ANA E requires 2-Bytes, 2 Machine Cycles (Opcode Fetch, Memory Read) and 7 T-States for execution as shown in the timing diagram.
[ { "code": null, "e": 1558, "s": 1062, "text": "In 8085 Instruction set, ANI is a mnemonic, which stands for “ANd Immediate with Accumulator” and “d8” stands for any 8-bit or 1-Bytedata. This instruction is used to AND 8-bit immediate data with the Accumulator’s content. The result of this ANDingoperation will be stored in the Accumulator itself over writing its previous content. As it is an arithmetic operation do S, P, and Z flags are affected based on the result. Cy is reset to 0, and AC is set to 1. It occupies 2-Bytes in the memory." }, { "code": null, "e": 1890, "s": 1558, "text": "Let us consider ANI CDH as a sample instruction of this type. It is a 2-Byte instruction. We are considering the initial content of Accumulator is ABH. So after this ANI operation result will be stored back on to the Accumulator itself. The result of execution of this instruction has been depicted in the following tracing table −" }, { "code": null, "e": 1894, "s": 1890, "text": "(A)" }, { "code": null, "e": 1898, "s": 1894, "text": "(F)" }, { "code": null, "e": 1950, "s": 1898, "text": "The internal calculation has been done as follows −" }, { "code": null, "e": 2053, "s": 1950, "text": "(A) ABH ---> 1010 1011\n(d8) CDH ---> 1100 1101\n ---------\n ANI CDH ---> 1000 1001 (89H)\n" }, { "code": null, "e": 2130, "s": 2053, "text": "The timing diagram against this instruction ANI CDH execution is as follows." }, { "code": null, "e": 2290, "s": 2130, "text": "Summary − So this instruction ANA E requires 2-Bytes, 2 Machine Cycles (Opcode Fetch, Memory Read) and 7 T-States for execution as shown in the timing diagram." } ]
Customize loss function to make LSTM model more applicable in stock price prediction | by Zedric Cheung | Towards Data Science
There are many tutorials or articles online teaching you how to build a LSTM model to predict stock price. Either it is simple or sophisticated, we can somehow obtain a “desirable” result, something similar to the below graph (Exhibit 1). Yes, it is desirable if we simply judge the model by looking at mean squared error (MSE). But is it good enough to do well and help us earn big money in real world trading? Sorry to say, the answer is always NO. In this article, we would give a try to customize the loss function to make our LSTM model more applicable in real world. It’s not because something goes wrong in the tutorials or the model is not well-trained enough. But fundamentally, there are several major limitations that are hard to solve. 1. All free libraries only provide daily data of stock price — without real-time data, it’s impossible for us to execute any orders within the day 2. The commonly used loss function (MSE) is a purely statistical loss function –pure price difference doesn’t represent the full picture 3. LSTM model or any other recurrent neural network model is always a black box — trading strategy can only be based on price movement without any reasons to support, and the strategies are hard to extend to portfolio allocation The limitations (1) and (3) are hard to solve without any more resources. For (1), the solution may be connecting to real time trading data provider such as Bloomberg, and then train up a real-time LSTM model. The trading orders for next second can then be automatically placed. But sorry to say, it’s hard to do so if you are not working on trading floor. For (3), if aiming to extend to portfolio allocation with some explanations, probably other concepts like mean-variance optimization, with some robust estimators and then considering Value at Risk (VaR) are more appropriate. But those are completely other stories. In this article, we would like to pinpoint the second limitation and focus on one of the possible ways — Customize loss function by taking account of directional loss to make the LSTM model more applicable given limited resources. Let’s back to the above graph (Exhibit 1). It looks perfect and indicates that the model’s prediction power is very high. True, its MSE for training loss is only 0.000529 after training 300 epochs, but its accuracy on predicting the direction of next day’s price movement is only 0.449889, even lower than flipping the coins !!! MSE mainly focuses on the difference between real price and predicted price without considering whether the predicted direction is correct or not. This characteristic would create huge troubles if we apply trading strategies like put / call options based on the prediction from LSTM model. From such perspective, correctness in direction should be emphasized. Furthermore, the model is daily price based given data availability and tries to predict the next day’s close price, which doesn’t capture the price fluctuation within the day. Under such condition, directional accuracy is even more important than the price difference. Even you may earn less on some of the days, but at least it won’t lead to money loss. Now, let’s start to customize the loss function. For the details of data pre-processing and how to build a simple LSTM model stock prediction, please refer to the Github link here. Full codes could be also found there. Step 1: Extract necessary information from the input tensors for loss function def custom_loss(y_true, y_pred): #extract the "next day's price" of tensor y_true_next = y_true[1:] y_pred_next = y_pred[1:] #extract the "today's price" of tensor y_true_tdy = y_true[:-1] y_pred_tdy = y_pred[:-1] Always remember that the inputs for the loss function are two tensors, y_true (the true price) and y_pred (the predicted price). First, we have to create four new tensors to store the “next day’s price” and “today’s price” from the two input sensors for further use. Step 2: Create new tensors to record the price movement (up / down) #substract to get up/down movement of the two tensorsy_true_diff = tf.subtract(y_true_next, y_true_tdy)y_pred_diff = tf.subtract(y_pred_next, y_pred_tdy)#create a standard tensor with zero value for comparisonstandard = tf.zeros_like(y_pred_diff)#compare with the standard; if true, UP; else DOWNy_true_move = tf.greater_equal(y_true_diff, standard)y_pred_move = tf.greater_equal(y_pred_diff, standard) The tf.substract is to substract the element-wise value in y_true_tdy tensor from that in y_true_next tensor. We then compare the two difference tensors (y_true_diff and y_pred_diff) with a standard zero tensor. If the value is greater than or equal to zero, then it belongs to an upward movement, otherwise downward. The tf.greater_equal will return a boolean tensor. Step 3: Find out indices when the movement of the two tensors are not in same direction #find indices where the directions are not the samecondition = tf.not_equal(y_true_move, y_pred_move)indices = tf.where(condition)ones = tf.ones_like(indices)indices = tf.add(indices, ones) (a) The tf.not_equal compares the two boolean tensors, y_true_move and y_pred_move, and generates another new boolean tensor — condition. If the direction in the next day is the same between the true movement and the predicted movement, True is returned, otherwise False. (b) The tf.where returns the position of “True” in the condition tensor. (c) The tf.add adds one to each element in indices tensor. If you are careful enough, you may notice that the shape of any processed tensors is (49, 1) , one unit shorter than the that of original inputs (50, 1). Adding one means that we move the indices one day later, which represents the true location of next day within the original input tensors. Step 4: Create a tensor to store directional loss and put it into custom loss output direction_loss = tf.Variable(tf.ones_like(y_pred), dtype='float32')updates = K.cast(tf.ones_like(indices), dtype='float32')alpha = 1000direction_loss = tf.scatter_nd_update(direction_loss, indices, alpha*updates)custom_loss = K.mean(tf.multiply(K.square(y_true - y_pred), direction_loss), axis=-1) Now, we are creating the most important tensor — direction_loss. Since it should be a trainable tensor and be put into the final output — custom_loss, it has to be set as a variable tensor using tf.Variable. The tensor indices has stored the location where the direction doesn’t match between the true price and the predicted price. Through tf.scatter_nd_update, we can update the values in tensor direction_loss by specifying the location and replaced with new values. But keep in mind that shapes of indices and updates have to be the same. The end product of direction_loss is a tensor with value either 1 or 1000. Last by not least, we multiply the squared difference between true price and predicted price with the direction_loss tensor. The concept here is that if the direction matches between the true price and the predicted price for the day, we keep the loss as squared difference. If it doesn’t match, then we multiply the squared difference by alpha (1000). Finally, a customized loss function is completed. We have now taken consideration of whether the predicted price is in the same direction as the true price. If we apply LSTM model with the same settings (batch size: 50, epochs: 300, time steps: 60) to predict stock price of HSBC (0005.HK), the accuracy to predict the price direction has increased from 0.444343 to 0.561158. A big improvement but still far from perfect. We will discuss some hurdles to overcome at the last part of this article if we want to build an even better loss function. Most of the time, we may have to customize the loss function with completely different concepts from the above. Below are some tricks that can help to save your time or track errors during the process. (a) get_shape — when you are not sure about the tensor’s shape, never hesitate to use this function to print it out. Nearly all the processing functions require all inputted tensors’ shape to be the same. (b) keras.backend.cast — when the error message says the format of elements in the tensor doesn’t match with others’, try to use this function to change the format of the tensors’ elements into specific type. (c) tensorflow.reshape — when the error message says the shape doesn’t match with the original inputs, which should hold a consistent shape of (x, 1), try to use this function tf.reshape(tensor, [-1]) to flatten the tensor. (d) custom_loss — keep in mind that the end product must consist of the two inputted tensors, y_true and y_pred, and will be returned to the main body of the LSTM model to compile. The result now has shown a big improvement, but still far from perfect. However, to step further, many hurdles are waiting us, and below are some of them. (a) Hard to balance between price difference and directional loss — if alpha is set to be too high, you may find that the predicted price shows very little fluctuation. If we plot it, it’s nearly a flat line. This means that directional loss dominates the loss function. Under such situation, the predicted price becomes meaningless but only its direction is meaningful. We are simply betting whether the next day’s price is upward or downward. (b) Hard to apply categorical classifier on stock price prediction —many of you may find that if we are simply betting the price movement (up/down), then why don’t we apply categorical classifier to do the prediction or turn the loss function as tf.binary_crossentropy. Sorry to say, the result shows no improvement. I have tried to first convert all the price data into “movement data” represented by 0 (down) or 1 (up), and input them for training. But since the nature of the data is time series, unlike handwriting recognition, the 0 or 1 arrays in every training batch are not distinguished enough to make the prediction of next day’s price movement. Some methods like support vector machine (SVM) and convolutional neural network (CNN), which perform very well in classification, are hard to apply to this case. (c) Alpha is very specific for every stock —I have tried to apply the same model on stock price prediction for other 10 stocks, but not all show big improvements. For every stock, the relationship between price difference and directional loss seems very unique. So we may have to spend lots of time to figure out what’s the best combination for each stock. It’s always not difficult to build a desirable LSTM model for stock price prediction from the perspective of minimizing MSE. But it is far from applicable in real world. This article introduces one of the possible ways — Customize loss function by taking account of directional loss, and have discussed some difficulties during the journey and provide some suggestions. I hope that it would open the discussion on how to improve our LSTM model. As mentioned, there are many hurdles have to be overcome if we want to step further, especially given limited resources. This article is also my first publication on Medium. In the future, I will try to explore more about application of data science and machine learning techniques on economics and finance areas. Thanks for supports !!! Asutosh Nayak. (2019). Predicting Stock Price with LSTM.Dhiraj K. (2019). How to create a custom loss function in Keras.Eyal Zakkay. (2019). Advanced Keras — Constructing Complex Custom Losses and Metrics. Asutosh Nayak. (2019). Predicting Stock Price with LSTM. Dhiraj K. (2019). How to create a custom loss function in Keras. Eyal Zakkay. (2019). Advanced Keras — Constructing Complex Custom Losses and Metrics.
[ { "code": null, "e": 501, "s": 172, "text": "There are many tutorials or articles online teaching you how to build a LSTM model to predict stock price. Either it is simple or sophisticated, we can somehow obtain a “desirable” result, something similar to the below graph (Exhibit 1). Yes, it is desirable if we simply judge the model by looking at mean squared error (MSE)." }, { "code": null, "e": 745, "s": 501, "text": "But is it good enough to do well and help us earn big money in real world trading? Sorry to say, the answer is always NO. In this article, we would give a try to customize the loss function to make our LSTM model more applicable in real world." }, { "code": null, "e": 920, "s": 745, "text": "It’s not because something goes wrong in the tutorials or the model is not well-trained enough. But fundamentally, there are several major limitations that are hard to solve." }, { "code": null, "e": 1067, "s": 920, "text": "1. All free libraries only provide daily data of stock price — without real-time data, it’s impossible for us to execute any orders within the day" }, { "code": null, "e": 1204, "s": 1067, "text": "2. The commonly used loss function (MSE) is a purely statistical loss function –pure price difference doesn’t represent the full picture" }, { "code": null, "e": 1433, "s": 1204, "text": "3. LSTM model or any other recurrent neural network model is always a black box — trading strategy can only be based on price movement without any reasons to support, and the strategies are hard to extend to portfolio allocation" }, { "code": null, "e": 1790, "s": 1433, "text": "The limitations (1) and (3) are hard to solve without any more resources. For (1), the solution may be connecting to real time trading data provider such as Bloomberg, and then train up a real-time LSTM model. The trading orders for next second can then be automatically placed. But sorry to say, it’s hard to do so if you are not working on trading floor." }, { "code": null, "e": 2055, "s": 1790, "text": "For (3), if aiming to extend to portfolio allocation with some explanations, probably other concepts like mean-variance optimization, with some robust estimators and then considering Value at Risk (VaR) are more appropriate. But those are completely other stories." }, { "code": null, "e": 2286, "s": 2055, "text": "In this article, we would like to pinpoint the second limitation and focus on one of the possible ways — Customize loss function by taking account of directional loss to make the LSTM model more applicable given limited resources." }, { "code": null, "e": 2615, "s": 2286, "text": "Let’s back to the above graph (Exhibit 1). It looks perfect and indicates that the model’s prediction power is very high. True, its MSE for training loss is only 0.000529 after training 300 epochs, but its accuracy on predicting the direction of next day’s price movement is only 0.449889, even lower than flipping the coins !!!" }, { "code": null, "e": 2975, "s": 2615, "text": "MSE mainly focuses on the difference between real price and predicted price without considering whether the predicted direction is correct or not. This characteristic would create huge troubles if we apply trading strategies like put / call options based on the prediction from LSTM model. From such perspective, correctness in direction should be emphasized." }, { "code": null, "e": 3331, "s": 2975, "text": "Furthermore, the model is daily price based given data availability and tries to predict the next day’s close price, which doesn’t capture the price fluctuation within the day. Under such condition, directional accuracy is even more important than the price difference. Even you may earn less on some of the days, but at least it won’t lead to money loss." }, { "code": null, "e": 3550, "s": 3331, "text": "Now, let’s start to customize the loss function. For the details of data pre-processing and how to build a simple LSTM model stock prediction, please refer to the Github link here. Full codes could be also found there." }, { "code": null, "e": 3629, "s": 3550, "text": "Step 1: Extract necessary information from the input tensors for loss function" }, { "code": null, "e": 3844, "s": 3629, "text": "def custom_loss(y_true, y_pred):\t\t#extract the \"next day's price\" of tensor\ty_true_next = y_true[1:]\ty_pred_next = y_pred[1:]\t#extract the \"today's price\" of tensor\ty_true_tdy = y_true[:-1]\ty_pred_tdy = y_pred[:-1]" }, { "code": null, "e": 4111, "s": 3844, "text": "Always remember that the inputs for the loss function are two tensors, y_true (the true price) and y_pred (the predicted price). First, we have to create four new tensors to store the “next day’s price” and “today’s price” from the two input sensors for further use." }, { "code": null, "e": 4179, "s": 4111, "text": "Step 2: Create new tensors to record the price movement (up / down)" }, { "code": null, "e": 4582, "s": 4179, "text": "#substract to get up/down movement of the two tensorsy_true_diff = tf.subtract(y_true_next, y_true_tdy)y_pred_diff = tf.subtract(y_pred_next, y_pred_tdy)#create a standard tensor with zero value for comparisonstandard = tf.zeros_like(y_pred_diff)#compare with the standard; if true, UP; else DOWNy_true_move = tf.greater_equal(y_true_diff, standard)y_pred_move = tf.greater_equal(y_pred_diff, standard)" }, { "code": null, "e": 4951, "s": 4582, "text": "The tf.substract is to substract the element-wise value in y_true_tdy tensor from that in y_true_next tensor. We then compare the two difference tensors (y_true_diff and y_pred_diff) with a standard zero tensor. If the value is greater than or equal to zero, then it belongs to an upward movement, otherwise downward. The tf.greater_equal will return a boolean tensor." }, { "code": null, "e": 5039, "s": 4951, "text": "Step 3: Find out indices when the movement of the two tensors are not in same direction" }, { "code": null, "e": 5229, "s": 5039, "text": "#find indices where the directions are not the samecondition = tf.not_equal(y_true_move, y_pred_move)indices = tf.where(condition)ones = tf.ones_like(indices)indices = tf.add(indices, ones)" }, { "code": null, "e": 5501, "s": 5229, "text": "(a) The tf.not_equal compares the two boolean tensors, y_true_move and y_pred_move, and generates another new boolean tensor — condition. If the direction in the next day is the same between the true movement and the predicted movement, True is returned, otherwise False." }, { "code": null, "e": 5574, "s": 5501, "text": "(b) The tf.where returns the position of “True” in the condition tensor." }, { "code": null, "e": 5926, "s": 5574, "text": "(c) The tf.add adds one to each element in indices tensor. If you are careful enough, you may notice that the shape of any processed tensors is (49, 1) , one unit shorter than the that of original inputs (50, 1). Adding one means that we move the indices one day later, which represents the true location of next day within the original input tensors." }, { "code": null, "e": 6011, "s": 5926, "text": "Step 4: Create a tensor to store directional loss and put it into custom loss output" }, { "code": null, "e": 6309, "s": 6011, "text": "direction_loss = tf.Variable(tf.ones_like(y_pred), dtype='float32')updates = K.cast(tf.ones_like(indices), dtype='float32')alpha = 1000direction_loss = tf.scatter_nd_update(direction_loss, indices, alpha*updates)custom_loss = K.mean(tf.multiply(K.square(y_true - y_pred), direction_loss), axis=-1)" }, { "code": null, "e": 6517, "s": 6309, "text": "Now, we are creating the most important tensor — direction_loss. Since it should be a trainable tensor and be put into the final output — custom_loss, it has to be set as a variable tensor using tf.Variable." }, { "code": null, "e": 6927, "s": 6517, "text": "The tensor indices has stored the location where the direction doesn’t match between the true price and the predicted price. Through tf.scatter_nd_update, we can update the values in tensor direction_loss by specifying the location and replaced with new values. But keep in mind that shapes of indices and updates have to be the same. The end product of direction_loss is a tensor with value either 1 or 1000." }, { "code": null, "e": 7280, "s": 6927, "text": "Last by not least, we multiply the squared difference between true price and predicted price with the direction_loss tensor. The concept here is that if the direction matches between the true price and the predicted price for the day, we keep the loss as squared difference. If it doesn’t match, then we multiply the squared difference by alpha (1000)." }, { "code": null, "e": 7826, "s": 7280, "text": "Finally, a customized loss function is completed. We have now taken consideration of whether the predicted price is in the same direction as the true price. If we apply LSTM model with the same settings (batch size: 50, epochs: 300, time steps: 60) to predict stock price of HSBC (0005.HK), the accuracy to predict the price direction has increased from 0.444343 to 0.561158. A big improvement but still far from perfect. We will discuss some hurdles to overcome at the last part of this article if we want to build an even better loss function." }, { "code": null, "e": 8028, "s": 7826, "text": "Most of the time, we may have to customize the loss function with completely different concepts from the above. Below are some tricks that can help to save your time or track errors during the process." }, { "code": null, "e": 8233, "s": 8028, "text": "(a) get_shape — when you are not sure about the tensor’s shape, never hesitate to use this function to print it out. Nearly all the processing functions require all inputted tensors’ shape to be the same." }, { "code": null, "e": 8442, "s": 8233, "text": "(b) keras.backend.cast — when the error message says the format of elements in the tensor doesn’t match with others’, try to use this function to change the format of the tensors’ elements into specific type." }, { "code": null, "e": 8666, "s": 8442, "text": "(c) tensorflow.reshape — when the error message says the shape doesn’t match with the original inputs, which should hold a consistent shape of (x, 1), try to use this function tf.reshape(tensor, [-1]) to flatten the tensor." }, { "code": null, "e": 8847, "s": 8666, "text": "(d) custom_loss — keep in mind that the end product must consist of the two inputted tensors, y_true and y_pred, and will be returned to the main body of the LSTM model to compile." }, { "code": null, "e": 9002, "s": 8847, "text": "The result now has shown a big improvement, but still far from perfect. However, to step further, many hurdles are waiting us, and below are some of them." }, { "code": null, "e": 9447, "s": 9002, "text": "(a) Hard to balance between price difference and directional loss — if alpha is set to be too high, you may find that the predicted price shows very little fluctuation. If we plot it, it’s nearly a flat line. This means that directional loss dominates the loss function. Under such situation, the predicted price becomes meaningless but only its direction is meaningful. We are simply betting whether the next day’s price is upward or downward." }, { "code": null, "e": 10265, "s": 9447, "text": "(b) Hard to apply categorical classifier on stock price prediction —many of you may find that if we are simply betting the price movement (up/down), then why don’t we apply categorical classifier to do the prediction or turn the loss function as tf.binary_crossentropy. Sorry to say, the result shows no improvement. I have tried to first convert all the price data into “movement data” represented by 0 (down) or 1 (up), and input them for training. But since the nature of the data is time series, unlike handwriting recognition, the 0 or 1 arrays in every training batch are not distinguished enough to make the prediction of next day’s price movement. Some methods like support vector machine (SVM) and convolutional neural network (CNN), which perform very well in classification, are hard to apply to this case." }, { "code": null, "e": 10622, "s": 10265, "text": "(c) Alpha is very specific for every stock —I have tried to apply the same model on stock price prediction for other 10 stocks, but not all show big improvements. For every stock, the relationship between price difference and directional loss seems very unique. So we may have to spend lots of time to figure out what’s the best combination for each stock." }, { "code": null, "e": 11188, "s": 10622, "text": "It’s always not difficult to build a desirable LSTM model for stock price prediction from the perspective of minimizing MSE. But it is far from applicable in real world. This article introduces one of the possible ways — Customize loss function by taking account of directional loss, and have discussed some difficulties during the journey and provide some suggestions. I hope that it would open the discussion on how to improve our LSTM model. As mentioned, there are many hurdles have to be overcome if we want to step further, especially given limited resources." }, { "code": null, "e": 11405, "s": 11188, "text": "This article is also my first publication on Medium. In the future, I will try to explore more about application of data science and machine learning techniques on economics and finance areas. Thanks for supports !!!" }, { "code": null, "e": 11611, "s": 11405, "text": "Asutosh Nayak. (2019). Predicting Stock Price with LSTM.Dhiraj K. (2019). How to create a custom loss function in Keras.Eyal Zakkay. (2019). Advanced Keras — Constructing Complex Custom Losses and Metrics." }, { "code": null, "e": 11668, "s": 11611, "text": "Asutosh Nayak. (2019). Predicting Stock Price with LSTM." }, { "code": null, "e": 11733, "s": 11668, "text": "Dhiraj K. (2019). How to create a custom loss function in Keras." } ]
How do I change the background color of the ActionBar of an ActionBarActivity?
This example demonstrates how to change the background color of the ActionBar of an ActionBarActivity 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"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> Step 3 − Add the following code to src/MainActivity.java package com.app.sample; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } } Step 4 − Add the following code to Manifests/AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.app.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Step 4 − Add the following code to res/values/styles.xml <resources> <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> <item name="colorPrimary">#995544</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style> <style name="ActionBar.Solid.Ribbit.TitleTextStyle" parent="TextAppearance.AppCompat.Widget.ActionBar.Title"> <item name="android:textColor">#976325</item> </style> </resources> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − Click here to download the project code.
[ { "code": null, "e": 1164, "s": 1062, "text": "This example demonstrates how to change the background color of the ActionBar of an ActionBarActivity" }, { "code": null, "e": 1293, "s": 1164, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1358, "s": 1293, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2121, "s": 1358, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<androidx.constraintlayout.widget.ConstraintLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Hello World!\"\n app:layout_constraintBottom_toBottomOf=\"parent\"\n app:layout_constraintLeft_toLeftOf=\"parent\"\n app:layout_constraintRight_toRightOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\" />\n</androidx.constraintlayout.widget.ConstraintLayout>\n" }, { "code": null, "e": 2178, "s": 2121, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 2495, "s": 2178, "text": "package com.app.sample;\nimport androidx.appcompat.app.AppCompatActivity;\nimport android.os.Bundle;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n }\n}" }, { "code": null, "e": 2560, "s": 2495, "text": "Step 4 − Add the following code to Manifests/AndroidManifest.xml" }, { "code": null, "e": 3230, "s": 2560, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.app.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 3287, "s": 3230, "text": "Step 4 − Add the following code to res/values/styles.xml" }, { "code": null, "e": 3750, "s": 3287, "text": "<resources>\n <style name=\"AppTheme\" parent=\"Theme.AppCompat.Light.DarkActionBar\">\n <item name=\"colorPrimary\">#995544</item>\n <item name=\"colorPrimaryDark\">@color/colorPrimaryDark</item>\n <item name=\"colorAccent\">@color/colorAccent</item>\n </style>\n <style name=\"ActionBar.Solid.Ribbit.TitleTextStyle\"\n parent=\"TextAppearance.AppCompat.Widget.ActionBar.Title\">\n <item name=\"android:textColor\">#976325</item>\n </style>\n</resources>" }, { "code": null, "e": 4101, "s": 3750, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click 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": 4142, "s": 4101, "text": "Click here to download the project code." } ]
C library function - strncmp()
The C library function int strncmp(const char *str1, const char *str2, size_t n) compares at most the first n bytes of str1 and str2. Following is the declaration for strncmp() function. int strncmp(const char *str1, const char *str2, size_t n) str1 − This is the first string to be compared. str1 − This is the first string to be compared. str2 − This is the second string to be compared. str2 − This is the second string to be compared. n − The maximum number of characters to be compared. n − The maximum number of characters to be compared. This function return values that are as follows − if Return value < 0 then it indicates str1 is less than str2. if Return value < 0 then it indicates str1 is less than str2. if Return value > 0 then it indicates str2 is less than str1. if Return value > 0 then it indicates str2 is less than str1. if Return value = 0 then it indicates str1 is equal to str2. if Return value = 0 then it indicates str1 is equal to str2. The following example shows the usage of strncmp() function. #include <stdio.h> #include <string.h> int main () { char str1[15]; char str2[15]; int ret; strcpy(str1, "abcdef"); strcpy(str2, "ABCDEF"); ret = strncmp(str1, str2, 4); if(ret < 0) { printf("str1 is less than str2"); } else if(ret > 0) { printf("str2 is less than str1"); } else { printf("str1 is equal to str2"); } return(0); } Let us compile and run the above program that will produce the following result − str2 is less than str1 12 Lectures 2 hours Nishant Malik 12 Lectures 2.5 hours Nishant Malik 48 Lectures 6.5 hours Asif Hussain 12 Lectures 2 hours Richa Maheshwari 20 Lectures 3.5 hours Vandana Annavaram 44 Lectures 1 hours Amit Diwan Print Add Notes Bookmark this page
[ { "code": null, "e": 2141, "s": 2007, "text": "The C library function int strncmp(const char *str1, const char *str2, size_t n) compares at most the first n bytes of str1 and str2." }, { "code": null, "e": 2194, "s": 2141, "text": "Following is the declaration for strncmp() function." }, { "code": null, "e": 2252, "s": 2194, "text": "int strncmp(const char *str1, const char *str2, size_t n)" }, { "code": null, "e": 2300, "s": 2252, "text": "str1 − This is the first string to be compared." }, { "code": null, "e": 2348, "s": 2300, "text": "str1 − This is the first string to be compared." }, { "code": null, "e": 2397, "s": 2348, "text": "str2 − This is the second string to be compared." }, { "code": null, "e": 2446, "s": 2397, "text": "str2 − This is the second string to be compared." }, { "code": null, "e": 2499, "s": 2446, "text": "n − The maximum number of characters to be compared." }, { "code": null, "e": 2552, "s": 2499, "text": "n − The maximum number of characters to be compared." }, { "code": null, "e": 2602, "s": 2552, "text": "This function return values that are as follows −" }, { "code": null, "e": 2664, "s": 2602, "text": "if Return value < 0 then it indicates str1 is less than str2." }, { "code": null, "e": 2726, "s": 2664, "text": "if Return value < 0 then it indicates str1 is less than str2." }, { "code": null, "e": 2788, "s": 2726, "text": "if Return value > 0 then it indicates str2 is less than str1." }, { "code": null, "e": 2850, "s": 2788, "text": "if Return value > 0 then it indicates str2 is less than str1." }, { "code": null, "e": 2911, "s": 2850, "text": "if Return value = 0 then it indicates str1 is equal to str2." }, { "code": null, "e": 2972, "s": 2911, "text": "if Return value = 0 then it indicates str1 is equal to str2." }, { "code": null, "e": 3033, "s": 2972, "text": "The following example shows the usage of strncmp() function." }, { "code": null, "e": 3422, "s": 3033, "text": "#include <stdio.h>\n#include <string.h>\n\nint main () {\n char str1[15];\n char str2[15];\n int ret;\n\n strcpy(str1, \"abcdef\");\n strcpy(str2, \"ABCDEF\");\n\n ret = strncmp(str1, str2, 4);\n\n if(ret < 0) {\n printf(\"str1 is less than str2\");\n } else if(ret > 0) {\n printf(\"str2 is less than str1\");\n } else {\n printf(\"str1 is equal to str2\");\n }\n \n return(0);\n}" }, { "code": null, "e": 3504, "s": 3422, "text": "Let us compile and run the above program that will produce the following result −" }, { "code": null, "e": 3528, "s": 3504, "text": "str2 is less than str1\n" }, { "code": null, "e": 3561, "s": 3528, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3576, "s": 3561, "text": " Nishant Malik" }, { "code": null, "e": 3611, "s": 3576, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3626, "s": 3611, "text": " Nishant Malik" }, { "code": null, "e": 3661, "s": 3626, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3675, "s": 3661, "text": " Asif Hussain" }, { "code": null, "e": 3708, "s": 3675, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3726, "s": 3708, "text": " Richa Maheshwari" }, { "code": null, "e": 3761, "s": 3726, "text": "\n 20 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3780, "s": 3761, "text": " Vandana Annavaram" }, { "code": null, "e": 3813, "s": 3780, "text": "\n 44 Lectures \n 1 hours \n" }, { "code": null, "e": 3825, "s": 3813, "text": " Amit Diwan" }, { "code": null, "e": 3832, "s": 3825, "text": " Print" }, { "code": null, "e": 3843, "s": 3832, "text": " Add Notes" } ]
DocumentDB - Update Document
In this chapter, we will learn how to update the documents. Using Azure portal, you can easily update document by opening the document in Document explorer and updating it in editor like a text file. Click ‘Save’ button. Now when you need to change a document using .Net SDK you can just replace it. You don't need to delete and recreate it, which besides being tedious, would also change the resource id, which you wouldn't want to do when you're just modifying a document. Here are the following steps to update the document using .Net SDK. Let’s take a look at the following ReplaceDocuments task where we will query for documents where the isNew property is true, but we will get none because there aren't any. So, let's modify the documents we added earlier, those whose names start with New Customer. Step 1 − Add the isNew property to these documents and set its value to true. private async static Task ReplaceDocuments(DocumentClient client) { Console.WriteLine(); Console.WriteLine(">>> Replace Documents <<<"); Console.WriteLine(); Console.WriteLine("Quering for documents with 'isNew' flag"); var sql = "SELECT * FROM c WHERE c.isNew = true"; var documents = client.CreateDocumentQuery(collection.SelfLink, sql).ToList(); Console.WriteLine("Documents with 'isNew' flag: {0} ", documents.Count); Console.WriteLine(); Console.WriteLine("Quering for documents to be updated"); sql = "SELECT * FROM c WHERE STARTSWITH(c.name, 'New Customer') = true"; documents = client.CreateDocumentQuery(collection.SelfLink, sql).ToList(); Console.WriteLine("Found {0} documents to be updated", documents.Count); foreach (var document in documents) { document.isNew = true; var result = await client.ReplaceDocumentAsync(document._self, document); var updatedDocument = result.Resource; Console.WriteLine("Updated document 'isNew' flag: {0}", updatedDocument.isNew); } Console.WriteLine(); Console.WriteLine("Quering for documents with 'isNew' flag"); sql = "SELECT * FROM c WHERE c.isNew = true"; documents = client.CreateDocumentQuery(collection.SelfLink, sql).ToList(); Console.WriteLine("Documents with 'isNew' flag: {0}: ", documents.Count); Console.WriteLine(); } Step 2 − Get the documents to be updated using the same STARTSWITH query and that gives us the documents, which we are getting back here as dynamic objects. Step 3 − Attach the isNew property and set it to true for each document. Step 4 − Call ReplaceDocumentAsync, passing in the document's SelfLink, along with the updated document. Now just to prove that this worked, query for documents where isNew equaled true. Let’s call the above queries from the CreateDocumentClient task. private static async Task CreateDocumentClient() { // Create a new instance of the DocumentClient using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) { database = client.CreateDatabaseQuery("SELECT * FROM c WHERE c.id = 'myfirstdb'").AsEnumerable().First(); collection = client.CreateDocumentCollectionQuery(database.CollectionsLink, "SELECT * FROM c WHERE c.id = 'MyCollection'").AsEnumerable().First(); //await CreateDocuments(client); //QueryDocumentsWithSql(client); //await QueryDocumentsWithPaging(client); //QueryDocumentsWithLinq(client); await ReplaceDocuments(client); } } When the above code is compiled and executed, you will receive the following output. **** Replace Documents **** Quering for documents with 'isNew' flag Documents with 'isNew' flag: 0 Quering for documents to be updated Found 2 documents to be updated Updated document ‘isNew’ flag: True Updated document ‘isNew’ flag: True Quering for documents with 'isNew' flag Documents with 'isNew' flag: 2 Print Add Notes Bookmark this page
[ { "code": null, "e": 2480, "s": 2280, "text": "In this chapter, we will learn how to update the documents. Using Azure portal, you can easily update document by opening the document in Document explorer and updating it in editor like a text file." }, { "code": null, "e": 2823, "s": 2480, "text": "Click ‘Save’ button. Now when you need to change a document using .Net SDK you can just replace it. You don't need to delete and recreate it, which besides being tedious, would also change the resource id, which you wouldn't want to do when you're just modifying a document. Here are the following steps to update the document using .Net SDK." }, { "code": null, "e": 3087, "s": 2823, "text": "Let’s take a look at the following ReplaceDocuments task where we will query for documents where the isNew property is true, but we will get none because there aren't any. So, let's modify the documents we added earlier, those whose names start with New Customer." }, { "code": null, "e": 3165, "s": 3087, "text": "Step 1 − Add the isNew property to these documents and set its value to true." }, { "code": null, "e": 4563, "s": 3165, "text": "private async static Task ReplaceDocuments(DocumentClient client) {\n\n Console.WriteLine(); \n Console.WriteLine(\">>> Replace Documents <<<\"); \n Console.WriteLine(); \n Console.WriteLine(\"Quering for documents with 'isNew' flag\");\n\t\n var sql = \"SELECT * FROM c WHERE c.isNew = true\"; \n var documents = client.CreateDocumentQuery(collection.SelfLink, sql).ToList();\n\t\n Console.WriteLine(\"Documents with 'isNew' flag: {0} \", documents.Count); \n Console.WriteLine(); \n Console.WriteLine(\"Quering for documents to be updated\"); \n\t\n sql = \"SELECT * FROM c WHERE STARTSWITH(c.name, 'New Customer') = true\"; \n documents = client.CreateDocumentQuery(collection.SelfLink, sql).ToList(); \n Console.WriteLine(\"Found {0} documents to be updated\", documents.Count); \n\t\n foreach (var document in documents) {\n document.isNew = true; \n var result = await client.ReplaceDocumentAsync(document._self, document); \n var updatedDocument = result.Resource; \n Console.WriteLine(\"Updated document 'isNew' flag: {0}\", updatedDocument.isNew); \n }\n\t\n Console.WriteLine(); \n Console.WriteLine(\"Quering for documents with 'isNew' flag\");\n\t\n sql = \"SELECT * FROM c WHERE c.isNew = true\"; \n documents = client.CreateDocumentQuery(collection.SelfLink, sql).ToList(); \n Console.WriteLine(\"Documents with 'isNew' flag: {0}: \", documents.Count); \n Console.WriteLine(); \n}" }, { "code": null, "e": 4720, "s": 4563, "text": "Step 2 − Get the documents to be updated using the same STARTSWITH query and that gives us the documents, which we are getting back here as dynamic objects." }, { "code": null, "e": 4793, "s": 4720, "text": "Step 3 − Attach the isNew property and set it to true for each document." }, { "code": null, "e": 4898, "s": 4793, "text": "Step 4 − Call ReplaceDocumentAsync, passing in the document's SelfLink, along with the updated document." }, { "code": null, "e": 5045, "s": 4898, "text": "Now just to prove that this worked, query for documents where isNew equaled true. Let’s call the above queries from the CreateDocumentClient task." }, { "code": null, "e": 5744, "s": 5045, "text": "private static async Task CreateDocumentClient() {\n // Create a new instance of the DocumentClient\n\t\n using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) {\n database = client.CreateDatabaseQuery(\"SELECT * FROM c WHERE c.id =\n 'myfirstdb'\").AsEnumerable().First(); \n\t\t\t\n collection = client.CreateDocumentCollectionQuery(database.CollectionsLink,\n \"SELECT * FROM c WHERE c.id = 'MyCollection'\").AsEnumerable().First();\n\t\t\t\n //await CreateDocuments(client); \n //QueryDocumentsWithSql(client); \n //await QueryDocumentsWithPaging(client); \n //QueryDocumentsWithLinq(client); \n await ReplaceDocuments(client); \n }\n\t\n}" }, { "code": null, "e": 5829, "s": 5744, "text": "When the above code is compiled and executed, you will receive the following output." }, { "code": null, "e": 6150, "s": 5829, "text": "**** Replace Documents **** \nQuering for documents with 'isNew' flag \nDocuments with 'isNew' flag: 0 \nQuering for documents to be updated \nFound 2 documents to be updated \nUpdated document ‘isNew’ flag: True \nUpdated document ‘isNew’ flag: True \nQuering for documents with 'isNew' flag \nDocuments with 'isNew' flag: 2 \n" }, { "code": null, "e": 6157, "s": 6150, "text": " Print" }, { "code": null, "e": 6168, "s": 6157, "text": " Add Notes" } ]
Python Scope of Variables - GeeksforGeeks
20 Oct, 2021 In Python, variables are the containers for storing data values. They are reference, or pointers, to an object in memory which means that whenever a variable is assigned to an instance, it gets mapped to that instance. Unlike other languages like C/C++/JAVA, Python is not “statically typed”. We do not need to declare variables before using them or declare their type. A variable is created the moment we first assign a value to it.Example: Python3 # Python program to demonstrate# variable assignment # An integer assignmentage = 45 # A floating pointsalary = 1456.8 # A string name = "John" print(age)print(salary)print(name) Output: 45 1456.8 John Note: To know more about variables click here. The location where we can find a variable and also access it if required is called the scope of a variable. Global variables are the ones that are defined and declared outside any function and are not specified to any function. They can be used by any part of the program.Example: Python3 # This function uses global variable sdef f(): print(s) # Global scopes = "I love Geeksforgeeks"f() Output: I love Geeksforgeeks Now suppose a variable with the same name is defined inside the scope of function as well then it will print the value given inside the function only and not the global value. Python3 # This function has a variable with# name same as s.def f(): s = "Me too." print(s) # Global scopes = "I love Geeksforgeeks"f()print(s) Output: Me too. I love Geeksforgeeks The variable s is defined as the string “I love Geeksforgeeks”, before we call the function f(). The only statement in f() is the print(s) statement. As there is no local s, the value from the global s will be used.The question is, what will happen if we change the value of s inside of the function f()? Will it affect the global s as well? We test it in the following piece of code: Python3 def f(): print(s) # This program will NOT show error # if we comment below line. s = "Me too." print(s) # Global scopes = "I love Geeksforgeeks"f()print(s) Output: Traceback (most recent call last): File "/home/370cac45bae7f1e6096520b7a0edb604.py", line 13, in f() File "/home/370cac45bae7f1e6096520b7a0edb604.py", line 3, in f print(s) UnboundLocalError: local variable 's' referenced before assignment To make the above program work, we need to use global keyword. We only need to use global keyword in a function if we want to do assignments / change them. global is not needed for printing and accessing. Why? Python “assumes” that we want a local variable due to the assignment to s inside of f(), so the first print statement throws this error message. Any variable which is changed or created inside of a function is local, if it hasn’t been declared as a global variable. To tell Python, that we want to use the global variable, we have to use the keyword global, as can be seen in the following example: Python3 # This function modifies global variable 's'def f(): global s print(s) s = "Look for Geeksforgeeks Python Section" print(s) # Global Scopes = "Python is great !"f()print(s) Output: Python is great! Look for Geeksforgeeks Python Section Look for Geeksforgeeks Python Section Consider the below example for better understanding of the topic. Python3 # Python program to demonstrate# scope of variable a = 1 # Uses global because there is no local 'a'def f(): print('Inside f() : ', a) # Variable 'a' is redefined as a localdef g(): a = 2 print('Inside g() : ', a) # Uses global keyword to modify global 'a'def h(): global a a = 3 print('Inside h() : ', a) # Global scopeprint('global : ', a)f()print('global : ', a)g()print('global : ', a)h()print('global : ', a) Output: global : 1 Inside f() : 1 global : 1 Inside g() : 2 global : 1 Inside h() : 3 global : 3 In Python, nonlocal keyword is used in the case of nested functions. This keyword works similar to the global, but rather than global, this keyword declares a variable to point to the variable of outside enclosing function, in case of nested functions.Example: Python3 # Python program to demonstrate# nonlocal keyword print ("Value of a using nonlocal is : ", end ="")def outer(): a = 5 def inner(): nonlocal a a = 10 inner() print (a) outer() # demonstrating without non local # inner loop not changing the value of outer a# prints 5print ("Value of a without using nonlocal is : ", end ="")def outer(): a = 5 def inner(): a = 10 inner() print (a) outer() Output: Value of a using nonlocal is : 10 Value of a without using nonlocal is : 5 adityashetty0302 python-basics Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Defaultdict in Python Different ways to create Pandas Dataframe sum() function in Python How to Install PIP on Windows ? Deque in Python Python String | replace() Convert integer to string in Python Stack in Python
[ { "code": null, "e": 23988, "s": 23960, "text": "\n20 Oct, 2021" }, { "code": null, "e": 24432, "s": 23988, "text": "In Python, variables are the containers for storing data values. They are reference, or pointers, to an object in memory which means that whenever a variable is assigned to an instance, it gets mapped to that instance. Unlike other languages like C/C++/JAVA, Python is not “statically typed”. We do not need to declare variables before using them or declare their type. A variable is created the moment we first assign a value to it.Example: " }, { "code": null, "e": 24440, "s": 24432, "text": "Python3" }, { "code": "# Python program to demonstrate# variable assignment # An integer assignmentage = 45 # A floating pointsalary = 1456.8 # A string name = \"John\" print(age)print(salary)print(name)", "e": 24674, "s": 24440, "text": null }, { "code": null, "e": 24684, "s": 24674, "text": "Output: " }, { "code": null, "e": 24699, "s": 24684, "text": "45\n1456.8\nJohn" }, { "code": null, "e": 24747, "s": 24699, "text": "Note: To know more about variables click here. " }, { "code": null, "e": 24856, "s": 24747, "text": "The location where we can find a variable and also access it if required is called the scope of a variable. " }, { "code": null, "e": 25031, "s": 24856, "text": "Global variables are the ones that are defined and declared outside any function and are not specified to any function. They can be used by any part of the program.Example: " }, { "code": null, "e": 25039, "s": 25031, "text": "Python3" }, { "code": "# This function uses global variable sdef f(): print(s) # Global scopes = \"I love Geeksforgeeks\"f()", "e": 25145, "s": 25039, "text": null }, { "code": null, "e": 25155, "s": 25145, "text": "Output: " }, { "code": null, "e": 25176, "s": 25155, "text": "I love Geeksforgeeks" }, { "code": null, "e": 25353, "s": 25176, "text": "Now suppose a variable with the same name is defined inside the scope of function as well then it will print the value given inside the function only and not the global value. " }, { "code": null, "e": 25361, "s": 25353, "text": "Python3" }, { "code": "# This function has a variable with# name same as s.def f(): s = \"Me too.\" print(s) # Global scopes = \"I love Geeksforgeeks\"f()print(s)", "e": 25506, "s": 25361, "text": null }, { "code": null, "e": 25516, "s": 25506, "text": "Output: " }, { "code": null, "e": 25545, "s": 25516, "text": "Me too.\nI love Geeksforgeeks" }, { "code": null, "e": 25931, "s": 25545, "text": "The variable s is defined as the string “I love Geeksforgeeks”, before we call the function f(). The only statement in f() is the print(s) statement. As there is no local s, the value from the global s will be used.The question is, what will happen if we change the value of s inside of the function f()? Will it affect the global s as well? We test it in the following piece of code: " }, { "code": null, "e": 25939, "s": 25931, "text": "Python3" }, { "code": "def f(): print(s) # This program will NOT show error # if we comment below line. s = \"Me too.\" print(s) # Global scopes = \"I love Geeksforgeeks\"f()print(s)", "e": 26120, "s": 25939, "text": null }, { "code": null, "e": 26130, "s": 26120, "text": "Output: " }, { "code": null, "e": 26385, "s": 26130, "text": "Traceback (most recent call last):\n File \"/home/370cac45bae7f1e6096520b7a0edb604.py\", line 13, in \n f() \n File \"/home/370cac45bae7f1e6096520b7a0edb604.py\", line 3, in f\n print(s) \nUnboundLocalError: local variable 's' referenced before assignment" }, { "code": null, "e": 26995, "s": 26385, "text": "To make the above program work, we need to use global keyword. We only need to use global keyword in a function if we want to do assignments / change them. global is not needed for printing and accessing. Why? Python “assumes” that we want a local variable due to the assignment to s inside of f(), so the first print statement throws this error message. Any variable which is changed or created inside of a function is local, if it hasn’t been declared as a global variable. To tell Python, that we want to use the global variable, we have to use the keyword global, as can be seen in the following example: " }, { "code": null, "e": 27003, "s": 26995, "text": "Python3" }, { "code": "# This function modifies global variable 's'def f(): global s print(s) s = \"Look for Geeksforgeeks Python Section\" print(s) # Global Scopes = \"Python is great !\"f()print(s)", "e": 27190, "s": 27003, "text": null }, { "code": null, "e": 27200, "s": 27190, "text": "Output: " }, { "code": null, "e": 27293, "s": 27200, "text": "Python is great!\nLook for Geeksforgeeks Python Section\nLook for Geeksforgeeks Python Section" }, { "code": null, "e": 27361, "s": 27293, "text": "Consider the below example for better understanding of the topic. " }, { "code": null, "e": 27369, "s": 27361, "text": "Python3" }, { "code": "# Python program to demonstrate# scope of variable a = 1 # Uses global because there is no local 'a'def f(): print('Inside f() : ', a) # Variable 'a' is redefined as a localdef g(): a = 2 print('Inside g() : ', a) # Uses global keyword to modify global 'a'def h(): global a a = 3 print('Inside h() : ', a) # Global scopeprint('global : ', a)f()print('global : ', a)g()print('global : ', a)h()print('global : ', a)", "e": 27817, "s": 27369, "text": null }, { "code": null, "e": 27827, "s": 27817, "text": "Output: " }, { "code": null, "e": 27923, "s": 27827, "text": "global : 1\nInside f() : 1\nglobal : 1\nInside g() : 2\nglobal : 1\nInside h() : 3\nglobal : 3" }, { "code": null, "e": 28188, "s": 27925, "text": "In Python, nonlocal keyword is used in the case of nested functions. This keyword works similar to the global, but rather than global, this keyword declares a variable to point to the variable of outside enclosing function, in case of nested functions.Example: " }, { "code": null, "e": 28196, "s": 28188, "text": "Python3" }, { "code": "# Python program to demonstrate# nonlocal keyword print (\"Value of a using nonlocal is : \", end =\"\")def outer(): a = 5 def inner(): nonlocal a a = 10 inner() print (a) outer() # demonstrating without non local # inner loop not changing the value of outer a# prints 5print (\"Value of a without using nonlocal is : \", end =\"\")def outer(): a = 5 def inner(): a = 10 inner() print (a) outer()", "e": 28637, "s": 28196, "text": null }, { "code": null, "e": 28647, "s": 28637, "text": "Output: " }, { "code": null, "e": 28722, "s": 28647, "text": "Value of a using nonlocal is : 10\nValue of a without using nonlocal is : 5" }, { "code": null, "e": 28741, "s": 28724, "text": "adityashetty0302" }, { "code": null, "e": 28755, "s": 28741, "text": "python-basics" }, { "code": null, "e": 28762, "s": 28755, "text": "Python" }, { "code": null, "e": 28860, "s": 28762, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28869, "s": 28860, "text": "Comments" }, { "code": null, "e": 28882, "s": 28869, "text": "Old Comments" }, { "code": null, "e": 28900, "s": 28882, "text": "Python Dictionary" }, { "code": null, "e": 28935, "s": 28900, "text": "Read a file line by line in Python" }, { "code": null, "e": 28957, "s": 28935, "text": "Defaultdict in Python" }, { "code": null, "e": 28999, "s": 28957, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29024, "s": 28999, "text": "sum() function in Python" }, { "code": null, "e": 29056, "s": 29024, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29072, "s": 29056, "text": "Deque in Python" }, { "code": null, "e": 29098, "s": 29072, "text": "Python String | replace()" }, { "code": null, "e": 29134, "s": 29098, "text": "Convert integer to string in Python" } ]
Flask – URL Building
The url_for() function is very useful for dynamically building a URL for a specific function. The function accepts the name of a function as first argument, and one or more keyword arguments, each corresponding to the variable part of URL. The following script demonstrates use of url_for() function. from flask import Flask, redirect, url_for app = Flask(__name__) @app.route('/admin') def hello_admin(): return 'Hello Admin' @app.route('/guest/<guest>') def hello_guest(guest): return 'Hello %s as Guest' % guest @app.route('/user/<name>') def hello_user(name): if name =='admin': return redirect(url_for('hello_admin')) else: return redirect(url_for('hello_guest',guest = name)) if __name__ == '__main__': app.run(debug = True) The above script has a function user(name) which accepts a value to its argument from the URL. The User() function checks if an argument received matches ‘admin’ or not. If it matches, the application is redirected to the hello_admin() function using url_for(), otherwise to the hello_guest() function passing the received argument as guest parameter to it. Save the above code and run from Python shell. Open the browser and enter URL as − http://localhost:5000/user/admin The application response in browser is − Hello Admin Enter the following URL in the browser − http://localhost:5000/user/mvl The application response now changes to − Hello mvl as Guest 22 Lectures 6 hours Malhar Lathkar 21 Lectures 1.5 hours Jack Chan 16 Lectures 4 hours Malhar Lathkar 54 Lectures 6 hours Srikanth Guskra 88 Lectures 3.5 hours Jorge Escobar 80 Lectures 12 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2273, "s": 2033, "text": "The url_for() function is very useful for dynamically building a URL for a specific function. The function accepts the name of a function as first argument, and one or more keyword arguments, each corresponding to the variable part of URL." }, { "code": null, "e": 2334, "s": 2273, "text": "The following script demonstrates use of url_for() function." }, { "code": null, "e": 2795, "s": 2334, "text": "from flask import Flask, redirect, url_for\napp = Flask(__name__)\n\n@app.route('/admin')\ndef hello_admin():\n return 'Hello Admin'\n\n@app.route('/guest/<guest>')\ndef hello_guest(guest):\n return 'Hello %s as Guest' % guest\n\n@app.route('/user/<name>')\ndef hello_user(name):\n if name =='admin':\n return redirect(url_for('hello_admin'))\n else:\n return redirect(url_for('hello_guest',guest = name))\n\nif __name__ == '__main__':\n app.run(debug = True)" }, { "code": null, "e": 2890, "s": 2795, "text": "The above script has a function user(name) which accepts a value to its argument from the URL." }, { "code": null, "e": 3153, "s": 2890, "text": "The User() function checks if an argument received matches ‘admin’ or not. If it matches, the application is redirected to the hello_admin() function using url_for(), otherwise to the hello_guest() function passing the received argument as guest parameter to it." }, { "code": null, "e": 3200, "s": 3153, "text": "Save the above code and run from Python shell." }, { "code": null, "e": 3269, "s": 3200, "text": "Open the browser and enter URL as − http://localhost:5000/user/admin" }, { "code": null, "e": 3310, "s": 3269, "text": "The application response in browser is −" }, { "code": null, "e": 3323, "s": 3310, "text": "Hello Admin\n" }, { "code": null, "e": 3395, "s": 3323, "text": "Enter the following URL in the browser − http://localhost:5000/user/mvl" }, { "code": null, "e": 3437, "s": 3395, "text": "The application response now changes to −" }, { "code": null, "e": 3457, "s": 3437, "text": "Hello mvl as Guest\n" }, { "code": null, "e": 3490, "s": 3457, "text": "\n 22 Lectures \n 6 hours \n" }, { "code": null, "e": 3506, "s": 3490, "text": " Malhar Lathkar" }, { "code": null, "e": 3541, "s": 3506, "text": "\n 21 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3552, "s": 3541, "text": " Jack Chan" }, { "code": null, "e": 3585, "s": 3552, "text": "\n 16 Lectures \n 4 hours \n" }, { "code": null, "e": 3601, "s": 3585, "text": " Malhar Lathkar" }, { "code": null, "e": 3634, "s": 3601, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 3651, "s": 3634, "text": " Srikanth Guskra" }, { "code": null, "e": 3686, "s": 3651, "text": "\n 88 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3701, "s": 3686, "text": " Jorge Escobar" }, { "code": null, "e": 3735, "s": 3701, "text": "\n 80 Lectures \n 12 hours \n" }, { "code": null, "e": 3758, "s": 3735, "text": " Stone River ELearning" }, { "code": null, "e": 3765, "s": 3758, "text": " Print" }, { "code": null, "e": 3776, "s": 3765, "text": " Add Notes" } ]
TensorFlow - Recurrent Neural Networks
Recurrent neural networks is a type of deep learning-oriented algorithm, which follows a sequential approach. In neural networks, we always assume that each input and output is independent of all other layers. These type of neural networks are called recurrent because they perform mathematical computations in sequential manner. Consider the following steps to train a recurrent neural network − Step 1 − Input a specific example from dataset. Step 2 − Network will take an example and compute some calculations using randomly initialized variables. Step 3 − A predicted result is then computed. Step 4 − The comparison of actual result generated with the expected value will produce an error. Step 5 − To trace the error, it is propagated through same path where the variables are also adjusted. Step 6 − The steps from 1 to 5 are repeated until we are confident that the variables declared to get the output are defined properly. Step 7 − A systematic prediction is made by applying these variables to get new unseen input. The schematic approach of representing recurrent neural networks is described below − In this section, we will learn how to implement recurrent neural network with TensorFlow. Step 1 − TensorFlow includes various libraries for specific implementation of the recurrent neural network module. #Import necessary modules from __future__ import print_function import tensorflow as tf from tensorflow.contrib import rnn from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("/tmp/data/", one_hot = True) As mentioned above, the libraries help in defining the input data, which forms the primary part of recurrent neural network implementation. Step 2 − Our primary motive is to classify the images using a recurrent neural network, where we consider every image row as a sequence of pixels. MNIST image shape is specifically defined as 28*28 px. Now we will handle 28 sequences of 28 steps for each sample that is mentioned. We will define the input parameters to get the sequential pattern done. n_input = 28 # MNIST data input with img shape 28*28 n_steps = 28 n_hidden = 128 n_classes = 10 # tf Graph input x = tf.placeholder("float", [None, n_steps, n_input]) y = tf.placeholder("float", [None, n_classes] weights = { 'out': tf.Variable(tf.random_normal([n_hidden, n_classes])) } biases = { 'out': tf.Variable(tf.random_normal([n_classes])) } Step 3 − Compute the results using a defined function in RNN to get the best results. Here, each data shape is compared with current input shape and the results are computed to maintain the accuracy rate. def RNN(x, weights, biases): x = tf.unstack(x, n_steps, 1) # Define a lstm cell with tensorflow lstm_cell = rnn.BasicLSTMCell(n_hidden, forget_bias=1.0) # Get lstm cell output outputs, states = rnn.static_rnn(lstm_cell, x, dtype = tf.float32) # Linear activation, using rnn inner loop last output return tf.matmul(outputs[-1], weights['out']) + biases['out'] pred = RNN(x, weights, biases) # Define loss and optimizer cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = pred, labels = y)) optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(cost) # Evaluate model correct_pred = tf.equal(tf.argmax(pred,1), tf.argmax(y,1)) accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32)) # Initializing the variables init = tf.global_variables_initializer() Step 4 − In this step, we will launch the graph to get the computational results. This also helps in calculating the accuracy for test results. with tf.Session() as sess: sess.run(init) step = 1 # Keep training until reach max iterations while step * batch_size < training_iters: batch_x, batch_y = mnist.train.next_batch(batch_size) batch_x = batch_x.reshape((batch_size, n_steps, n_input)) sess.run(optimizer, feed_dict={x: batch_x, y: batch_y}) if step % display_step == 0: # Calculate batch accuracy acc = sess.run(accuracy, feed_dict={x: batch_x, y: batch_y}) # Calculate batch loss loss = sess.run(cost, feed_dict={x: batch_x, y: batch_y}) print("Iter " + str(step*batch_size) + ", Minibatch Loss= " + \ "{:.6f}".format(loss) + ", Training Accuracy= " + \ "{:.5f}".format(acc)) step += 1 print("Optimization Finished!") test_len = 128 test_data = mnist.test.images[:test_len].reshape((-1, n_steps, n_input)) test_label = mnist.test.labels[:test_len] print("Testing Accuracy:", \ sess.run(accuracy, feed_dict={x: test_data, y: test_label})) The screenshots below show the output generated − 61 Lectures 9 hours Abhishek And Pukhraj 57 Lectures 7 hours Abhishek And Pukhraj 52 Lectures 7 hours Abhishek And Pukhraj 52 Lectures 6 hours Abhishek And Pukhraj 29 Lectures 3.5 hours Mohammad Nauman 82 Lectures 4 hours Anis Koubaa Print Add Notes Bookmark this page
[ { "code": null, "e": 2645, "s": 2315, "text": "Recurrent neural networks is a type of deep learning-oriented algorithm, which follows a sequential approach. In neural networks, we always assume that each input and output is independent of all other layers. These type of neural networks are called recurrent because they perform mathematical computations in sequential manner." }, { "code": null, "e": 2712, "s": 2645, "text": "Consider the following steps to train a recurrent neural network −" }, { "code": null, "e": 2760, "s": 2712, "text": "Step 1 − Input a specific example from dataset." }, { "code": null, "e": 2866, "s": 2760, "text": "Step 2 − Network will take an example and compute some calculations using randomly initialized variables." }, { "code": null, "e": 2912, "s": 2866, "text": "Step 3 − A predicted result is then computed." }, { "code": null, "e": 3010, "s": 2912, "text": "Step 4 − The comparison of actual result generated with the expected value will produce an error." }, { "code": null, "e": 3113, "s": 3010, "text": "Step 5 − To trace the error, it is propagated through same path where the variables are also adjusted." }, { "code": null, "e": 3248, "s": 3113, "text": "Step 6 − The steps from 1 to 5 are repeated until we are confident that the variables declared to get the output are defined properly." }, { "code": null, "e": 3342, "s": 3248, "text": "Step 7 − A systematic prediction is made by applying these variables to get new unseen input." }, { "code": null, "e": 3428, "s": 3342, "text": "The schematic approach of representing recurrent neural networks is described below −" }, { "code": null, "e": 3518, "s": 3428, "text": "In this section, we will learn how to implement recurrent neural network with TensorFlow." }, { "code": null, "e": 3633, "s": 3518, "text": "Step 1 − TensorFlow includes various libraries for specific implementation of the recurrent neural network module." }, { "code": null, "e": 3880, "s": 3633, "text": "#Import necessary modules\nfrom __future__ import print_function\n\nimport tensorflow as tf\nfrom tensorflow.contrib import rnn\nfrom tensorflow.examples.tutorials.mnist import input_data\nmnist = input_data.read_data_sets(\"/tmp/data/\", one_hot = True)" }, { "code": null, "e": 4020, "s": 3880, "text": "As mentioned above, the libraries help in defining the input data, which forms the primary part of recurrent neural network implementation." }, { "code": null, "e": 4373, "s": 4020, "text": "Step 2 − Our primary motive is to classify the images using a recurrent neural network, where we consider every image row as a sequence of pixels. MNIST image shape is specifically defined as 28*28 px. Now we will handle 28 sequences of 28 steps for each sample that is mentioned. We will define the input parameters to get the sequential pattern done." }, { "code": null, "e": 4730, "s": 4373, "text": "n_input = 28 # MNIST data input with img shape 28*28\nn_steps = 28\nn_hidden = 128\nn_classes = 10\n\n# tf Graph input\nx = tf.placeholder(\"float\", [None, n_steps, n_input])\ny = tf.placeholder(\"float\", [None, n_classes]\nweights = {\n 'out': tf.Variable(tf.random_normal([n_hidden, n_classes]))\n}\nbiases = {\n 'out': tf.Variable(tf.random_normal([n_classes]))\n}" }, { "code": null, "e": 4935, "s": 4730, "text": "Step 3 − Compute the results using a defined function in RNN to get the best results. Here, each data shape is compared with current input shape and the results are computed to maintain the accuracy rate." }, { "code": null, "e": 5759, "s": 4935, "text": "def RNN(x, weights, biases):\n x = tf.unstack(x, n_steps, 1)\n\n # Define a lstm cell with tensorflow\n lstm_cell = rnn.BasicLSTMCell(n_hidden, forget_bias=1.0)\n\n # Get lstm cell output\n outputs, states = rnn.static_rnn(lstm_cell, x, dtype = tf.float32)\n\n # Linear activation, using rnn inner loop last output\n return tf.matmul(outputs[-1], weights['out']) + biases['out']\n\npred = RNN(x, weights, biases)\n\n# Define loss and optimizer\ncost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = pred, labels = y))\noptimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(cost)\n\n# Evaluate model\ncorrect_pred = tf.equal(tf.argmax(pred,1), tf.argmax(y,1))\naccuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n\n# Initializing the variables\ninit = tf.global_variables_initializer()" }, { "code": null, "e": 5903, "s": 5759, "text": "Step 4 − In this step, we will launch the graph to get the computational results. This also helps in calculating the accuracy for test results." }, { "code": null, "e": 6975, "s": 5903, "text": "with tf.Session() as sess:\n sess.run(init)\n step = 1\n # Keep training until reach max iterations\n \n while step * batch_size < training_iters:\n batch_x, batch_y = mnist.train.next_batch(batch_size)\n batch_x = batch_x.reshape((batch_size, n_steps, n_input))\n sess.run(optimizer, feed_dict={x: batch_x, y: batch_y})\n \n if step % display_step == 0:\n # Calculate batch accuracy\n acc = sess.run(accuracy, feed_dict={x: batch_x, y: batch_y})\n \n # Calculate batch loss\n loss = sess.run(cost, feed_dict={x: batch_x, y: batch_y})\n \n print(\"Iter \" + str(step*batch_size) + \", Minibatch Loss= \" + \\\n \"{:.6f}\".format(loss) + \", Training Accuracy= \" + \\\n \"{:.5f}\".format(acc))\n step += 1\n print(\"Optimization Finished!\")\n test_len = 128\n test_data = mnist.test.images[:test_len].reshape((-1, n_steps, n_input))\n \n test_label = mnist.test.labels[:test_len]\n print(\"Testing Accuracy:\", \\\n sess.run(accuracy, feed_dict={x: test_data, y: test_label}))" }, { "code": null, "e": 7025, "s": 6975, "text": "The screenshots below show the output generated −" }, { "code": null, "e": 7058, "s": 7025, "text": "\n 61 Lectures \n 9 hours \n" }, { "code": null, "e": 7080, "s": 7058, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 7113, "s": 7080, "text": "\n 57 Lectures \n 7 hours \n" }, { "code": null, "e": 7135, "s": 7113, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 7168, "s": 7135, "text": "\n 52 Lectures \n 7 hours \n" }, { "code": null, "e": 7190, "s": 7168, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 7223, "s": 7190, "text": "\n 52 Lectures \n 6 hours \n" }, { "code": null, "e": 7245, "s": 7223, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 7280, "s": 7245, "text": "\n 29 Lectures \n 3.5 hours \n" }, { "code": null, "e": 7297, "s": 7280, "text": " Mohammad Nauman" }, { "code": null, "e": 7330, "s": 7297, "text": "\n 82 Lectures \n 4 hours \n" }, { "code": null, "e": 7343, "s": 7330, "text": " Anis Koubaa" }, { "code": null, "e": 7350, "s": 7343, "text": " Print" }, { "code": null, "e": 7361, "s": 7350, "text": " Add Notes" } ]
Program to find length of longest palindromic substring in Python
Suppose we have a string S. We have to find the length of longest palindromic substring in S. We are assuming that the length of the string S is 1000. So if the string is “BABAC”, then the longest palindromic substring is “BAB” and length is 3. To solve this, we will follow these steps − Define one square matrix of order same as the length of string, and fill it with False Define one square matrix of order same as the length of string, and fill it with False Set the major diagonal elements as true, so DP[i, i] = True for all i from 0 to order – 1 Set the major diagonal elements as true, so DP[i, i] = True for all i from 0 to order – 1 start := 0 start := 0 for l in range 2 to length of S + 1for i in range 0 to length of S – l + 1end := i + lif l = 2, thenif S[i] = S[end - 1], thenDP[i, end - 1] = True, max_len := l, and start := iotherwiseif S[i] = S[end - 1] and DP[i + 1, end - 2], thenDP[i, end - 1] = True, max_len := l, and start := i for l in range 2 to length of S + 1 for i in range 0 to length of S – l + 1end := i + lif l = 2, thenif S[i] = S[end - 1], thenDP[i, end - 1] = True, max_len := l, and start := iotherwiseif S[i] = S[end - 1] and DP[i + 1, end - 2], thenDP[i, end - 1] = True, max_len := l, and start := i for i in range 0 to length of S – l + 1 end := i + l end := i + l if l = 2, thenif S[i] = S[end - 1], thenDP[i, end - 1] = True, max_len := l, and start := i if l = 2, then if S[i] = S[end - 1], thenDP[i, end - 1] = True, max_len := l, and start := i if S[i] = S[end - 1], then DP[i, end - 1] = True, max_len := l, and start := i DP[i, end - 1] = True, max_len := l, and start := i otherwiseif S[i] = S[end - 1] and DP[i + 1, end - 2], thenDP[i, end - 1] = True, max_len := l, and start := i otherwise if S[i] = S[end - 1] and DP[i + 1, end - 2], thenDP[i, end - 1] = True, max_len := l, and start := i if S[i] = S[end - 1] and DP[i + 1, end - 2], then DP[i, end - 1] = True, max_len := l, and start := i DP[i, end - 1] = True, max_len := l, and start := i return max_len return max_len Let us see the following implementation to get better understanding − class Solution(object): def solve(self, s): dp = [[False for i in range(len(s))] for i in range(len(s))] for i in range(len(s)): dp[i][i] = True max_length = 1 start = 0 for l in range(2,len(s)+1): for i in range(len(s)-l+1): end = i+l if l==2: if s[i] == s[end-1]: dp[i][end-1]=True max_length = l start = i else: if s[i] == s[end-1] and dp[i+1][end-2]: dp[i][end-1]=True max_length = l start = i return max_length ob = Solution() print(ob.solve('BABAC')) "ABBABBC" 5
[ { "code": null, "e": 1307, "s": 1062, "text": "Suppose we have a string S. We have to find the length of longest palindromic substring in S.\nWe are assuming that the length of the string S is 1000. So if the string is “BABAC”, then the\nlongest palindromic substring is “BAB” and length is 3." }, { "code": null, "e": 1351, "s": 1307, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1438, "s": 1351, "text": "Define one square matrix of order same as the length of string, and fill it with False" }, { "code": null, "e": 1525, "s": 1438, "text": "Define one square matrix of order same as the length of string, and fill it with False" }, { "code": null, "e": 1615, "s": 1525, "text": "Set the major diagonal elements as true, so DP[i, i] = True for all i from 0 to order – 1" }, { "code": null, "e": 1705, "s": 1615, "text": "Set the major diagonal elements as true, so DP[i, i] = True for all i from 0 to order – 1" }, { "code": null, "e": 1716, "s": 1705, "text": "start := 0" }, { "code": null, "e": 1727, "s": 1716, "text": "start := 0" }, { "code": null, "e": 2014, "s": 1727, "text": "for l in range 2 to length of S + 1for i in range 0 to length of S – l + 1end := i + lif l = 2, thenif S[i] = S[end - 1], thenDP[i, end - 1] = True, max_len := l, and start := iotherwiseif S[i] = S[end - 1] and DP[i + 1, end - 2], thenDP[i, end - 1] = True, max_len := l, and start := i" }, { "code": null, "e": 2050, "s": 2014, "text": "for l in range 2 to length of S + 1" }, { "code": null, "e": 2302, "s": 2050, "text": "for i in range 0 to length of S – l + 1end := i + lif l = 2, thenif S[i] = S[end - 1], thenDP[i, end - 1] = True, max_len := l, and start := iotherwiseif S[i] = S[end - 1] and DP[i + 1, end - 2], thenDP[i, end - 1] = True, max_len := l, and start := i" }, { "code": null, "e": 2342, "s": 2302, "text": "for i in range 0 to length of S – l + 1" }, { "code": null, "e": 2355, "s": 2342, "text": "end := i + l" }, { "code": null, "e": 2368, "s": 2355, "text": "end := i + l" }, { "code": null, "e": 2460, "s": 2368, "text": "if l = 2, thenif S[i] = S[end - 1], thenDP[i, end - 1] = True, max_len := l, and start := i" }, { "code": null, "e": 2475, "s": 2460, "text": "if l = 2, then" }, { "code": null, "e": 2553, "s": 2475, "text": "if S[i] = S[end - 1], thenDP[i, end - 1] = True, max_len := l, and start := i" }, { "code": null, "e": 2580, "s": 2553, "text": "if S[i] = S[end - 1], then" }, { "code": null, "e": 2632, "s": 2580, "text": "DP[i, end - 1] = True, max_len := l, and start := i" }, { "code": null, "e": 2684, "s": 2632, "text": "DP[i, end - 1] = True, max_len := l, and start := i" }, { "code": null, "e": 2794, "s": 2684, "text": "otherwiseif S[i] = S[end - 1] and DP[i + 1, end - 2], thenDP[i, end - 1] = True, max_len := l, and start := i" }, { "code": null, "e": 2804, "s": 2794, "text": "otherwise" }, { "code": null, "e": 2905, "s": 2804, "text": "if S[i] = S[end - 1] and DP[i + 1, end - 2], thenDP[i, end - 1] = True, max_len := l, and start := i" }, { "code": null, "e": 2955, "s": 2905, "text": "if S[i] = S[end - 1] and DP[i + 1, end - 2], then" }, { "code": null, "e": 3007, "s": 2955, "text": "DP[i, end - 1] = True, max_len := l, and start := i" }, { "code": null, "e": 3059, "s": 3007, "text": "DP[i, end - 1] = True, max_len := l, and start := i" }, { "code": null, "e": 3074, "s": 3059, "text": "return max_len" }, { "code": null, "e": 3089, "s": 3074, "text": "return max_len" }, { "code": null, "e": 3159, "s": 3089, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 3889, "s": 3159, "text": "class Solution(object):\n def solve(self, s):\n dp = [[False for i in range(len(s))] for i in range(len(s))]\n for i in range(len(s)):\n dp[i][i] = True\n max_length = 1\n start = 0\n for l in range(2,len(s)+1):\n for i in range(len(s)-l+1):\n\n end = i+l\n\n if l==2:\n if s[i] == s[end-1]:\n dp[i][end-1]=True\n max_length = l\n start = i\n else:\n if s[i] == s[end-1] and dp[i+1][end-2]:\n dp[i][end-1]=True\n max_length = l\n start = i\nreturn max_length\n\nob = Solution()\nprint(ob.solve('BABAC'))" }, { "code": null, "e": 3899, "s": 3889, "text": "\"ABBABBC\"" }, { "code": null, "e": 3901, "s": 3899, "text": "5" } ]
Java Deprecated API Scanner tool (jdepscan) in Java 9 with Examples - GeeksforGeeks
30 Jan, 2020 Java Deprecated API Scanner tool: Java Deprecated API Scanner tool i.e. jdeprscan is a static analyzing command-line tool which is introduced in JDK 9 for find out the uses of deprecated API in the given input. Here the input can be .class file name, directory or JAR file. Whenever we provide any input to jdeprscan command line tool then it generates the dependencies to the system console. jdeprscan introduced with various options which affect the output. As per option, jdeprscan command-line tool generates the output. jdeprscan tool identifies the deprecated APIs which defined by Java SE Deprecated APIs but it will not list out the deprecated APIs which is used by third-party libraries. Syntax for using jdeprscan tool: jdeprscan [options] {class|dir|jar} Example: // Program to illustrate the output of jdeprscan tool import java.awt.*;class Geeks extends Thread { public void run() { System.out.println("Child Thread"); } public static void main(String args[]) { Thread thread = new Thread(); thread.start(); thread.stop(); List list = new List(); list.addItem("Geeksforgeeks"); Integer i = new Integer(100); System.out.println(i); }} Compile Time Console: Note: Geeks.java uses or overrides a deprecated API. Note: Recompile with -Xlint:deprecation for details. Output: jdeprscan Geeks.class Various options available for jdeprscan: –release 6|7|8|9: It will list out the uses of deprecated APIs in the given argument as per given release. Suppose we are using JDK 9 and we want to list out the deprecated APIs as per Java release 7, then we can use this option.Output:jdeprscan --release 6 Geeks.classjdeprscan --release 7 Geeks.class–verbose: It will enable printing of additional message during listing out deprecated APIs.Output:jdeprscan --verbose Geeks.class–version: It will specify the version of jdeprscan.Output:jdeprscan --version9.0.4 –full-version: It will print the version of the jdeprscan tool.Output:jdeprscan --full-version9.0.4+11 –help: It will display the help message for user. Instead of using -help, we can use -h also.Output:jdeprscan --help–list: It will list out the deprecated APIs. Instead of using -list, we can use -l also.Output:jdeprscan --list –release 6|7|8|9: It will list out the uses of deprecated APIs in the given argument as per given release. Suppose we are using JDK 9 and we want to list out the deprecated APIs as per Java release 7, then we can use this option.Output:jdeprscan --release 6 Geeks.classjdeprscan --release 7 Geeks.class Output: jdeprscan --release 6 Geeks.class jdeprscan --release 7 Geeks.class –verbose: It will enable printing of additional message during listing out deprecated APIs.Output:jdeprscan --verbose Geeks.class Output: jdeprscan --verbose Geeks.class –version: It will specify the version of jdeprscan.Output:jdeprscan --version9.0.4 Output: jdeprscan --version 9.0.4 –full-version: It will print the version of the jdeprscan tool.Output:jdeprscan --full-version9.0.4+11 Output: jdeprscan --full-version 9.0.4+11 –help: It will display the help message for user. Instead of using -help, we can use -h also.Output:jdeprscan --help Output: jdeprscan --help –list: It will list out the deprecated APIs. Instead of using -list, we can use -l also.Output:jdeprscan --list Output: jdeprscan --list Technical Scripter 2019 Java Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Hashtable in Java Constructors in Java Different ways of Reading a text file in Java Comparator Interface in Java with Examples Java Math random() method with Examples HashMap containsKey() Method in Java How to Create Array of Objects in Java? Convert Double to Integer in Java Iterating over ArrayLists in Java Generating random numbers in Java
[ { "code": null, "e": 23557, "s": 23529, "text": "\n30 Jan, 2020" }, { "code": null, "e": 24254, "s": 23557, "text": "Java Deprecated API Scanner tool: Java Deprecated API Scanner tool i.e. jdeprscan is a static analyzing command-line tool which is introduced in JDK 9 for find out the uses of deprecated API in the given input. Here the input can be .class file name, directory or JAR file. Whenever we provide any input to jdeprscan command line tool then it generates the dependencies to the system console. jdeprscan introduced with various options which affect the output. As per option, jdeprscan command-line tool generates the output. jdeprscan tool identifies the deprecated APIs which defined by Java SE Deprecated APIs but it will not list out the deprecated APIs which is used by third-party libraries." }, { "code": null, "e": 24287, "s": 24254, "text": "Syntax for using jdeprscan tool:" }, { "code": null, "e": 24324, "s": 24287, "text": "jdeprscan [options] {class|dir|jar}\n" }, { "code": null, "e": 24333, "s": 24324, "text": "Example:" }, { "code": "// Program to illustrate the output of jdeprscan tool import java.awt.*;class Geeks extends Thread { public void run() { System.out.println(\"Child Thread\"); } public static void main(String args[]) { Thread thread = new Thread(); thread.start(); thread.stop(); List list = new List(); list.addItem(\"Geeksforgeeks\"); Integer i = new Integer(100); System.out.println(i); }}", "e": 24786, "s": 24333, "text": null }, { "code": null, "e": 24808, "s": 24786, "text": "Compile Time Console:" }, { "code": null, "e": 24915, "s": 24808, "text": "Note: Geeks.java uses or overrides a deprecated API.\nNote: Recompile with -Xlint:deprecation for details.\n" }, { "code": null, "e": 24923, "s": 24915, "text": "Output:" }, { "code": null, "e": 24945, "s": 24923, "text": "jdeprscan Geeks.class" }, { "code": null, "e": 24986, "s": 24945, "text": "Various options available for jdeprscan:" }, { "code": null, "e": 25833, "s": 24986, "text": "–release 6|7|8|9: It will list out the uses of deprecated APIs in the given argument as per given release. Suppose we are using JDK 9 and we want to list out the deprecated APIs as per Java release 7, then we can use this option.Output:jdeprscan --release 6 Geeks.classjdeprscan --release 7 Geeks.class–verbose: It will enable printing of additional message during listing out deprecated APIs.Output:jdeprscan --verbose Geeks.class–version: It will specify the version of jdeprscan.Output:jdeprscan --version9.0.4\n–full-version: It will print the version of the jdeprscan tool.Output:jdeprscan --full-version9.0.4+11\n–help: It will display the help message for user. Instead of using -help, we can use -h also.Output:jdeprscan --help–list: It will list out the deprecated APIs. Instead of using -list, we can use -l also.Output:jdeprscan --list" }, { "code": null, "e": 26138, "s": 25833, "text": "–release 6|7|8|9: It will list out the uses of deprecated APIs in the given argument as per given release. Suppose we are using JDK 9 and we want to list out the deprecated APIs as per Java release 7, then we can use this option.Output:jdeprscan --release 6 Geeks.classjdeprscan --release 7 Geeks.class" }, { "code": null, "e": 26146, "s": 26138, "text": "Output:" }, { "code": null, "e": 26181, "s": 26146, "text": "jdeprscan --release 6 Geeks.class" }, { "code": null, "e": 26216, "s": 26181, "text": "jdeprscan --release 7 Geeks.class" }, { "code": null, "e": 26346, "s": 26216, "text": "–verbose: It will enable printing of additional message during listing out deprecated APIs.Output:jdeprscan --verbose Geeks.class" }, { "code": null, "e": 26354, "s": 26346, "text": "Output:" }, { "code": null, "e": 26386, "s": 26354, "text": "jdeprscan --verbose Geeks.class" }, { "code": null, "e": 26470, "s": 26386, "text": "–version: It will specify the version of jdeprscan.Output:jdeprscan --version9.0.4\n" }, { "code": null, "e": 26478, "s": 26470, "text": "Output:" }, { "code": null, "e": 26498, "s": 26478, "text": "jdeprscan --version" }, { "code": null, "e": 26505, "s": 26498, "text": "9.0.4\n" }, { "code": null, "e": 26609, "s": 26505, "text": "–full-version: It will print the version of the jdeprscan tool.Output:jdeprscan --full-version9.0.4+11\n" }, { "code": null, "e": 26617, "s": 26609, "text": "Output:" }, { "code": null, "e": 26642, "s": 26617, "text": "jdeprscan --full-version" }, { "code": null, "e": 26652, "s": 26642, "text": "9.0.4+11\n" }, { "code": null, "e": 26769, "s": 26652, "text": "–help: It will display the help message for user. Instead of using -help, we can use -h also.Output:jdeprscan --help" }, { "code": null, "e": 26777, "s": 26769, "text": "Output:" }, { "code": null, "e": 26794, "s": 26777, "text": "jdeprscan --help" }, { "code": null, "e": 26906, "s": 26794, "text": "–list: It will list out the deprecated APIs. Instead of using -list, we can use -l also.Output:jdeprscan --list" }, { "code": null, "e": 26914, "s": 26906, "text": "Output:" }, { "code": null, "e": 26931, "s": 26914, "text": "jdeprscan --list" }, { "code": null, "e": 26955, "s": 26931, "text": "Technical Scripter 2019" }, { "code": null, "e": 26960, "s": 26955, "text": "Java" }, { "code": null, "e": 26979, "s": 26960, "text": "Technical Scripter" }, { "code": null, "e": 26984, "s": 26979, "text": "Java" }, { "code": null, "e": 27082, "s": 26984, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27091, "s": 27082, "text": "Comments" }, { "code": null, "e": 27104, "s": 27091, "text": "Old Comments" }, { "code": null, "e": 27122, "s": 27104, "text": "Hashtable in Java" }, { "code": null, "e": 27143, "s": 27122, "text": "Constructors in Java" }, { "code": null, "e": 27189, "s": 27143, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 27232, "s": 27189, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 27272, "s": 27232, "text": "Java Math random() method with Examples" }, { "code": null, "e": 27309, "s": 27272, "text": "HashMap containsKey() Method in Java" }, { "code": null, "e": 27349, "s": 27309, "text": "How to Create Array of Objects in Java?" }, { "code": null, "e": 27383, "s": 27349, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 27417, "s": 27383, "text": "Iterating over ArrayLists in Java" } ]
React Native - Router
In this chapter, we will understand navigation in React Native. To begin with, we need to install the Router. We will use the React Native Router Flux in this chapter. You can run the following command in terminal, from the project folder. npm i react-native-router-flux --save Since we want our router to handle the entire application, we will add it in index.ios.js. For Android, you can do the same in index.android.js. import React, { Component } from 'react'; import { AppRegistry, View } from 'react-native'; import Routes from './Routes.js' class reactTutorialApp extends Component { render() { return ( <Routes /> ) } } export default reactTutorialApp AppRegistry.registerComponent('reactTutorialApp', () => reactTutorialApp) Now we will create the Routes component inside the components folder. It will return Router with several scenes. Each scene will need key, component and title. Router uses the key property to switch between scenes, component will be rendered on screen and the title will be shown in the navigation bar. We can also set the initial property to the scene that is to be rendered initially. import React from 'react' import { Router, Scene } from 'react-native-router-flux' import Home from './Home.js' import About from './About.js' const Routes = () => ( <Router> <Scene key = "root"> <Scene key = "home" component = {Home} title = "Home" initial = {true} /> <Scene key = "about" component = {About} title = "About" /> </Scene> </Router> ) export default Routes We already have the Home component from previous chapters; now, we need to add the About component. We will add the goToAbout and the goToHome functions to switch between scenes. import React from 'react' import { TouchableOpacity, Text } from 'react-native'; import { Actions } from 'react-native-router-flux'; const Home = () => { const goToAbout = () => { Actions.about() } return ( <TouchableOpacity style = {{ margin: 128 }} onPress = {goToAbout}> <Text>This is HOME!</Text> </TouchableOpacity> ) } export default Home import React from 'react' import { TouchableOpacity, Text } from 'react-native' import { Actions } from 'react-native-router-flux' const About = () => { const goToHome = () => { Actions.home() } return ( <TouchableOpacity style = {{ margin: 128 }} onPress = {goToHome}> <Text>This is ABOUT</Text> </TouchableOpacity> ) } export default About The app will render the initial Home screen. You can press the button to switch to the about screen. The Back arrow will appear; you can use it to get back to the previous screen. 20 Lectures 1.5 hours Anadi Sharma 61 Lectures 6.5 hours A To Z Mentor 40 Lectures 4.5 hours Eduonix Learning Solutions 56 Lectures 12.5 hours Eduonix Learning Solutions 62 Lectures 4.5 hours Senol Atac 67 Lectures 4.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2408, "s": 2344, "text": "In this chapter, we will understand navigation in React Native." }, { "code": null, "e": 2584, "s": 2408, "text": "To begin with, we need to install the Router. We will use the React Native Router Flux in this chapter. You can run the following command in terminal, from the project folder." }, { "code": null, "e": 2623, "s": 2584, "text": "npm i react-native-router-flux --save\n" }, { "code": null, "e": 2768, "s": 2623, "text": "Since we want our router to handle the entire application, we will add it in index.ios.js. For Android, you can do the same in index.android.js." }, { "code": null, "e": 3107, "s": 2768, "text": "import React, { Component } from 'react';\nimport { AppRegistry, View } from 'react-native';\nimport Routes from './Routes.js'\n\nclass reactTutorialApp extends Component {\n render() {\n return (\n <Routes />\n )\n }\n}\nexport default reactTutorialApp\nAppRegistry.registerComponent('reactTutorialApp', () => reactTutorialApp)" }, { "code": null, "e": 3494, "s": 3107, "text": "Now we will create the Routes component inside the components folder. It will return Router with several scenes. Each scene will need key, component and title. Router uses the key property to switch between scenes, component will be rendered on screen and the title will be shown in the navigation bar. We can also set the initial property to the scene that is to be rendered initially." }, { "code": null, "e": 3904, "s": 3494, "text": "import React from 'react'\nimport { Router, Scene } from 'react-native-router-flux'\nimport Home from './Home.js'\nimport About from './About.js'\n\nconst Routes = () => (\n <Router>\n <Scene key = \"root\">\n <Scene key = \"home\" component = {Home} title = \"Home\" initial = {true} />\n <Scene key = \"about\" component = {About} title = \"About\" />\n </Scene>\n </Router>\n)\nexport default Routes" }, { "code": null, "e": 4083, "s": 3904, "text": "We already have the Home component from previous chapters; now, we need to add the About component. We will add the goToAbout and the goToHome functions to switch between scenes." }, { "code": null, "e": 4468, "s": 4083, "text": "import React from 'react'\nimport { TouchableOpacity, Text } from 'react-native';\nimport { Actions } from 'react-native-router-flux';\n\nconst Home = () => {\n const goToAbout = () => {\n Actions.about()\n }\n return (\n <TouchableOpacity style = {{ margin: 128 }} onPress = {goToAbout}>\n <Text>This is HOME!</Text>\n </TouchableOpacity>\n )\n}\nexport default Home" }, { "code": null, "e": 4850, "s": 4468, "text": "import React from 'react'\nimport { TouchableOpacity, Text } from 'react-native'\nimport { Actions } from 'react-native-router-flux'\n\nconst About = () => {\n const goToHome = () => {\n Actions.home()\n }\n return (\n <TouchableOpacity style = {{ margin: 128 }} onPress = {goToHome}>\n <Text>This is ABOUT</Text>\n </TouchableOpacity>\n )\n}\nexport default About" }, { "code": null, "e": 4895, "s": 4850, "text": "The app will render the initial Home screen." }, { "code": null, "e": 5030, "s": 4895, "text": "You can press the button to switch to the about screen. The Back arrow will appear; you can use it to get back to the previous screen." }, { "code": null, "e": 5065, "s": 5030, "text": "\n 20 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5079, "s": 5065, "text": " Anadi Sharma" }, { "code": null, "e": 5114, "s": 5079, "text": "\n 61 Lectures \n 6.5 hours \n" }, { "code": null, "e": 5129, "s": 5114, "text": " A To Z Mentor" }, { "code": null, "e": 5164, "s": 5129, "text": "\n 40 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5192, "s": 5164, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5228, "s": 5192, "text": "\n 56 Lectures \n 12.5 hours \n" }, { "code": null, "e": 5256, "s": 5228, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5291, "s": 5256, "text": "\n 62 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5303, "s": 5291, "text": " Senol Atac" }, { "code": null, "e": 5338, "s": 5303, "text": "\n 67 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5350, "s": 5338, "text": " Senol Atac" }, { "code": null, "e": 5357, "s": 5350, "text": " Print" }, { "code": null, "e": 5368, "s": 5357, "text": " Add Notes" } ]
Do You Read Excel Files with Python? There is a 1000x Faster Way. | by Nicolas Vandeput | Towards Data Science
As a Python user, I use excel files to load/store data as business people like to share data in excel or csv format. Unfortunately, Python is especially slow with Excel files. In this article, I’ll show you five ways to load data in Python. In the end, we’ll achieve a speedup of 3 orders of magnitude. It’ll be lightning-fast. Edit (18/07/2021): I found a way to make the process 5 times faster (resulting in a 5000x speedup). I added it as a bonus at the end of the article. Let’s imagine that we want to load 10 Excel files with 20000 rows and 25 columns (that’s around 70MB in total). This is a representative case where you want to load transactional data from an ERP (SAP) to Python to perform some analysis. Let’s populate this dummy data and import the required libraries (we’ll discuss pickle and joblib later in the article). import pandas as pdimport numpy as npfrom joblib import Parallel, delayedimport timefor file_number in range(10): values = np.random.uniform(size=(20000,25)) pd.DataFrame(values).to_csv(f”Dummy {file_number}.csv”) pd.DataFrame(values).to_excel(f”Dummy {file_number}.xlsx”) pd.DataFrame(values).to_pickle(f”Dummy {file_number}.pickle”) Let’s start with a straightforward way to load these files. We’ll create a first Pandas Dataframe and then append each Excel file to it. start = time.time()df = pd.read_excel(“Dummy 0.xlsx”)for file_number in range(1,10): df.append(pd.read_excel(f”Dummy {file_number}.xlsx”))end = time.time()print(“Excel:”, end — start)>> Excel: 53.4 It takes around 50 seconds to run. Pretty slow. Let’s now imagine that we saved these files as .csv (rather than .xlsx) from our ERP/System/SAP. start = time.time()df = pd.read_csv(“Dummy 0.csv”)for file_number in range(1,10): df.append(pd.read_csv(f”Dummy {file_number}.csv”))end = time.time()print(“CSV:”, end — start)>> CSV: 0.632 We can now load these files in 0.63 seconds. That’s nearly 10 times faster! Python loads CSV files 100 times faster than Excel files. Use CSVs. Con: csv files are nearly always bigger than .xlsx files. In this example .csv files are 9.5MB, whereas .xlsx are 6.4MB. We can speed up our process by changing the way we create our pandas DataFrames. Instead of appending each file to an existing DataFrame, We load each DataFrame independently in a list.Then concatenate the whole list in a single DataFrame. We load each DataFrame independently in a list. Then concatenate the whole list in a single DataFrame. start = time.time()df = []for file_number in range(10): temp = pd.read_csv(f”Dummy {file_number}.csv”) df.append(temp)df = pd.concat(df, ignore_index=True)end = time.time()print(“CSV2:”, end — start)>> CSV2: 0.619 We reduced the time by a few percent. Based on my experience, this trick will become useful when you deal with bigger Dataframes (df >> 100MB). We want to load 10 files in Python. Instead of loading each file one by one, why not loading them all, at once, in parallel? We can do this easily using joblib. start = time.time()def loop(file_number): return pd.read_csv(f”Dummy {file_number}.csv”)df = Parallel(n_jobs=-1, verbose=10)(delayed(loop)(file_number) for file_number in range(10))df = pd.concat(df, ignore_index=True)end = time.time()print(“CSV//:”, end — start)>> CSV//: 0.386 That’s nearly twice as fast as the single core version. However, as a general rule, do not expect to speed up your processes eightfold by using 8 cores (here, I got x2 speed up by using 8 cores on a Mac Air using the new M1 chip). Joblib is a simple Python library that allows you to run a function in //. In practice, joblib works as a list comprehension. Except each iteration is performed by a different thread. Here’s an example. def loop(file_number): return pd.read_csv(f”Dummy {file_number}.csv”)df = Parallel(n_jobs=-1, verbose=10)(delayed(loop)(file_number) for file_number in range(10))#equivalent todf = [loop(file_number) for file_number in range(10)] You can go (much) faster by storing data in pickle files — a specific format used by Python — rather than .csv files. Con: you won’t be able to manually open a pickle file and see what’s in it. start = time.time()def loop(file_number): return pd.read_pickle(f”Dummy {file_number}.pickle”)df = Parallel(n_jobs=-1, verbose=10)(delayed(loop)(file_number) for file_number in range(10))df = pd.concat(df, ignore_index=True)end = time.time()print(“Pickle//:”, end — start)>> Pickle//: 0.072 We just cut the running time by 80%! In general, it is much faster to work with pickle files than csv files. But, on the other hand, pickles files usually take more space on your drive (not in this specific example). In practice, you will not be able to extract data from a system directly in pickle files. I would advise using pickles in the two following cases: You want to save data from one of your Python processes (and you don’t plan on opening it on Excel) to use it later/in another process. Save your Dataframes as pickles instead of .csvYou need to reload the same file(s) multiple times. The first time you open a file, save it as a pickle so that you will be able to load the pickle version directly next time. Example: Imagine that you use transactional monthly data (each month you load a new month of data). You can save all historical data as .pickle and, each time you receive a new file, you can load it once as a .csv and then keep it as a .pickle for the next time. You want to save data from one of your Python processes (and you don’t plan on opening it on Excel) to use it later/in another process. Save your Dataframes as pickles instead of .csv You need to reload the same file(s) multiple times. The first time you open a file, save it as a pickle so that you will be able to load the pickle version directly next time. Example: Imagine that you use transactional monthly data (each month you load a new month of data). You can save all historical data as .pickle and, each time you receive a new file, you can load it once as a .csv and then keep it as a .pickle for the next time. Let’s imagine that you received excel files and that you have no other choice but to load them as is. You can also use joblib to parallelize this. Compared to our pickle code from above, we only need to update the loop function. start = time.time()def loop(file_number): return pd.read_excel(f"Dummy {file_number}.xlsx")df = Parallel(n_jobs=-1, verbose=10)(delayed(loop)(file_number) for file_number in range(10))df = pd.concat(df, ignore_index=True)end = time.time()print("Excel//:", end - start)>> 13.45 We could reduce the loading time by 70% (from 50 seconds to 13 seconds). You can also use this loop to create pickle files on the fly. So that, next time you load these files, you’ll be able to achieve lightning fast loading times. def loop(file_number): temp = pd.read_excel(f"Dummy {file_number}.xlsx") temp.to_pickle(f"Dummy {file_number}.pickle") return temp By loading pickle files in parallel, we decreased the loading time from 50 seconds to less than a tenth of a second. Excel: 50 seconds CSV: 0.63 seconds Smarter CSV: 0.62 seconds CSV in //: 0.34 seconds Pickle in //: 0.07 seconds Excel in //: 13.5 seconds Joblib allows to change the parallelization backend to remove some overheads. You can do this by giving prefer=”threads" to Parallel. We obtain a speed of around 0.0096 seconds (over 50 runs with a 2021 MacBook Air). Using prefer=”threads” with CSV and Excel parallelization gives the following results. As you can see using the “Thread” backend results in a worse score when reading Excel files. But to an astonishing performance with pickles (it takes 50 seconds to load Excel files one by one, and only 0.01 seconds to load the data reading pickles files in //). Nicolas Vandeput is a supply chain data scientist specialized in demand forecasting and inventory optimization. He founded his consultancy company SupChains in 2016 and co-founded SKU Science — a fast, simple, and affordable demand forecasting platform — in 2018. Passionate about education, Nicolas is both an avid learner and enjoys teaching at universities: he has taught forecasting and inventory optimization to master students since 2014 in Brussels, Belgium. Since 2020 he is also teaching both subjects at CentraleSupelec, Paris, France. He published Data Science for Supply Chain Forecasting in 2018 (2nd edition in 2021) and Inventory Optimization: Models and Simulations in 2020.
[ { "code": null, "e": 347, "s": 171, "text": "As a Python user, I use excel files to load/store data as business people like to share data in excel or csv format. Unfortunately, Python is especially slow with Excel files." }, { "code": null, "e": 499, "s": 347, "text": "In this article, I’ll show you five ways to load data in Python. In the end, we’ll achieve a speedup of 3 orders of magnitude. It’ll be lightning-fast." }, { "code": null, "e": 648, "s": 499, "text": "Edit (18/07/2021): I found a way to make the process 5 times faster (resulting in a 5000x speedup). I added it as a bonus at the end of the article." }, { "code": null, "e": 886, "s": 648, "text": "Let’s imagine that we want to load 10 Excel files with 20000 rows and 25 columns (that’s around 70MB in total). This is a representative case where you want to load transactional data from an ERP (SAP) to Python to perform some analysis." }, { "code": null, "e": 1007, "s": 886, "text": "Let’s populate this dummy data and import the required libraries (we’ll discuss pickle and joblib later in the article)." }, { "code": null, "e": 1342, "s": 1007, "text": "import pandas as pdimport numpy as npfrom joblib import Parallel, delayedimport timefor file_number in range(10): values = np.random.uniform(size=(20000,25)) pd.DataFrame(values).to_csv(f”Dummy {file_number}.csv”) pd.DataFrame(values).to_excel(f”Dummy {file_number}.xlsx”) pd.DataFrame(values).to_pickle(f”Dummy {file_number}.pickle”)" }, { "code": null, "e": 1479, "s": 1342, "text": "Let’s start with a straightforward way to load these files. We’ll create a first Pandas Dataframe and then append each Excel file to it." }, { "code": null, "e": 1677, "s": 1479, "text": "start = time.time()df = pd.read_excel(“Dummy 0.xlsx”)for file_number in range(1,10): df.append(pd.read_excel(f”Dummy {file_number}.xlsx”))end = time.time()print(“Excel:”, end — start)>> Excel: 53.4" }, { "code": null, "e": 1725, "s": 1677, "text": "It takes around 50 seconds to run. Pretty slow." }, { "code": null, "e": 1822, "s": 1725, "text": "Let’s now imagine that we saved these files as .csv (rather than .xlsx) from our ERP/System/SAP." }, { "code": null, "e": 2011, "s": 1822, "text": "start = time.time()df = pd.read_csv(“Dummy 0.csv”)for file_number in range(1,10): df.append(pd.read_csv(f”Dummy {file_number}.csv”))end = time.time()print(“CSV:”, end — start)>> CSV: 0.632" }, { "code": null, "e": 2087, "s": 2011, "text": "We can now load these files in 0.63 seconds. That’s nearly 10 times faster!" }, { "code": null, "e": 2155, "s": 2087, "text": "Python loads CSV files 100 times faster than Excel files. Use CSVs." }, { "code": null, "e": 2276, "s": 2155, "text": "Con: csv files are nearly always bigger than .xlsx files. In this example .csv files are 9.5MB, whereas .xlsx are 6.4MB." }, { "code": null, "e": 2414, "s": 2276, "text": "We can speed up our process by changing the way we create our pandas DataFrames. Instead of appending each file to an existing DataFrame," }, { "code": null, "e": 2516, "s": 2414, "text": "We load each DataFrame independently in a list.Then concatenate the whole list in a single DataFrame." }, { "code": null, "e": 2564, "s": 2516, "text": "We load each DataFrame independently in a list." }, { "code": null, "e": 2619, "s": 2564, "text": "Then concatenate the whole list in a single DataFrame." }, { "code": null, "e": 2833, "s": 2619, "text": "start = time.time()df = []for file_number in range(10): temp = pd.read_csv(f”Dummy {file_number}.csv”) df.append(temp)df = pd.concat(df, ignore_index=True)end = time.time()print(“CSV2:”, end — start)>> CSV2: 0.619" }, { "code": null, "e": 2977, "s": 2833, "text": "We reduced the time by a few percent. Based on my experience, this trick will become useful when you deal with bigger Dataframes (df >> 100MB)." }, { "code": null, "e": 3102, "s": 2977, "text": "We want to load 10 files in Python. Instead of loading each file one by one, why not loading them all, at once, in parallel?" }, { "code": null, "e": 3138, "s": 3102, "text": "We can do this easily using joblib." }, { "code": null, "e": 3417, "s": 3138, "text": "start = time.time()def loop(file_number): return pd.read_csv(f”Dummy {file_number}.csv”)df = Parallel(n_jobs=-1, verbose=10)(delayed(loop)(file_number) for file_number in range(10))df = pd.concat(df, ignore_index=True)end = time.time()print(“CSV//:”, end — start)>> CSV//: 0.386" }, { "code": null, "e": 3648, "s": 3417, "text": "That’s nearly twice as fast as the single core version. However, as a general rule, do not expect to speed up your processes eightfold by using 8 cores (here, I got x2 speed up by using 8 cores on a Mac Air using the new M1 chip)." }, { "code": null, "e": 3851, "s": 3648, "text": "Joblib is a simple Python library that allows you to run a function in //. In practice, joblib works as a list comprehension. Except each iteration is performed by a different thread. Here’s an example." }, { "code": null, "e": 4081, "s": 3851, "text": "def loop(file_number): return pd.read_csv(f”Dummy {file_number}.csv”)df = Parallel(n_jobs=-1, verbose=10)(delayed(loop)(file_number) for file_number in range(10))#equivalent todf = [loop(file_number) for file_number in range(10)]" }, { "code": null, "e": 4199, "s": 4081, "text": "You can go (much) faster by storing data in pickle files — a specific format used by Python — rather than .csv files." }, { "code": null, "e": 4275, "s": 4199, "text": "Con: you won’t be able to manually open a pickle file and see what’s in it." }, { "code": null, "e": 4566, "s": 4275, "text": "start = time.time()def loop(file_number): return pd.read_pickle(f”Dummy {file_number}.pickle”)df = Parallel(n_jobs=-1, verbose=10)(delayed(loop)(file_number) for file_number in range(10))df = pd.concat(df, ignore_index=True)end = time.time()print(“Pickle//:”, end — start)>> Pickle//: 0.072" }, { "code": null, "e": 4603, "s": 4566, "text": "We just cut the running time by 80%!" }, { "code": null, "e": 4783, "s": 4603, "text": "In general, it is much faster to work with pickle files than csv files. But, on the other hand, pickles files usually take more space on your drive (not in this specific example)." }, { "code": null, "e": 4873, "s": 4783, "text": "In practice, you will not be able to extract data from a system directly in pickle files." }, { "code": null, "e": 4930, "s": 4873, "text": "I would advise using pickles in the two following cases:" }, { "code": null, "e": 5552, "s": 4930, "text": "You want to save data from one of your Python processes (and you don’t plan on opening it on Excel) to use it later/in another process. Save your Dataframes as pickles instead of .csvYou need to reload the same file(s) multiple times. The first time you open a file, save it as a pickle so that you will be able to load the pickle version directly next time. Example: Imagine that you use transactional monthly data (each month you load a new month of data). You can save all historical data as .pickle and, each time you receive a new file, you can load it once as a .csv and then keep it as a .pickle for the next time." }, { "code": null, "e": 5736, "s": 5552, "text": "You want to save data from one of your Python processes (and you don’t plan on opening it on Excel) to use it later/in another process. Save your Dataframes as pickles instead of .csv" }, { "code": null, "e": 6175, "s": 5736, "text": "You need to reload the same file(s) multiple times. The first time you open a file, save it as a pickle so that you will be able to load the pickle version directly next time. Example: Imagine that you use transactional monthly data (each month you load a new month of data). You can save all historical data as .pickle and, each time you receive a new file, you can load it once as a .csv and then keep it as a .pickle for the next time." }, { "code": null, "e": 6404, "s": 6175, "text": "Let’s imagine that you received excel files and that you have no other choice but to load them as is. You can also use joblib to parallelize this. Compared to our pickle code from above, we only need to update the loop function." }, { "code": null, "e": 6684, "s": 6404, "text": "start = time.time()def loop(file_number): return pd.read_excel(f\"Dummy {file_number}.xlsx\")df = Parallel(n_jobs=-1, verbose=10)(delayed(loop)(file_number) for file_number in range(10))df = pd.concat(df, ignore_index=True)end = time.time()print(\"Excel//:\", end - start)>> 13.45" }, { "code": null, "e": 6757, "s": 6684, "text": "We could reduce the loading time by 70% (from 50 seconds to 13 seconds)." }, { "code": null, "e": 6916, "s": 6757, "text": "You can also use this loop to create pickle files on the fly. So that, next time you load these files, you’ll be able to achieve lightning fast loading times." }, { "code": null, "e": 7056, "s": 6916, "text": "def loop(file_number): temp = pd.read_excel(f\"Dummy {file_number}.xlsx\") temp.to_pickle(f\"Dummy {file_number}.pickle\") return temp" }, { "code": null, "e": 7173, "s": 7056, "text": "By loading pickle files in parallel, we decreased the loading time from 50 seconds to less than a tenth of a second." }, { "code": null, "e": 7191, "s": 7173, "text": "Excel: 50 seconds" }, { "code": null, "e": 7209, "s": 7191, "text": "CSV: 0.63 seconds" }, { "code": null, "e": 7235, "s": 7209, "text": "Smarter CSV: 0.62 seconds" }, { "code": null, "e": 7259, "s": 7235, "text": "CSV in //: 0.34 seconds" }, { "code": null, "e": 7286, "s": 7259, "text": "Pickle in //: 0.07 seconds" }, { "code": null, "e": 7312, "s": 7286, "text": "Excel in //: 13.5 seconds" }, { "code": null, "e": 7446, "s": 7312, "text": "Joblib allows to change the parallelization backend to remove some overheads. You can do this by giving prefer=”threads\" to Parallel." }, { "code": null, "e": 7529, "s": 7446, "text": "We obtain a speed of around 0.0096 seconds (over 50 runs with a 2021 MacBook Air)." }, { "code": null, "e": 7616, "s": 7529, "text": "Using prefer=”threads” with CSV and Excel parallelization gives the following results." }, { "code": null, "e": 7878, "s": 7616, "text": "As you can see using the “Thread” backend results in a worse score when reading Excel files. But to an astonishing performance with pickles (it takes 50 seconds to load Excel files one by one, and only 0.01 seconds to load the data reading pickles files in //)." } ]
Python: Key Value pair using argparse
03 Dec, 2021 The argparse module in Python helps create a program in a command-line-environment in a way that appears not only easy to code but also improves interaction. It also automatically generates help and usage messages and issues errors when users give the program invalid arguments. Creating a Parser: Importing argparse module is the first way of dealing with the concept. After you’ve imported it you have to create a parser or an ArgumentParser object that will store all the necessary information that has to be passed from the python command-line.Adding Arguments: Next step is to fill the ArgumentParser with information about the arguments of the program. This implies a call to the add_argument() method. These informations tell ArgumentParser how to take arguments from the command-line and turn them into objects.Parsing Arguments: The information gathered in step 2 is stored and used when arguments are parsed through parse_args(). The data is initially stored in sys.argv array in a string format. Calling parse_args() with the command-line data first converts them into the required data type and then invokes the appropriate action to produce a result. Creating a Parser: Importing argparse module is the first way of dealing with the concept. After you’ve imported it you have to create a parser or an ArgumentParser object that will store all the necessary information that has to be passed from the python command-line. Adding Arguments: Next step is to fill the ArgumentParser with information about the arguments of the program. This implies a call to the add_argument() method. These informations tell ArgumentParser how to take arguments from the command-line and turn them into objects. Parsing Arguments: The information gathered in step 2 is stored and used when arguments are parsed through parse_args(). The data is initially stored in sys.argv array in a string format. Calling parse_args() with the command-line data first converts them into the required data type and then invokes the appropriate action to produce a result. Key-Value Pair Using Argparse: To take arguments as key-value pairs, the input is first taken as a string, and using a python inbuilt method split() we are dividing it into two separate strings, here representing key and its value. In the next step, these made to fit into a dictionary form. Python3 #importing argparse moduleimport argparse # create a keyvalue classclass keyvalue(argparse.Action): # Constructor calling def __call__( self , parser, namespace, values, option_string = None): setattr(namespace, self.dest, dict()) for value in values: # split it into key and value key, value = value.split('=') # assign into dictionary getattr(namespace, self.dest)[key] = value # creating parser objectparser = argparse.ArgumentParser() # adding an arguments parser.add_argument('--kwargs', nargs='*', action = keyvalue) #parsing arguments args = parser.parse_args() # show the dictionaryprint(args.kwargs) Output: sagar0719kumar python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Dec, 2021" }, { "code": null, "e": 307, "s": 28, "text": "The argparse module in Python helps create a program in a command-line-environment in a way that appears not only easy to code but also improves interaction. It also automatically generates help and usage messages and issues errors when users give the program invalid arguments." }, { "code": null, "e": 1192, "s": 307, "text": "Creating a Parser: Importing argparse module is the first way of dealing with the concept. After you’ve imported it you have to create a parser or an ArgumentParser object that will store all the necessary information that has to be passed from the python command-line.Adding Arguments: Next step is to fill the ArgumentParser with information about the arguments of the program. This implies a call to the add_argument() method. These informations tell ArgumentParser how to take arguments from the command-line and turn them into objects.Parsing Arguments: The information gathered in step 2 is stored and used when arguments are parsed through parse_args(). The data is initially stored in sys.argv array in a string format. Calling parse_args() with the command-line data first converts them into the required data type and then invokes the appropriate action to produce a result." }, { "code": null, "e": 1462, "s": 1192, "text": "Creating a Parser: Importing argparse module is the first way of dealing with the concept. After you’ve imported it you have to create a parser or an ArgumentParser object that will store all the necessary information that has to be passed from the python command-line." }, { "code": null, "e": 1734, "s": 1462, "text": "Adding Arguments: Next step is to fill the ArgumentParser with information about the arguments of the program. This implies a call to the add_argument() method. These informations tell ArgumentParser how to take arguments from the command-line and turn them into objects." }, { "code": null, "e": 2079, "s": 1734, "text": "Parsing Arguments: The information gathered in step 2 is stored and used when arguments are parsed through parse_args(). The data is initially stored in sys.argv array in a string format. Calling parse_args() with the command-line data first converts them into the required data type and then invokes the appropriate action to produce a result." }, { "code": null, "e": 2372, "s": 2079, "text": "Key-Value Pair Using Argparse: To take arguments as key-value pairs, the input is first taken as a string, and using a python inbuilt method split() we are dividing it into two separate strings, here representing key and its value. In the next step, these made to fit into a dictionary form. " }, { "code": null, "e": 2380, "s": 2372, "text": "Python3" }, { "code": "#importing argparse moduleimport argparse # create a keyvalue classclass keyvalue(argparse.Action): # Constructor calling def __call__( self , parser, namespace, values, option_string = None): setattr(namespace, self.dest, dict()) for value in values: # split it into key and value key, value = value.split('=') # assign into dictionary getattr(namespace, self.dest)[key] = value # creating parser objectparser = argparse.ArgumentParser() # adding an arguments parser.add_argument('--kwargs', nargs='*', action = keyvalue) #parsing arguments args = parser.parse_args() # show the dictionaryprint(args.kwargs)", "e": 3125, "s": 2380, "text": null }, { "code": null, "e": 3134, "s": 3125, "text": "Output: " }, { "code": null, "e": 3151, "s": 3136, "text": "sagar0719kumar" }, { "code": null, "e": 3166, "s": 3151, "text": "python-modules" }, { "code": null, "e": 3173, "s": 3166, "text": "Python" }, { "code": null, "e": 3271, "s": 3173, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3303, "s": 3271, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3330, "s": 3303, "text": "Python Classes and Objects" }, { "code": null, "e": 3351, "s": 3330, "text": "Python OOPs Concepts" }, { "code": null, "e": 3374, "s": 3351, "text": "Introduction To PYTHON" }, { "code": null, "e": 3430, "s": 3374, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 3461, "s": 3430, "text": "Python | os.path.join() method" }, { "code": null, "e": 3503, "s": 3461, "text": "Check if element exists in list in Python" }, { "code": null, "e": 3545, "s": 3503, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 3584, "s": 3545, "text": "Python | Get unique values from a list" } ]
Difference between Entity constraints, Referential constraints and Semantic constraints
11 Oct, 2021 The data in a relational database is stored in form of a table. A table makes the data look organized. Yet in some cases we might face issues while working with the data like repetition. We might want enforce rules on the data to avoid such technical problems. Theses rules are called constraints. A constraint can be defined as a rule that has to enforced on the data to avoid faults. There are three kinds of constraints: entity, referential and semantic constraints. Listed below are the differences between these three constraints : 1. Entity constraints :These constraints are given within one table. The entity constraints are primary key, foreign key, unique. Example : create table student (rollnumber int primary key, name varchar2(30), course varchar2(10)); Insert into student values(111, 'ABC', 'Chemical'); Insert into student values(112, 'JJP', 'Mech'); These values are inserted in the table. Suppose a value given below is inserted : Insert into student values(111, 'MAB', 'EEE'); It gives an error as the roll-number is enforced a primary key constraint that refrains from duplication. These constraints ensures to maintain uniqueness in the tables to avoid duplication’s. 2. Referential constraints :These constraints are used for referring other tables to enforce conditions on the data. The widely used referential constraint is foreign key. Example : create table marks (rollnumber int, name varchar2(30), course varchar2(30) references student, marks int); A table is created with a constraint that the marks should be rewarded to those students that are pursuing courses stated in the student table only. If a user tries to enter a value that doesn’t exist, it returns an error. 3. Semantic constraints :Datatypes are the semantic constraints enforced in a table. Datatypes help the data segregate according to its type. Example :A name is a combination of different letters. We can place the name column in the char datatype yet char doesn’t satisfy the condition thereby varchar is preferably used for name. name varchar2(30); Difference between Entity constraints, Referential constraints and Semantic constraints : surindertarika1234 DBMS Difference Between SQL DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of Functional dependencies in DBMS MySQL | Regular expressions (Regexp) What is Temporary Table in SQL? Difference between OLAP and OLTP in DBMS Difference between Where and Having Clause in SQL Class method vs Static method in Python Difference between BFS and DFS Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Differences between JDK, JRE and JVM
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Oct, 2021" }, { "code": null, "e": 565, "s": 28, "text": "The data in a relational database is stored in form of a table. A table makes the data look organized. Yet in some cases we might face issues while working with the data like repetition. We might want enforce rules on the data to avoid such technical problems. Theses rules are called constraints. A constraint can be defined as a rule that has to enforced on the data to avoid faults. There are three kinds of constraints: entity, referential and semantic constraints. Listed below are the differences between these three constraints :" }, { "code": null, "e": 695, "s": 565, "text": "1. Entity constraints :These constraints are given within one table. The entity constraints are primary key, foreign key, unique." }, { "code": null, "e": 705, "s": 695, "text": "Example :" }, { "code": null, "e": 897, "s": 705, "text": "create table student (rollnumber int primary key, name varchar2(30), course varchar2(10));\nInsert into student values(111, 'ABC', 'Chemical');\nInsert into student values(112, 'JJP', 'Mech');\n" }, { "code": null, "e": 979, "s": 897, "text": "These values are inserted in the table. Suppose a value given below is inserted :" }, { "code": null, "e": 1027, "s": 979, "text": "Insert into student values(111, 'MAB', 'EEE');\n" }, { "code": null, "e": 1220, "s": 1027, "text": "It gives an error as the roll-number is enforced a primary key constraint that refrains from duplication. These constraints ensures to maintain uniqueness in the tables to avoid duplication’s." }, { "code": null, "e": 1392, "s": 1220, "text": "2. Referential constraints :These constraints are used for referring other tables to enforce conditions on the data. The widely used referential constraint is foreign key." }, { "code": null, "e": 1402, "s": 1392, "text": "Example :" }, { "code": null, "e": 1510, "s": 1402, "text": "create table marks (rollnumber int, name varchar2(30), course varchar2(30)\nreferences student, marks int);\n" }, { "code": null, "e": 1733, "s": 1510, "text": "A table is created with a constraint that the marks should be rewarded to those students that are pursuing courses stated in the student table only. If a user tries to enter a value that doesn’t exist, it returns an error." }, { "code": null, "e": 1875, "s": 1733, "text": "3. Semantic constraints :Datatypes are the semantic constraints enforced in a table. Datatypes help the data segregate according to its type." }, { "code": null, "e": 2064, "s": 1875, "text": "Example :A name is a combination of different letters. We can place the name column in the char datatype yet char doesn’t satisfy the condition thereby varchar is preferably used for name." }, { "code": null, "e": 2084, "s": 2064, "text": "name varchar2(30);\n" }, { "code": null, "e": 2174, "s": 2084, "text": "Difference between Entity constraints, Referential constraints and Semantic constraints :" }, { "code": null, "e": 2193, "s": 2174, "text": "surindertarika1234" }, { "code": null, "e": 2198, "s": 2193, "text": "DBMS" }, { "code": null, "e": 2217, "s": 2198, "text": "Difference Between" }, { "code": null, "e": 2221, "s": 2217, "text": "SQL" }, { "code": null, "e": 2226, "s": 2221, "text": "DBMS" }, { "code": null, "e": 2230, "s": 2226, "text": "SQL" }, { "code": null, "e": 2328, "s": 2230, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2369, "s": 2328, "text": "Types of Functional dependencies in DBMS" }, { "code": null, "e": 2406, "s": 2369, "text": "MySQL | Regular expressions (Regexp)" }, { "code": null, "e": 2438, "s": 2406, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 2479, "s": 2438, "text": "Difference between OLAP and OLTP in DBMS" }, { "code": null, "e": 2529, "s": 2479, "text": "Difference between Where and Having Clause in SQL" }, { "code": null, "e": 2569, "s": 2529, "text": "Class method vs Static method in Python" }, { "code": null, "e": 2600, "s": 2569, "text": "Difference between BFS and DFS" }, { "code": null, "e": 2661, "s": 2600, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2729, "s": 2661, "text": "Difference Between Method Overloading and Method Overriding in Java" } ]
Node.js MySQL-Create Table Using Sequelize
18 Nov, 2021 Introduction to Sequelize: Sequelize is a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server. Its features are solid transaction support, relations, eager and lazy loading, read replication and many more. Connect to MySql Database using Sequelize: To establish connection between MySQL and Node.js using Sequelize, visit How to use Sequelize in Node.js. After getting connected successfully, we would have required three files:SequelizeDemo>app.js which is our root file.SequelizeDemo>utils>database.js which is responsible for MySql connection.SequelizeDemo>models>user.js which is responsible for defining the model. SequelizeDemo>app.js which is our root file.SequelizeDemo>utils>database.js which is responsible for MySql connection.SequelizeDemo>models>user.js which is responsible for defining the model. SequelizeDemo>app.js which is our root file. SequelizeDemo>utils>database.js which is responsible for MySql connection. SequelizeDemo>models>user.js which is responsible for defining the model. Configure database.js: SequelizeDemo>utils>database.js Establish connection is the way mentioned in article How to use Sequelize in Node.js and now, we can use that exported sequelize object from SequelizeDemo>utils>database.js to define our models. Note: Make sure the database that you are using is created in your database. Configure user.js: Use SequelizeDemo>models>user.js file to define mappings between a model and a table, use the define method. Javascript // Include Sequelize module.const Sequelize = require('sequelize') // Import sequelize object, // Database connection pool managed by Sequelize.const sequelize = require('../utils/database') // Define method takes two arguments// 1st - name of table// 2nd - columns inside the tableconst User = sequelize.define('user', { // Column-1, user_id is an object with // properties like type, keys, // validation of column. user_id:{ // Sequelize module has INTEGER Data_Type. type:Sequelize.INTEGER, // To increment user_id automatically. autoIncrement:true, // user_id can not be null. allowNull:false, // For uniquely identify user. primaryKey:true }, // Column-2, name name: { type: Sequelize.STRING, allowNull:false }, // Column-3, email email: { type: Sequelize.STRING, allowNull:false }, // Column-4, default values for // dates => current time myDate: { type: Sequelize.DATE, defaultValue: Sequelize.NOW }, // Timestamps createdAt: Sequelize.DATE, updatedAt: Sequelize.DATE,}) // Exporting User, using this constant// we can perform CRUD operations on// 'user' table.module.exports = User To know more about Sequelize Data Types visit Datatypes. In SequelizeDemo>models>user.js file, we have defined the model. Configure app.js: Filename => SequelizeDemo>app.js To create the model, we can use one of the following way- sync() Method: This method will create model if the model does not exist, however, if already exist it would not overwrite it.sync({force:true}) Method: This method will create model if the model does not exist, however, if already exist it would overwrite it. sync() Method: This method will create model if the model does not exist, however, if already exist it would not overwrite it. sync({force:true}) Method: This method will create model if the model does not exist, however, if already exist it would overwrite it. Javascript // Import the sequelize object on which // we have defined model. const sequelize = require('./utils/database') // Import the user model we have defined const User = require('./models/user) // Create all the table defined using // sequelize in Database // Sync all models that are not // already in the database sequelize.sync() // Force sync all models // It will drop the table first // and re-create it afterwards sequelize.sync({force:true}) Database Synchronization: When starting a new project you won’t have a database structure and using Sequelize you won’t need to. Just specify your model structures and let the library do the rest. Steps to run the program: The project structure will look like this: Install required modules for this project: npm install mysql2 npm install sequelize Execute app.js (root file) using below command: node app.js In MySql Database, now we can describe User model we have created using Sequelize. Use the below commands use database geeksforgeeks desc users; simmytarika5 harshrawal8295 NodeJS-Questions Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Node.js fs.writeFile() Method How to install the previous version of node.js and npm ? Difference between promise and async await in Node.js Mongoose | findByIdAndUpdate() Function JWT Authentication with Node.js Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 54, "s": 26, "text": "\n18 Nov, 2021" }, { "code": null, "e": 296, "s": 54, "text": "Introduction to Sequelize: Sequelize is a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server. Its features are solid transaction support, relations, eager and lazy loading, read replication and many more." }, { "code": null, "e": 340, "s": 296, "text": "Connect to MySql Database using Sequelize: " }, { "code": null, "e": 446, "s": 340, "text": "To establish connection between MySQL and Node.js using Sequelize, visit How to use Sequelize in Node.js." }, { "code": null, "e": 711, "s": 446, "text": "After getting connected successfully, we would have required three files:SequelizeDemo>app.js which is our root file.SequelizeDemo>utils>database.js which is responsible for MySql connection.SequelizeDemo>models>user.js which is responsible for defining the model." }, { "code": null, "e": 903, "s": 711, "text": "SequelizeDemo>app.js which is our root file.SequelizeDemo>utils>database.js which is responsible for MySql connection.SequelizeDemo>models>user.js which is responsible for defining the model." }, { "code": null, "e": 948, "s": 903, "text": "SequelizeDemo>app.js which is our root file." }, { "code": null, "e": 1023, "s": 948, "text": "SequelizeDemo>utils>database.js which is responsible for MySql connection." }, { "code": null, "e": 1097, "s": 1023, "text": "SequelizeDemo>models>user.js which is responsible for defining the model." }, { "code": null, "e": 1153, "s": 1097, "text": "Configure database.js: SequelizeDemo>utils>database.js " }, { "code": null, "e": 1348, "s": 1153, "text": "Establish connection is the way mentioned in article How to use Sequelize in Node.js and now, we can use that exported sequelize object from SequelizeDemo>utils>database.js to define our models." }, { "code": null, "e": 1425, "s": 1348, "text": "Note: Make sure the database that you are using is created in your database." }, { "code": null, "e": 1446, "s": 1425, "text": "Configure user.js: " }, { "code": null, "e": 1555, "s": 1446, "text": "Use SequelizeDemo>models>user.js file to define mappings between a model and a table, use the define method." }, { "code": null, "e": 1566, "s": 1555, "text": "Javascript" }, { "code": "// Include Sequelize module.const Sequelize = require('sequelize') // Import sequelize object, // Database connection pool managed by Sequelize.const sequelize = require('../utils/database') // Define method takes two arguments// 1st - name of table// 2nd - columns inside the tableconst User = sequelize.define('user', { // Column-1, user_id is an object with // properties like type, keys, // validation of column. user_id:{ // Sequelize module has INTEGER Data_Type. type:Sequelize.INTEGER, // To increment user_id automatically. autoIncrement:true, // user_id can not be null. allowNull:false, // For uniquely identify user. primaryKey:true }, // Column-2, name name: { type: Sequelize.STRING, allowNull:false }, // Column-3, email email: { type: Sequelize.STRING, allowNull:false }, // Column-4, default values for // dates => current time myDate: { type: Sequelize.DATE, defaultValue: Sequelize.NOW }, // Timestamps createdAt: Sequelize.DATE, updatedAt: Sequelize.DATE,}) // Exporting User, using this constant// we can perform CRUD operations on// 'user' table.module.exports = User", "e": 2795, "s": 1566, "text": null }, { "code": null, "e": 2852, "s": 2795, "text": "To know more about Sequelize Data Types visit Datatypes." }, { "code": null, "e": 2917, "s": 2852, "text": "In SequelizeDemo>models>user.js file, we have defined the model." }, { "code": null, "e": 2937, "s": 2917, "text": "Configure app.js: " }, { "code": null, "e": 2971, "s": 2937, "text": "Filename => SequelizeDemo>app.js " }, { "code": null, "e": 3291, "s": 2971, "text": "To create the model, we can use one of the following way- sync() Method: This method will create model if the model does not exist, however, if already exist it would not overwrite it.sync({force:true}) Method: This method will create model if the model does not exist, however, if already exist it would overwrite it. " }, { "code": null, "e": 3418, "s": 3291, "text": "sync() Method: This method will create model if the model does not exist, however, if already exist it would not overwrite it." }, { "code": null, "e": 3554, "s": 3418, "text": "sync({force:true}) Method: This method will create model if the model does not exist, however, if already exist it would overwrite it. " }, { "code": null, "e": 3565, "s": 3554, "text": "Javascript" }, { "code": "// Import the sequelize object on which // we have defined model. const sequelize = require('./utils/database') // Import the user model we have defined const User = require('./models/user) // Create all the table defined using // sequelize in Database // Sync all models that are not // already in the database sequelize.sync() // Force sync all models // It will drop the table first // and re-create it afterwards sequelize.sync({force:true})", "e": 4030, "s": 3565, "text": null }, { "code": null, "e": 4227, "s": 4030, "text": "Database Synchronization: When starting a new project you won’t have a database structure and using Sequelize you won’t need to. Just specify your model structures and let the library do the rest." }, { "code": null, "e": 4255, "s": 4227, "text": "Steps to run the program: " }, { "code": null, "e": 4300, "s": 4255, "text": "The project structure will look like this: " }, { "code": null, "e": 4344, "s": 4300, "text": "Install required modules for this project: " }, { "code": null, "e": 4385, "s": 4344, "text": "npm install mysql2\nnpm install sequelize" }, { "code": null, "e": 4434, "s": 4385, "text": "Execute app.js (root file) using below command: " }, { "code": null, "e": 4446, "s": 4434, "text": "node app.js" }, { "code": null, "e": 4553, "s": 4446, "text": "In MySql Database, now we can describe User model we have created using Sequelize. Use the below commands " }, { "code": null, "e": 4592, "s": 4553, "text": "use database geeksforgeeks\ndesc users;" }, { "code": null, "e": 4607, "s": 4594, "text": "simmytarika5" }, { "code": null, "e": 4622, "s": 4607, "text": "harshrawal8295" }, { "code": null, "e": 4639, "s": 4622, "text": "NodeJS-Questions" }, { "code": null, "e": 4647, "s": 4639, "text": "Node.js" }, { "code": null, "e": 4664, "s": 4647, "text": "Web Technologies" }, { "code": null, "e": 4762, "s": 4664, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4792, "s": 4762, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 4849, "s": 4792, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 4903, "s": 4849, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 4943, "s": 4903, "text": "Mongoose | findByIdAndUpdate() Function" }, { "code": null, "e": 4975, "s": 4943, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 5037, "s": 4975, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 5098, "s": 5037, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5148, "s": 5098, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 5191, "s": 5148, "text": "How to fetch data from an API in ReactJS ?" } ]
Command Method – Python Design Patterns
07 Oct, 2021 Command Method is Behavioral Design Pattern that encapsulates a request as an object, thereby allowing for the parameterization of clients with different requests and the queuing or logging of requests. Parameterizing other objects with different requests in our analogy means that the button used to turn on the lights can later be used to turn on stereo or maybe open the garage door. It helps in promoting the “invocation of a method on an object” to full object status. Basically, it encapsulates all the information needed to perform an action or trigger an event. Imagine you are working on a code editor. Your current task is to add the new buttons in the toolbar of the editor for various different operations. It’s definitely easy to create a single Button Class that can be used for the buttons. As we know that all the buttons used in the editor look similar, so what should we do? Should we create a lot of sub-classes for each place where the button is used? Problem-without-Command-method Let’s have a look at the solution for the above-described problem. It’s always a good idea to divide the software into different layers which helps in easy coding as well as debugging. The command pattern suggests that objects shouldn’t send these requests directly. Instead, you should extract all of the request details, such as the object being called, the name of the method and the list of arguments into a separate command class with a single method that triggers this request. Python3 """Use built-in abc to implement Abstract classes and methods"""from abc import ABC, abstractmethod """Class Dedicated to Command"""class Command(ABC): """constructor method""" def __init__(self, receiver): self.receiver = receiver """process method""" def process(self): pass """Class dedicated to Command Implementation"""class CommandImplementation(Command): """constructor method""" def __init__(self, receiver): self.receiver = receiver """process method""" def process(self): self.receiver.perform_action() """Class dedicated to Receiver"""class Receiver: """perform-action method""" def perform_action(self): print('Action performed in receiver.') """Class dedicated to Invoker"""class Invoker: """command method""" def command(self, cmd): self.cmd = cmd """execute method""" def execute(self): self.cmd.process() """main method"""if __name__ == "__main__": """create Receiver object""" receiver = Receiver() cmd = CommandImplementation(receiver) invoker = Invoker() invoker.command(cmd) invoker.execute() Action performed in receiver. Following is the class diagram for the Command method Class-diagram-Command-Method Open/Closed Principle: We can introduce the new commands into the application without breaking the existing client’s code. Single Responsibility Principle: It’s really easy to decouple the classes here that invoke operations from other classes. Implementable UNDO/REDO: It’s possible to implement the functionalities of UNDO/REDO with the help of Command method. Encapsulation: It helps in encapsulating all the information needed to perform an action or an event. Complexity Increases: The complexity of the code increases as we are introducing certain layers between the senders and the receivers. Quantity of classes increases: For each individual command, the quantity of the classes increases. Concrete Command: Every individual command is a ConcreteCommand class that increases the volume of the classes for implementation and maintenance. Implementing Reversible operations: As the Command method provides the functionalities for UNDO/REDO operations, we can possibly reverse the operations. Parameterization: It’s always preferred to use Command method when we have to parameterize the objects with the operations. Further Read – Command Method in Java sweetyty sagar0719kumar python-design-pattern Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python | os.path.join() method Introduction To PYTHON Python OOPs Concepts How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Oct, 2021" }, { "code": null, "e": 598, "s": 28, "text": "Command Method is Behavioral Design Pattern that encapsulates a request as an object, thereby allowing for the parameterization of clients with different requests and the queuing or logging of requests. Parameterizing other objects with different requests in our analogy means that the button used to turn on the lights can later be used to turn on stereo or maybe open the garage door. It helps in promoting the “invocation of a method on an object” to full object status. Basically, it encapsulates all the information needed to perform an action or trigger an event." }, { "code": null, "e": 1000, "s": 598, "text": "Imagine you are working on a code editor. Your current task is to add the new buttons in the toolbar of the editor for various different operations. It’s definitely easy to create a single Button Class that can be used for the buttons. As we know that all the buttons used in the editor look similar, so what should we do? Should we create a lot of sub-classes for each place where the button is used?" }, { "code": null, "e": 1031, "s": 1000, "text": "Problem-without-Command-method" }, { "code": null, "e": 1515, "s": 1031, "text": "Let’s have a look at the solution for the above-described problem. It’s always a good idea to divide the software into different layers which helps in easy coding as well as debugging. The command pattern suggests that objects shouldn’t send these requests directly. Instead, you should extract all of the request details, such as the object being called, the name of the method and the list of arguments into a separate command class with a single method that triggers this request." }, { "code": null, "e": 1523, "s": 1515, "text": "Python3" }, { "code": "\"\"\"Use built-in abc to implement Abstract classes and methods\"\"\"from abc import ABC, abstractmethod \"\"\"Class Dedicated to Command\"\"\"class Command(ABC): \"\"\"constructor method\"\"\" def __init__(self, receiver): self.receiver = receiver \"\"\"process method\"\"\" def process(self): pass \"\"\"Class dedicated to Command Implementation\"\"\"class CommandImplementation(Command): \"\"\"constructor method\"\"\" def __init__(self, receiver): self.receiver = receiver \"\"\"process method\"\"\" def process(self): self.receiver.perform_action() \"\"\"Class dedicated to Receiver\"\"\"class Receiver: \"\"\"perform-action method\"\"\" def perform_action(self): print('Action performed in receiver.') \"\"\"Class dedicated to Invoker\"\"\"class Invoker: \"\"\"command method\"\"\" def command(self, cmd): self.cmd = cmd \"\"\"execute method\"\"\" def execute(self): self.cmd.process() \"\"\"main method\"\"\"if __name__ == \"__main__\": \"\"\"create Receiver object\"\"\" receiver = Receiver() cmd = CommandImplementation(receiver) invoker = Invoker() invoker.command(cmd) invoker.execute()", "e": 2690, "s": 1523, "text": null }, { "code": null, "e": 2720, "s": 2690, "text": "Action performed in receiver." }, { "code": null, "e": 2774, "s": 2720, "text": "Following is the class diagram for the Command method" }, { "code": null, "e": 2803, "s": 2774, "text": "Class-diagram-Command-Method" }, { "code": null, "e": 2926, "s": 2803, "text": "Open/Closed Principle: We can introduce the new commands into the application without breaking the existing client’s code." }, { "code": null, "e": 3048, "s": 2926, "text": "Single Responsibility Principle: It’s really easy to decouple the classes here that invoke operations from other classes." }, { "code": null, "e": 3166, "s": 3048, "text": "Implementable UNDO/REDO: It’s possible to implement the functionalities of UNDO/REDO with the help of Command method." }, { "code": null, "e": 3268, "s": 3166, "text": "Encapsulation: It helps in encapsulating all the information needed to perform an action or an event." }, { "code": null, "e": 3403, "s": 3268, "text": "Complexity Increases: The complexity of the code increases as we are introducing certain layers between the senders and the receivers." }, { "code": null, "e": 3502, "s": 3403, "text": "Quantity of classes increases: For each individual command, the quantity of the classes increases." }, { "code": null, "e": 3649, "s": 3502, "text": "Concrete Command: Every individual command is a ConcreteCommand class that increases the volume of the classes for implementation and maintenance." }, { "code": null, "e": 3802, "s": 3649, "text": "Implementing Reversible operations: As the Command method provides the functionalities for UNDO/REDO operations, we can possibly reverse the operations." }, { "code": null, "e": 3926, "s": 3802, "text": "Parameterization: It’s always preferred to use Command method when we have to parameterize the objects with the operations." }, { "code": null, "e": 3965, "s": 3926, "text": "Further Read – Command Method in Java " }, { "code": null, "e": 3974, "s": 3965, "text": "sweetyty" }, { "code": null, "e": 3989, "s": 3974, "text": "sagar0719kumar" }, { "code": null, "e": 4011, "s": 3989, "text": "python-design-pattern" }, { "code": null, "e": 4018, "s": 4011, "text": "Python" }, { "code": null, "e": 4116, "s": 4018, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4148, "s": 4116, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4175, "s": 4148, "text": "Python Classes and Objects" }, { "code": null, "e": 4206, "s": 4175, "text": "Python | os.path.join() method" }, { "code": null, "e": 4229, "s": 4206, "text": "Introduction To PYTHON" }, { "code": null, "e": 4250, "s": 4229, "text": "Python OOPs Concepts" }, { "code": null, "e": 4306, "s": 4250, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 4348, "s": 4306, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 4390, "s": 4348, "text": "Check if element exists in list in Python" }, { "code": null, "e": 4429, "s": 4390, "text": "Python | Get unique values from a list" } ]
Foreach in C++ and Java
09 Jun, 2022 Foreach loop is used to iterate over the elements of a containers (array, vectors etc) quickly without performing initialization, testing and increment/decrement. The working of foreach loops is to do something for every element rather than doing something n times. There is no foreach loop in C, but both C++ and Java have support for foreach type of loop. In C++, it was introduced in C++ 11 and Java in JDK 1.5.0 The keyword used for foreach loop is “for” in both C++ and Java. Syntax: for (data_type variable_name : container_type) { operations using variable_name } With the introduction of auto keyword in C++ and var keyword in Java, we no longer need to specify data type for the variable in foreach loop. Type inference detects the data type of the container and automatically sets the same data type to the variable used for traversing. Below code displays the use case of foreach loop for different containers along with auto/var keywords in C++/Java. C++/Java Program for array: C++ Java // C++ program to demonstrate use of foreach for array#include <iostream>using namespace std; int main(){ int arr[] = { 10, 20, 30, 40 }; // Printing elements of an array using // foreach loop // Here, int is the data type, x is the variable name // and arr is the array for which we want to iterate foreach cout<<"Traversing the array with foreach using array's data type: "; for (int x : arr) cout<<x<<" "; // data type of x is set as int cout<<"\nTraversing the array with foreach using auto keyword : "; for (auto x : arr) cout<<x<<" ";} // Java program to demonstrate use of foreachpublic class Main { public static void main(String[] args) { // Declaring 1-D array with size 4 int arr[] = { 10, 20, 30, 40 }; // Printing elements of an array using // foreach loop // Here, int is the data type, x is the variable name // and arr is the array for which we want to iterate foreach System.out.print("Traversing the array with foreach using array's data type: "); for (int x : arr) System.out.print(x+" "); // data type of x is set as int System.out.print("\nTraversing the array with foreach using auto keyword : "); for (var x : arr) System.out.print(x+" "); }} Traversing the array with foreach using array's data type: 10 20 30 40 Traversing the array with foreach using auto keyword : 10 20 30 40 C++ Program for vector: C++ #include <iostream>#include <vector>using namespace std; int main() { vector<string> value{"This", "is", "foreach", "example", "using", "vector."}; cout<<"Traversing the vector with foreach using vector's data type: "; for (string v : value) { cout<<v<<" "; } cout<<"\nTraversing the vector with foreach using auto keyword : "; for (auto v : value) cout<<v<<" "; return 0;} Traversing the vector with foreach using vector's data type: This is foreach example using vector. Traversing the vector with foreach using auto keyword : This is foreach example using vector. C++/Java Program for set: C++ Java #include <iostream>#include <set>using namespace std; int main() { set<int> value = {6, 2, 7, 4, 10, 5, 1}; cout<<"Traversing the set with foreach using set's data type: "; for (int v : value) { cout<<v<<" "; } cout<<"\nTraversing the set with foreach using auto keyword : "; for (auto v : value) cout<<v<<" "; return 0;} import java.util.*; public class GFG { public static void main(String[] args) { Set<String> hash_Set = new HashSet<String>(); hash_Set.add("Geeks"); hash_Set.add("For"); hash_Set.add("Geeks"); hash_Set.add("Foreach"); hash_Set.add("Example"); hash_Set.add("Set"); System.out.print("Traversing the set with foreach using set's data type: "); for(String hs : hash_Set) { System.out.print(hs+" "); } System.out.print("\nTraversing the set with foreach using auto keyword : "); for (var hs : hash_Set) { System.out.print(hs+" "); } }} Traversing the set with foreach using set's data type: 1 2 4 5 6 7 10 Traversing the set with foreach using auto keyword : 1 2 4 5 6 7 10 Note: We can use different data types in foreach for array, vector and set. C++/Java Program for map: C++14 Java #include <iostream>#include <map>using namespace std; int main() { map<int, string> mapExample; mapExample.insert(pair<int, string>(1, "Geeks")); mapExample.insert(pair<int, string>(2, "4")); mapExample.insert(pair<int, string>(3, "Geeks")); mapExample.insert(pair<int, string>(4, "Map")); mapExample.insert(pair<int, string>(5, "Foreach")); mapExample.insert(pair<int, string>(6, "Example")); cout<<"Traversing the map with foreach using map's data type\n"; for (pair<int, string> mpEx : mapExample ) { cout<<mpEx.first<<" "<<mpEx.second<<endl; } cout<<"\nTraversing the map with foreach using auto keyword\n"; for (auto mpEx : mapExample){ cout<<mpEx.first<<" "<<mpEx.second<<endl; } return 0;} import java.io.*;import java.util.Map;import java.util.HashMap; class GFG { public static void main (String[] args) { Map<Integer,String> gfg = new HashMap<Integer,String>(); gfg.put(1, "Geeks"); gfg.put(2, "4"); gfg.put(3, "Geeks"); gfg.put(4, "Map"); gfg.put(5, "Foreach"); gfg.put(6, "Example"); System.out.println("Traversing the map with foreach using map's data type"); for (Map.Entry<Integer, String> entry : gfg.entrySet()) System.out.println(entry.getKey() + " " + entry.getValue()); System.out.println("\nTraversing the map with foreach using auto keyword"); for (var entry : gfg.entrySet()) System.out.println(entry.getKey() + " " + entry.getValue()); }} Traversing the map with foreach using map's data type 1 Geeks 2 4 3 Geeks 4 Map 5 Foreach 6 Example Traversing the map with foreach using auto keyword 1 Geeks 2 4 3 Geeks 4 Map 5 Foreach 6 Example Advantages of foreach loop: Makes the code more readable. Eliminates the errors of over-running or under-running the data. Disadvantage of foreach loop: Cannot iterate over the elements in reverse order. Each and every element will be accessed, cannot skip any elements in between. gyanendra371 XD_DX shubham_singh SoldMonk cpp-advanced C++ Java Java CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bitwise Operators in C/C++ Set in C++ Standard Template Library (STL) vector erase() and clear() in C++ unordered_map in C++ STL Inheritance in C++ Arrays in Java Split() String method in Java with examples Arrays.sort() in Java with examples Object Oriented Programming (OOPs) Concept in Java Reverse a string in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n09 Jun, 2022" }, { "code": null, "e": 535, "s": 52, "text": "Foreach loop is used to iterate over the elements of a containers (array, vectors etc) quickly without performing initialization, testing and increment/decrement. The working of foreach loops is to do something for every element rather than doing something n times. There is no foreach loop in C, but both C++ and Java have support for foreach type of loop. In C++, it was introduced in C++ 11 and Java in JDK 1.5.0 The keyword used for foreach loop is “for” in both C++ and Java. " }, { "code": null, "e": 543, "s": 535, "text": "Syntax:" }, { "code": null, "e": 593, "s": 543, "text": "for (data_type variable_name : container_type) {" }, { "code": null, "e": 629, "s": 593, "text": " operations using variable_name" }, { "code": null, "e": 631, "s": 629, "text": "}" }, { "code": null, "e": 907, "s": 631, "text": "With the introduction of auto keyword in C++ and var keyword in Java, we no longer need to specify data type for the variable in foreach loop. Type inference detects the data type of the container and automatically sets the same data type to the variable used for traversing." }, { "code": null, "e": 1024, "s": 907, "text": "Below code displays the use case of foreach loop for different containers along with auto/var keywords in C++/Java. " }, { "code": null, "e": 1053, "s": 1024, "text": "C++/Java Program for array: " }, { "code": null, "e": 1057, "s": 1053, "text": "C++" }, { "code": null, "e": 1062, "s": 1057, "text": "Java" }, { "code": "// C++ program to demonstrate use of foreach for array#include <iostream>using namespace std; int main(){ int arr[] = { 10, 20, 30, 40 }; // Printing elements of an array using // foreach loop // Here, int is the data type, x is the variable name // and arr is the array for which we want to iterate foreach cout<<\"Traversing the array with foreach using array's data type: \"; for (int x : arr) cout<<x<<\" \"; // data type of x is set as int cout<<\"\\nTraversing the array with foreach using auto keyword : \"; for (auto x : arr) cout<<x<<\" \";}", "e": 1664, "s": 1062, "text": null }, { "code": "// Java program to demonstrate use of foreachpublic class Main { public static void main(String[] args) { // Declaring 1-D array with size 4 int arr[] = { 10, 20, 30, 40 }; // Printing elements of an array using // foreach loop // Here, int is the data type, x is the variable name // and arr is the array for which we want to iterate foreach System.out.print(\"Traversing the array with foreach using array's data type: \"); for (int x : arr) System.out.print(x+\" \"); // data type of x is set as int System.out.print(\"\\nTraversing the array with foreach using auto keyword : \"); for (var x : arr) System.out.print(x+\" \"); }}", "e": 2416, "s": 1664, "text": null }, { "code": null, "e": 2560, "s": 2416, "text": "Traversing the array with foreach using array's data type: 10 20 30 40 \nTraversing the array with foreach using auto keyword : 10 20 30 40 " }, { "code": null, "e": 2584, "s": 2560, "text": "C++ Program for vector:" }, { "code": null, "e": 2588, "s": 2584, "text": "C++" }, { "code": "#include <iostream>#include <vector>using namespace std; int main() { vector<string> value{\"This\", \"is\", \"foreach\", \"example\", \"using\", \"vector.\"}; cout<<\"Traversing the vector with foreach using vector's data type: \"; for (string v : value) { cout<<v<<\" \"; } cout<<\"\\nTraversing the vector with foreach using auto keyword : \"; for (auto v : value) cout<<v<<\" \"; return 0;}", "e": 3011, "s": 2588, "text": null }, { "code": null, "e": 3211, "s": 3011, "text": "Traversing the vector with foreach using vector's data type: This is foreach example using vector. \nTraversing the vector with foreach using auto keyword : This is foreach example using vector. " }, { "code": null, "e": 3237, "s": 3211, "text": "C++/Java Program for set:" }, { "code": null, "e": 3241, "s": 3237, "text": "C++" }, { "code": null, "e": 3246, "s": 3241, "text": "Java" }, { "code": "#include <iostream>#include <set>using namespace std; int main() { set<int> value = {6, 2, 7, 4, 10, 5, 1}; cout<<\"Traversing the set with foreach using set's data type: \"; for (int v : value) { cout<<v<<\" \"; } cout<<\"\\nTraversing the set with foreach using auto keyword : \"; for (auto v : value) cout<<v<<\" \"; return 0;}", "e": 3617, "s": 3246, "text": null }, { "code": "import java.util.*; public class GFG { public static void main(String[] args) { Set<String> hash_Set = new HashSet<String>(); hash_Set.add(\"Geeks\"); hash_Set.add(\"For\"); hash_Set.add(\"Geeks\"); hash_Set.add(\"Foreach\"); hash_Set.add(\"Example\"); hash_Set.add(\"Set\"); System.out.print(\"Traversing the set with foreach using set's data type: \"); for(String hs : hash_Set) { System.out.print(hs+\" \"); } System.out.print(\"\\nTraversing the set with foreach using auto keyword : \"); for (var hs : hash_Set) { System.out.print(hs+\" \"); } }}", "e": 4302, "s": 3617, "text": null }, { "code": null, "e": 4444, "s": 4302, "text": "Traversing the set with foreach using set's data type: 1 2 4 5 6 7 10 \nTraversing the set with foreach using auto keyword : 1 2 4 5 6 7 10 " }, { "code": null, "e": 4520, "s": 4444, "text": "Note: We can use different data types in foreach for array, vector and set." }, { "code": null, "e": 4546, "s": 4520, "text": "C++/Java Program for map:" }, { "code": null, "e": 4552, "s": 4546, "text": "C++14" }, { "code": null, "e": 4557, "s": 4552, "text": "Java" }, { "code": "#include <iostream>#include <map>using namespace std; int main() { map<int, string> mapExample; mapExample.insert(pair<int, string>(1, \"Geeks\")); mapExample.insert(pair<int, string>(2, \"4\")); mapExample.insert(pair<int, string>(3, \"Geeks\")); mapExample.insert(pair<int, string>(4, \"Map\")); mapExample.insert(pair<int, string>(5, \"Foreach\")); mapExample.insert(pair<int, string>(6, \"Example\")); cout<<\"Traversing the map with foreach using map's data type\\n\"; for (pair<int, string> mpEx : mapExample ) { cout<<mpEx.first<<\" \"<<mpEx.second<<endl; } cout<<\"\\nTraversing the map with foreach using auto keyword\\n\"; for (auto mpEx : mapExample){ cout<<mpEx.first<<\" \"<<mpEx.second<<endl; } return 0;}", "e": 5328, "s": 4557, "text": null }, { "code": "import java.io.*;import java.util.Map;import java.util.HashMap; class GFG { public static void main (String[] args) { Map<Integer,String> gfg = new HashMap<Integer,String>(); gfg.put(1, \"Geeks\"); gfg.put(2, \"4\"); gfg.put(3, \"Geeks\"); gfg.put(4, \"Map\"); gfg.put(5, \"Foreach\"); gfg.put(6, \"Example\"); System.out.println(\"Traversing the map with foreach using map's data type\"); for (Map.Entry<Integer, String> entry : gfg.entrySet()) System.out.println(entry.getKey() + \" \" + entry.getValue()); System.out.println(\"\\nTraversing the map with foreach using auto keyword\"); for (var entry : gfg.entrySet()) System.out.println(entry.getKey() + \" \" + entry.getValue()); }}", "e": 6130, "s": 5328, "text": null }, { "code": null, "e": 6328, "s": 6130, "text": "Traversing the map with foreach using map's data type\n1 Geeks\n2 4\n3 Geeks\n4 Map\n5 Foreach\n6 Example\n\nTraversing the map with foreach using auto keyword\n1 Geeks\n2 4\n3 Geeks\n4 Map\n5 Foreach\n6 Example" }, { "code": null, "e": 6356, "s": 6328, "text": "Advantages of foreach loop:" }, { "code": null, "e": 6388, "s": 6356, "text": " Makes the code more readable. " }, { "code": null, "e": 6454, "s": 6388, "text": " Eliminates the errors of over-running or under-running the data." }, { "code": null, "e": 6484, "s": 6454, "text": "Disadvantage of foreach loop:" }, { "code": null, "e": 6535, "s": 6484, "text": "Cannot iterate over the elements in reverse order." }, { "code": null, "e": 6613, "s": 6535, "text": "Each and every element will be accessed, cannot skip any elements in between." }, { "code": null, "e": 6626, "s": 6613, "text": "gyanendra371" }, { "code": null, "e": 6632, "s": 6626, "text": "XD_DX" }, { "code": null, "e": 6646, "s": 6632, "text": "shubham_singh" }, { "code": null, "e": 6655, "s": 6646, "text": "SoldMonk" }, { "code": null, "e": 6668, "s": 6655, "text": "cpp-advanced" }, { "code": null, "e": 6672, "s": 6668, "text": "C++" }, { "code": null, "e": 6677, "s": 6672, "text": "Java" }, { "code": null, "e": 6682, "s": 6677, "text": "Java" }, { "code": null, "e": 6686, "s": 6682, "text": "CPP" }, { "code": null, "e": 6784, "s": 6686, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6811, "s": 6784, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 6854, "s": 6811, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 6888, "s": 6854, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 6913, "s": 6888, "text": "unordered_map in C++ STL" }, { "code": null, "e": 6932, "s": 6913, "text": "Inheritance in C++" }, { "code": null, "e": 6947, "s": 6932, "text": "Arrays in Java" }, { "code": null, "e": 6991, "s": 6947, "text": "Split() String method in Java with examples" }, { "code": null, "e": 7027, "s": 6991, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 7078, "s": 7027, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
Hypercube Graph
13 May, 2022 You are given input as order of graph n (highest number of edges connected to a node), you have to find the number of vertices in a Hypercube graph of order n. Examples: Input : n = 3 Output : 8 Input : n = 2 Output : 4 In hypercube graph Q(n), n represents the degree of the graph. Hypercube graph represents the maximum number of edges that can be connected to a graph to make it an n degree graph, every vertex has the same degree n and in that representation, only a fixed number of edges and vertices are added as shown in the figure below: All hypercube graphs are Hamiltonian, hypercube graph of order n has (2^n) vertices, , for input n as the order of graph we have to find the corresponding power of 2. C++ Java Python3 C# PHP Javascript // C++ program to find vertices in a hypercube// graph of order n#include <iostream>using namespace std; // function to find power of 2int power(int n){ if (n == 1) return 2; return 2 * power(n - 1);} // driver programint main(){ // n is the order of the graph int n = 4; cout << power(n); return 0;} // Java program to find vertices in// a hypercube graph of order nclass GfG{ // Function to find power of 2 static int power(int n) { if (n == 1) return 2; return 2 * power(n - 1); } // Driver program public static void main(String []args) { // n is the order of the graph int n = 4; System.out.println(power(n)); }} // This code is contributed by Rituraj Jain # Python3 program to find vertices in a hypercube# graph of order n # function to find power of 2def power(n): if n==1: return 2 return 2*power(n-1) # Driver coden =4print(power(n)) # This code is contributed by Shrikant13 // C# program to find vertices in// a hypercube graph of order nusing System; class GfG{ // Function to find power of 2 static int power(int n) { if (n == 1) return 2; return 2 * power(n - 1); } // Driver code public static void Main() { // n is the order of the graph int n = 4; Console.WriteLine(power(n)); }} // This code is contributed by Mukul Singh <?php// PHP program to find vertices in// a hypercube graph of order n{ // Function to find power of 2 function power($n) { if ($n == 1) return 2; return 2 * power($n - 1); } // Driver Code { // n is the order of the graph $n = 4; echo(power($n)); }} // This code is contributed by Code_Mech?> <script> // Javascript program to find vertices in a hypercube// graph of order n // function to find power of 2function power(n){ if (n == 1) return 2; return 2 * power(n - 1);} // driver program// n is the order of the graphvar n = 4;document.write( power(n)); </script> Output: 16 shrikanth13 rituraj_jain Code_Mech rutvik_56 sumitgumber28 Graph 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 What is Data Structure: Types, Classifications and Applications Find if there is a path between two vertices in an undirected graph Minimum steps to reach target by a Knight | Set 1 Top 50 Graph Coding Problems for Interviews Bridges in a graph Water Jug problem using BFS Detect Cycle in a Directed Graph using BFS Longest Path in a Directed Acyclic Graph
[ { "code": null, "e": 53, "s": 25, "text": "\n13 May, 2022" }, { "code": null, "e": 225, "s": 53, "text": "You are given input as order of graph n (highest number of edges connected to a node), you have to find the number of vertices in a Hypercube graph of order n. Examples: " }, { "code": null, "e": 276, "s": 225, "text": "Input : n = 3\nOutput : 8\n\nInput : n = 2\nOutput : 4" }, { "code": null, "e": 605, "s": 278, "text": "In hypercube graph Q(n), n represents the degree of the graph. Hypercube graph represents the maximum number of edges that can be connected to a graph to make it an n degree graph, every vertex has the same degree n and in that representation, only a fixed number of edges and vertices are added as shown in the figure below: " }, { "code": null, "e": 774, "s": 605, "text": "All hypercube graphs are Hamiltonian, hypercube graph of order n has (2^n) vertices, , for input n as the order of graph we have to find the corresponding power of 2. " }, { "code": null, "e": 778, "s": 774, "text": "C++" }, { "code": null, "e": 783, "s": 778, "text": "Java" }, { "code": null, "e": 791, "s": 783, "text": "Python3" }, { "code": null, "e": 794, "s": 791, "text": "C#" }, { "code": null, "e": 798, "s": 794, "text": "PHP" }, { "code": null, "e": 809, "s": 798, "text": "Javascript" }, { "code": "// C++ program to find vertices in a hypercube// graph of order n#include <iostream>using namespace std; // function to find power of 2int power(int n){ if (n == 1) return 2; return 2 * power(n - 1);} // driver programint main(){ // n is the order of the graph int n = 4; cout << power(n); return 0;}", "e": 1135, "s": 809, "text": null }, { "code": "// Java program to find vertices in// a hypercube graph of order nclass GfG{ // Function to find power of 2 static int power(int n) { if (n == 1) return 2; return 2 * power(n - 1); } // Driver program public static void main(String []args) { // n is the order of the graph int n = 4; System.out.println(power(n)); }} // This code is contributed by Rituraj Jain", "e": 1581, "s": 1135, "text": null }, { "code": "# Python3 program to find vertices in a hypercube# graph of order n # function to find power of 2def power(n): if n==1: return 2 return 2*power(n-1) # Driver coden =4print(power(n)) # This code is contributed by Shrikant13", "e": 1820, "s": 1581, "text": null }, { "code": "// C# program to find vertices in// a hypercube graph of order nusing System; class GfG{ // Function to find power of 2 static int power(int n) { if (n == 1) return 2; return 2 * power(n - 1); } // Driver code public static void Main() { // n is the order of the graph int n = 4; Console.WriteLine(power(n)); }} // This code is contributed by Mukul Singh", "e": 2260, "s": 1820, "text": null }, { "code": "<?php// PHP program to find vertices in// a hypercube graph of order n{ // Function to find power of 2 function power($n) { if ($n == 1) return 2; return 2 * power($n - 1); } // Driver Code { // n is the order of the graph $n = 4; echo(power($n)); }} // This code is contributed by Code_Mech?>", "e": 2636, "s": 2260, "text": null }, { "code": "<script> // Javascript program to find vertices in a hypercube// graph of order n // function to find power of 2function power(n){ if (n == 1) return 2; return 2 * power(n - 1);} // driver program// n is the order of the graphvar n = 4;document.write( power(n)); </script>", "e": 2923, "s": 2636, "text": null }, { "code": null, "e": 2933, "s": 2923, "text": "Output: " }, { "code": null, "e": 2936, "s": 2933, "text": "16" }, { "code": null, "e": 2950, "s": 2938, "text": "shrikanth13" }, { "code": null, "e": 2963, "s": 2950, "text": "rituraj_jain" }, { "code": null, "e": 2973, "s": 2963, "text": "Code_Mech" }, { "code": null, "e": 2983, "s": 2973, "text": "rutvik_56" }, { "code": null, "e": 2997, "s": 2983, "text": "sumitgumber28" }, { "code": null, "e": 3003, "s": 2997, "text": "Graph" }, { "code": null, "e": 3009, "s": 3003, "text": "Graph" }, { "code": null, "e": 3107, "s": 3009, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3172, "s": 3107, "text": "Find if there is a path between two vertices in a directed graph" }, { "code": null, "e": 3204, "s": 3172, "text": "Introduction to Data Structures" }, { "code": null, "e": 3268, "s": 3204, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 3336, "s": 3268, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 3386, "s": 3336, "text": "Minimum steps to reach target by a Knight | Set 1" }, { "code": null, "e": 3430, "s": 3386, "text": "Top 50 Graph Coding Problems for Interviews" }, { "code": null, "e": 3449, "s": 3430, "text": "Bridges in a graph" }, { "code": null, "e": 3477, "s": 3449, "text": "Water Jug problem using BFS" }, { "code": null, "e": 3520, "s": 3477, "text": "Detect Cycle in a Directed Graph using BFS" } ]
How to get the image size (height & width) using JavaScript ?
15 Apr, 2019 For getting size of an image (height and width), Element.clientHeight and Element.clientWidth properties is used. Element.clientHeight: We can access the inner height of an element with this property. This height include the padding but not the margin and border. Element.clientWidth: We can access the inner width of an element with this property. This width include the padding but not the margin and border. Note: Here Element is image, So image.clientHeight and image.clientWidth will be used respectively for getting height and width of the image. Example: Getting image size. <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <title> getting-height-width-image-using-javascript </title> <style> h1 { text-align: center; letter-spacing: 1px; } img, button { display: block; margin: 0 auto; } button { font-size: large; } </style></head> <body> <h1> Getting height and width of an image </h1> <br> <br> <img src="https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-20.png" alt="logo-geeksforgeeks" id="image"> <button type="submit" onclick="myFunc()"> Get height and width </button> <div style="background-color: lightgray"> <div id="height"> </div> <div id="width"> </div> </div></body> <script> function myFunc() { let image = document.getElementById('image'); let height = document.getElementById('height'); var width = document.getElementById('width'); height.innerHTML += '<h1>height of image is :' + image.clientHeight + 'px </h1>'; width.innerHTML += '<h1>width of image is :' + image.clientWidth + 'px </h1>'; }</script> </html> Output:After clicking on the button: After clicking on the button: Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Difference Between PUT and PATCH Request How to Open URL in New Tab using JavaScript ? Installation of Node.js on Linux 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 ?
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Apr, 2019" }, { "code": null, "e": 142, "s": 28, "text": "For getting size of an image (height and width), Element.clientHeight and Element.clientWidth properties is used." }, { "code": null, "e": 292, "s": 142, "text": "Element.clientHeight: We can access the inner height of an element with this property. This height include the padding but not the margin and border." }, { "code": null, "e": 439, "s": 292, "text": "Element.clientWidth: We can access the inner width of an element with this property. This width include the padding but not the margin and border." }, { "code": null, "e": 581, "s": 439, "text": "Note: Here Element is image, So image.clientHeight and image.clientWidth will be used respectively for getting height and width of the image." }, { "code": null, "e": 610, "s": 581, "text": "Example: Getting image size." }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <title> getting-height-width-image-using-javascript </title> <style> h1 { text-align: center; letter-spacing: 1px; } img, button { display: block; margin: 0 auto; } button { font-size: large; } </style></head> <body> <h1> Getting height and width of an image </h1> <br> <br> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-20.png\" alt=\"logo-geeksforgeeks\" id=\"image\"> <button type=\"submit\" onclick=\"myFunc()\"> Get height and width </button> <div style=\"background-color: lightgray\"> <div id=\"height\"> </div> <div id=\"width\"> </div> </div></body> <script> function myFunc() { let image = document.getElementById('image'); let height = document.getElementById('height'); var width = document.getElementById('width'); height.innerHTML += '<h1>height of image is :' + image.clientHeight + 'px </h1>'; width.innerHTML += '<h1>width of image is :' + image.clientWidth + 'px </h1>'; }</script> </html>", "e": 1903, "s": 610, "text": null }, { "code": null, "e": 1940, "s": 1903, "text": "Output:After clicking on the button:" }, { "code": null, "e": 1970, "s": 1940, "text": "After clicking on the button:" }, { "code": null, "e": 1977, "s": 1970, "text": "Picked" }, { "code": null, "e": 1988, "s": 1977, "text": "JavaScript" }, { "code": null, "e": 2005, "s": 1988, "text": "Web Technologies" }, { "code": null, "e": 2032, "s": 2005, "text": "Web technologies Questions" }, { "code": null, "e": 2130, "s": 2032, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2191, "s": 2130, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2263, "s": 2191, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 2303, "s": 2263, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2344, "s": 2303, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 2390, "s": 2344, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 2423, "s": 2390, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2485, "s": 2423, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2546, "s": 2485, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2596, "s": 2546, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to Execute Character Count Program in MapReduce Hadoop?
10 Sep, 2020 Prerequisites: Hadoop and MapReduce Required setup for completing the below task. Java InstallationHadoop installation Java Installation Hadoop installation Our task is to count the frequency of each character present in our input file. We are using Java for implementing this particular scenario. However, The MapReduce program can also be written in Python or C++. Execute the below steps to complete the task for finding the occurrence of each character. Example: Input GeeksforGeeks Output F 1 G 2 e 4 k 2 o 1 r 1 s 2 Step 1: First Open Eclipse -> then select File -> New -> Java Project ->Name it CharCount -> then select use an execution environment -> choose JavaSE-1.8 then next -> Finish. Step 2: Create Three Java Classes into the project. Name them CharCountDriver(having the main function), CharCountMapper, CharCountReducer. Mapper Code: You have to copy and paste this program into the CharCountMapper Java Class file. Java import java.io.IOException; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapred.MapReduceBase; import org.apache.hadoop.mapred.Mapper; import org.apache.hadoop.mapred.OutputCollector; import org.apache.hadoop.mapred.Reporter; public class CharCountMapper extends MapReduceBase implements Mapper<LongWritable,Text,Text,IntWritable>{ public void map(LongWritable key, Text value,OutputCollector<Text,IntWritable> output, Reporter reporter) throws IOException{ String line = value.toString(); String tokenizer[] = line.split(""); for(String SingleChar : tokenizer) { Text charKey = new Text(SingleChar); IntWritable One = new IntWritable(1); output.collect(charKey, One); } } } Reducer Code: You have to copy-paste this below program into the CharCountReducer Java Class file. Java import java.io.IOException;import java.util.Iterator;import org.apache.hadoop.io.IntWritable;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapred.MapReduceBase;import org.apache.hadoop.mapred.OutputCollector;import org.apache.hadoop.mapred.Reducer;import org.apache.hadoop.mapred.Reporter; public class CharCountReducer extends MapReduceBase implements Reducer<Text, IntWritable, Text, IntWritable> { public void reduce(Text key, Iterator<IntWritable> values, OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException { int sum = 0; while (values.hasNext()) { sum += values.next().get(); } output.collect(key, new IntWritable(sum)); }} Driver Code: You have to copy-paste this below program into the CharCountDriver Java Class file. Java import java.io.IOException;import org.apache.hadoop.fs.Path;import org.apache.hadoop.io.IntWritable;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapred.FileInputFormat;import org.apache.hadoop.mapred.FileOutputFormat;import org.apache.hadoop.mapred.JobClient;import org.apache.hadoop.mapred.JobConf;import org.apache.hadoop.mapred.TextInputFormat;import org.apache.hadoop.mapred.TextOutputFormat;public class CharCountDriver { public static void main(String[] args) throws IOException { JobConf conf = new JobConf(CharCountDriver.class); conf.setJobName("CharCount"); conf.setOutputKeyClass(Text.class); conf.setOutputValueClass(IntWritable.class); conf.setMapperClass(CharCountMapper.class); conf.setCombinerClass(CharCountReducer.class); conf.setReducerClass(CharCountReducer.class); conf.setInputFormat(TextInputFormat.class); conf.setOutputFormat(TextOutputFormat.class); FileInputFormat.setInputPaths(conf, new Path(args[0])); FileOutputFormat.setOutputPath(conf, new Path(args[1])); JobClient.runJob(conf); }} Step 3: Now we need to add an external jar for the packages that we have import. Download the jar package Hadoop Common and Hadoop MapReduce Core according to your Hadoop version. You can check Hadoop Version with the below command: hadoop version Step 4: Now we add these external jars to our CharCount project. Right Click on CharCount -> then select Build Path-> Click on Configure Build Path and select Add External jars.... and add jars from it’s download location then click -> Apply and Close. Step 5: Now export the project as a jar file. Right-click on CharCount choose Export.. and go to Java -> JAR file click -> Next and choose your export destination then click -> Next. Choose Main Class as CharCount by clicking -> Browse and then click -> Finish -> Ok. Now the Jar file is successfully created and saved at /Documents directory with the name charectercount.jar in my case. Step 6: Create a simple text file and add some data to it. nano test.txt You can also add text to the file manually or using some other editor like Vim or gedit. To see the content of the file use cat command available in Linux. cat test.txt Step 7: Start our Hadoop Daemons start-dfs.sh start-yarn.sh Step 8: Move your test.txt file to the Hadoop HDFS. Syntax: hdfs dfs -put /file_path /destination In below command / shows the root directory of our HDFS. hdfs dfs -put /home/dikshant/Documents/test.txt / Check the file is present in the root directory of HDFS or not. hdfs dfs -ls / Step 9: Now Run your Jar File with the below command and produce the output in CharCountResult File. Syntax: hadoop jar /jar_file_location /dataset_location_in_HDFS /output-file_name Command: hadoop jar /home/dikshant/Documents/charectercount.jar /test.txt /CharCountResult Step 10: Now Move to localhost:50070/, under utilities select Browse the file system and download part-r-00000 in /CharCountResult directory to see result. we can also check the result i.e. that part-r-00000 file with cat command as shown below. hdfs dfs -cat /CharCountResult/part-00000 MapReduce Hadoop Hadoop Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Create Table in Hive? What is Hadoop Streaming? What is Schema On Read and Schema On Write in Hadoop? Apache Hive MapReduce - Understanding With Real-Life Example How to Install Single Node Cluster Hadoop on Windows? Import and Export Data using SQOOP Hadoop - HDFS (Hadoop Distributed File System) Hive - Alter Table Difference Between Hadoop 2.x vs Hadoop 3.x
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Sep, 2020" }, { "code": null, "e": 64, "s": 28, "text": "Prerequisites: Hadoop and MapReduce" }, { "code": null, "e": 110, "s": 64, "text": "Required setup for completing the below task." }, { "code": null, "e": 148, "s": 110, "text": "Java InstallationHadoop installation " }, { "code": null, "e": 166, "s": 148, "text": "Java Installation" }, { "code": null, "e": 187, "s": 166, "text": "Hadoop installation " }, { "code": null, "e": 488, "s": 187, "text": "Our task is to count the frequency of each character present in our input file. We are using Java for implementing this particular scenario. However, The MapReduce program can also be written in Python or C++. Execute the below steps to complete the task for finding the occurrence of each character." }, { "code": null, "e": 497, "s": 488, "text": "Example:" }, { "code": null, "e": 503, "s": 497, "text": "Input" }, { "code": null, "e": 519, "s": 503, "text": "GeeksforGeeks \n" }, { "code": null, "e": 526, "s": 519, "text": "Output" }, { "code": null, "e": 562, "s": 526, "text": "F 1\nG 2\ne 4\nk 2\no 1\nr 1\ns 2\n" }, { "code": null, "e": 739, "s": 562, "text": "Step 1: First Open Eclipse -> then select File -> New -> Java Project ->Name it CharCount -> then select use an execution environment -> choose JavaSE-1.8 then next -> Finish. " }, { "code": null, "e": 879, "s": 739, "text": "Step 2: Create Three Java Classes into the project. Name them CharCountDriver(having the main function), CharCountMapper, CharCountReducer." }, { "code": null, "e": 974, "s": 879, "text": "Mapper Code: You have to copy and paste this program into the CharCountMapper Java Class file." }, { "code": null, "e": 979, "s": 974, "text": "Java" }, { "code": "import java.io.IOException; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapred.MapReduceBase; import org.apache.hadoop.mapred.Mapper; import org.apache.hadoop.mapred.OutputCollector; import org.apache.hadoop.mapred.Reporter; public class CharCountMapper extends MapReduceBase implements Mapper<LongWritable,Text,Text,IntWritable>{ public void map(LongWritable key, Text value,OutputCollector<Text,IntWritable> output, Reporter reporter) throws IOException{ String line = value.toString(); String tokenizer[] = line.split(\"\"); for(String SingleChar : tokenizer) { Text charKey = new Text(SingleChar); IntWritable One = new IntWritable(1); output.collect(charKey, One); } } }", "e": 1919, "s": 979, "text": null }, { "code": null, "e": 2018, "s": 1919, "text": "Reducer Code: You have to copy-paste this below program into the CharCountReducer Java Class file." }, { "code": null, "e": 2023, "s": 2018, "text": "Java" }, { "code": "import java.io.IOException;import java.util.Iterator;import org.apache.hadoop.io.IntWritable;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapred.MapReduceBase;import org.apache.hadoop.mapred.OutputCollector;import org.apache.hadoop.mapred.Reducer;import org.apache.hadoop.mapred.Reporter; public class CharCountReducer extends MapReduceBase implements Reducer<Text, IntWritable, Text, IntWritable> { public void reduce(Text key, Iterator<IntWritable> values, OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException { int sum = 0; while (values.hasNext()) { sum += values.next().get(); } output.collect(key, new IntWritable(sum)); }}", "e": 2791, "s": 2023, "text": null }, { "code": null, "e": 2888, "s": 2791, "text": "Driver Code: You have to copy-paste this below program into the CharCountDriver Java Class file." }, { "code": null, "e": 2893, "s": 2888, "text": "Java" }, { "code": "import java.io.IOException;import org.apache.hadoop.fs.Path;import org.apache.hadoop.io.IntWritable;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapred.FileInputFormat;import org.apache.hadoop.mapred.FileOutputFormat;import org.apache.hadoop.mapred.JobClient;import org.apache.hadoop.mapred.JobConf;import org.apache.hadoop.mapred.TextInputFormat;import org.apache.hadoop.mapred.TextOutputFormat;public class CharCountDriver { public static void main(String[] args) throws IOException { JobConf conf = new JobConf(CharCountDriver.class); conf.setJobName(\"CharCount\"); conf.setOutputKeyClass(Text.class); conf.setOutputValueClass(IntWritable.class); conf.setMapperClass(CharCountMapper.class); conf.setCombinerClass(CharCountReducer.class); conf.setReducerClass(CharCountReducer.class); conf.setInputFormat(TextInputFormat.class); conf.setOutputFormat(TextOutputFormat.class); FileInputFormat.setInputPaths(conf, new Path(args[0])); FileOutputFormat.setOutputPath(conf, new Path(args[1])); JobClient.runJob(conf); }}", "e": 4097, "s": 2893, "text": null }, { "code": null, "e": 4330, "s": 4097, "text": "Step 3: Now we need to add an external jar for the packages that we have import. Download the jar package Hadoop Common and Hadoop MapReduce Core according to your Hadoop version. You can check Hadoop Version with the below command:" }, { "code": null, "e": 4346, "s": 4330, "text": "hadoop version\n" }, { "code": null, "e": 4599, "s": 4346, "text": "Step 4: Now we add these external jars to our CharCount project. Right Click on CharCount -> then select Build Path-> Click on Configure Build Path and select Add External jars.... and add jars from it’s download location then click -> Apply and Close." }, { "code": null, "e": 4867, "s": 4599, "text": "Step 5: Now export the project as a jar file. Right-click on CharCount choose Export.. and go to Java -> JAR file click -> Next and choose your export destination then click -> Next. Choose Main Class as CharCount by clicking -> Browse and then click -> Finish -> Ok." }, { "code": null, "e": 4987, "s": 4867, "text": "Now the Jar file is successfully created and saved at /Documents directory with the name charectercount.jar in my case." }, { "code": null, "e": 5046, "s": 4987, "text": "Step 6: Create a simple text file and add some data to it." }, { "code": null, "e": 5061, "s": 5046, "text": "nano test.txt\n" }, { "code": null, "e": 5152, "s": 5061, "text": "You can also add text to the file manually or using some other editor like Vim or gedit. " }, { "code": null, "e": 5219, "s": 5152, "text": "To see the content of the file use cat command available in Linux." }, { "code": null, "e": 5233, "s": 5219, "text": "cat test.txt\n" }, { "code": null, "e": 5266, "s": 5233, "text": "Step 7: Start our Hadoop Daemons" }, { "code": null, "e": 5280, "s": 5266, "text": "start-dfs.sh\n" }, { "code": null, "e": 5295, "s": 5280, "text": "start-yarn.sh\n" }, { "code": null, "e": 5347, "s": 5295, "text": "Step 8: Move your test.txt file to the Hadoop HDFS." }, { "code": null, "e": 5355, "s": 5347, "text": "Syntax:" }, { "code": null, "e": 5394, "s": 5355, "text": "hdfs dfs -put /file_path /destination\n" }, { "code": null, "e": 5451, "s": 5394, "text": "In below command / shows the root directory of our HDFS." }, { "code": null, "e": 5502, "s": 5451, "text": "hdfs dfs -put /home/dikshant/Documents/test.txt /\n" }, { "code": null, "e": 5566, "s": 5502, "text": "Check the file is present in the root directory of HDFS or not." }, { "code": null, "e": 5582, "s": 5566, "text": "hdfs dfs -ls /\n" }, { "code": null, "e": 5683, "s": 5582, "text": "Step 9: Now Run your Jar File with the below command and produce the output in CharCountResult File." }, { "code": null, "e": 5691, "s": 5683, "text": "Syntax:" }, { "code": null, "e": 5766, "s": 5691, "text": "hadoop jar /jar_file_location /dataset_location_in_HDFS /output-file_name\n" }, { "code": null, "e": 5775, "s": 5766, "text": "Command:" }, { "code": null, "e": 5858, "s": 5775, "text": "hadoop jar /home/dikshant/Documents/charectercount.jar /test.txt /CharCountResult\n" }, { "code": null, "e": 6104, "s": 5858, "text": "Step 10: Now Move to localhost:50070/, under utilities select Browse the file system and download part-r-00000 in /CharCountResult directory to see result. we can also check the result i.e. that part-r-00000 file with cat command as shown below." }, { "code": null, "e": 6148, "s": 6104, "text": "hdfs dfs -cat /CharCountResult/part-00000 \n" }, { "code": null, "e": 6158, "s": 6148, "text": "MapReduce" }, { "code": null, "e": 6165, "s": 6158, "text": "Hadoop" }, { "code": null, "e": 6172, "s": 6165, "text": "Hadoop" }, { "code": null, "e": 6270, "s": 6172, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6299, "s": 6270, "text": "How to Create Table in Hive?" }, { "code": null, "e": 6325, "s": 6299, "text": "What is Hadoop Streaming?" }, { "code": null, "e": 6379, "s": 6325, "text": "What is Schema On Read and Schema On Write in Hadoop?" }, { "code": null, "e": 6391, "s": 6379, "text": "Apache Hive" }, { "code": null, "e": 6440, "s": 6391, "text": "MapReduce - Understanding With Real-Life Example" }, { "code": null, "e": 6494, "s": 6440, "text": "How to Install Single Node Cluster Hadoop on Windows?" }, { "code": null, "e": 6529, "s": 6494, "text": "Import and Export Data using SQOOP" }, { "code": null, "e": 6576, "s": 6529, "text": "Hadoop - HDFS (Hadoop Distributed File System)" }, { "code": null, "e": 6595, "s": 6576, "text": "Hive - Alter Table" } ]
How to create an Editable Table with add delete and search filter using ReactJS ?
01 Jul, 2021 Tables is used to display a set of data. In some projects, you need to implement the dynamic table with editable/non-editable modes where a user can add or delete any row. Also, Material UI for React has a customizable Table Component available, and it is very easy to integrate, but there is no such functionality to handle rows addition and deletion individually. We will use React.js and Material UI and implement these functionalities in it. Creating React Application And Installing Module: Step 1: Create a React application using the following command.npx create-react-app foldername Step 1: Create a React application using the following command. npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command.cd foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command. cd foldername Step 3: After creating the React.js application, install the material-ui modules using the following command.npm install @material-ui/core npm install @material-ui/icons npm install @material-ui/lab npm install @material-ui/core npm install @material-ui/icons npm install @material-ui/lab Default Project Structure: It will look like the following. Initial Project Structure Changing the Project Structure: We don’t need some files like App.css, logo.svg. Remove them and add a new file TableDemo.js where our table component will reside. Changing the Project Structure Example: Now write down the following code in the App.js and TableDemo.js files accordingly. Here, App is our default component where we have replaced the default code. App.js import React from "react";import TableDemo from "./TableDemo"; function App() { return ( <div> {/* Header with inline css */} <h1 style={{ display: 'flex', justifyContent: 'center', padding: '15px', border: '13px solid #b4f0b4', color: 'rgb(11, 167, 11)' }}> Geeks For Geeks Material UI Table </h1> {/* Table component below header */} <TableDemo /> </div> )} export default App; TableDemo.js import React, { useState } from "react";import CreateIcon from "@material-ui/icons/Create";import { Box, Button, Snackbar, Table, TableBody, TableCell, TableHead, TableRow} from "@material-ui/core";import DeleteOutlineIcon from "@material-ui/icons/DeleteOutline";import AddBoxIcon from "@material-ui/icons/AddBox";import DoneIcon from "@material-ui/icons/Done";import ClearIcon from "@material-ui/icons/Clear";import { makeStyles } from "@material-ui/core/styles";import Alert from "@material-ui/lab/Alert";import Dialog from "@material-ui/core/Dialog";import DialogActions from "@material-ui/core/DialogActions";import DialogContent from "@material-ui/core/DialogContent";import DialogContentText from "@material-ui/core/DialogContentText";import DialogTitle from "@material-ui/core/DialogTitle"; // Creating stylesconst useStyles = makeStyles({ root: { "& > *": { borderBottom: "unset", }, }, table: { minWidth: 650, }, snackbar: { bottom: "104px", },}); function TableDemo() { // Creating style object const classes = useStyles(); // Defining a state named rows // which we can update by calling on setRows function const [rows, setRows] = useState([ { id: 1, firstname: "", lastname: "", city: "" }, ]); // Initial states const [open, setOpen] = React.useState(false); const [isEdit, setEdit] = React.useState(false); const [disable, setDisable] = React.useState(true); const [showConfirm, setShowConfirm] = React.useState(false); // Function For closing the alert snackbar const handleClose = (event, reason) => { if (reason === "clickaway") { return; } setOpen(false); }; // Function For adding new row object const handleAdd = () => { setRows([ ...rows, { id: rows.length + 1, firstname: "", lastname: "", city: "" }, ]); setEdit(true); }; // Function to handle edit const handleEdit = (i) => { // If edit mode is true setEdit will // set it to false and vice versa setEdit(!isEdit); }; // Function to handle save const handleSave = () => { setEdit(!isEdit); setRows(rows); console.log("saved : ", rows); setDisable(true); setOpen(true); }; // The handleInputChange handler can be set up to handle // many different inputs in the form, listen for changes // to input elements and record their values in state const handleInputChange = (e, index) => { setDisable(false); const { name, value } = e.target; const list = [...rows]; list[index][name] = value; setRows(list); }; // Showing delete confirmation to users const handleConfirm = () => { setShowConfirm(true); }; // Handle the case of delete confirmation where // user click yes delete a specific row of id:i const handleRemoveClick = (i) => { const list = [...rows]; list.splice(i, 1); setRows(list); setShowConfirm(false); }; // Handle the case of delete confirmation // where user click no const handleNo = () => { setShowConfirm(false); }; return ( <TableBody> <Snackbar open={open} autoHideDuration={2000} onClose={handleClose} className={classes.snackbar} > <Alert onClose={handleClose} severity="success"> Record saved successfully! </Alert> </Snackbar> <Box margin={1}> <div style={{ display: "flex", justifyContent: "space-between" }}> <div> {isEdit ? ( <div> <Button onClick={handleAdd}> <AddBoxIcon onClick={handleAdd} /> ADD </Button> {rows.length !== 0 && ( <div> {disable ? ( <Button disabled align="right" onClick={handleSave}> <DoneIcon /> SAVE </Button> ) : ( <Button align="right" onClick={handleSave}> <DoneIcon /> SAVE </Button> )} </div> )} </div> ) : ( <div> <Button onClick={handleAdd}> <AddBoxIcon onClick={handleAdd} /> ADD </Button> <Button align="right" onClick={handleEdit}> <CreateIcon /> EDIT </Button> </div> )} </div> </div> <TableRow align="center"> </TableRow> <Table className={classes.table} size="small" aria-label="a dense table" > <TableHead> <TableRow> <TableCell>First Name</TableCell> <TableCell>Last Name</TableCell> <TableCell align="center">City</TableCell> <TableCell align="center"> </TableCell> </TableRow> </TableHead> <TableBody> {rows.map((row, i) => { return ( <div> <TableRow> {isEdit ? ( <div> <TableCell padding="none"> <input value={row.firstname} name="firstname" onChange={(e) => handleInputChange(e, i)} /> </TableCell> <TableCell padding="none"> <input value={row.lastname} name="lastname" onChange={(e) => handleInputChange(e, i)} /> </TableCell> <TableCell padding="none"> <select style={{ width: "100px" }} name="city" value={row.city} onChange={(e) => handleInputChange(e, i)} > <option value=""></option> <option value="Karanja">Karanja</option> <option value="Hingoli">Hingoli</option> <option value="Bhandara">Bhandara</option> <option value="Amaravati">Amaravati</option> <option value="Pulgaon">Pulgaon</option> </select> </TableCell> </div> ) : ( <div> <TableCell component="th" scope="row"> {row.firstname} </TableCell> <TableCell component="th" scope="row"> {row.lastname} </TableCell> <TableCell component="th" scope="row" align="center"> {row.city} </TableCell> <TableCell component="th" scope="row" align="center" ></TableCell> </div> )} {isEdit ? ( <Button className="mr10" onClick={handleConfirm}> <ClearIcon /> </Button> ) : ( <Button className="mr10" onClick={handleConfirm}> <DeleteOutlineIcon /> </Button> )} {showConfirm && ( <div> <Dialog open={showConfirm} onClose={handleNo} aria-labelledby="alert-dialog-title" aria-describedby="alert-dialog-description" > <DialogTitle id="alert-dialog-title"> {"Confirm Delete"} </DialogTitle> <DialogContent> <DialogContentText id="alert-dialog-description"> Are you sure to delete </DialogContentText> </DialogContent> <DialogActions> <Button onClick={() => handleRemoveClick(i)} color="primary" autoFocus > Yes </Button> <Button onClick={handleNo} color="primary" autoFocus > No </Button> </DialogActions> </Dialog> </div> )} </TableRow> </div> ); })} </TableBody> </Table> </Box> </TableBody> );} export default TableDemo; Step to Run Application: Run the application using the following command from the root directory of the project. npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output. Table functionality Demo Explanation: The useState() is a hook in ReactJs which allows a functional component to have a state. We pass the initial state in this function, and it returns us a variable and a function to update that state. Using this we can handle edit/non-edit mode and buttons to be displayed accordingly. Initially, the Table will be displayed in non-edit mode. After clicking EDIT, table rows will be modified in edit mode where the user can add as many rows or delete any row. In edit mode when the user tries to change row data, the EDIT button will be changed to SAVE. After clicking SAVE, a saving alert message will be popped up. When a user tries to delete a row, confirmation delete will be shown. If the user select yes, then that particular row will be deleted, and if the user selects no, the row will not be deleted. Observe the above output and notice the changes. You can also modify those changes according to your choice. Material-UI Picked React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Axios in React: A Guide for Beginners ReactJS setState() How to pass data from one component to other component in ReactJS ? Re-rendering Components in ReactJS ReactJS defaultProps Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 52, "s": 24, "text": "\n01 Jul, 2021" }, { "code": null, "e": 498, "s": 52, "text": "Tables is used to display a set of data. In some projects, you need to implement the dynamic table with editable/non-editable modes where a user can add or delete any row. Also, Material UI for React has a customizable Table Component available, and it is very easy to integrate, but there is no such functionality to handle rows addition and deletion individually. We will use React.js and Material UI and implement these functionalities in it." }, { "code": null, "e": 548, "s": 498, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 643, "s": 548, "text": "Step 1: Create a React application using the following command.npx create-react-app foldername" }, { "code": null, "e": 707, "s": 643, "text": "Step 1: Create a React application using the following command." }, { "code": null, "e": 739, "s": 707, "text": "npx create-react-app foldername" }, { "code": null, "e": 852, "s": 739, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command.cd foldername" }, { "code": null, "e": 952, "s": 852, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command." }, { "code": null, "e": 966, "s": 952, "text": "cd foldername" }, { "code": null, "e": 1167, "s": 968, "text": "Step 3: After creating the React.js application, install the material-ui modules using the following command.npm install @material-ui/core\nnpm install @material-ui/icons\nnpm install @material-ui/lab" }, { "code": null, "e": 1257, "s": 1167, "text": "npm install @material-ui/core\nnpm install @material-ui/icons\nnpm install @material-ui/lab" }, { "code": null, "e": 1317, "s": 1257, "text": "Default Project Structure: It will look like the following." }, { "code": null, "e": 1343, "s": 1317, "text": "Initial Project Structure" }, { "code": null, "e": 1507, "s": 1343, "text": "Changing the Project Structure: We don’t need some files like App.css, logo.svg. Remove them and add a new file TableDemo.js where our table component will reside." }, { "code": null, "e": 1538, "s": 1507, "text": "Changing the Project Structure" }, { "code": null, "e": 1707, "s": 1538, "text": "Example: Now write down the following code in the App.js and TableDemo.js files accordingly. Here, App is our default component where we have replaced the default code." }, { "code": null, "e": 1714, "s": 1707, "text": "App.js" }, { "code": "import React from \"react\";import TableDemo from \"./TableDemo\"; function App() { return ( <div> {/* Header with inline css */} <h1 style={{ display: 'flex', justifyContent: 'center', padding: '15px', border: '13px solid #b4f0b4', color: 'rgb(11, 167, 11)' }}> Geeks For Geeks Material UI Table </h1> {/* Table component below header */} <TableDemo /> </div> )} export default App;", "e": 2254, "s": 1714, "text": null }, { "code": null, "e": 2267, "s": 2254, "text": "TableDemo.js" }, { "code": "import React, { useState } from \"react\";import CreateIcon from \"@material-ui/icons/Create\";import { Box, Button, Snackbar, Table, TableBody, TableCell, TableHead, TableRow} from \"@material-ui/core\";import DeleteOutlineIcon from \"@material-ui/icons/DeleteOutline\";import AddBoxIcon from \"@material-ui/icons/AddBox\";import DoneIcon from \"@material-ui/icons/Done\";import ClearIcon from \"@material-ui/icons/Clear\";import { makeStyles } from \"@material-ui/core/styles\";import Alert from \"@material-ui/lab/Alert\";import Dialog from \"@material-ui/core/Dialog\";import DialogActions from \"@material-ui/core/DialogActions\";import DialogContent from \"@material-ui/core/DialogContent\";import DialogContentText from \"@material-ui/core/DialogContentText\";import DialogTitle from \"@material-ui/core/DialogTitle\"; // Creating stylesconst useStyles = makeStyles({ root: { \"& > *\": { borderBottom: \"unset\", }, }, table: { minWidth: 650, }, snackbar: { bottom: \"104px\", },}); function TableDemo() { // Creating style object const classes = useStyles(); // Defining a state named rows // which we can update by calling on setRows function const [rows, setRows] = useState([ { id: 1, firstname: \"\", lastname: \"\", city: \"\" }, ]); // Initial states const [open, setOpen] = React.useState(false); const [isEdit, setEdit] = React.useState(false); const [disable, setDisable] = React.useState(true); const [showConfirm, setShowConfirm] = React.useState(false); // Function For closing the alert snackbar const handleClose = (event, reason) => { if (reason === \"clickaway\") { return; } setOpen(false); }; // Function For adding new row object const handleAdd = () => { setRows([ ...rows, { id: rows.length + 1, firstname: \"\", lastname: \"\", city: \"\" }, ]); setEdit(true); }; // Function to handle edit const handleEdit = (i) => { // If edit mode is true setEdit will // set it to false and vice versa setEdit(!isEdit); }; // Function to handle save const handleSave = () => { setEdit(!isEdit); setRows(rows); console.log(\"saved : \", rows); setDisable(true); setOpen(true); }; // The handleInputChange handler can be set up to handle // many different inputs in the form, listen for changes // to input elements and record their values in state const handleInputChange = (e, index) => { setDisable(false); const { name, value } = e.target; const list = [...rows]; list[index][name] = value; setRows(list); }; // Showing delete confirmation to users const handleConfirm = () => { setShowConfirm(true); }; // Handle the case of delete confirmation where // user click yes delete a specific row of id:i const handleRemoveClick = (i) => { const list = [...rows]; list.splice(i, 1); setRows(list); setShowConfirm(false); }; // Handle the case of delete confirmation // where user click no const handleNo = () => { setShowConfirm(false); }; return ( <TableBody> <Snackbar open={open} autoHideDuration={2000} onClose={handleClose} className={classes.snackbar} > <Alert onClose={handleClose} severity=\"success\"> Record saved successfully! </Alert> </Snackbar> <Box margin={1}> <div style={{ display: \"flex\", justifyContent: \"space-between\" }}> <div> {isEdit ? ( <div> <Button onClick={handleAdd}> <AddBoxIcon onClick={handleAdd} /> ADD </Button> {rows.length !== 0 && ( <div> {disable ? ( <Button disabled align=\"right\" onClick={handleSave}> <DoneIcon /> SAVE </Button> ) : ( <Button align=\"right\" onClick={handleSave}> <DoneIcon /> SAVE </Button> )} </div> )} </div> ) : ( <div> <Button onClick={handleAdd}> <AddBoxIcon onClick={handleAdd} /> ADD </Button> <Button align=\"right\" onClick={handleEdit}> <CreateIcon /> EDIT </Button> </div> )} </div> </div> <TableRow align=\"center\"> </TableRow> <Table className={classes.table} size=\"small\" aria-label=\"a dense table\" > <TableHead> <TableRow> <TableCell>First Name</TableCell> <TableCell>Last Name</TableCell> <TableCell align=\"center\">City</TableCell> <TableCell align=\"center\"> </TableCell> </TableRow> </TableHead> <TableBody> {rows.map((row, i) => { return ( <div> <TableRow> {isEdit ? ( <div> <TableCell padding=\"none\"> <input value={row.firstname} name=\"firstname\" onChange={(e) => handleInputChange(e, i)} /> </TableCell> <TableCell padding=\"none\"> <input value={row.lastname} name=\"lastname\" onChange={(e) => handleInputChange(e, i)} /> </TableCell> <TableCell padding=\"none\"> <select style={{ width: \"100px\" }} name=\"city\" value={row.city} onChange={(e) => handleInputChange(e, i)} > <option value=\"\"></option> <option value=\"Karanja\">Karanja</option> <option value=\"Hingoli\">Hingoli</option> <option value=\"Bhandara\">Bhandara</option> <option value=\"Amaravati\">Amaravati</option> <option value=\"Pulgaon\">Pulgaon</option> </select> </TableCell> </div> ) : ( <div> <TableCell component=\"th\" scope=\"row\"> {row.firstname} </TableCell> <TableCell component=\"th\" scope=\"row\"> {row.lastname} </TableCell> <TableCell component=\"th\" scope=\"row\" align=\"center\"> {row.city} </TableCell> <TableCell component=\"th\" scope=\"row\" align=\"center\" ></TableCell> </div> )} {isEdit ? ( <Button className=\"mr10\" onClick={handleConfirm}> <ClearIcon /> </Button> ) : ( <Button className=\"mr10\" onClick={handleConfirm}> <DeleteOutlineIcon /> </Button> )} {showConfirm && ( <div> <Dialog open={showConfirm} onClose={handleNo} aria-labelledby=\"alert-dialog-title\" aria-describedby=\"alert-dialog-description\" > <DialogTitle id=\"alert-dialog-title\"> {\"Confirm Delete\"} </DialogTitle> <DialogContent> <DialogContentText id=\"alert-dialog-description\"> Are you sure to delete </DialogContentText> </DialogContent> <DialogActions> <Button onClick={() => handleRemoveClick(i)} color=\"primary\" autoFocus > Yes </Button> <Button onClick={handleNo} color=\"primary\" autoFocus > No </Button> </DialogActions> </Dialog> </div> )} </TableRow> </div> ); })} </TableBody> </Table> </Box> </TableBody> );} export default TableDemo;", "e": 11822, "s": 2267, "text": null }, { "code": null, "e": 11935, "s": 11822, "text": "Step to Run Application: Run the application using the following command from the root directory of the project." }, { "code": null, "e": 11945, "s": 11935, "text": "npm start" }, { "code": null, "e": 12044, "s": 11945, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output." }, { "code": null, "e": 12069, "s": 12044, "text": "Table functionality Demo" }, { "code": null, "e": 12083, "s": 12069, "text": "Explanation: " }, { "code": null, "e": 12367, "s": 12083, "text": "The useState() is a hook in ReactJs which allows a functional component to have a state. We pass the initial state in this function, and it returns us a variable and a function to update that state. Using this we can handle edit/non-edit mode and buttons to be displayed accordingly." }, { "code": null, "e": 12541, "s": 12367, "text": "Initially, the Table will be displayed in non-edit mode. After clicking EDIT, table rows will be modified in edit mode where the user can add as many rows or delete any row." }, { "code": null, "e": 12698, "s": 12541, "text": "In edit mode when the user tries to change row data, the EDIT button will be changed to SAVE. After clicking SAVE, a saving alert message will be popped up." }, { "code": null, "e": 12891, "s": 12698, "text": "When a user tries to delete a row, confirmation delete will be shown. If the user select yes, then that particular row will be deleted, and if the user selects no, the row will not be deleted." }, { "code": null, "e": 13000, "s": 12891, "text": "Observe the above output and notice the changes. You can also modify those changes according to your choice." }, { "code": null, "e": 13012, "s": 13000, "text": "Material-UI" }, { "code": null, "e": 13019, "s": 13012, "text": "Picked" }, { "code": null, "e": 13035, "s": 13019, "text": "React-Questions" }, { "code": null, "e": 13043, "s": 13035, "text": "ReactJS" }, { "code": null, "e": 13060, "s": 13043, "text": "Web Technologies" }, { "code": null, "e": 13158, "s": 13060, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 13196, "s": 13158, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 13215, "s": 13196, "text": "ReactJS setState()" }, { "code": null, "e": 13283, "s": 13215, "text": "How to pass data from one component to other component in ReactJS ?" }, { "code": null, "e": 13318, "s": 13283, "text": "Re-rendering Components in ReactJS" }, { "code": null, "e": 13339, "s": 13318, "text": "ReactJS defaultProps" }, { "code": null, "e": 13401, "s": 13339, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 13434, "s": 13401, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 13495, "s": 13434, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 13545, "s": 13495, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
MySQL | PASSWORD Function
08 Nov, 2019 The MySQL PASSWORD function is used for the generation of a hashed password using a plain-text password string It uses hashing techniques to generate the hashed password. This function is carried out by the authentication system. MySQL server uses the PASSWORD function to encrypt MySQL passwords for storage in the Password column of the user grant table. The value returned by the PASSWORD function is a hashed string, or NULL if the argument was NULL. The PASSWORD function accepts one parameter which is the string to be encrypted. Syntax: PASSWORD( string_to_encrypt ) Parameters Used: string_to_encrypt – It is used to specify the plain text string that is to be encrypted. Return Value:The PASSWORD function in MySQL returns a hashed string. Supported Versions of MySQL: MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 Example-1: Implementing PASSWORD function on a string. SELECT PASSWORD('xyz'); Output: 6gd7gb67shy87865 Example-2: Implementing PASSWORD function on a string with a combination of characters and integer values. SELECT PASSWORD('xyz123'); Output: 54fg56gs32sgi3862 Example-3: Implementing PASSWORD function on a bigger string. SELECT PASSWORD('geeksforgeeks'); Output: 79sgs54uksr1fy76509 Example-4: Implementing PASSWORD function on a NULL string. SELECT PASSWORD('NULL'); Output: NULL mysql SQLmysql SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. CTE in SQL How to Update Multiple Columns in Single Update Statement in SQL? SQL Trigger | Student Database SQL Interview Questions SQL | Views Difference between DELETE, DROP and TRUNCATE Difference between SQL and NoSQL MySQL | Group_CONCAT() Function Window functions in SQL Difference between DDL and DML in DBMS
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Nov, 2019" }, { "code": null, "e": 258, "s": 28, "text": "The MySQL PASSWORD function is used for the generation of a hashed password using a plain-text password string It uses hashing techniques to generate the hashed password. This function is carried out by the authentication system." }, { "code": null, "e": 564, "s": 258, "text": "MySQL server uses the PASSWORD function to encrypt MySQL passwords for storage in the Password column of the user grant table. The value returned by the PASSWORD function is a hashed string, or NULL if the argument was NULL. The PASSWORD function accepts one parameter which is the string to be encrypted." }, { "code": null, "e": 572, "s": 564, "text": "Syntax:" }, { "code": null, "e": 602, "s": 572, "text": "PASSWORD( string_to_encrypt )" }, { "code": null, "e": 619, "s": 602, "text": "Parameters Used:" }, { "code": null, "e": 708, "s": 619, "text": "string_to_encrypt – It is used to specify the plain text string that is to be encrypted." }, { "code": null, "e": 777, "s": 708, "text": "Return Value:The PASSWORD function in MySQL returns a hashed string." }, { "code": null, "e": 806, "s": 777, "text": "Supported Versions of MySQL:" }, { "code": null, "e": 816, "s": 806, "text": "MySQL 5.7" }, { "code": null, "e": 826, "s": 816, "text": "MySQL 5.6" }, { "code": null, "e": 836, "s": 826, "text": "MySQL 5.5" }, { "code": null, "e": 846, "s": 836, "text": "MySQL 5.1" }, { "code": null, "e": 856, "s": 846, "text": "MySQL 5.0" }, { "code": null, "e": 866, "s": 856, "text": "MySQL 4.1" }, { "code": null, "e": 921, "s": 866, "text": "Example-1: Implementing PASSWORD function on a string." }, { "code": null, "e": 947, "s": 921, "text": "SELECT \nPASSWORD('xyz'); " }, { "code": null, "e": 955, "s": 947, "text": "Output:" }, { "code": null, "e": 973, "s": 955, "text": "6gd7gb67shy87865 " }, { "code": null, "e": 1080, "s": 973, "text": "Example-2: Implementing PASSWORD function on a string with a combination of characters and integer values." }, { "code": null, "e": 1109, "s": 1080, "text": "SELECT \nPASSWORD('xyz123'); " }, { "code": null, "e": 1117, "s": 1109, "text": "Output:" }, { "code": null, "e": 1136, "s": 1117, "text": "54fg56gs32sgi3862 " }, { "code": null, "e": 1198, "s": 1136, "text": "Example-3: Implementing PASSWORD function on a bigger string." }, { "code": null, "e": 1234, "s": 1198, "text": "SELECT \nPASSWORD('geeksforgeeks'); " }, { "code": null, "e": 1242, "s": 1234, "text": "Output:" }, { "code": null, "e": 1263, "s": 1242, "text": "79sgs54uksr1fy76509 " }, { "code": null, "e": 1323, "s": 1263, "text": "Example-4: Implementing PASSWORD function on a NULL string." }, { "code": null, "e": 1350, "s": 1323, "text": "SELECT \nPASSWORD('NULL'); " }, { "code": null, "e": 1358, "s": 1350, "text": "Output:" }, { "code": null, "e": 1364, "s": 1358, "text": "NULL " }, { "code": null, "e": 1370, "s": 1364, "text": "mysql" }, { "code": null, "e": 1379, "s": 1370, "text": "SQLmysql" }, { "code": null, "e": 1383, "s": 1379, "text": "SQL" }, { "code": null, "e": 1387, "s": 1383, "text": "SQL" }, { "code": null, "e": 1485, "s": 1387, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1496, "s": 1485, "text": "CTE in SQL" }, { "code": null, "e": 1562, "s": 1496, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 1593, "s": 1562, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 1617, "s": 1593, "text": "SQL Interview Questions" }, { "code": null, "e": 1629, "s": 1617, "text": "SQL | Views" }, { "code": null, "e": 1674, "s": 1629, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 1707, "s": 1674, "text": "Difference between SQL and NoSQL" }, { "code": null, "e": 1739, "s": 1707, "text": "MySQL | Group_CONCAT() Function" }, { "code": null, "e": 1763, "s": 1739, "text": "Window functions in SQL" } ]
What is Smart Contract in Solidity?
11 May, 2022 Solidity’s code is encapsulated in contracts which means a contract in Solidity is a collection of code (its functions) and data (its state) that resides at a specific address on the Ethereum blockchain. A contract is a fundamental block of building an application on the Ethereum. Example: Solidity // Solidity program to // demonstrate how to// write a smart contract pragma solidity >= 0.4.16 < 0.7.0; // Defining a contractcontract Storage{ // Declaring state variables uint public setData; // Defining public function // that sets the value of // the state variable function set(uint x) public { setData = x; } // Defining function to // print the value of // state variable function get( ) public view returns (uint) { return setData; }} Explanation: 1. Version Pragma: pragma solidity >=0.4.16 <0.7.0; Pragmas are instructions to the compiler on how to treat the code. All solidity source code should start with a “version pragma” which is a declaration of the version of the solidity compiler this code should use. This helps the code from being incompatible with the future versions of the compiler which may bring changes. The above-mentioned code states that it is compatible with compilers of version greater than and equal to 0.4.16 but less than version 0.7.0. 2. The contract keyword: contract Storage{ //Functions and Data } The contract keyword declares a contract under which is the code encapsulated. 3. State variables: uint public setData; State variables are permanently stored in contract storage that is they are written in Ethereum Blockchain. The line uint setData declares a state variable called setData of type uint (unsigned integer of 256 bits). Think of it as adding a slot in a database. 4. A function declaration: function set(uint x) public function get() public view returns (uint) This is a function named set of access modifier type public which takes a variable x of datatype uint as a parameter. This was an example of a simple smart contract which updates the value of setData. Anyone can call the function set and overwrite the value of setData which is stored in Ethereum blockchain and there is possibly no way for anyone to stop someone from using this function. This is an example of a decentralized application that is censorship proof and unaffected to the shutdown of any centralized server. As long as someone is running a single node of Ethereum blockchain, this smart contract will be accessible. Function get will retrieve and print the value of the state variable. Output: Blockchain Solidity Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 May, 2022" }, { "code": null, "e": 311, "s": 28, "text": "Solidity’s code is encapsulated in contracts which means a contract in Solidity is a collection of code (its functions) and data (its state) that resides at a specific address on the Ethereum blockchain. A contract is a fundamental block of building an application on the Ethereum. " }, { "code": null, "e": 320, "s": 311, "text": "Example:" }, { "code": null, "e": 329, "s": 320, "text": "Solidity" }, { "code": "// Solidity program to // demonstrate how to// write a smart contract pragma solidity >= 0.4.16 < 0.7.0; // Defining a contractcontract Storage{ // Declaring state variables uint public setData; // Defining public function // that sets the value of // the state variable function set(uint x) public { setData = x; } // Defining function to // print the value of // state variable function get( ) public view returns (uint) { return setData; }}", "e": 844, "s": 329, "text": null }, { "code": null, "e": 857, "s": 844, "text": "Explanation:" }, { "code": null, "e": 877, "s": 857, "text": "1. Version Pragma: " }, { "code": null, "e": 911, "s": 877, "text": "pragma solidity >=0.4.16 <0.7.0;\n" }, { "code": null, "e": 1377, "s": 911, "text": "Pragmas are instructions to the compiler on how to treat the code. All solidity source code should start with a “version pragma” which is a declaration of the version of the solidity compiler this code should use. This helps the code from being incompatible with the future versions of the compiler which may bring changes. The above-mentioned code states that it is compatible with compilers of version greater than and equal to 0.4.16 but less than version 0.7.0." }, { "code": null, "e": 1403, "s": 1377, "text": "2. The contract keyword: " }, { "code": null, "e": 1447, "s": 1403, "text": "contract Storage{ \n//Functions and Data \n}\n" }, { "code": null, "e": 1526, "s": 1447, "text": "The contract keyword declares a contract under which is the code encapsulated." }, { "code": null, "e": 1547, "s": 1526, "text": "3. State variables: " }, { "code": null, "e": 1569, "s": 1547, "text": "uint public setData;\n" }, { "code": null, "e": 1829, "s": 1569, "text": "State variables are permanently stored in contract storage that is they are written in Ethereum Blockchain. The line uint setData declares a state variable called setData of type uint (unsigned integer of 256 bits). Think of it as adding a slot in a database." }, { "code": null, "e": 1856, "s": 1829, "text": "4. A function declaration:" }, { "code": null, "e": 1927, "s": 1856, "text": "function set(uint x) public\nfunction get() public view returns (uint)\n" }, { "code": null, "e": 2558, "s": 1927, "text": "This is a function named set of access modifier type public which takes a variable x of datatype uint as a parameter. This was an example of a simple smart contract which updates the value of setData. Anyone can call the function set and overwrite the value of setData which is stored in Ethereum blockchain and there is possibly no way for anyone to stop someone from using this function. This is an example of a decentralized application that is censorship proof and unaffected to the shutdown of any centralized server. As long as someone is running a single node of Ethereum blockchain, this smart contract will be accessible." }, { "code": null, "e": 2628, "s": 2558, "text": "Function get will retrieve and print the value of the state variable." }, { "code": null, "e": 2636, "s": 2628, "text": "Output:" }, { "code": null, "e": 2647, "s": 2636, "text": "Blockchain" }, { "code": null, "e": 2656, "s": 2647, "text": "Solidity" } ]
Python | Removing newline character from string
05 Jul, 2022 Many times, while working with Python strings, we can have a problem in which we have a huge amount of data and we need to perform preprocessing of a certain kind. This can also be removing stray newline characters in strings. Let’s discuss certain ways in which this task can be performed. Here, we will cover 4 different methods to Remove Newline From String in Python: Using the replace() function Using the strip() function Using splitlines() method Using the re.sub() Function This task can be performed using brute force in which we check for “\n” as a string in a string and replace that from each string using a loop. Python3 # initialize listtest_list = ['gf\ng', 'i\ns', 'b\nest', 'fo\nr', 'geeks\n'] # printing original listprint("The original list : " + str(test_list)) # Removing newline character from string# using loopres = []for sub in test_list: res.append(sub.replace("\n", "")) # printing resultprint("List after newline character removal : " + str(res)) Output : The original list : ['gf\ng', 'i\ns', 'b\nest', 'fo\nr', 'geeks\n'] List after newline character removal : ['gfg', 'is', 'best', 'for', 'geeks'] The strip() method in-built function of Python is used to remove all the leading and trailing spaces from a string. Our task can be performed using strip function() in which we check for “\n” as a string in a string. Python3 lis = "\n Geeks for Geeks \n"string = lis.strip()print(string) Output: Geeks for Geeks Python String splitlines() method is used to split the lines at line boundaries. The function returns a list of lines in the string, including the line break. Python3 def func(value): return ''.join(value.splitlines()) mystring = "\n Geeks \n for \n Geeks \n"print("Original string:", mystring)print("After deleting the new line:", func(mystring)) Output: Actual string: Geeks for Geeks After deleting the new line: Geeks for Geeks This task can also be executed using regex functions which can also perform the global replace of all the newline characters with an empty string. Python3 import re # initialize listtest_list = ['gf\ng', 'i\ns', 'b\nest', 'fo\nr', 'geeks\n'] # printing original listprint("The original list : " + str(test_list)) # Removing newline character from string# Using regexres = []for sub in test_list: res.append(re.sub('\n', '', sub)) # printing resultprint("List after newline character removal : " + str(res)) Output : The original list : ['gf\ng', 'i\ns', 'b\nest', 'fo\nr', 'geeks\n'] List after newline character removal : ['gfg', 'is', 'best', 'for', 'geeks'] surajkumarguptaintern Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Jul, 2022" }, { "code": null, "e": 319, "s": 28, "text": "Many times, while working with Python strings, we can have a problem in which we have a huge amount of data and we need to perform preprocessing of a certain kind. This can also be removing stray newline characters in strings. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 400, "s": 319, "text": "Here, we will cover 4 different methods to Remove Newline From String in Python:" }, { "code": null, "e": 429, "s": 400, "text": "Using the replace() function" }, { "code": null, "e": 456, "s": 429, "text": "Using the strip() function" }, { "code": null, "e": 483, "s": 456, "text": "Using splitlines() method" }, { "code": null, "e": 511, "s": 483, "text": "Using the re.sub() Function" }, { "code": null, "e": 656, "s": 511, "text": "This task can be performed using brute force in which we check for “\\n” as a string in a string and replace that from each string using a loop. " }, { "code": null, "e": 664, "s": 656, "text": "Python3" }, { "code": "# initialize listtest_list = ['gf\\ng', 'i\\ns', 'b\\nest', 'fo\\nr', 'geeks\\n'] # printing original listprint(\"The original list : \" + str(test_list)) # Removing newline character from string# using loopres = []for sub in test_list: res.append(sub.replace(\"\\n\", \"\")) # printing resultprint(\"List after newline character removal : \" + str(res))", "e": 1008, "s": 664, "text": null }, { "code": null, "e": 1017, "s": 1008, "text": "Output :" }, { "code": null, "e": 1162, "s": 1017, "text": "The original list : ['gf\\ng', 'i\\ns', 'b\\nest', 'fo\\nr', 'geeks\\n']\nList after newline character removal : ['gfg', 'is', 'best', 'for', 'geeks']" }, { "code": null, "e": 1380, "s": 1162, "text": "The strip() method in-built function of Python is used to remove all the leading and trailing spaces from a string. Our task can be performed using strip function() in which we check for “\\n” as a string in a string. " }, { "code": null, "e": 1388, "s": 1380, "text": "Python3" }, { "code": "lis = \"\\n Geeks for Geeks \\n\"string = lis.strip()print(string)", "e": 1452, "s": 1388, "text": null }, { "code": null, "e": 1460, "s": 1452, "text": "Output:" }, { "code": null, "e": 1477, "s": 1460, "text": "Geeks for Geeks" }, { "code": null, "e": 1636, "s": 1477, "text": "Python String splitlines() method is used to split the lines at line boundaries. The function returns a list of lines in the string, including the line break." }, { "code": null, "e": 1644, "s": 1636, "text": "Python3" }, { "code": "def func(value): return ''.join(value.splitlines()) mystring = \"\\n Geeks \\n for \\n Geeks \\n\"print(\"Original string:\", mystring)print(\"After deleting the new line:\", func(mystring))", "e": 1830, "s": 1644, "text": null }, { "code": null, "e": 1838, "s": 1830, "text": "Output:" }, { "code": null, "e": 1927, "s": 1838, "text": "Actual string: \n Geeks \n for \n Geeks \n\nAfter deleting the new line: Geeks for Geeks " }, { "code": null, "e": 2074, "s": 1927, "text": "This task can also be executed using regex functions which can also perform the global replace of all the newline characters with an empty string." }, { "code": null, "e": 2082, "s": 2074, "text": "Python3" }, { "code": "import re # initialize listtest_list = ['gf\\ng', 'i\\ns', 'b\\nest', 'fo\\nr', 'geeks\\n'] # printing original listprint(\"The original list : \" + str(test_list)) # Removing newline character from string# Using regexres = []for sub in test_list: res.append(re.sub('\\n', '', sub)) # printing resultprint(\"List after newline character removal : \" + str(res))", "e": 2437, "s": 2082, "text": null }, { "code": null, "e": 2446, "s": 2437, "text": "Output :" }, { "code": null, "e": 2591, "s": 2446, "text": "The original list : ['gf\\ng', 'i\\ns', 'b\\nest', 'fo\\nr', 'geeks\\n']\nList after newline character removal : ['gfg', 'is', 'best', 'for', 'geeks']" }, { "code": null, "e": 2613, "s": 2591, "text": "surajkumarguptaintern" }, { "code": null, "e": 2634, "s": 2613, "text": "Python list-programs" }, { "code": null, "e": 2641, "s": 2634, "text": "Python" }, { "code": null, "e": 2657, "s": 2641, "text": "Python Programs" } ]
SymPy - Integration
The SymPy package contains integrals module. It implements methods to calculate definite and indefinite integrals of expressions. The integrate() method is used to compute both definite and indefinite integrals. To compute an indefinite or primitive integral, just pass the variable after the expression. For example − integrate(f, x) To compute a definite integral, pass the argument as follows − (integration_variable, lower_limit, upper_limit) >>> from sympy import * >>> x,y = symbols('x y') >>> expr=x**2 + x + 1 >>> integrate(expr, x) The above code snippet gives an output equivalent to the below expression − x33+x22+x >>> expr=sin(x)*tan(x) >>> expr >>> integrate(expr,x) The above code snippet gives an output equivalent to the below expression − −log⁡(sin⁡(x)−1)2+log⁡(sin⁡(x)+1)2−sin⁡(x) The example of definite integral is given below − >>> expr=exp(-x**2) >>> integrate(expr,(x,0,oo) ) The above code snippet gives an output equivalent to the below expression − π2 You can pass multiple limit tuples to perform a multiple integral. An example is given below − >>> expr=exp(-x**2 - y**2) >>> integrate(expr,(x,0,oo),(y,0,oo)) The above code snippet gives an output equivalent to the below expression − π4 You can create unevaluated integral using Integral object, which can be evaluated by calling doit() method. >>> expr = Integral(log(x)**2, x) >>> expr The above code snippet gives an output equivalent to the below expression − ∫log(x)2dx >>> expr.doit() The above code snippet gives an output equivalent to the below expression − xlog⁡(x)2−2xlog(x)+2x SymPy supports various types of integral transforms as follows − laplace_transform fourier_transform sine_transform cosine_transform hankel_transform These functions are defined in sympy.integrals.transforms module. Following examples compute Fourier transform and Laplace transform respectively. Example 1 >>> from sympy import fourier_transform, exp >>> from sympy.abc import x, k >>> expr=exp(-x**2) >>> fourier_transform(expr, x, k) On executing the above command in python shell, following output will be generated − sqrt(pi)*exp(-pi**2*k**2) Which is equivalent to − π∗eπ2k2 Example 2 >>> from sympy.integrals import laplace_transform >>> from sympy.abc import t, s, a >>> laplace_transform(t**a, t, s) On executing the above command in python shell, following output will be generated − (s**(-a)*gamma(a + 1)/s, 0, re(a) > -1)
[ { "code": null, "e": 2458, "s": 2153, "text": "The SymPy package contains integrals module. It implements methods to calculate definite and indefinite integrals of expressions. The integrate() method is used to compute both definite and indefinite integrals. To compute an indefinite or primitive integral, just pass the variable after the expression." }, { "code": null, "e": 2472, "s": 2458, "text": "For example −" }, { "code": null, "e": 2489, "s": 2472, "text": "integrate(f, x)\n" }, { "code": null, "e": 2552, "s": 2489, "text": "To compute a definite integral, pass the argument as follows −" }, { "code": null, "e": 2602, "s": 2552, "text": "(integration_variable, lower_limit, upper_limit)\n" }, { "code": null, "e": 2700, "s": 2602, "text": ">>> from sympy import * \n>>> x,y = symbols('x y') \n>>> expr=x**2 + x + 1 \n>>> integrate(expr, x)\n" }, { "code": null, "e": 2776, "s": 2700, "text": "The above code snippet gives an output equivalent to the below expression −" }, { "code": null, "e": 2786, "s": 2776, "text": "x33+x22+x" }, { "code": null, "e": 2843, "s": 2786, "text": ">>> expr=sin(x)*tan(x) \n>>> expr \n>>> integrate(expr,x)\n" }, { "code": null, "e": 2919, "s": 2843, "text": "The above code snippet gives an output equivalent to the below expression −" }, { "code": null, "e": 2962, "s": 2919, "text": "−log⁡(sin⁡(x)−1)2+log⁡(sin⁡(x)+1)2−sin⁡(x)" }, { "code": null, "e": 3012, "s": 2962, "text": "The example of definite integral is given below −" }, { "code": null, "e": 3064, "s": 3012, "text": ">>> expr=exp(-x**2) \n>>> integrate(expr,(x,0,oo) )\n" }, { "code": null, "e": 3140, "s": 3064, "text": "The above code snippet gives an output equivalent to the below expression −" }, { "code": null, "e": 3143, "s": 3140, "text": "π2" }, { "code": null, "e": 3238, "s": 3143, "text": "You can pass multiple limit tuples to perform a multiple integral. An example is given below −" }, { "code": null, "e": 3304, "s": 3238, "text": ">>> expr=exp(-x**2 - y**2)\n>>> integrate(expr,(x,0,oo),(y,0,oo))\n" }, { "code": null, "e": 3380, "s": 3304, "text": "The above code snippet gives an output equivalent to the below expression −" }, { "code": null, "e": 3383, "s": 3380, "text": "π4" }, { "code": null, "e": 3491, "s": 3383, "text": "You can create unevaluated integral using Integral object, which can be evaluated by calling doit() method." }, { "code": null, "e": 3536, "s": 3491, "text": ">>> expr = Integral(log(x)**2, x) \n>>> expr\n" }, { "code": null, "e": 3612, "s": 3536, "text": "The above code snippet gives an output equivalent to the below expression −" }, { "code": null, "e": 3623, "s": 3612, "text": "∫log(x)2dx" }, { "code": null, "e": 3640, "s": 3623, "text": ">>> expr.doit()\n" }, { "code": null, "e": 3716, "s": 3640, "text": "The above code snippet gives an output equivalent to the below expression −" }, { "code": null, "e": 3738, "s": 3716, "text": "xlog⁡(x)2−2xlog(x)+2x" }, { "code": null, "e": 3803, "s": 3738, "text": "SymPy supports various types of integral transforms as follows −" }, { "code": null, "e": 3821, "s": 3803, "text": "laplace_transform" }, { "code": null, "e": 3839, "s": 3821, "text": "fourier_transform" }, { "code": null, "e": 3854, "s": 3839, "text": "sine_transform" }, { "code": null, "e": 3871, "s": 3854, "text": "cosine_transform" }, { "code": null, "e": 3888, "s": 3871, "text": "hankel_transform" }, { "code": null, "e": 4035, "s": 3888, "text": "These functions are defined in sympy.integrals.transforms module. Following examples compute Fourier transform and Laplace transform respectively." }, { "code": null, "e": 4045, "s": 4035, "text": "Example 1" }, { "code": null, "e": 4179, "s": 4045, "text": ">>> from sympy import fourier_transform, exp \n>>> from sympy.abc import x, k \n>>> expr=exp(-x**2) \n>>> fourier_transform(expr, x, k)\n" }, { "code": null, "e": 4264, "s": 4179, "text": "On executing the above command in python shell, following output will be generated −" }, { "code": null, "e": 4291, "s": 4264, "text": "sqrt(pi)*exp(-pi**2*k**2)\n" }, { "code": null, "e": 4316, "s": 4291, "text": "Which is equivalent to −" }, { "code": null, "e": 4324, "s": 4316, "text": "π∗eπ2k2" }, { "code": null, "e": 4334, "s": 4324, "text": "Example 2" }, { "code": null, "e": 4455, "s": 4334, "text": ">>> from sympy.integrals import laplace_transform \n>>> from sympy.abc import t, s, a \n>>> laplace_transform(t**a, t, s)\n" }, { "code": null, "e": 4540, "s": 4455, "text": "On executing the above command in python shell, following output will be generated −" } ]
SQL | Date Functions (Set-2)
19 Jul, 2018 In SQL, dates are complicated for newbies, since while working with a database, the format of the date in the table must be matched with the input date in order to insert. In various scenarios instead of date, datetime (time is also involved with date) is used. Some of the date functions have been already discussed in the Set-1. In this post, the remaining date functions have been discussed. Below are the remaining date functions that are used in SQL: MICROSECOND(): It returns the microsecond portion of a date value.Syntax: SELECT MICROSECOND("2018-07-18 09:12:00.000345");Output: 345MINUTE(): It returns the minute portion of a date value.Syntax: SELECT MINUTE("2018-07-18 09:12:00");Output: 12MONTH(): It returns the month portion of a date value.Syntax: SELECT MONTH ('2018/07/18')AS MONTH;Output: 7MONTHNAME(): It returns the full month name for a date.Syntax: SELECT MONTHNAME("2018/07/18");Output: JULYNOW(): It returns the current date and time.Syntax: SELECT NOW();Output: 2018-07-18 09:14:32PERIOD_ADD(): It takes a period and adds a specified number of months to it.Syntax: SELECT PERIOD_ADD(201803, 6);Output: 201809PERIOD_DIFF(): It returns the difference in months between two periods.Syntax: SELECT PERIOD_DIFF(201810, 201802);Output: 8QUARTER(): It returns the quarter portion of a date value.Syntax: SELECT QUARTER("2018/07/18");Output: 3SECOND(): It returns the second portion of a date value.Syntax: SELECT SECOND("09:14:00:00032");Output: 0SEC_TO_TIME(): It converts numeric seconds into a time value.Syntax: SELECT SEC_TO_TIME(1);Output: 00:00:01STR_TO_DATE(): It takes a string and returns a date specified by a format mask.Syntax: SELECT STR_TO_DATE("JULY 18 2018", "%M %D %Y");Output: 0018-07-18SUBDATE(): It returns a date after which a certain time/date interval has been subtracted.Syntax: SELECT SUBDATE("2017-06-15", INTERVAL 10 DAY);Output: 2017-06-05SUBTIME(): It returns a time/date time value after a certain time interval has been subtracted.Syntax: SELECT SUBDATE("2018/07/18", INTERVAL 10 DAY);Output: 2018-07-18 09:15:17.542768SYSDATE(): It returns the current date and time.Syntax: SELECT SYSDATE();Output: 2018-07-18 09:19:03TIME(): It extracts the time value from a time/date time expression.Syntax: SELECT TIME("09:16:10");Output: 09:16:10TIME_FORMAT(): It formats the time as specified by a format mask.Syntax: SELECT TIME_FORMAT("09:16:10", "%H %I %S");Output: 09 09 10TIME_TO_SEC(): It converts a time value into numeric seconds.Syntax: SELECT TIME_TO_SEC("09:16:10");Output: 33370TIMEDIFF(): It returns the difference between two time/datetime values.Syntax: SELECT TIMEDIFF("09:16:10", "09:16:04");Output: 00:00:06TIMESTAMP(): It converts an expression to a date time value and if specified adds an optional time interval to the value.Syntax: SELECT TIMESTAMP("2018-07-18", "09:16:10");Output: 2018-07-18 09:16:10TO_DAYS(): It converts a date into numeric days.Syntax: SELECT TO_DAYS("2018-07-18");Output: 737258WEEK(): It returns the week portion of a date value.Syntax: SELECT WEEK("2018-07-18");Output: 28WEEKDAY(): It returns the weekday index for a date value.Syntax: SELECT WEEKDAY("2018-07-18");Output: 2WEEKOFYEAR(): It returns the week of the year for a date value.Syntax: SELECT WEEKOFYEAR("2018-07-18");Output: 29YEAR(): It returns the year portion of a date value.Syntax: SELECT YEAR("2018-07-18");Output: 2018YEARWEEK(): It returns the year and week for a date value.Syntax: SELECT YEARWEEK("2018-07-18");Output: 201828 MICROSECOND(): It returns the microsecond portion of a date value.Syntax: SELECT MICROSECOND("2018-07-18 09:12:00.000345");Output: 345 Syntax: SELECT MICROSECOND("2018-07-18 09:12:00.000345"); Output: 345 MINUTE(): It returns the minute portion of a date value.Syntax: SELECT MINUTE("2018-07-18 09:12:00");Output: 12 Syntax: SELECT MINUTE("2018-07-18 09:12:00"); Output: 12 MONTH(): It returns the month portion of a date value.Syntax: SELECT MONTH ('2018/07/18')AS MONTH;Output: 7 Syntax: SELECT MONTH ('2018/07/18')AS MONTH; Output: 7 MONTHNAME(): It returns the full month name for a date.Syntax: SELECT MONTHNAME("2018/07/18");Output: JULY Syntax: SELECT MONTHNAME("2018/07/18"); Output: JULY NOW(): It returns the current date and time.Syntax: SELECT NOW();Output: 2018-07-18 09:14:32 Syntax: SELECT NOW(); Output: 2018-07-18 09:14:32 PERIOD_ADD(): It takes a period and adds a specified number of months to it.Syntax: SELECT PERIOD_ADD(201803, 6);Output: 201809 Syntax: SELECT PERIOD_ADD(201803, 6); Output: 201809 PERIOD_DIFF(): It returns the difference in months between two periods.Syntax: SELECT PERIOD_DIFF(201810, 201802);Output: 8 Syntax: SELECT PERIOD_DIFF(201810, 201802); Output: 8 QUARTER(): It returns the quarter portion of a date value.Syntax: SELECT QUARTER("2018/07/18");Output: 3 Syntax: SELECT QUARTER("2018/07/18"); Output: 3 SECOND(): It returns the second portion of a date value.Syntax: SELECT SECOND("09:14:00:00032");Output: 0 Syntax: SELECT SECOND("09:14:00:00032"); Output: 0 SEC_TO_TIME(): It converts numeric seconds into a time value.Syntax: SELECT SEC_TO_TIME(1);Output: 00:00:01 Syntax: SELECT SEC_TO_TIME(1); Output: 00:00:01 STR_TO_DATE(): It takes a string and returns a date specified by a format mask.Syntax: SELECT STR_TO_DATE("JULY 18 2018", "%M %D %Y");Output: 0018-07-18 Syntax: SELECT STR_TO_DATE("JULY 18 2018", "%M %D %Y"); Output: 0018-07-18 SUBDATE(): It returns a date after which a certain time/date interval has been subtracted.Syntax: SELECT SUBDATE("2017-06-15", INTERVAL 10 DAY);Output: 2017-06-05 Syntax: SELECT SUBDATE("2017-06-15", INTERVAL 10 DAY); Output: 2017-06-05 SUBTIME(): It returns a time/date time value after a certain time interval has been subtracted.Syntax: SELECT SUBDATE("2018/07/18", INTERVAL 10 DAY);Output: 2018-07-18 09:15:17.542768 Syntax: SELECT SUBDATE("2018/07/18", INTERVAL 10 DAY); Output: 2018-07-18 09:15:17.542768 SYSDATE(): It returns the current date and time.Syntax: SELECT SYSDATE();Output: 2018-07-18 09:19:03 Syntax: SELECT SYSDATE(); Output: 2018-07-18 09:19:03 TIME(): It extracts the time value from a time/date time expression.Syntax: SELECT TIME("09:16:10");Output: 09:16:10 Syntax: SELECT TIME("09:16:10"); Output: 09:16:10 TIME_FORMAT(): It formats the time as specified by a format mask.Syntax: SELECT TIME_FORMAT("09:16:10", "%H %I %S");Output: 09 09 10 Syntax: SELECT TIME_FORMAT("09:16:10", "%H %I %S"); Output: 09 09 10 TIME_TO_SEC(): It converts a time value into numeric seconds.Syntax: SELECT TIME_TO_SEC("09:16:10");Output: 33370 Syntax: SELECT TIME_TO_SEC("09:16:10"); Output: 33370 TIMEDIFF(): It returns the difference between two time/datetime values.Syntax: SELECT TIMEDIFF("09:16:10", "09:16:04");Output: 00:00:06 Syntax: SELECT TIMEDIFF("09:16:10", "09:16:04"); Output: 00:00:06 TIMESTAMP(): It converts an expression to a date time value and if specified adds an optional time interval to the value.Syntax: SELECT TIMESTAMP("2018-07-18", "09:16:10");Output: 2018-07-18 09:16:10 Syntax: SELECT TIMESTAMP("2018-07-18", "09:16:10"); Output: 2018-07-18 09:16:10 TO_DAYS(): It converts a date into numeric days.Syntax: SELECT TO_DAYS("2018-07-18");Output: 737258 Syntax: SELECT TO_DAYS("2018-07-18"); Output: 737258 WEEK(): It returns the week portion of a date value.Syntax: SELECT WEEK("2018-07-18");Output: 28 Syntax: SELECT WEEK("2018-07-18"); Output: 28 WEEKDAY(): It returns the weekday index for a date value.Syntax: SELECT WEEKDAY("2018-07-18");Output: 2 Syntax: SELECT WEEKDAY("2018-07-18"); Output: 2 WEEKOFYEAR(): It returns the week of the year for a date value.Syntax: SELECT WEEKOFYEAR("2018-07-18");Output: 29 Syntax: SELECT WEEKOFYEAR("2018-07-18"); Output: 29 YEAR(): It returns the year portion of a date value.Syntax: SELECT YEAR("2018-07-18");Output: 2018 Syntax: SELECT YEAR("2018-07-18"); Output: 2018 YEARWEEK(): It returns the year and week for a date value.Syntax: SELECT YEARWEEK("2018-07-18");Output: 201828 Syntax: SELECT YEARWEEK("2018-07-18"); Output: 201828 SQL-Functions SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. CTE in SQL SQL Trigger | Student Database How to Update Multiple Columns in Single Update Statement in SQL? SQL Interview Questions SQL | Views Difference between DELETE, DROP and TRUNCATE Window functions in SQL MySQL | Group_CONCAT() Function Difference between DELETE and TRUNCATE Difference between DDL and DML in DBMS
[ { "code": null, "e": 52, "s": 24, "text": "\n19 Jul, 2018" }, { "code": null, "e": 314, "s": 52, "text": "In SQL, dates are complicated for newbies, since while working with a database, the format of the date in the table must be matched with the input date in order to insert. In various scenarios instead of date, datetime (time is also involved with date) is used." }, { "code": null, "e": 447, "s": 314, "text": "Some of the date functions have been already discussed in the Set-1. In this post, the remaining date functions have been discussed." }, { "code": null, "e": 508, "s": 447, "text": "Below are the remaining date functions that are used in SQL:" }, { "code": null, "e": 3538, "s": 508, "text": "MICROSECOND(): It returns the microsecond portion of a date value.Syntax: SELECT MICROSECOND(\"2018-07-18 09:12:00.000345\");Output: 345MINUTE(): It returns the minute portion of a date value.Syntax: SELECT MINUTE(\"2018-07-18 09:12:00\");Output: 12MONTH(): It returns the month portion of a date value.Syntax: SELECT MONTH ('2018/07/18')AS MONTH;Output: 7MONTHNAME(): It returns the full month name for a date.Syntax: SELECT MONTHNAME(\"2018/07/18\");Output: JULYNOW(): It returns the current date and time.Syntax: SELECT NOW();Output: 2018-07-18 09:14:32PERIOD_ADD(): It takes a period and adds a specified number of months to it.Syntax: SELECT PERIOD_ADD(201803, 6);Output: 201809PERIOD_DIFF(): It returns the difference in months between two periods.Syntax: SELECT PERIOD_DIFF(201810, 201802);Output: 8QUARTER(): It returns the quarter portion of a date value.Syntax: SELECT QUARTER(\"2018/07/18\");Output: 3SECOND(): It returns the second portion of a date value.Syntax: SELECT SECOND(\"09:14:00:00032\");Output: 0SEC_TO_TIME(): It converts numeric seconds into a time value.Syntax: SELECT SEC_TO_TIME(1);Output: 00:00:01STR_TO_DATE(): It takes a string and returns a date specified by a format mask.Syntax: SELECT STR_TO_DATE(\"JULY 18 2018\", \"%M %D %Y\");Output: 0018-07-18SUBDATE(): It returns a date after which a certain time/date interval has been subtracted.Syntax: SELECT SUBDATE(\"2017-06-15\", INTERVAL 10 DAY);Output: 2017-06-05SUBTIME(): It returns a time/date time value after a certain time interval has been subtracted.Syntax: SELECT SUBDATE(\"2018/07/18\", INTERVAL 10 DAY);Output: 2018-07-18 09:15:17.542768SYSDATE(): It returns the current date and time.Syntax: SELECT SYSDATE();Output: 2018-07-18 09:19:03TIME(): It extracts the time value from a time/date time expression.Syntax: SELECT TIME(\"09:16:10\");Output: 09:16:10TIME_FORMAT(): It formats the time as specified by a format mask.Syntax: SELECT TIME_FORMAT(\"09:16:10\", \"%H %I %S\");Output: 09 09 10TIME_TO_SEC(): It converts a time value into numeric seconds.Syntax: SELECT TIME_TO_SEC(\"09:16:10\");Output: 33370TIMEDIFF(): It returns the difference between two time/datetime values.Syntax: SELECT TIMEDIFF(\"09:16:10\", \"09:16:04\");Output: 00:00:06TIMESTAMP(): It converts an expression to a date time value and if specified adds an optional time interval to the value.Syntax: SELECT TIMESTAMP(\"2018-07-18\", \"09:16:10\");Output: 2018-07-18 09:16:10TO_DAYS(): It converts a date into numeric days.Syntax: SELECT TO_DAYS(\"2018-07-18\");Output: 737258WEEK(): It returns the week portion of a date value.Syntax: SELECT WEEK(\"2018-07-18\");Output: 28WEEKDAY(): It returns the weekday index for a date value.Syntax: SELECT WEEKDAY(\"2018-07-18\");Output: 2WEEKOFYEAR(): It returns the week of the year for a date value.Syntax: SELECT WEEKOFYEAR(\"2018-07-18\");Output: 29YEAR(): It returns the year portion of a date value.Syntax: SELECT YEAR(\"2018-07-18\");Output: 2018YEARWEEK(): It returns the year and week for a date value.Syntax: SELECT YEARWEEK(\"2018-07-18\");Output: 201828" }, { "code": null, "e": 3673, "s": 3538, "text": "MICROSECOND(): It returns the microsecond portion of a date value.Syntax: SELECT MICROSECOND(\"2018-07-18 09:12:00.000345\");Output: 345" }, { "code": null, "e": 3731, "s": 3673, "text": "Syntax: SELECT MICROSECOND(\"2018-07-18 09:12:00.000345\");" }, { "code": null, "e": 3743, "s": 3731, "text": "Output: 345" }, { "code": null, "e": 3855, "s": 3743, "text": "MINUTE(): It returns the minute portion of a date value.Syntax: SELECT MINUTE(\"2018-07-18 09:12:00\");Output: 12" }, { "code": null, "e": 3901, "s": 3855, "text": "Syntax: SELECT MINUTE(\"2018-07-18 09:12:00\");" }, { "code": null, "e": 3912, "s": 3901, "text": "Output: 12" }, { "code": null, "e": 4020, "s": 3912, "text": "MONTH(): It returns the month portion of a date value.Syntax: SELECT MONTH ('2018/07/18')AS MONTH;Output: 7" }, { "code": null, "e": 4065, "s": 4020, "text": "Syntax: SELECT MONTH ('2018/07/18')AS MONTH;" }, { "code": null, "e": 4075, "s": 4065, "text": "Output: 7" }, { "code": null, "e": 4182, "s": 4075, "text": "MONTHNAME(): It returns the full month name for a date.Syntax: SELECT MONTHNAME(\"2018/07/18\");Output: JULY" }, { "code": null, "e": 4222, "s": 4182, "text": "Syntax: SELECT MONTHNAME(\"2018/07/18\");" }, { "code": null, "e": 4235, "s": 4222, "text": "Output: JULY" }, { "code": null, "e": 4328, "s": 4235, "text": "NOW(): It returns the current date and time.Syntax: SELECT NOW();Output: 2018-07-18 09:14:32" }, { "code": null, "e": 4350, "s": 4328, "text": "Syntax: SELECT NOW();" }, { "code": null, "e": 4378, "s": 4350, "text": "Output: 2018-07-18 09:14:32" }, { "code": null, "e": 4506, "s": 4378, "text": "PERIOD_ADD(): It takes a period and adds a specified number of months to it.Syntax: SELECT PERIOD_ADD(201803, 6);Output: 201809" }, { "code": null, "e": 4544, "s": 4506, "text": "Syntax: SELECT PERIOD_ADD(201803, 6);" }, { "code": null, "e": 4559, "s": 4544, "text": "Output: 201809" }, { "code": null, "e": 4683, "s": 4559, "text": "PERIOD_DIFF(): It returns the difference in months between two periods.Syntax: SELECT PERIOD_DIFF(201810, 201802);Output: 8" }, { "code": null, "e": 4727, "s": 4683, "text": "Syntax: SELECT PERIOD_DIFF(201810, 201802);" }, { "code": null, "e": 4737, "s": 4727, "text": "Output: 8" }, { "code": null, "e": 4842, "s": 4737, "text": "QUARTER(): It returns the quarter portion of a date value.Syntax: SELECT QUARTER(\"2018/07/18\");Output: 3" }, { "code": null, "e": 4880, "s": 4842, "text": "Syntax: SELECT QUARTER(\"2018/07/18\");" }, { "code": null, "e": 4890, "s": 4880, "text": "Output: 3" }, { "code": null, "e": 4996, "s": 4890, "text": "SECOND(): It returns the second portion of a date value.Syntax: SELECT SECOND(\"09:14:00:00032\");Output: 0" }, { "code": null, "e": 5037, "s": 4996, "text": "Syntax: SELECT SECOND(\"09:14:00:00032\");" }, { "code": null, "e": 5047, "s": 5037, "text": "Output: 0" }, { "code": null, "e": 5155, "s": 5047, "text": "SEC_TO_TIME(): It converts numeric seconds into a time value.Syntax: SELECT SEC_TO_TIME(1);Output: 00:00:01" }, { "code": null, "e": 5186, "s": 5155, "text": "Syntax: SELECT SEC_TO_TIME(1);" }, { "code": null, "e": 5203, "s": 5186, "text": "Output: 00:00:01" }, { "code": null, "e": 5357, "s": 5203, "text": "STR_TO_DATE(): It takes a string and returns a date specified by a format mask.Syntax: SELECT STR_TO_DATE(\"JULY 18 2018\", \"%M %D %Y\");Output: 0018-07-18" }, { "code": null, "e": 5414, "s": 5357, "text": "Syntax: SELECT STR_TO_DATE(\"JULY 18 2018\", \"%M %D %Y\");" }, { "code": null, "e": 5433, "s": 5414, "text": "Output: 0018-07-18" }, { "code": null, "e": 5596, "s": 5433, "text": "SUBDATE(): It returns a date after which a certain time/date interval has been subtracted.Syntax: SELECT SUBDATE(\"2017-06-15\", INTERVAL 10 DAY);Output: 2017-06-05" }, { "code": null, "e": 5651, "s": 5596, "text": "Syntax: SELECT SUBDATE(\"2017-06-15\", INTERVAL 10 DAY);" }, { "code": null, "e": 5670, "s": 5651, "text": "Output: 2017-06-05" }, { "code": null, "e": 5854, "s": 5670, "text": "SUBTIME(): It returns a time/date time value after a certain time interval has been subtracted.Syntax: SELECT SUBDATE(\"2018/07/18\", INTERVAL 10 DAY);Output: 2018-07-18 09:15:17.542768" }, { "code": null, "e": 5909, "s": 5854, "text": "Syntax: SELECT SUBDATE(\"2018/07/18\", INTERVAL 10 DAY);" }, { "code": null, "e": 5944, "s": 5909, "text": "Output: 2018-07-18 09:15:17.542768" }, { "code": null, "e": 6045, "s": 5944, "text": "SYSDATE(): It returns the current date and time.Syntax: SELECT SYSDATE();Output: 2018-07-18 09:19:03" }, { "code": null, "e": 6071, "s": 6045, "text": "Syntax: SELECT SYSDATE();" }, { "code": null, "e": 6099, "s": 6071, "text": "Output: 2018-07-18 09:19:03" }, { "code": null, "e": 6216, "s": 6099, "text": "TIME(): It extracts the time value from a time/date time expression.Syntax: SELECT TIME(\"09:16:10\");Output: 09:16:10" }, { "code": null, "e": 6249, "s": 6216, "text": "Syntax: SELECT TIME(\"09:16:10\");" }, { "code": null, "e": 6266, "s": 6249, "text": "Output: 09:16:10" }, { "code": null, "e": 6399, "s": 6266, "text": "TIME_FORMAT(): It formats the time as specified by a format mask.Syntax: SELECT TIME_FORMAT(\"09:16:10\", \"%H %I %S\");Output: 09 09 10" }, { "code": null, "e": 6451, "s": 6399, "text": "Syntax: SELECT TIME_FORMAT(\"09:16:10\", \"%H %I %S\");" }, { "code": null, "e": 6468, "s": 6451, "text": "Output: 09 09 10" }, { "code": null, "e": 6582, "s": 6468, "text": "TIME_TO_SEC(): It converts a time value into numeric seconds.Syntax: SELECT TIME_TO_SEC(\"09:16:10\");Output: 33370" }, { "code": null, "e": 6622, "s": 6582, "text": "Syntax: SELECT TIME_TO_SEC(\"09:16:10\");" }, { "code": null, "e": 6636, "s": 6622, "text": "Output: 33370" }, { "code": null, "e": 6772, "s": 6636, "text": "TIMEDIFF(): It returns the difference between two time/datetime values.Syntax: SELECT TIMEDIFF(\"09:16:10\", \"09:16:04\");Output: 00:00:06" }, { "code": null, "e": 6821, "s": 6772, "text": "Syntax: SELECT TIMEDIFF(\"09:16:10\", \"09:16:04\");" }, { "code": null, "e": 6838, "s": 6821, "text": "Output: 00:00:06" }, { "code": null, "e": 7038, "s": 6838, "text": "TIMESTAMP(): It converts an expression to a date time value and if specified adds an optional time interval to the value.Syntax: SELECT TIMESTAMP(\"2018-07-18\", \"09:16:10\");Output: 2018-07-18 09:16:10" }, { "code": null, "e": 7090, "s": 7038, "text": "Syntax: SELECT TIMESTAMP(\"2018-07-18\", \"09:16:10\");" }, { "code": null, "e": 7118, "s": 7090, "text": "Output: 2018-07-18 09:16:10" }, { "code": null, "e": 7218, "s": 7118, "text": "TO_DAYS(): It converts a date into numeric days.Syntax: SELECT TO_DAYS(\"2018-07-18\");Output: 737258" }, { "code": null, "e": 7256, "s": 7218, "text": "Syntax: SELECT TO_DAYS(\"2018-07-18\");" }, { "code": null, "e": 7271, "s": 7256, "text": "Output: 737258" }, { "code": null, "e": 7368, "s": 7271, "text": "WEEK(): It returns the week portion of a date value.Syntax: SELECT WEEK(\"2018-07-18\");Output: 28" }, { "code": null, "e": 7403, "s": 7368, "text": "Syntax: SELECT WEEK(\"2018-07-18\");" }, { "code": null, "e": 7414, "s": 7403, "text": "Output: 28" }, { "code": null, "e": 7518, "s": 7414, "text": "WEEKDAY(): It returns the weekday index for a date value.Syntax: SELECT WEEKDAY(\"2018-07-18\");Output: 2" }, { "code": null, "e": 7556, "s": 7518, "text": "Syntax: SELECT WEEKDAY(\"2018-07-18\");" }, { "code": null, "e": 7566, "s": 7556, "text": "Output: 2" }, { "code": null, "e": 7680, "s": 7566, "text": "WEEKOFYEAR(): It returns the week of the year for a date value.Syntax: SELECT WEEKOFYEAR(\"2018-07-18\");Output: 29" }, { "code": null, "e": 7721, "s": 7680, "text": "Syntax: SELECT WEEKOFYEAR(\"2018-07-18\");" }, { "code": null, "e": 7732, "s": 7721, "text": "Output: 29" }, { "code": null, "e": 7831, "s": 7732, "text": "YEAR(): It returns the year portion of a date value.Syntax: SELECT YEAR(\"2018-07-18\");Output: 2018" }, { "code": null, "e": 7866, "s": 7831, "text": "Syntax: SELECT YEAR(\"2018-07-18\");" }, { "code": null, "e": 7879, "s": 7866, "text": "Output: 2018" }, { "code": null, "e": 7991, "s": 7879, "text": "YEARWEEK(): It returns the year and week for a date value.Syntax: SELECT YEARWEEK(\"2018-07-18\");Output: 201828" }, { "code": null, "e": 8031, "s": 7991, "text": "Syntax: SELECT YEARWEEK(\"2018-07-18\");" }, { "code": null, "e": 8046, "s": 8031, "text": "Output: 201828" }, { "code": null, "e": 8060, "s": 8046, "text": "SQL-Functions" }, { "code": null, "e": 8064, "s": 8060, "text": "SQL" }, { "code": null, "e": 8068, "s": 8064, "text": "SQL" }, { "code": null, "e": 8166, "s": 8068, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8177, "s": 8166, "text": "CTE in SQL" }, { "code": null, "e": 8208, "s": 8177, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 8274, "s": 8208, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 8298, "s": 8274, "text": "SQL Interview Questions" }, { "code": null, "e": 8310, "s": 8298, "text": "SQL | Views" }, { "code": null, "e": 8355, "s": 8310, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 8379, "s": 8355, "text": "Window functions in SQL" }, { "code": null, "e": 8411, "s": 8379, "text": "MySQL | Group_CONCAT() Function" }, { "code": null, "e": 8450, "s": 8411, "text": "Difference between DELETE and TRUNCATE" } ]
Program to print number pattern
04 Jun, 2022 We have to print a pattern where in middle column contains only 1, right side columns contain constant digit which is greater than 1 and left side columns contains constant digit which is greater than 1. Every row should look like a Palindrome. Examples : Input : 3 Output : 1 2 1 2 1 Input : 5 Output : 1 2 1 2 3 2 1 2 3 2 1 2 1 Below is the implementation to print the following pattern : C++ Java Python3 C# PHP Javascript // CPP program to print pattern#include <bits/stdc++.h>using namespace std; void display(){ int n = 5; int space = n / 2, num = 1; // Outer for loop for // number of rows for (int i = 1; i <= n; i++) { // Inner for loop for // printing space for (int j = 1; j <= space; j++) cout<<" "; // Logic for printing // the pattern for everyline int count = num / 2 + 1; for (int k = 1; k <= num; k++) { cout<<count; // Value of count decrements // in every cycle if (k <= num /2 ) count--; // Value of count will // increment in every cycle else count++; } cout<<"\n"; // Before reaching half Space // is decreased by 1 and num // is increased by 2 if (i <= n / 2) { space = space - 1; num = num + 2; } // After reaching to half // space is increased by 1 // and num is decreased by 2 else { space = space + 1; num = num - 2; } }} // Driver Codeint main(){ display(); return 0;} // This code is contributed by Nikita tiwari. // Java program to print above patternimport java.util.Scanner;class Pattern{ void display() { int n = 5; int space = n / 2, num = 1; // Outer for loop for // number of rows for (int i = 1; i <= n; i++) { // Inner for loop // for printing space for (int j = 1; j <= space; j++) System.out.print(" "); // Logic for printing // the pattern for everyline int count = num / 2 + 1; for (int k = 1; k <= num; k++) { System.out.print(count); // Value of count decrements // in every cycle if (k <= num /2 ) count--; // Value of count will increment // in every cycle else count++; } System.out.println(); // Before reaching half Space is decreased // by 1 and num is increased by 2 if (i <= n / 2) { space = space - 1; num = num + 2; } // After reaching to half space is increased // by 1 and num is decreased by 2 else { space = space + 1; num = num - 2; } } } // Driver Code public static void main(String[] args) { Pattern p = new Pattern(); p.display(); }} # Python 3 program to# print above pattern def display() : n = 5 space = n // 2 num = 1 # Outer for loop for # number of rows for i in range(1, n+1) : # Inner for loop for # printing space for j in range(1, space+1) : print(" ", end = "") # Logic for printing the # pattern for everyline count = num // 2 + 1 for k in range(1, num+1) : print(count, end = "") # Value of count decrements # in every cycle if (k <= num // 2 ) : count = count -1 # Value of count will # increment in every cycle else : count = count + 1 print() # Before reaching half Space # is decreased by 1 and num # is increased by 2 if (i <= n // 2) : space = space - 1 num = num + 2 # After reaching to half # space is increased by 1 # and num is decreased by 2 else : space = space + 1 num = num - 2 # Driver Codedisplay() #This code is contributed by Nikita Tiwari. // C# program to print above patternusing System;class Pattern{ void display() { int n = 5; int space = n / 2, num = 1; // Outer for loop for // number of rows for (int i = 1; i <= n; i++) { // Inner for loop // for printing space for (int j = 1; j <= space; j++) Console.Write(" "); // Logic for printing // the pattern for everyline int count = num / 2 + 1; for (int k = 1; k <= num; k++) { Console.Write(count); // Value of count decrements // in every cycle if (k <= num /2 ) count--; // Value of count will increment // in every cycle else count++; } Console.WriteLine(); // Before reaching half Space is decreased // by 1 and num is increased by 2 if (i <= n / 2) { space = space - 1; num = num + 2; } // After reaching to half space is increased // by 1 and num is decreased by 2 else { space = space + 1; num = num - 2; } } } // Driver Code public static void Main() { Pattern p = new Pattern(); p.display(); }}// This code is contributed by vt_m. <?php// php program to print// above pattern function display($n) { $space = $n / 2; $num = 1; // Outer for loop for // number of rows for ($i = 1; $i <= $n; $i++) { // Inner for loop // for printing space for ($j = 1; $j <= $space; $j++) echo " "; // Logic for printing // the pattern for everyline $count = $num / 2 + 1; for ($k = 1; $k <= $num; $k++) { echo floor($count); // Value of count decrements // in every cycle if ($k <= $num /2 ) $count--; // Value of count will increment // in every cycle else $count++; } echo "\n"; // Before reaching half Space // is decreased by 1 and // num is increased by 2 if ($i <= $n / 2) { $space = $space - 1; $num = $num + 2; } // After reaching to half // space is increased by 1 // and num is decreased by 2 else { $space = $space + 1; $num = $num - 2; } } } // Driver Code$n = 5;display($n); // This code is contributed by mits?> <script> // JavaScript program to print pattern function display() { var n = 5; var space = parseInt(n / 2), num = 1; // Outer for loop for // number of rows for (var i = 1; i <= n; i++) { // Inner for loop for // printing space for (var j = 1; j <= space; j++) document.write(" "); // Logic for printing // the pattern for everyline var count = parseInt(num / 2 + 1); for (var k = 1; k <= num; k++) { document.write(count); // Value of count decrements // in every cycle if (k <= num / 2) count--; // Value of count will // increment in every cycle else count++; } document.write("<br>"); // Before reaching half Space // is decreased by 1 and num // is increased by 2 if (i <= n / 2) { space = space - 1; num = num + 2; } // After reaching to half // space is increased by 1 // and num is decreased by 2 else { space = space + 1; num = num - 2; } } } // Driver Code display(); </script> Output : 1 212 32123 212 1 Time Complexity: O(n2), where n represents the given input.Auxiliary Space: O(1), no extra space is required, so it is a constant. Mithun Kumar rdtank sweetyty samim2000 pattern-printing School Programming pattern-printing Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Constructors in Java Exceptions in Java Python Exception Handling Python Try Except Ternary Operator in Python How JVM Works - JVM Architecture? Python program to add two numbers Variables in Java Data types in Java Difference between Abstract Class and Interface in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n04 Jun, 2022" }, { "code": null, "e": 299, "s": 54, "text": "We have to print a pattern where in middle column contains only 1, right side columns contain constant digit which is greater than 1 and left side columns contains constant digit which is greater than 1. Every row should look like a Palindrome." }, { "code": null, "e": 311, "s": 299, "text": "Examples : " }, { "code": null, "e": 417, "s": 311, "text": "Input : 3\nOutput :\n 1\n 2 1 2\n 1\n\nInput : 5\nOutput :\n 1\n 2 1 2\n3 2 1 2 3\n 2 1 2\n 1" }, { "code": null, "e": 478, "s": 417, "text": "Below is the implementation to print the following pattern :" }, { "code": null, "e": 482, "s": 478, "text": "C++" }, { "code": null, "e": 487, "s": 482, "text": "Java" }, { "code": null, "e": 495, "s": 487, "text": "Python3" }, { "code": null, "e": 498, "s": 495, "text": "C#" }, { "code": null, "e": 502, "s": 498, "text": "PHP" }, { "code": null, "e": 513, "s": 502, "text": "Javascript" }, { "code": "// CPP program to print pattern#include <bits/stdc++.h>using namespace std; void display(){ int n = 5; int space = n / 2, num = 1; // Outer for loop for // number of rows for (int i = 1; i <= n; i++) { // Inner for loop for // printing space for (int j = 1; j <= space; j++) cout<<\" \"; // Logic for printing // the pattern for everyline int count = num / 2 + 1; for (int k = 1; k <= num; k++) { cout<<count; // Value of count decrements // in every cycle if (k <= num /2 ) count--; // Value of count will // increment in every cycle else count++; } cout<<\"\\n\"; // Before reaching half Space // is decreased by 1 and num // is increased by 2 if (i <= n / 2) { space = space - 1; num = num + 2; } // After reaching to half // space is increased by 1 // and num is decreased by 2 else { space = space + 1; num = num - 2; } }} // Driver Codeint main(){ display(); return 0;} // This code is contributed by Nikita tiwari.", "e": 1831, "s": 513, "text": null }, { "code": "// Java program to print above patternimport java.util.Scanner;class Pattern{ void display() { int n = 5; int space = n / 2, num = 1; // Outer for loop for // number of rows for (int i = 1; i <= n; i++) { // Inner for loop // for printing space for (int j = 1; j <= space; j++) System.out.print(\" \"); // Logic for printing // the pattern for everyline int count = num / 2 + 1; for (int k = 1; k <= num; k++) { System.out.print(count); // Value of count decrements // in every cycle if (k <= num /2 ) count--; // Value of count will increment // in every cycle else count++; } System.out.println(); // Before reaching half Space is decreased // by 1 and num is increased by 2 if (i <= n / 2) { space = space - 1; num = num + 2; } // After reaching to half space is increased // by 1 and num is decreased by 2 else { space = space + 1; num = num - 2; } } } // Driver Code public static void main(String[] args) { Pattern p = new Pattern(); p.display(); }}", "e": 3345, "s": 1831, "text": null }, { "code": "# Python 3 program to# print above pattern def display() : n = 5 space = n // 2 num = 1 # Outer for loop for # number of rows for i in range(1, n+1) : # Inner for loop for # printing space for j in range(1, space+1) : print(\" \", end = \"\") # Logic for printing the # pattern for everyline count = num // 2 + 1 for k in range(1, num+1) : print(count, end = \"\") # Value of count decrements # in every cycle if (k <= num // 2 ) : count = count -1 # Value of count will # increment in every cycle else : count = count + 1 print() # Before reaching half Space # is decreased by 1 and num # is increased by 2 if (i <= n // 2) : space = space - 1 num = num + 2 # After reaching to half # space is increased by 1 # and num is decreased by 2 else : space = space + 1 num = num - 2 # Driver Codedisplay() #This code is contributed by Nikita Tiwari.", "e": 4548, "s": 3345, "text": null }, { "code": "// C# program to print above patternusing System;class Pattern{ void display() { int n = 5; int space = n / 2, num = 1; // Outer for loop for // number of rows for (int i = 1; i <= n; i++) { // Inner for loop // for printing space for (int j = 1; j <= space; j++) Console.Write(\" \"); // Logic for printing // the pattern for everyline int count = num / 2 + 1; for (int k = 1; k <= num; k++) { Console.Write(count); // Value of count decrements // in every cycle if (k <= num /2 ) count--; // Value of count will increment // in every cycle else count++; } Console.WriteLine(); // Before reaching half Space is decreased // by 1 and num is increased by 2 if (i <= n / 2) { space = space - 1; num = num + 2; } // After reaching to half space is increased // by 1 and num is decreased by 2 else { space = space + 1; num = num - 2; } } } // Driver Code public static void Main() { Pattern p = new Pattern(); p.display(); }}// This code is contributed by vt_m.", "e": 6060, "s": 4548, "text": null }, { "code": "<?php// php program to print// above pattern function display($n) { $space = $n / 2; $num = 1; // Outer for loop for // number of rows for ($i = 1; $i <= $n; $i++) { // Inner for loop // for printing space for ($j = 1; $j <= $space; $j++) echo \" \"; // Logic for printing // the pattern for everyline $count = $num / 2 + 1; for ($k = 1; $k <= $num; $k++) { echo floor($count); // Value of count decrements // in every cycle if ($k <= $num /2 ) $count--; // Value of count will increment // in every cycle else $count++; } echo \"\\n\"; // Before reaching half Space // is decreased by 1 and // num is increased by 2 if ($i <= $n / 2) { $space = $space - 1; $num = $num + 2; } // After reaching to half // space is increased by 1 // and num is decreased by 2 else { $space = $space + 1; $num = $num - 2; } } } // Driver Code$n = 5;display($n); // This code is contributed by mits?>", "e": 7486, "s": 6060, "text": null }, { "code": "<script> // JavaScript program to print pattern function display() { var n = 5; var space = parseInt(n / 2), num = 1; // Outer for loop for // number of rows for (var i = 1; i <= n; i++) { // Inner for loop for // printing space for (var j = 1; j <= space; j++) document.write(\" \"); // Logic for printing // the pattern for everyline var count = parseInt(num / 2 + 1); for (var k = 1; k <= num; k++) { document.write(count); // Value of count decrements // in every cycle if (k <= num / 2) count--; // Value of count will // increment in every cycle else count++; } document.write(\"<br>\"); // Before reaching half Space // is decreased by 1 and num // is increased by 2 if (i <= n / 2) { space = space - 1; num = num + 2; } // After reaching to half // space is increased by 1 // and num is decreased by 2 else { space = space + 1; num = num - 2; } } } // Driver Code display(); </script>", "e": 8793, "s": 7486, "text": null }, { "code": null, "e": 8803, "s": 8793, "text": "Output : " }, { "code": null, "e": 8827, "s": 8803, "text": " 1\n 212\n32123\n 212\n 1" }, { "code": null, "e": 8958, "s": 8827, "text": "Time Complexity: O(n2), where n represents the given input.Auxiliary Space: O(1), no extra space is required, so it is a constant." }, { "code": null, "e": 8971, "s": 8958, "text": "Mithun Kumar" }, { "code": null, "e": 8978, "s": 8971, "text": "rdtank" }, { "code": null, "e": 8987, "s": 8978, "text": "sweetyty" }, { "code": null, "e": 8997, "s": 8987, "text": "samim2000" }, { "code": null, "e": 9014, "s": 8997, "text": "pattern-printing" }, { "code": null, "e": 9033, "s": 9014, "text": "School Programming" }, { "code": null, "e": 9050, "s": 9033, "text": "pattern-printing" }, { "code": null, "e": 9148, "s": 9050, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9169, "s": 9148, "text": "Constructors in Java" }, { "code": null, "e": 9188, "s": 9169, "text": "Exceptions in Java" }, { "code": null, "e": 9214, "s": 9188, "text": "Python Exception Handling" }, { "code": null, "e": 9232, "s": 9214, "text": "Python Try Except" }, { "code": null, "e": 9259, "s": 9232, "text": "Ternary Operator in Python" }, { "code": null, "e": 9293, "s": 9259, "text": "How JVM Works - JVM Architecture?" }, { "code": null, "e": 9327, "s": 9293, "text": "Python program to add two numbers" }, { "code": null, "e": 9345, "s": 9327, "text": "Variables in Java" }, { "code": null, "e": 9364, "s": 9345, "text": "Data types in Java" } ]
Searching in a NumPy array
01 Oct, 2020 Numpy provides various methods for searching different kinds of numerical values, in this article, we will cover two important ones. numpy.where() numpy.searchsorted() 1. numpy.where:() It returns the indices of elements in an input array where the given condition is satisfied. Syntax: numpy.where(condition[, x, y]) Parameters: condition : When True, yield x, otherwise yield y. x, y : Values from which to choose. x, y and condition need to be broadcastable to some shape. Returns:out : [ndarray or tuple of ndarrays] If both x and y are specified, the output array contains elements of x where condition is True, and elements from y elsewhere. If only condition is given, return the tuple condition.nonzero(), the indices where condition is True. The following example demonstrates how to search using where(). Python3 # importing the moduleimport numpy as np # creating the arrayarr = np.array([10, 32, 30, 50, 20, 82, 91, 45]) # printing arrprint("arr = {}".format(arr)) # looking for value 30 in arr and storing its index in ii = np.where(arr == 30)print("i = {}".format(i)) Output: arr = [10 32 30 50 20 82 91 45] i = (array([2], dtype=int64),) As you can see variable i is an iterable with the index of our searched value as the first element. We can make it look better by replacing the last print statement with print("i = {}".format(i[0])) This will change the final output to arr = [10 32 30 50 20 82 91 45] i = [2] 2. numpy.searchsorted(): The function is used to find the indices into a sorted array arr such that, if elements are inserted before the indices, the order of arr would be still preserved. Here, a binary search is used to find the required insertion indices. Syntax : numpy.searchsorted(arr, num, side=’left’, sorter=None) Parameters : arr : [array_like] Input array. If sorter is None, then it must be sorted in ascending order, otherwise sorter must be an array of indices that sort it. num : [array_like]The Values which we want to insert into arr. side : [‘left’, ‘right’], optional.If ‘left’, the index of the first suitable location found is given. If ‘right’, return the last such index. If there is no suitable index, return either 0 or N (where N is the length of a). num : [array_like, Optional] array of integer indices that sort array a into ascending order. They are typically the result of argsort. Return : [indices], Array of insertion points with the same shape as num. The following example explains the use of searchsorted(). Python3 # importing the moduleimport numpy as np # creating the arrayarr = [1, 2, 2, 3, 3, 3, 4, 5, 6, 6]print("arr = {}".format(arr)) # left-most 3print("left-most index = {}".format(np.searchsorted(arr, 3, side="left"))) # right-most 3print("right-most index = {}".format(np.searchsorted(arr, 3, side="right"))) Output: arr = [1, 2, 2, 3, 3, 3, 4, 5, 6, 6] left-most index = 3 right-most index = 6 Python numpy-Sorting Searching Python-numpy 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 How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Iterate over a list in Python Introduction To PYTHON Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Oct, 2020" }, { "code": null, "e": 161, "s": 28, "text": "Numpy provides various methods for searching different kinds of numerical values, in this article, we will cover two important ones." }, { "code": null, "e": 175, "s": 161, "text": "numpy.where()" }, { "code": null, "e": 196, "s": 175, "text": "numpy.searchsorted()" }, { "code": null, "e": 307, "s": 196, "text": "1. numpy.where:() It returns the indices of elements in an input array where the given condition is satisfied." }, { "code": null, "e": 347, "s": 307, "text": "Syntax: numpy.where(condition[, x, y]) " }, { "code": null, "e": 359, "s": 347, "text": "Parameters:" }, { "code": null, "e": 410, "s": 359, "text": "condition : When True, yield x, otherwise yield y." }, { "code": null, "e": 505, "s": 410, "text": "x, y : Values from which to choose. x, y and condition need to be broadcastable to some shape." }, { "code": null, "e": 677, "s": 505, "text": "Returns:out : [ndarray or tuple of ndarrays] If both x and y are specified, the output array contains elements of x where condition is True, and elements from y elsewhere." }, { "code": null, "e": 780, "s": 677, "text": "If only condition is given, return the tuple condition.nonzero(), the indices where condition is True." }, { "code": null, "e": 844, "s": 780, "text": "The following example demonstrates how to search using where()." }, { "code": null, "e": 852, "s": 844, "text": "Python3" }, { "code": "# importing the moduleimport numpy as np # creating the arrayarr = np.array([10, 32, 30, 50, 20, 82, 91, 45]) # printing arrprint(\"arr = {}\".format(arr)) # looking for value 30 in arr and storing its index in ii = np.where(arr == 30)print(\"i = {}\".format(i))", "e": 1116, "s": 852, "text": null }, { "code": null, "e": 1124, "s": 1116, "text": "Output:" }, { "code": null, "e": 1188, "s": 1124, "text": "arr = [10 32 30 50 20 82 91 45]\ni = (array([2], dtype=int64),)\n" }, { "code": null, "e": 1359, "s": 1188, "text": "As you can see variable i is an iterable with the index of our searched value as the first element. We can make it look better by replacing the last print statement with" }, { "code": null, "e": 1389, "s": 1359, "text": "print(\"i = {}\".format(i[0]))\n" }, { "code": null, "e": 1426, "s": 1389, "text": "This will change the final output to" }, { "code": null, "e": 1467, "s": 1426, "text": "arr = [10 32 30 50 20 82 91 45]\ni = [2]\n" }, { "code": null, "e": 1726, "s": 1467, "text": "2. numpy.searchsorted(): The function is used to find the indices into a sorted array arr such that, if elements are inserted before the indices, the order of arr would be still preserved. Here, a binary search is used to find the required insertion indices." }, { "code": null, "e": 1790, "s": 1726, "text": "Syntax : numpy.searchsorted(arr, num, side=’left’, sorter=None)" }, { "code": null, "e": 1803, "s": 1790, "text": "Parameters :" }, { "code": null, "e": 1956, "s": 1803, "text": "arr : [array_like] Input array. If sorter is None, then it must be sorted in ascending order, otherwise sorter must be an array of indices that sort it." }, { "code": null, "e": 2019, "s": 1956, "text": "num : [array_like]The Values which we want to insert into arr." }, { "code": null, "e": 2244, "s": 2019, "text": "side : [‘left’, ‘right’], optional.If ‘left’, the index of the first suitable location found is given. If ‘right’, return the last such index. If there is no suitable index, return either 0 or N (where N is the length of a)." }, { "code": null, "e": 2380, "s": 2244, "text": "num : [array_like, Optional] array of integer indices that sort array a into ascending order. They are typically the result of argsort." }, { "code": null, "e": 2454, "s": 2380, "text": "Return : [indices], Array of insertion points with the same shape as num." }, { "code": null, "e": 2512, "s": 2454, "text": "The following example explains the use of searchsorted()." }, { "code": null, "e": 2520, "s": 2512, "text": "Python3" }, { "code": "# importing the moduleimport numpy as np # creating the arrayarr = [1, 2, 2, 3, 3, 3, 4, 5, 6, 6]print(\"arr = {}\".format(arr)) # left-most 3print(\"left-most index = {}\".format(np.searchsorted(arr, 3, side=\"left\"))) # right-most 3print(\"right-most index = {}\".format(np.searchsorted(arr, 3, side=\"right\")))", "e": 2829, "s": 2520, "text": null }, { "code": null, "e": 2837, "s": 2829, "text": "Output:" }, { "code": null, "e": 2916, "s": 2837, "text": "arr = [1, 2, 2, 3, 3, 3, 4, 5, 6, 6]\nleft-most index = 3\nright-most index = 6\n" }, { "code": null, "e": 2947, "s": 2916, "text": "Python numpy-Sorting Searching" }, { "code": null, "e": 2960, "s": 2947, "text": "Python-numpy" }, { "code": null, "e": 2967, "s": 2960, "text": "Python" }, { "code": null, "e": 3065, "s": 2967, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3083, "s": 3065, "text": "Python Dictionary" }, { "code": null, "e": 3125, "s": 3083, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3147, "s": 3125, "text": "Enumerate() in Python" }, { "code": null, "e": 3179, "s": 3147, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3208, "s": 3179, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3235, "s": 3208, "text": "Python Classes and Objects" }, { "code": null, "e": 3256, "s": 3235, "text": "Python OOPs Concepts" }, { "code": null, "e": 3286, "s": 3256, "text": "Iterate over a list in Python" }, { "code": null, "e": 3309, "s": 3286, "text": "Introduction To PYTHON" } ]
Matplotlib.pyplot.sca() in Python
03 May, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc. The sca() method pyplot module of matplotlib library is used to set the current axes to be a. Syntax: matplotlib.pyplot.sca(self, a) Parameters: This method accept the following parameters that are discussed below: a:This parameter is the current axes. Returns: This method returns the axes. Below examples illustrate the matplotlib.pyplot.sca() function in matplotlib.figure: Example 1: # Implementation of matplotlib functionimport matplotlib.pyplot as pltfrom scipy import sin, cos fig, ax = plt.subplots(2, 1)x = [1, 2, 3, 4, 5, 6, 7, 8, 9] y1 = sin(x)y2 = cos(x) plt.sca(ax[0])plt.plot(x, y1) plt.sca(ax[1])plt.plot(x, y2) fig.suptitle("""matplotlib.pyplot.sca()function Example\n\n""", fontweight ="bold") plt.show() Output: Example 2: # Implementation of matplotlib functionimport matplotlib.pyplot as plt fig, axes = plt.subplots(2, 2) axes = axes.flatten() for i in range(4): plt.sca(axes[i]) axes[i].text(0.5, 0.5, i + 1) fig.suptitle("""matplotlib.pyplot.sca()function Example\n\n""", fontweight ="bold") plt.show() Output: Matplotlib Pyplot-class Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python | os.path.join() method Python OOPs Concepts How to drop one or multiple columns in Pandas Dataframe Introduction To PYTHON How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n03 May, 2020" }, { "code": null, "e": 333, "s": 28, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc." }, { "code": null, "e": 427, "s": 333, "text": "The sca() method pyplot module of matplotlib library is used to set the current axes to be a." }, { "code": null, "e": 466, "s": 427, "text": "Syntax: matplotlib.pyplot.sca(self, a)" }, { "code": null, "e": 548, "s": 466, "text": "Parameters: This method accept the following parameters that are discussed below:" }, { "code": null, "e": 586, "s": 548, "text": "a:This parameter is the current axes." }, { "code": null, "e": 625, "s": 586, "text": "Returns: This method returns the axes." }, { "code": null, "e": 710, "s": 625, "text": "Below examples illustrate the matplotlib.pyplot.sca() function in matplotlib.figure:" }, { "code": null, "e": 721, "s": 710, "text": "Example 1:" }, { "code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltfrom scipy import sin, cos fig, ax = plt.subplots(2, 1)x = [1, 2, 3, 4, 5, 6, 7, 8, 9] y1 = sin(x)y2 = cos(x) plt.sca(ax[0])plt.plot(x, y1) plt.sca(ax[1])plt.plot(x, y2) fig.suptitle(\"\"\"matplotlib.pyplot.sca()function Example\\n\\n\"\"\", fontweight =\"bold\") plt.show() ", "e": 1068, "s": 721, "text": null }, { "code": null, "e": 1076, "s": 1068, "text": "Output:" }, { "code": null, "e": 1087, "s": 1076, "text": "Example 2:" }, { "code": "# Implementation of matplotlib functionimport matplotlib.pyplot as plt fig, axes = plt.subplots(2, 2) axes = axes.flatten() for i in range(4): plt.sca(axes[i]) axes[i].text(0.5, 0.5, i + 1) fig.suptitle(\"\"\"matplotlib.pyplot.sca()function Example\\n\\n\"\"\", fontweight =\"bold\") plt.show() ", "e": 1395, "s": 1087, "text": null }, { "code": null, "e": 1403, "s": 1395, "text": "Output:" }, { "code": null, "e": 1427, "s": 1403, "text": "Matplotlib Pyplot-class" }, { "code": null, "e": 1445, "s": 1427, "text": "Python-matplotlib" }, { "code": null, "e": 1452, "s": 1445, "text": "Python" }, { "code": null, "e": 1550, "s": 1452, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1582, "s": 1550, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1609, "s": 1582, "text": "Python Classes and Objects" }, { "code": null, "e": 1640, "s": 1609, "text": "Python | os.path.join() method" }, { "code": null, "e": 1661, "s": 1640, "text": "Python OOPs Concepts" }, { "code": null, "e": 1717, "s": 1661, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1740, "s": 1717, "text": "Introduction To PYTHON" }, { "code": null, "e": 1782, "s": 1740, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1824, "s": 1782, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1863, "s": 1824, "text": "Python | datetime.timedelta() function" } ]
Maximum profit by buying and selling a stock at most twice | Set 2
06 May, 2021 Given an array prices[] which denotes the prices of the stocks on different days, the task is to find the maximum profit possible after buying and selling the stocks on different days using transaction where at most two transactions are allowed.Note: You cannot engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again). Examples: Input: prices[] = {3, 3, 5, 0, 0, 3, 1, 4} Output: 6 Explanation: Buy on Day 4 and Sell at Day 6 => Profit = 3 – 0 = 3 Buy on Day 7 and Sell at Day 8 => Profit = 4 -1 = 3 Therefore, Total Profit = 3 + 3 = 6 Input: prices[] = {1, 2, 3, 4, 5} Output: 4 Explanation: Buy on Day 1 and sell at Day 6 => Profit = 5 -1 = 4 Therefore, Total Profit = 4 We have already discussed this problem using Dynamic Programming in O(N) space in this article.Efficient Approach: The idea used here is to keep track of the two transactions at the same time. The two stocks profit is computed as follows Maximum Profit for the First Transaction Find the minimum price we have to pay from our pocket (buy1) to get 1st stock which is the price of the stock on that day or on any previous day.Find the maximum profit by selling the 1st stock which on the current day. Find the minimum price we have to pay from our pocket (buy1) to get 1st stock which is the price of the stock on that day or on any previous day. Find the maximum profit by selling the 1st stock which on the current day. Maximum profit for the second Transaction The minimum price we have to pay from our pocket to buy second stocks will be The minimum price we have to pay from our pocket to buy second stocks will be buy2 = price[i] - profit1, // Profit 1 is the profit from // selling the first stock Find the maximum profit (profit2) by selling the 2nd stock. Explanation with Example: Let us take price[] = { 3, 5, 4, 5} We buy 1st stock on day 1 buy1 = 3.We sell 1st stock on day 2. profit1 = 5 – 3 = 2.We will make a profit of 2 after buying the stock on 1st day and selling on 2nd day. So, profit1 = 2Now we will buy the 2nd stock on 3rd dayStock price on 3rd day is 4 Since we already made a profit of 2, We will spend only 2 extra from our packet to buy the stock i.e., (4 – profit1) = 2buy2 = 2Now, we will sell second stock on day 4.Stock price on 4th day is 5. profit2 = 5 – buy2 = 5 – 2 = 3.Now, we can see that the final profit includes the profit of buying and selling two stocks Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implmenetation to find// maximum possible profit// with at most two transactions #include <bits/stdc++.h>using namespace std; // Function to find the maximum// profit with two transactions// on a given list of stock pricesint maxProfit(int price[], int n){ // buy1 - Money lent to buy 1 stock // profit1 - Profit after selling // the 1st stock buyed. // buy2 - Money lent to buy 2 stocks // including profit of selling 1st stock // profit2 - Profit after selling 2 stocks int buy1, profit1, buy2, profit2; // Set initial buying values to // INT_MAX as we want to minimize it buy1 = buy2 = INT_MAX; // Set initial selling values to // zero as we want to maximize it profit1 = profit2 = 0; for (int i = 0; i < n; i++) { // Money lent to buy the stock // should be minimum as possible. // buy1 tracks the minimum possible // stock to buy from 0 to i-1. buy1 = min(buy1, price[i]); // Profit after selling a stock // should be maximum as possible. // profit1 tracks maximum possible // profit we can make from 0 to i-1. profit1 = max(profit1, price[i] - buy1); // Now for buying the 2nd stock, // we will integrate profit made // from selling the 1st stock buy2 = min(buy2, price[i] - profit1); // Profit after selling a 2 stocks // should be maximum as possible. // profit2 tracks maximum possible // profit we can make from 0 to i-1. profit2 = max(profit2, price[i] - buy2); } return profit2;} // Driver Codeint main(){ int price[] = { 2, 30, 15, 10, 8, 25, 80 }; int n = sizeof(price) / sizeof(price[0]); cout << "Maximum Profit = " << maxProfit(price, n); return 0;} // Java implmenetation to find// maximum possible profit// with at most two transactionsimport java.util.*; class GFG{ // Function to find the maximum// profit with two transactions// on a given list of stock pricesstatic int maxProfit(int price[], int n){ // buy1 - Money lent to buy 1 stock // profit1 - Profit after selling // the 1st stock buyed. // buy2 - Money lent to buy 2 stocks // including profit of selling 1st stock // profit2 - Profit after selling 2 stocks int buy1, profit1, buy2, profit2; // Set initial buying values to // Integer.MAX_VALUE as we want to // minimize it buy1 = buy2 = Integer.MAX_VALUE; // Set initial selling values to // zero as we want to maximize it profit1 = profit2 = 0; for(int i = 0; i < n; i++) { // Money lent to buy the stock // should be minimum as possible. // buy1 tracks the minimum possible // stock to buy from 0 to i-1. buy1 = Math.min(buy1, price[i]); // Profit after selling a stock // should be maximum as possible. // profit1 tracks maximum possible // profit we can make from 0 to i-1. profit1 = Math.max(profit1, price[i] - buy1); // Now for buying the 2nd stock, // we will integrate profit made // from selling the 1st stock buy2 = Math.min(buy2, price[i] - profit1); // Profit after selling a 2 stocks // should be maximum as possible. // profit2 tracks maximum possible // profit we can make from 0 to i-1. profit2 = Math.max(profit2, price[i] - buy2); } return profit2;} // Driver Codepublic static void main(String[] args){ int price[] = { 2, 30, 15, 10, 8, 25, 80 }; int n = price.length; System.out.print("Maximum Profit = " + maxProfit(price, n));}} // This code is contributed by Rajput-Ji # Python3 implmenetation to find# maximum possible profit# with at most two transactionsimport sys # Function to find the maximum# profit with two transactions# on a given list of stock pricesdef maxProfit(price, n): # buy1 - Money lent to buy 1 stock # profit1 - Profit after selling # the 1st stock buyed. # buy2 - Money lent to buy 2 stocks # including profit of selling 1st stock # profit2 - Profit after selling 2 stocks # Set initial buying values to # INT_MAX as we want to minimize it buy1, buy2 = sys.maxsize, sys.maxsize # Set initial selling values to # zero as we want to maximize it profit1, profit2 = 0, 0 for i in range(n): # Money lent to buy the stock # should be minimum as possible. # buy1 tracks the minimum possible # stock to buy from 0 to i-1. buy1 = min(buy1, price[i]) # Profit after selling a stock # should be maximum as possible. # profit1 tracks maximum possible # profit we can make from 0 to i-1. profit1 = max(profit1, price[i] - buy1) # Now for buying the 2nd stock, # we will integrate profit made # from selling the 1st stock buy2 = min(buy2, price[i] - profit1) # Profit after selling a 2 stocks # should be maximum as possible. # profit2 tracks maximum possible # profit we can make from 0 to i-1. profit2 = max(profit2, price[i] - buy2) return profit2 # Driver codeprice = [ 2, 30, 15, 10, 8, 25, 80 ]n = len(price) print("Maximum Profit = ", maxProfit(price, n)) # This code is contributed by divyeshrabadiya07 // C# implmenetation to find// maximum possible profit// with at most two transactionsusing System; class GFG{ // Function to find the maximum// profit with two transactions// on a given list of stock pricesstatic int maxProfit(int []price, int n){ // buy1 - Money lent to buy 1 stock // profit1 - Profit after selling // the 1st stock buyed. // buy2 - Money lent to buy 2 stocks // including profit of selling 1st stock // profit2 - Profit after selling 2 stocks int buy1, profit1, buy2, profit2; // Set initial buying values to // int.MaxValue as we want to // minimize it buy1 = buy2 = int.MaxValue; // Set initial selling values to // zero as we want to maximize it profit1 = profit2 = 0; for(int i = 0; i < n; i++) { // Money lent to buy the stock // should be minimum as possible. // buy1 tracks the minimum possible // stock to buy from 0 to i-1. buy1 = Math.Min(buy1, price[i]); // Profit after selling a stock // should be maximum as possible. // profit1 tracks maximum possible // profit we can make from 0 to i-1. profit1 = Math.Max(profit1, price[i] - buy1); // Now for buying the 2nd stock, // we will integrate profit made // from selling the 1st stock buy2 = Math.Min(buy2, price[i] - profit1); // Profit after selling a 2 stocks // should be maximum as possible. // profit2 tracks maximum possible // profit we can make from 0 to i-1. profit2 = Math.Max(profit2, price[i] - buy2); } return profit2;} // Driver Codepublic static void Main(String[] args){ int []price = { 2, 30, 15, 10, 8, 25, 80 }; int n = price.Length; Console.Write("Maximum Profit = " + maxProfit(price, n));}} // This code is contributed by Rajput-Ji <script>// javascript implmenetation to find// maximum possible profit// with at most two transactions // Function to find the maximum // profit with two transactions // on a given list of stock prices function maxProfit(price , n) { // buy1 - Money lent to buy 1 stock // profit1 - Profit after selling // the 1st stock buyed. // buy2 - Money lent to buy 2 stocks // including profit of selling 1st stock // profit2 - Profit after selling 2 stocks var buy1, profit1, buy2, profit2; // Set initial buying values to // Number.MAX_VALUE as we want to // minimize it buy1 = buy2 = Number.MAX_VALUE; // Set initial selling values to // zero as we want to maximize it profit1 = profit2 = 0; for (i = 0; i < n; i++) { // Money lent to buy the stock // should be minimum as possible. // buy1 tracks the minimum possible // stock to buy from 0 to i-1. buy1 = Math.min(buy1, price[i]); // Profit after selling a stock // should be maximum as possible. // profit1 tracks maximum possible // profit we can make from 0 to i-1. profit1 = Math.max(profit1, price[i] - buy1); // Now for buying the 2nd stock, // we will integrate profit made // from selling the 1st stock buy2 = Math.min(buy2, price[i] - profit1); // Profit after selling a 2 stocks // should be maximum as possible. // profit2 tracks maximum possible // profit we can make from 0 to i-1. profit2 = Math.max(profit2, price[i] - buy2); } return profit2; } // Driver Code var price = [ 2, 30, 15, 10, 8, 25, 80 ]; var n = price.length; document.write("Maximum Profit = " + maxProfit(price, n)); // This code is contributed by todaysgaurav.</script> Maximum Profit = 100 Time complexity: O(N) Auxiliary Space: O(1) Rajput-Ji divyeshrabadiya07 8_bit_spider todaysgaurav Arrays Data Structures Java 8 Arrays Dynamic Programming Data Structures Arrays Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n06 May, 2021" }, { "code": null, "e": 419, "s": 54, "text": "Given an array prices[] which denotes the prices of the stocks on different days, the task is to find the maximum profit possible after buying and selling the stocks on different days using transaction where at most two transactions are allowed.Note: You cannot engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again)." }, { "code": null, "e": 430, "s": 419, "text": "Examples: " }, { "code": null, "e": 637, "s": 430, "text": "Input: prices[] = {3, 3, 5, 0, 0, 3, 1, 4} Output: 6 Explanation: Buy on Day 4 and Sell at Day 6 => Profit = 3 – 0 = 3 Buy on Day 7 and Sell at Day 8 => Profit = 4 -1 = 3 Therefore, Total Profit = 3 + 3 = 6" }, { "code": null, "e": 775, "s": 637, "text": "Input: prices[] = {1, 2, 3, 4, 5} Output: 4 Explanation: Buy on Day 1 and sell at Day 6 => Profit = 5 -1 = 4 Therefore, Total Profit = 4 " }, { "code": null, "e": 1014, "s": 775, "text": "We have already discussed this problem using Dynamic Programming in O(N) space in this article.Efficient Approach: The idea used here is to keep track of the two transactions at the same time. The two stocks profit is computed as follows " }, { "code": null, "e": 1275, "s": 1014, "text": "Maximum Profit for the First Transaction Find the minimum price we have to pay from our pocket (buy1) to get 1st stock which is the price of the stock on that day or on any previous day.Find the maximum profit by selling the 1st stock which on the current day." }, { "code": null, "e": 1421, "s": 1275, "text": "Find the minimum price we have to pay from our pocket (buy1) to get 1st stock which is the price of the stock on that day or on any previous day." }, { "code": null, "e": 1496, "s": 1421, "text": "Find the maximum profit by selling the 1st stock which on the current day." }, { "code": null, "e": 1616, "s": 1496, "text": "Maximum profit for the second Transaction The minimum price we have to pay from our pocket to buy second stocks will be" }, { "code": null, "e": 1694, "s": 1616, "text": "The minimum price we have to pay from our pocket to buy second stocks will be" }, { "code": null, "e": 1781, "s": 1694, "text": "buy2 = price[i] - profit1, \n// Profit 1 is the profit from \n// selling the first stock" }, { "code": null, "e": 1841, "s": 1781, "text": "Find the maximum profit (profit2) by selling the 2nd stock." }, { "code": null, "e": 1868, "s": 1841, "text": "Explanation with Example: " }, { "code": null, "e": 2476, "s": 1868, "text": "Let us take price[] = { 3, 5, 4, 5} We buy 1st stock on day 1 buy1 = 3.We sell 1st stock on day 2. profit1 = 5 – 3 = 2.We will make a profit of 2 after buying the stock on 1st day and selling on 2nd day. So, profit1 = 2Now we will buy the 2nd stock on 3rd dayStock price on 3rd day is 4 Since we already made a profit of 2, We will spend only 2 extra from our packet to buy the stock i.e., (4 – profit1) = 2buy2 = 2Now, we will sell second stock on day 4.Stock price on 4th day is 5. profit2 = 5 – buy2 = 5 – 2 = 3.Now, we can see that the final profit includes the profit of buying and selling two stocks " }, { "code": null, "e": 2528, "s": 2476, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 2532, "s": 2528, "text": "C++" }, { "code": null, "e": 2537, "s": 2532, "text": "Java" }, { "code": null, "e": 2545, "s": 2537, "text": "Python3" }, { "code": null, "e": 2548, "s": 2545, "text": "C#" }, { "code": null, "e": 2559, "s": 2548, "text": "Javascript" }, { "code": "// C++ implmenetation to find// maximum possible profit// with at most two transactions #include <bits/stdc++.h>using namespace std; // Function to find the maximum// profit with two transactions// on a given list of stock pricesint maxProfit(int price[], int n){ // buy1 - Money lent to buy 1 stock // profit1 - Profit after selling // the 1st stock buyed. // buy2 - Money lent to buy 2 stocks // including profit of selling 1st stock // profit2 - Profit after selling 2 stocks int buy1, profit1, buy2, profit2; // Set initial buying values to // INT_MAX as we want to minimize it buy1 = buy2 = INT_MAX; // Set initial selling values to // zero as we want to maximize it profit1 = profit2 = 0; for (int i = 0; i < n; i++) { // Money lent to buy the stock // should be minimum as possible. // buy1 tracks the minimum possible // stock to buy from 0 to i-1. buy1 = min(buy1, price[i]); // Profit after selling a stock // should be maximum as possible. // profit1 tracks maximum possible // profit we can make from 0 to i-1. profit1 = max(profit1, price[i] - buy1); // Now for buying the 2nd stock, // we will integrate profit made // from selling the 1st stock buy2 = min(buy2, price[i] - profit1); // Profit after selling a 2 stocks // should be maximum as possible. // profit2 tracks maximum possible // profit we can make from 0 to i-1. profit2 = max(profit2, price[i] - buy2); } return profit2;} // Driver Codeint main(){ int price[] = { 2, 30, 15, 10, 8, 25, 80 }; int n = sizeof(price) / sizeof(price[0]); cout << \"Maximum Profit = \" << maxProfit(price, n); return 0;}", "e": 4343, "s": 2559, "text": null }, { "code": "// Java implmenetation to find// maximum possible profit// with at most two transactionsimport java.util.*; class GFG{ // Function to find the maximum// profit with two transactions// on a given list of stock pricesstatic int maxProfit(int price[], int n){ // buy1 - Money lent to buy 1 stock // profit1 - Profit after selling // the 1st stock buyed. // buy2 - Money lent to buy 2 stocks // including profit of selling 1st stock // profit2 - Profit after selling 2 stocks int buy1, profit1, buy2, profit2; // Set initial buying values to // Integer.MAX_VALUE as we want to // minimize it buy1 = buy2 = Integer.MAX_VALUE; // Set initial selling values to // zero as we want to maximize it profit1 = profit2 = 0; for(int i = 0; i < n; i++) { // Money lent to buy the stock // should be minimum as possible. // buy1 tracks the minimum possible // stock to buy from 0 to i-1. buy1 = Math.min(buy1, price[i]); // Profit after selling a stock // should be maximum as possible. // profit1 tracks maximum possible // profit we can make from 0 to i-1. profit1 = Math.max(profit1, price[i] - buy1); // Now for buying the 2nd stock, // we will integrate profit made // from selling the 1st stock buy2 = Math.min(buy2, price[i] - profit1); // Profit after selling a 2 stocks // should be maximum as possible. // profit2 tracks maximum possible // profit we can make from 0 to i-1. profit2 = Math.max(profit2, price[i] - buy2); } return profit2;} // Driver Codepublic static void main(String[] args){ int price[] = { 2, 30, 15, 10, 8, 25, 80 }; int n = price.length; System.out.print(\"Maximum Profit = \" + maxProfit(price, n));}} // This code is contributed by Rajput-Ji", "e": 6235, "s": 4343, "text": null }, { "code": "# Python3 implmenetation to find# maximum possible profit# with at most two transactionsimport sys # Function to find the maximum# profit with two transactions# on a given list of stock pricesdef maxProfit(price, n): # buy1 - Money lent to buy 1 stock # profit1 - Profit after selling # the 1st stock buyed. # buy2 - Money lent to buy 2 stocks # including profit of selling 1st stock # profit2 - Profit after selling 2 stocks # Set initial buying values to # INT_MAX as we want to minimize it buy1, buy2 = sys.maxsize, sys.maxsize # Set initial selling values to # zero as we want to maximize it profit1, profit2 = 0, 0 for i in range(n): # Money lent to buy the stock # should be minimum as possible. # buy1 tracks the minimum possible # stock to buy from 0 to i-1. buy1 = min(buy1, price[i]) # Profit after selling a stock # should be maximum as possible. # profit1 tracks maximum possible # profit we can make from 0 to i-1. profit1 = max(profit1, price[i] - buy1) # Now for buying the 2nd stock, # we will integrate profit made # from selling the 1st stock buy2 = min(buy2, price[i] - profit1) # Profit after selling a 2 stocks # should be maximum as possible. # profit2 tracks maximum possible # profit we can make from 0 to i-1. profit2 = max(profit2, price[i] - buy2) return profit2 # Driver codeprice = [ 2, 30, 15, 10, 8, 25, 80 ]n = len(price) print(\"Maximum Profit = \", maxProfit(price, n)) # This code is contributed by divyeshrabadiya07", "e": 7887, "s": 6235, "text": null }, { "code": "// C# implmenetation to find// maximum possible profit// with at most two transactionsusing System; class GFG{ // Function to find the maximum// profit with two transactions// on a given list of stock pricesstatic int maxProfit(int []price, int n){ // buy1 - Money lent to buy 1 stock // profit1 - Profit after selling // the 1st stock buyed. // buy2 - Money lent to buy 2 stocks // including profit of selling 1st stock // profit2 - Profit after selling 2 stocks int buy1, profit1, buy2, profit2; // Set initial buying values to // int.MaxValue as we want to // minimize it buy1 = buy2 = int.MaxValue; // Set initial selling values to // zero as we want to maximize it profit1 = profit2 = 0; for(int i = 0; i < n; i++) { // Money lent to buy the stock // should be minimum as possible. // buy1 tracks the minimum possible // stock to buy from 0 to i-1. buy1 = Math.Min(buy1, price[i]); // Profit after selling a stock // should be maximum as possible. // profit1 tracks maximum possible // profit we can make from 0 to i-1. profit1 = Math.Max(profit1, price[i] - buy1); // Now for buying the 2nd stock, // we will integrate profit made // from selling the 1st stock buy2 = Math.Min(buy2, price[i] - profit1); // Profit after selling a 2 stocks // should be maximum as possible. // profit2 tracks maximum possible // profit we can make from 0 to i-1. profit2 = Math.Max(profit2, price[i] - buy2); } return profit2;} // Driver Codepublic static void Main(String[] args){ int []price = { 2, 30, 15, 10, 8, 25, 80 }; int n = price.Length; Console.Write(\"Maximum Profit = \" + maxProfit(price, n));}} // This code is contributed by Rajput-Ji", "e": 9755, "s": 7887, "text": null }, { "code": "<script>// javascript implmenetation to find// maximum possible profit// with at most two transactions // Function to find the maximum // profit with two transactions // on a given list of stock prices function maxProfit(price , n) { // buy1 - Money lent to buy 1 stock // profit1 - Profit after selling // the 1st stock buyed. // buy2 - Money lent to buy 2 stocks // including profit of selling 1st stock // profit2 - Profit after selling 2 stocks var buy1, profit1, buy2, profit2; // Set initial buying values to // Number.MAX_VALUE as we want to // minimize it buy1 = buy2 = Number.MAX_VALUE; // Set initial selling values to // zero as we want to maximize it profit1 = profit2 = 0; for (i = 0; i < n; i++) { // Money lent to buy the stock // should be minimum as possible. // buy1 tracks the minimum possible // stock to buy from 0 to i-1. buy1 = Math.min(buy1, price[i]); // Profit after selling a stock // should be maximum as possible. // profit1 tracks maximum possible // profit we can make from 0 to i-1. profit1 = Math.max(profit1, price[i] - buy1); // Now for buying the 2nd stock, // we will integrate profit made // from selling the 1st stock buy2 = Math.min(buy2, price[i] - profit1); // Profit after selling a 2 stocks // should be maximum as possible. // profit2 tracks maximum possible // profit we can make from 0 to i-1. profit2 = Math.max(profit2, price[i] - buy2); } return profit2; } // Driver Code var price = [ 2, 30, 15, 10, 8, 25, 80 ]; var n = price.length; document.write(\"Maximum Profit = \" + maxProfit(price, n)); // This code is contributed by todaysgaurav.</script>", "e": 11738, "s": 9755, "text": null }, { "code": null, "e": 11759, "s": 11738, "text": "Maximum Profit = 100" }, { "code": null, "e": 11805, "s": 11761, "text": "Time complexity: O(N) Auxiliary Space: O(1)" }, { "code": null, "e": 11815, "s": 11805, "text": "Rajput-Ji" }, { "code": null, "e": 11833, "s": 11815, "text": "divyeshrabadiya07" }, { "code": null, "e": 11846, "s": 11833, "text": "8_bit_spider" }, { "code": null, "e": 11859, "s": 11846, "text": "todaysgaurav" }, { "code": null, "e": 11866, "s": 11859, "text": "Arrays" }, { "code": null, "e": 11882, "s": 11866, "text": "Data Structures" }, { "code": null, "e": 11889, "s": 11882, "text": "Java 8" }, { "code": null, "e": 11896, "s": 11889, "text": "Arrays" }, { "code": null, "e": 11916, "s": 11896, "text": "Dynamic Programming" }, { "code": null, "e": 11932, "s": 11916, "text": "Data Structures" }, { "code": null, "e": 11939, "s": 11932, "text": "Arrays" }, { "code": null, "e": 11959, "s": 11939, "text": "Dynamic Programming" } ]
Node.js URL.fileURLToPath API
14 Oct, 2021 This URL.fileURLToPath function decodes the file URL to a path string and ensures that the URL control characters (/, %) are correctly appended/adjusted when converting the given file URL into a path. Syntax: url.fileURLToPath( url ) Parameters: This function accepts single parameter url which holds the file URL string or object to convert into path. Return Value: It returns a string which represents the fully-resolved platform-specific file path. Below programs illustrates the use of URL.fileURLToPath() Method in Node.js: Example 1: // Node program to demonstrate the // URL.fileURLToPath() API as Setter // Importing the module 'url' const url = require('url'); // Some random path from systemconst file = 'file://computerscience/geeksforgeeks.txt' // Converting our file to properly encoded path console.log(url.fileURLToPath(file)) Output: \\computerscience\geeksforgeeks.txt Example 2: // Node program to demonstrate the // URL.fileURLToPath() API as Setter // Importing the module 'url' const url = require('url'); // Some random path from systemconst file = 'file:///C:/path/example/gfg' // Converting the file to properly encoded pathconsole.log(url.fileURLToPath(file)) Output: C:\path\example\gfg Note: The above program will compile and run by using the node app.js command. Reference: https://nodejs.org/api/url.html#url_url_fileurltopath_url Node-URL 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 How to connect Node.js with React.js ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Roadmap to Learn JavaScript For Beginners
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Oct, 2021" }, { "code": null, "e": 229, "s": 28, "text": "This URL.fileURLToPath function decodes the file URL to a path string and ensures that the URL control characters (/, %) are correctly appended/adjusted when converting the given file URL into a path." }, { "code": null, "e": 237, "s": 229, "text": "Syntax:" }, { "code": null, "e": 262, "s": 237, "text": "url.fileURLToPath( url )" }, { "code": null, "e": 381, "s": 262, "text": "Parameters: This function accepts single parameter url which holds the file URL string or object to convert into path." }, { "code": null, "e": 480, "s": 381, "text": "Return Value: It returns a string which represents the fully-resolved platform-specific file path." }, { "code": null, "e": 557, "s": 480, "text": "Below programs illustrates the use of URL.fileURLToPath() Method in Node.js:" }, { "code": null, "e": 568, "s": 557, "text": "Example 1:" }, { "code": "// Node program to demonstrate the // URL.fileURLToPath() API as Setter // Importing the module 'url' const url = require('url'); // Some random path from systemconst file = 'file://computerscience/geeksforgeeks.txt' // Converting our file to properly encoded path console.log(url.fileURLToPath(file)) ", "e": 894, "s": 568, "text": null }, { "code": null, "e": 902, "s": 894, "text": "Output:" }, { "code": null, "e": 938, "s": 902, "text": "\\\\computerscience\\geeksforgeeks.txt" }, { "code": null, "e": 949, "s": 938, "text": "Example 2:" }, { "code": "// Node program to demonstrate the // URL.fileURLToPath() API as Setter // Importing the module 'url' const url = require('url'); // Some random path from systemconst file = 'file:///C:/path/example/gfg' // Converting the file to properly encoded pathconsole.log(url.fileURLToPath(file))", "e": 1241, "s": 949, "text": null }, { "code": null, "e": 1249, "s": 1241, "text": "Output:" }, { "code": null, "e": 1271, "s": 1249, "text": " C:\\path\\example\\gfg " }, { "code": null, "e": 1350, "s": 1271, "text": "Note: The above program will compile and run by using the node app.js command." }, { "code": null, "e": 1419, "s": 1350, "text": "Reference: https://nodejs.org/api/url.html#url_url_fileurltopath_url" }, { "code": null, "e": 1428, "s": 1419, "text": "Node-URL" }, { "code": null, "e": 1435, "s": 1428, "text": "Picked" }, { "code": null, "e": 1443, "s": 1435, "text": "Node.js" }, { "code": null, "e": 1460, "s": 1443, "text": "Web Technologies" }, { "code": null, "e": 1558, "s": 1460, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1590, "s": 1558, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 1625, "s": 1590, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 1695, "s": 1625, "text": "Difference between dependencies, devDependencies and peerDependencies" }, { "code": null, "e": 1722, "s": 1695, "text": "Mongoose Populate() Method" }, { "code": null, "e": 1761, "s": 1722, "text": "How to connect Node.js with React.js ?" }, { "code": null, "e": 1823, "s": 1761, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 1884, "s": 1823, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1927, "s": 1884, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 1977, "s": 1927, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Reader-Writer problem using Monitors (pthreads)
07 Feb, 2022 Prerequisite – Monitors, Readers-Writers Problem There is a shared resource that is accessed by multiple processes i.e. readers and writers. Any number of readers can read from the shared resource simultaneously, but only one writer can write to the shared resource at a time. When a writer is writing data to the resource, no other process can access the resource. A writer cannot write to the resource if there are any readers accessing the resource at that time. Similarly, a reader can not read if there is a writer accessing the resource or if there are any waiting writers.The Reader-Writer problem using a monitor can be implemented using pthreads. The POSIX threads (or pthread) libraries are a standards-based thread API for C/C++. The library provides the following synchronization mechanisms: Mutexes (pthread_mutex_t) – Mutual exclusion lock: Block access to variables by other threads. This enforces exclusive access by a thread to a variable or set of variables. Condition Variables – (pthread_cond_t): The condition variable mechanism allows threads to suspend execution and relinquish the processor until some condition is true. Implementation of Reader-Writer solution using pthread library:Execute the program using the following command in your Linux system $g++ -pthread program_name.cpp $./a.out or $g++ -pthread program_name.cpp -o object_name $./object_name Code: CPP // Reader-Writer problem using monitors #include <iostream>#include <pthread.h>#include <unistd.h>using namespace std; class monitor {private: // no. of readers int rcnt; // no. of writers int wcnt; // no. of readers waiting int waitr; // no. of writers waiting int waitw; // condition variable to check whether reader can read pthread_cond_t canread; // condition variable to check whether writer can write pthread_cond_t canwrite; // mutex for synchronization pthread_mutex_t condlock; public: monitor() { rcnt = 0; wcnt = 0; waitr = 0; waitw = 0; pthread_cond_init(&canread, NULL); pthread_cond_init(&canwrite, NULL); pthread_mutex_init(&condlock, NULL); } // mutex provide synchronization so that no other thread // can change the value of data void beginread(int i) { pthread_mutex_lock(&condlock); // if there are active or waiting writers if (wcnt == 1 || waitw > 0) { // incrementing waiting readers waitr++; // reader suspended pthread_cond_wait(&canread, &condlock); waitr--; } // else reader reads the resource rcnt++; cout << "reader " << i << " is reading\n"; pthread_mutex_unlock(&condlock); pthread_cond_broadcast(&canread); } void endread(int i) { // if there are no readers left then writer enters monitor pthread_mutex_lock(&condlock); if (--rcnt == 0) pthread_cond_signal(&canwrite); pthread_mutex_unlock(&condlock); } void beginwrite(int i) { pthread_mutex_lock(&condlock); // a writer can enter when there are no active // or waiting readers or other writer if (wcnt == 1 || rcnt > 0) { ++waitw; pthread_cond_wait(&canwrite, &condlock); --waitw; } wcnt = 1; cout << "writer " << i << " is writing\n"; pthread_mutex_unlock(&condlock); } void endwrite(int i) { pthread_mutex_lock(&condlock); wcnt = 0; // if any readers are waiting, threads are unblocked if (waitr > 0) pthread_cond_signal(&canread); else pthread_cond_signal(&canwrite); pthread_mutex_unlock(&condlock); } } // global object of monitor classM; void* reader(void* id){ int c = 0; int i = *(int*)id; // each reader attempts to read 5 times while (c < 5) { usleep(1); M.beginread(i); M.endread(i); c++; }} void* writer(void* id){ int c = 0; int i = *(int*)id; // each writer attempts to write 5 times while (c < 5) { usleep(1); M.beginwrite(i); M.endwrite(i); c++; }} int main(){ pthread_t r[5], w[5]; int id[5]; for (int i = 0; i < 5; i++) { id[i] = i; // creating threads which execute reader function pthread_create(&r[i], NULL, &reader, &id[i]); // creating threads which execute writer function pthread_create(&w[i], NULL, &writer, &id[i]); } for (int i = 0; i < 5; i++) { pthread_join(r[i], NULL); } for (int i = 0; i < 5; i++) { pthread_join(w[i], NULL); }} Output: rkbhola5 Process Synchronization Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. File Allocation Methods Memory Management in Operating System Different approaches or Structures of Operating Systems Segmentation in Operating System Logical and Physical Address in Operating System Structures of Directory in Operating System Difference between Internal and External fragmentation Introduction of System Call Process Table and Process Control Block (PCB) Architecture of IOS Operating System
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Feb, 2022" }, { "code": null, "e": 858, "s": 52, "text": "Prerequisite – Monitors, Readers-Writers Problem There is a shared resource that is accessed by multiple processes i.e. readers and writers. Any number of readers can read from the shared resource simultaneously, but only one writer can write to the shared resource at a time. When a writer is writing data to the resource, no other process can access the resource. A writer cannot write to the resource if there are any readers accessing the resource at that time. Similarly, a reader can not read if there is a writer accessing the resource or if there are any waiting writers.The Reader-Writer problem using a monitor can be implemented using pthreads. The POSIX threads (or pthread) libraries are a standards-based thread API for C/C++. The library provides the following synchronization mechanisms: " }, { "code": null, "e": 1033, "s": 858, "text": "Mutexes (pthread_mutex_t) – Mutual exclusion lock: Block access to variables by other threads. This enforces exclusive access by a thread to a variable or set of variables. " }, { "code": null, "e": 1203, "s": 1033, "text": "Condition Variables – (pthread_cond_t): The condition variable mechanism allows threads to suspend execution and relinquish the processor until some condition is true. " }, { "code": null, "e": 1337, "s": 1203, "text": "Implementation of Reader-Writer solution using pthread library:Execute the program using the following command in your Linux system " }, { "code": null, "e": 1441, "s": 1337, "text": "$g++ -pthread program_name.cpp\n$./a.out\nor\n$g++ -pthread program_name.cpp -o object_name\n$./object_name" }, { "code": null, "e": 1447, "s": 1441, "text": "Code:" }, { "code": null, "e": 1451, "s": 1447, "text": "CPP" }, { "code": "// Reader-Writer problem using monitors #include <iostream>#include <pthread.h>#include <unistd.h>using namespace std; class monitor {private: // no. of readers int rcnt; // no. of writers int wcnt; // no. of readers waiting int waitr; // no. of writers waiting int waitw; // condition variable to check whether reader can read pthread_cond_t canread; // condition variable to check whether writer can write pthread_cond_t canwrite; // mutex for synchronization pthread_mutex_t condlock; public: monitor() { rcnt = 0; wcnt = 0; waitr = 0; waitw = 0; pthread_cond_init(&canread, NULL); pthread_cond_init(&canwrite, NULL); pthread_mutex_init(&condlock, NULL); } // mutex provide synchronization so that no other thread // can change the value of data void beginread(int i) { pthread_mutex_lock(&condlock); // if there are active or waiting writers if (wcnt == 1 || waitw > 0) { // incrementing waiting readers waitr++; // reader suspended pthread_cond_wait(&canread, &condlock); waitr--; } // else reader reads the resource rcnt++; cout << \"reader \" << i << \" is reading\\n\"; pthread_mutex_unlock(&condlock); pthread_cond_broadcast(&canread); } void endread(int i) { // if there are no readers left then writer enters monitor pthread_mutex_lock(&condlock); if (--rcnt == 0) pthread_cond_signal(&canwrite); pthread_mutex_unlock(&condlock); } void beginwrite(int i) { pthread_mutex_lock(&condlock); // a writer can enter when there are no active // or waiting readers or other writer if (wcnt == 1 || rcnt > 0) { ++waitw; pthread_cond_wait(&canwrite, &condlock); --waitw; } wcnt = 1; cout << \"writer \" << i << \" is writing\\n\"; pthread_mutex_unlock(&condlock); } void endwrite(int i) { pthread_mutex_lock(&condlock); wcnt = 0; // if any readers are waiting, threads are unblocked if (waitr > 0) pthread_cond_signal(&canread); else pthread_cond_signal(&canwrite); pthread_mutex_unlock(&condlock); } } // global object of monitor classM; void* reader(void* id){ int c = 0; int i = *(int*)id; // each reader attempts to read 5 times while (c < 5) { usleep(1); M.beginread(i); M.endread(i); c++; }} void* writer(void* id){ int c = 0; int i = *(int*)id; // each writer attempts to write 5 times while (c < 5) { usleep(1); M.beginwrite(i); M.endwrite(i); c++; }} int main(){ pthread_t r[5], w[5]; int id[5]; for (int i = 0; i < 5; i++) { id[i] = i; // creating threads which execute reader function pthread_create(&r[i], NULL, &reader, &id[i]); // creating threads which execute writer function pthread_create(&w[i], NULL, &writer, &id[i]); } for (int i = 0; i < 5; i++) { pthread_join(r[i], NULL); } for (int i = 0; i < 5; i++) { pthread_join(w[i], NULL); }}", "e": 4734, "s": 1451, "text": null }, { "code": null, "e": 4743, "s": 4734, "text": "Output: " }, { "code": null, "e": 4754, "s": 4745, "text": "rkbhola5" }, { "code": null, "e": 4778, "s": 4754, "text": "Process Synchronization" }, { "code": null, "e": 4796, "s": 4778, "text": "Operating Systems" }, { "code": null, "e": 4814, "s": 4796, "text": "Operating Systems" }, { "code": null, "e": 4912, "s": 4814, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4936, "s": 4912, "text": "File Allocation Methods" }, { "code": null, "e": 4974, "s": 4936, "text": "Memory Management in Operating System" }, { "code": null, "e": 5030, "s": 4974, "text": "Different approaches or Structures of Operating Systems" }, { "code": null, "e": 5063, "s": 5030, "text": "Segmentation in Operating System" }, { "code": null, "e": 5112, "s": 5063, "text": "Logical and Physical Address in Operating System" }, { "code": null, "e": 5156, "s": 5112, "text": "Structures of Directory in Operating System" }, { "code": null, "e": 5211, "s": 5156, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 5239, "s": 5211, "text": "Introduction of System Call" }, { "code": null, "e": 5285, "s": 5239, "text": "Process Table and Process Control Block (PCB)" } ]
Python program to print the dictionary in table format
31 Aug, 2021 Given a Dictionary. The task is to print the dictionary in the table format.Examples: Input: {1: [“Samuel”, 21, ‘Data Structures’], 2: [“Richie”, 20, ‘Machine Learning’], 3: [“Lauren”, 21, ‘OOPS with java’], }Output: NAME AGE COURSE Samuel 21 Data Structures Richie 20 Machine Learning Lauren 21 OOPS with java Method 1: Displaying result by iterating through values. Python3 # Define the dictionarydict ={} # Insert data into dictionarydict1 = {1: ["Samuel", 21, 'Data Structures'], 2: ["Richie", 20, 'Machine Learning'], 3: ["Lauren", 21, 'OOPS with java'], } # Print the names of the columns.print ("{:<10} {:<10} {:<10}".format('NAME', 'AGE', 'COURSE')) # print each data item.for key, value in dict1.items(): name, age, course = value print ("{:<10} {:<10} {:<10}".format(name, age, course)) Output: NAME AGE COURSE Samuel 21 Data Structures Richie 20 Machine Learning Lauren 21 OOPS with java Method 2: Displaying by using matrix format Python3 # define the dictionarydict1 = {} # insert data into dictionarydict1 = {(0, 0): 'Samuel', (0, 1): 21, (0, 2): 'Data structures', (1, 0): 'Richie', (1, 1): 20, (1, 2): 'Machine Learning', (2, 0): 'Lauren', (2, 1):21, (2, 2): 'OOPS with Java'} # print the name of the columns explicitly.print(" NAME ", " AGE ", " COURSE " ) # Iterate through the dictionary# to print the data.for i in range(3): for j in range(3): print(dict1[(i, j)], end =' ') print() Output: NAME AGE COURSE Samuel 21 Data structures Richie 20 Machine Learning Lauren 21 OOPS with Java Method 3: Displaying by using zip format Python3 # define the dictionarydict1 = {} # insert data into dictionary.dict1 = {'NAME':['Samuel', 'Richie', 'Lauren'], 'AGE':[21, 20, 21], 'COURSE':['Data Structures', 'Machine Learning', 'OOPS with Java']} # print the contents using zip format.for each_row in zip(*([i] + (j) for i, j in dict1.items())): print(*each_row, " ") Output: NAME AGE COURSE Samuel 21 Data Structures Richie 20 Machine Learning Lauren 21 OOPS with Java sagar0719kumar python-dict Python python-dict Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n31 Aug, 2021" }, { "code": null, "e": 139, "s": 52, "text": "Given a Dictionary. The task is to print the dictionary in the table format.Examples: " }, { "code": null, "e": 366, "s": 139, "text": "Input: {1: [“Samuel”, 21, ‘Data Structures’], 2: [“Richie”, 20, ‘Machine Learning’], 3: [“Lauren”, 21, ‘OOPS with java’], }Output: NAME AGE COURSE Samuel 21 Data Structures Richie 20 Machine Learning Lauren 21 OOPS with java " }, { "code": null, "e": 425, "s": 366, "text": "Method 1: Displaying result by iterating through values. " }, { "code": null, "e": 433, "s": 425, "text": "Python3" }, { "code": "# Define the dictionarydict ={} # Insert data into dictionarydict1 = {1: [\"Samuel\", 21, 'Data Structures'], 2: [\"Richie\", 20, 'Machine Learning'], 3: [\"Lauren\", 21, 'OOPS with java'], } # Print the names of the columns.print (\"{:<10} {:<10} {:<10}\".format('NAME', 'AGE', 'COURSE')) # print each data item.for key, value in dict1.items(): name, age, course = value print (\"{:<10} {:<10} {:<10}\".format(name, age, course))", "e": 872, "s": 433, "text": null }, { "code": null, "e": 881, "s": 872, "text": "Output: " }, { "code": null, "e": 1028, "s": 881, "text": "NAME AGE COURSE \nSamuel 21 Data Structures\nRichie 20 Machine Learning\nLauren 21 OOPS with java" }, { "code": null, "e": 1074, "s": 1028, "text": "Method 2: Displaying by using matrix format " }, { "code": null, "e": 1082, "s": 1074, "text": "Python3" }, { "code": "# define the dictionarydict1 = {} # insert data into dictionarydict1 = {(0, 0): 'Samuel', (0, 1): 21, (0, 2): 'Data structures', (1, 0): 'Richie', (1, 1): 20, (1, 2): 'Machine Learning', (2, 0): 'Lauren', (2, 1):21, (2, 2): 'OOPS with Java'} # print the name of the columns explicitly.print(\" NAME \", \" AGE \", \" COURSE \" ) # Iterate through the dictionary# to print the data.for i in range(3): for j in range(3): print(dict1[(i, j)], end =' ') print()", "e": 1580, "s": 1082, "text": null }, { "code": null, "e": 1589, "s": 1580, "text": "Output: " }, { "code": null, "e": 1709, "s": 1589, "text": " NAME AGE COURSE \nSamuel 21 Data structures \nRichie 20 Machine Learning \nLauren 21 OOPS with Java " }, { "code": null, "e": 1752, "s": 1709, "text": "Method 3: Displaying by using zip format " }, { "code": null, "e": 1760, "s": 1752, "text": "Python3" }, { "code": "# define the dictionarydict1 = {} # insert data into dictionary.dict1 = {'NAME':['Samuel', 'Richie', 'Lauren'], 'AGE':[21, 20, 21], 'COURSE':['Data Structures', 'Machine Learning', 'OOPS with Java']} # print the contents using zip format.for each_row in zip(*([i] + (j) for i, j in dict1.items())): print(*each_row, \" \")", "e": 2128, "s": 1760, "text": null }, { "code": null, "e": 2137, "s": 2128, "text": "Output: " }, { "code": null, "e": 2238, "s": 2137, "text": "NAME AGE COURSE \nSamuel 21 Data Structures \nRichie 20 Machine Learning \nLauren 21 OOPS with Java" }, { "code": null, "e": 2255, "s": 2240, "text": "sagar0719kumar" }, { "code": null, "e": 2267, "s": 2255, "text": "python-dict" }, { "code": null, "e": 2274, "s": 2267, "text": "Python" }, { "code": null, "e": 2286, "s": 2274, "text": "python-dict" } ]
Python MongoDB – Update_many Query
26 May, 2020 MongoDB is a NoSQL database management system. Unlike MySQL the data in MongoDB is not stored as relations or tables. Data in mongoDB is stored as documents. Documents are Javascript/JSON like objects. More formally documents in MongoDB use BSON. PyMongo is a MongoDB API for python. It allows to read and write data from a MongoDB database using a python script. It needs both python and mongoDB to be installed on the system. Update function has been deprecated in newer versions of MongoDB (3.xx and above). Earlier update function could be used for both single updates and multiple using “multi = true”. But in newer versions of mongoDB it is recommended to use update_many() and update_one(). The major difference is that the user needs to plan ahead if the query is going to be updating single or multiple documents. Syntax: db.collection.updateMany( <filter>, <update>, { upsert: <boolean>, writeConcern: <document>, collation: <document>, arrayFilters: [ <filterdocument1>, ... ], hint: <document|string> } ) Update Operators in MongoDB Setting Values: $set: Used to set a fields value. $setOnInsert: Update value only if a new document insertion. $unset: Remove the field and its value. Numeric Operators: $inc: Increases the value by a given amount. $min/$max: returns minimum or maximum of value. $mul: multiplies the values by a given amount. Miscellaneous Operators: $currentDate: Updates value of a field to current date. $rename: Renames a field Sample Database: Some use cases we are going to see in this article where updating many records can be useful: Changing or incrementing several elements based on a condition.Inserting a new field to multiple or all documents. Changing or incrementing several elements based on a condition. Inserting a new field to multiple or all documents. Example 1: All the students with marks greater than 35 has been passed. Python3 from pymongo import MongoClient # Creating an instance of MongoClient # on default localhostclient = MongoClient('mongodb://localhost:27017') # Accessing desired database and collectiondb = client.gfgcollection = db["classroom"] # Update passed field to be true for all# students with marks greater than 35collection.update_many( {"marks": { "$gt": "35" } }, { "$set": { "passed" : "True" } }) Database After Query: Example 2: New field called address added to all documents Python from pymongo import MongoClient # Creating an instance of MongoClient # on default localhostclient = MongoClient('mongodb://localhost:27017') # Accessing desired database and collectiondb = client.gfgcollection = db["classroom"] # Address filed to be added to all documentscollection.update_many( {}, {"$set": { "Address": "value" } }, # don't insert if no document found upsert=False, array_filters=None ) Database After query: Python-mongoDB Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 May, 2020" }, { "code": null, "e": 457, "s": 28, "text": "MongoDB is a NoSQL database management system. Unlike MySQL the data in MongoDB is not stored as relations or tables. Data in mongoDB is stored as documents. Documents are Javascript/JSON like objects. More formally documents in MongoDB use BSON. PyMongo is a MongoDB API for python. It allows to read and write data from a MongoDB database using a python script. It needs both python and mongoDB to be installed on the system." }, { "code": null, "e": 729, "s": 457, "text": "Update function has been deprecated in newer versions of MongoDB (3.xx and above). Earlier update function could be used for both single updates and multiple using “multi = true”. But in newer versions of mongoDB it is recommended to use update_many() and update_one(). " }, { "code": null, "e": 854, "s": 729, "text": "The major difference is that the user needs to plan ahead if the query is going to be updating single or multiple documents." }, { "code": null, "e": 862, "s": 854, "text": "Syntax:" }, { "code": null, "e": 1087, "s": 862, "text": "db.collection.updateMany(\n <filter>,\n <update>,\n {\n upsert: <boolean>,\n writeConcern: <document>,\n collation: <document>,\n arrayFilters: [ <filterdocument1>, ... ],\n hint: <document|string>\n }\n)\n" }, { "code": null, "e": 1115, "s": 1087, "text": "Update Operators in MongoDB" }, { "code": null, "e": 1131, "s": 1115, "text": "Setting Values:" }, { "code": null, "e": 1165, "s": 1131, "text": "$set: Used to set a fields value." }, { "code": null, "e": 1226, "s": 1165, "text": "$setOnInsert: Update value only if a new document insertion." }, { "code": null, "e": 1266, "s": 1226, "text": "$unset: Remove the field and its value." }, { "code": null, "e": 1285, "s": 1266, "text": "Numeric Operators:" }, { "code": null, "e": 1330, "s": 1285, "text": "$inc: Increases the value by a given amount." }, { "code": null, "e": 1378, "s": 1330, "text": "$min/$max: returns minimum or maximum of value." }, { "code": null, "e": 1425, "s": 1378, "text": "$mul: multiplies the values by a given amount." }, { "code": null, "e": 1450, "s": 1425, "text": "Miscellaneous Operators:" }, { "code": null, "e": 1506, "s": 1450, "text": "$currentDate: Updates value of a field to current date." }, { "code": null, "e": 1531, "s": 1506, "text": "$rename: Renames a field" }, { "code": null, "e": 1548, "s": 1531, "text": "Sample Database:" }, { "code": null, "e": 1643, "s": 1548, "text": "Some use cases we are going to see in this article where updating many records can be useful: " }, { "code": null, "e": 1758, "s": 1643, "text": "Changing or incrementing several elements based on a condition.Inserting a new field to multiple or all documents." }, { "code": null, "e": 1822, "s": 1758, "text": "Changing or incrementing several elements based on a condition." }, { "code": null, "e": 1874, "s": 1822, "text": "Inserting a new field to multiple or all documents." }, { "code": null, "e": 1946, "s": 1874, "text": "Example 1: All the students with marks greater than 35 has been passed." }, { "code": null, "e": 1954, "s": 1946, "text": "Python3" }, { "code": "from pymongo import MongoClient # Creating an instance of MongoClient # on default localhostclient = MongoClient('mongodb://localhost:27017') # Accessing desired database and collectiondb = client.gfgcollection = db[\"classroom\"] # Update passed field to be true for all# students with marks greater than 35collection.update_many( {\"marks\": { \"$gt\": \"35\" } }, { \"$set\": { \"passed\" : \"True\" } })", "e": 2381, "s": 1954, "text": null }, { "code": null, "e": 2404, "s": 2381, "text": "Database After Query: " }, { "code": null, "e": 2463, "s": 2404, "text": "Example 2: New field called address added to all documents" }, { "code": null, "e": 2470, "s": 2463, "text": "Python" }, { "code": "from pymongo import MongoClient # Creating an instance of MongoClient # on default localhostclient = MongoClient('mongodb://localhost:27017') # Accessing desired database and collectiondb = client.gfgcollection = db[\"classroom\"] # Address filed to be added to all documentscollection.update_many( {}, {\"$set\": { \"Address\": \"value\" } }, # don't insert if no document found upsert=False, array_filters=None )", "e": 2952, "s": 2470, "text": null }, { "code": null, "e": 2975, "s": 2952, "text": "Database After query: " }, { "code": null, "e": 2990, "s": 2975, "text": "Python-mongoDB" }, { "code": null, "e": 2997, "s": 2990, "text": "Python" } ]
Node.js console.warn() Function
14 Oct, 2021 The console.warn() function from console class of Node.js is used to display the warning messages on the console. It prints to stderr with newline. Note: This function is an alias of console.error() function. Syntax: console.warn( [data][, ...args] ) Parameter: This function can contains multiple parameters. The first parameter is used for the primary message and other parameters are used for substitution values. Return Value: The function returns the warning message. Below programs demonstrate the working of the console.warn() function: Program 1: function displayWarning(x) { console.warn(`GeeksforGeeks is a ${x} portal`);} const x = 'Computer Science'; displayWarning(x); Output: GeeksforGeeks is a Computer Science portal Program 2: function compareNumber(x, y) { // Check condition if (x > y) { console.warn(`${x} is greater then ${y}`); } else { console.warn(`${x} is less then or equal to ${y}`); }} // Store number to variablex = 100;y = 50; compareNumber(x, y); Output: 100 is greater then 50 NodeJS-function Node.js 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": "\n14 Oct, 2021" }, { "code": null, "e": 176, "s": 28, "text": "The console.warn() function from console class of Node.js is used to display the warning messages on the console. It prints to stderr with newline." }, { "code": null, "e": 237, "s": 176, "text": "Note: This function is an alias of console.error() function." }, { "code": null, "e": 245, "s": 237, "text": "Syntax:" }, { "code": null, "e": 279, "s": 245, "text": "console.warn( [data][, ...args] )" }, { "code": null, "e": 445, "s": 279, "text": "Parameter: This function can contains multiple parameters. The first parameter is used for the primary message and other parameters are used for substitution values." }, { "code": null, "e": 501, "s": 445, "text": "Return Value: The function returns the warning message." }, { "code": null, "e": 572, "s": 501, "text": "Below programs demonstrate the working of the console.warn() function:" }, { "code": null, "e": 583, "s": 572, "text": "Program 1:" }, { "code": "function displayWarning(x) { console.warn(`GeeksforGeeks is a ${x} portal`);} const x = 'Computer Science'; displayWarning(x);", "e": 716, "s": 583, "text": null }, { "code": null, "e": 724, "s": 716, "text": "Output:" }, { "code": null, "e": 767, "s": 724, "text": "GeeksforGeeks is a Computer Science portal" }, { "code": null, "e": 778, "s": 767, "text": "Program 2:" }, { "code": "function compareNumber(x, y) { // Check condition if (x > y) { console.warn(`${x} is greater then ${y}`); } else { console.warn(`${x} is less then or equal to ${y}`); }} // Store number to variablex = 100;y = 50; compareNumber(x, y);", "e": 1049, "s": 778, "text": null }, { "code": null, "e": 1057, "s": 1049, "text": "Output:" }, { "code": null, "e": 1080, "s": 1057, "text": "100 is greater then 50" }, { "code": null, "e": 1096, "s": 1080, "text": "NodeJS-function" }, { "code": null, "e": 1104, "s": 1096, "text": "Node.js" }, { "code": null, "e": 1121, "s": 1104, "text": "Web Technologies" } ]
minimize_window driver method – Selenium Python
15 May, 2020 Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc. This article revolves around minimize_window driver method in Selenium. minimize_window method minimizes the current window that webdriver is using. Syntax – driver.minimize_window() Example –Now one can use minimize_window method as a driver method as below – diver.get("https://www.geeksforgeeks.org/") driver.minimize_window() To demonstrate, minimize_window method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object. Let’s minimize window, Program – # import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # minimize window positiondriver.minimize_window() Output –Screenshot added – Python-selenium selenium Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n15 May, 2020" }, { "code": null, "e": 767, "s": 28, "text": "Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc." }, { "code": null, "e": 916, "s": 767, "text": "This article revolves around minimize_window driver method in Selenium. minimize_window method minimizes the current window that webdriver is using." }, { "code": null, "e": 925, "s": 916, "text": "Syntax –" }, { "code": null, "e": 950, "s": 925, "text": "driver.minimize_window()" }, { "code": null, "e": 1028, "s": 950, "text": "Example –Now one can use minimize_window method as a driver method as below –" }, { "code": null, "e": 1098, "s": 1028, "text": "diver.get(\"https://www.geeksforgeeks.org/\")\ndriver.minimize_window()\n" }, { "code": null, "e": 1267, "s": 1098, "text": "To demonstrate, minimize_window method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object. Let’s minimize window," }, { "code": null, "e": 1277, "s": 1267, "text": "Program –" }, { "code": "# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # minimize window positiondriver.minimize_window()", "e": 1504, "s": 1277, "text": null }, { "code": null, "e": 1531, "s": 1504, "text": "Output –Screenshot added –" }, { "code": null, "e": 1547, "s": 1531, "text": "Python-selenium" }, { "code": null, "e": 1556, "s": 1547, "text": "selenium" }, { "code": null, "e": 1563, "s": 1556, "text": "Python" } ]
Computer Organization | Instruction Formats (Zero, One, Two and Three Address Instruction)
04 Oct, 2021 A computer performs a task based on the instruction provided. Instruction in computers comprises groups called fields. These fields contain different information as for computers everything is in 0 and 1 so each field has different significance based on which a CPU decides what to perform. The most common fields are: Operation field specifies the operation to be performed like addition. Address field which contains the location of the operand, i.e., register or memory location. Mode field which specifies how operand is to be founded. Instruction is of variable length depending upon the number of addresses it contains. Generally, CPU organization is of three types based on the number of address fields: Single Accumulator organizationGeneral register organizationStack organization Single Accumulator organization General register organization Stack organization In the first organization, the operation is done involving a special register called the accumulator. In second on multiple registers are used for the computation purpose. In the third organization the work on stack basis operation due to which it does not contain any address field. Only a single organization doesn’t need to be applied, a blend of various organizations is mostly what we see generally. Based on the number of address, instructions are classified as: Note that we will use X = (A+B)*(C+D) expression to showcase the procedure. Zero Address Instructions – Zero Address Instructions – A stack-based computer does not use the address field in the instruction. To evaluate an expression first it is converted to reverse Polish Notation i.e. Postfix Notation. Expression: X = (A+B)*(C+D) Postfixed : X = AB+CD+* TOP means top of stack M[X] is any memory location 2 .One Address Instructions – This uses an implied ACCUMULATOR register for data manipulation. One operand is in the accumulator and the other is in the register or memory location. Implied means that the CPU already knows that one operand is in the accumulator so there is no need to specify it. Expression: X = (A+B)*(C+D) AC is accumulator M[] is any memory location M[T] is temporary location 3.Two Address Instructions – This is common in commercial computers. Here two addresses can be specified in the instruction. Unlike earlier in one address instruction, the result was stored in the accumulator, here the result can be stored at different locations rather than just accumulators, but require more number of bit to represent address. Here destination address can also contain operand. Expression: X = (A+B)*(C+D) R1, R2 are registers M[] is any memory location 4.Three Address Instructions – This has three address field to specify a register or a memory location. Program created are much short in size but number of bits per instruction increase. These instructions make creation of program much easier but it does not mean that program will run much faster because now instruction only contain more information but each micro operation (changing content of register, loading address in address bus etc.) will be performed in one cycle only. Expression: X = (A+B)*(C+D) R1, R2 are registers M[] is any memory location Abhilash Gogoi 1 nidhi_biet om_mishra priyapal741 surindertarika1234 anikaseth98 Computer Organization & Architecture GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n04 Oct, 2021" }, { "code": null, "e": 371, "s": 52, "text": "A computer performs a task based on the instruction provided. Instruction in computers comprises groups called fields. These fields contain different information as for computers everything is in 0 and 1 so each field has different significance based on which a CPU decides what to perform. The most common fields are:" }, { "code": null, "e": 442, "s": 371, "text": "Operation field specifies the operation to be performed like addition." }, { "code": null, "e": 535, "s": 442, "text": "Address field which contains the location of the operand, i.e., register or memory location." }, { "code": null, "e": 592, "s": 535, "text": "Mode field which specifies how operand is to be founded." }, { "code": null, "e": 763, "s": 592, "text": "Instruction is of variable length depending upon the number of addresses it contains. Generally, CPU organization is of three types based on the number of address fields:" }, { "code": null, "e": 842, "s": 763, "text": "Single Accumulator organizationGeneral register organizationStack organization" }, { "code": null, "e": 874, "s": 842, "text": "Single Accumulator organization" }, { "code": null, "e": 904, "s": 874, "text": "General register organization" }, { "code": null, "e": 923, "s": 904, "text": "Stack organization" }, { "code": null, "e": 1329, "s": 923, "text": "In the first organization, the operation is done involving a special register called the accumulator. In second on multiple registers are used for the computation purpose. In the third organization the work on stack basis operation due to which it does not contain any address field. Only a single organization doesn’t need to be applied, a blend of various organizations is mostly what we see generally. " }, { "code": null, "e": 1394, "s": 1329, "text": "Based on the number of address, instructions are classified as: " }, { "code": null, "e": 1471, "s": 1394, "text": "Note that we will use X = (A+B)*(C+D) expression to showcase the procedure. " }, { "code": null, "e": 1503, "s": 1473, "text": "Zero Address Instructions – " }, { "code": null, "e": 1533, "s": 1503, "text": "Zero Address Instructions – " }, { "code": null, "e": 1706, "s": 1533, "text": "A stack-based computer does not use the address field in the instruction. To evaluate an expression first it is converted to reverse Polish Notation i.e. Postfix Notation. " }, { "code": null, "e": 1809, "s": 1706, "text": "Expression: X = (A+B)*(C+D)\nPostfixed : X = AB+CD+*\nTOP means top of stack\nM[X] is any memory location" }, { "code": null, "e": 2109, "s": 1811, "text": "2 .One Address Instructions – This uses an implied ACCUMULATOR register for data manipulation. One operand is in the accumulator and the other is in the register or memory location. Implied means that the CPU already knows that one operand is in the accumulator so there is no need to specify it. " }, { "code": null, "e": 2211, "s": 2111, "text": "Expression: X = (A+B)*(C+D)\nAC is accumulator\nM[] is any memory location\nM[T] is temporary location" }, { "code": null, "e": 2560, "s": 2211, "text": "3.Two Address Instructions – This is common in commercial computers. Here two addresses can be specified in the instruction. Unlike earlier in one address instruction, the result was stored in the accumulator, here the result can be stored at different locations rather than just accumulators, but require more number of bit to represent address. " }, { "code": null, "e": 2612, "s": 2560, "text": "Here destination address can also contain operand. " }, { "code": null, "e": 2688, "s": 2612, "text": "Expression: X = (A+B)*(C+D)\nR1, R2 are registers\nM[] is any memory location" }, { "code": null, "e": 3172, "s": 2688, "text": "4.Three Address Instructions – This has three address field to specify a register or a memory location. Program created are much short in size but number of bits per instruction increase. These instructions make creation of program much easier but it does not mean that program will run much faster because now instruction only contain more information but each micro operation (changing content of register, loading address in address bus etc.) will be performed in one cycle only. " }, { "code": null, "e": 3250, "s": 3174, "text": "Expression: X = (A+B)*(C+D)\nR1, R2 are registers\nM[] is any memory location" }, { "code": null, "e": 3267, "s": 3250, "text": "Abhilash Gogoi 1" }, { "code": null, "e": 3278, "s": 3267, "text": "nidhi_biet" }, { "code": null, "e": 3288, "s": 3278, "text": "om_mishra" }, { "code": null, "e": 3300, "s": 3288, "text": "priyapal741" }, { "code": null, "e": 3319, "s": 3300, "text": "surindertarika1234" }, { "code": null, "e": 3331, "s": 3319, "text": "anikaseth98" }, { "code": null, "e": 3368, "s": 3331, "text": "Computer Organization & Architecture" }, { "code": null, "e": 3376, "s": 3368, "text": "GATE CS" } ]
Matplotlib.axis.Axis.set_minor_locator() function in Python
03 Jun, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. It is an amazing visualization library in Python for 2D plots of arrays and used for working with the broader SciPy stack. The Axis.set_minor_locator() function in axis module of matplotlib library is used to set the locator of the minor ticker. Syntax: Axis.set_minor_locator(self, locator) Parameters: This method accepts the following parameters. formatter: This parameter is the locator. Return value: This method does not returns any value. Below examples illustrate the matplotlib.axis.Axis.set_minor_locator() function in matplotlib.axis:Example 1: Python3 # Implementation of matplotlib function from matplotlib.axis import Axisimport matplotlib.pyplot as plt import matplotlib.ticker as ticker x = [0, 5, 9, 10, 15] y = [0, 1, 2, 3, 4] tick_spacing = 0.4 fig, ax = plt.subplots(1, 1) ax.plot(x, y) ax.xaxis.set_minor_locator(ticker.MultipleLocator(tick_spacing)) fig.suptitle("Matplotlib.axis.Axis.set_minor_locator()\n\Function Example", fontsize = 12, fontweight ='bold') plt.show() Output: Example 2: Python3 # Implementation of matplotlib function from matplotlib.axis import Axisimport datetime import matplotlib.pyplot as plt from matplotlib.dates import DayLocator, HourLocator, DateFormatter, drange import numpy as np date1 = datetime.datetime(2020, 4, 2) date2 = datetime.datetime(2020, 4, 6) delta = datetime.timedelta(hours = 6) dates = drange(date1, date2, delta) y = np.arange(len(dates)) fig, ax = plt.subplots() ax.plot_date(dates, y ** 2) ax.set_xlim(dates[0], dates[-1]) ax.xaxis.set_major_locator(DayLocator()) Axis.set_minor_locator(ax.xaxis, HourLocator(range(0, 25, 6))) ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d')) ax.fmt_xdata = DateFormatter('%Y-%m-%d %H:%M:%S') fig.autofmt_xdate() fig.suptitle("Matplotlib.axis.Axis.set_minor_locator()\n\Function Example", fontsize = 12, fontweight ='bold') plt.show() Output: Matplotlib-Axis Class Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Jun, 2020" }, { "code": null, "e": 250, "s": 28, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. It is an amazing visualization library in Python for 2D plots of arrays and used for working with the broader SciPy stack. " }, { "code": null, "e": 374, "s": 250, "text": "The Axis.set_minor_locator() function in axis module of matplotlib library is used to set the locator of the minor ticker. " }, { "code": null, "e": 420, "s": 374, "text": "Syntax: Axis.set_minor_locator(self, locator)" }, { "code": null, "e": 479, "s": 420, "text": "Parameters: This method accepts the following parameters. " }, { "code": null, "e": 521, "s": 479, "text": "formatter: This parameter is the locator." }, { "code": null, "e": 577, "s": 521, "text": "Return value: This method does not returns any value. " }, { "code": null, "e": 688, "s": 577, "text": "Below examples illustrate the matplotlib.axis.Axis.set_minor_locator() function in matplotlib.axis:Example 1: " }, { "code": null, "e": 696, "s": 688, "text": "Python3" }, { "code": "# Implementation of matplotlib function from matplotlib.axis import Axisimport matplotlib.pyplot as plt import matplotlib.ticker as ticker x = [0, 5, 9, 10, 15] y = [0, 1, 2, 3, 4] tick_spacing = 0.4 fig, ax = plt.subplots(1, 1) ax.plot(x, y) ax.xaxis.set_minor_locator(ticker.MultipleLocator(tick_spacing)) fig.suptitle(\"Matplotlib.axis.Axis.set_minor_locator()\\n\\Function Example\", fontsize = 12, fontweight ='bold') plt.show()", "e": 1150, "s": 696, "text": null }, { "code": null, "e": 1160, "s": 1150, "text": "Output: " }, { "code": null, "e": 1172, "s": 1160, "text": "Example 2: " }, { "code": null, "e": 1180, "s": 1172, "text": "Python3" }, { "code": "# Implementation of matplotlib function from matplotlib.axis import Axisimport datetime import matplotlib.pyplot as plt from matplotlib.dates import DayLocator, HourLocator, DateFormatter, drange import numpy as np date1 = datetime.datetime(2020, 4, 2) date2 = datetime.datetime(2020, 4, 6) delta = datetime.timedelta(hours = 6) dates = drange(date1, date2, delta) y = np.arange(len(dates)) fig, ax = plt.subplots() ax.plot_date(dates, y ** 2) ax.set_xlim(dates[0], dates[-1]) ax.xaxis.set_major_locator(DayLocator()) Axis.set_minor_locator(ax.xaxis, HourLocator(range(0, 25, 6))) ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d')) ax.fmt_xdata = DateFormatter('%Y-%m-%d %H:%M:%S') fig.autofmt_xdate() fig.suptitle(\"Matplotlib.axis.Axis.set_minor_locator()\\n\\Function Example\", fontsize = 12, fontweight ='bold') plt.show()", "e": 2036, "s": 1180, "text": null }, { "code": null, "e": 2046, "s": 2036, "text": "Output: " }, { "code": null, "e": 2070, "s": 2048, "text": "Matplotlib-Axis Class" }, { "code": null, "e": 2088, "s": 2070, "text": "Python-matplotlib" }, { "code": null, "e": 2095, "s": 2088, "text": "Python" } ]
Comprehension Passages | English
04 May, 2022 Comprehension passages are sure shot scoring questions. We are given a passage and some questions that follow the passage. The questions are to be answered by using the data given in the passage, even if it differs from real life facts. Example : Read the passage and answer the questions that follow : Mike and Morris lived in the same village. While Morris owned the largest jewellery shop in the village, Mike was a poor farmer. Both had large families with many sons, daughters-in-law and grandchildren. One fine day, Mike, tired of not being able to feed his family, decided to leave the village and move to the city where he was certain to earn enough to feed everyone. Along with his family, he left the village for the city. At night, they stopped under a large tree. There was a stream running nearby where they could freshen up themselves. He told his sons to clear the area below the tree, he told his wife to fetch water and he instructed his daughters-in-law to make up the fire and started cutting wood from the tree himself. They didn’t know that in the branches of the tree, there was a thief hiding. He watched as Mike’s family worked together and also noticed that they had nothing to cook. Mike’s wife also thought the same and asked her husband ” Everything is ready but what shall we eat?”. Mike raised his hands to heaven and said ” Don’t worry. He is watching all of this from above. He will help us.” The thief got worried as he had seen that the family was large and worked well together. Taking advantage of the fact that they did not know he was hiding in the branches, he decided to make a quick escape. He climbed down safely when they were not looking and ran for his life. But, he left behind the bundle of stolen jewels and money which dropped into Mike’s lap. Mike opened it and jumped with joy when he saw the contents. The family gathered all their belongings and returned to the village. There was great excitement when they told everyone how they got rich. Morris thought that the tree was miraculous and this was a nice and quick way to earn some money. He ordered his family to pack some clothes and they set off as if on a journey. They also stopped under the same tree and Morris started commanding everyone as Mike had done. But no one in his family was willing to obey his orders. Being a rich family, they were used to having servants all around. So, the one who went to the river to fetch water enjoyed a nice bath. The one who went to get wood for fire went off to sleep. Morris’s wife said ” Everything is ready but what shall we eat ?” Morris raised his hands and said, ” Don’t worry. He is watching all of this from above. He will help us.” As soon as he finished saying, the thief jumped down from the tree with a knife in hand. Seeing him, everyone started running around to save their lives. The thief stole everything they had and Morris and his family had to return to the village empty handed, having lost all their valuables that they had taken with them. Question 1 : Why did Mike and his family decide to rest under the thief’s tree ? A) Being a large family, they knew that they could easily defeat the thief B) It was a convenient spot for taking a halt at night C) There was a stream nearby and wood enough to build a house D) That was the only large tree that could shelter their large family Solution : B) It was a convenient spot for taking a halt at night A is incorrect as they didn’t know that a thief was hiding on the tree. C is incorrect as nothing has been mentioned in the passage about the amount of wood D is incorrect as nothing has been mentioned about the number of trees. Question 2 : Which of the following best describes Morris ? A) He was a rich businessman B) He bullied his wife C) He paid his servants well D) He was greedy and imitated Mike Solution : D) He was greedy and imitated Mike Question 3 : What did Mike mean when he said “He is watching all this from above”? A) He had spotted the thief and wanted to scare him B) He was telling his wife to have faith in god C) It was just a warning for his family members to stick together D) He was begging the thief to help his family Solution : B) He was telling his wife to have faith in god Question 4 : Why did the thief return to the tree? A) To wait for Mike to return B) To set up a trap C) To wait for Morris’s family D) Not mentioned in the passage Solution : D) Not mentioned in the passage Question 5 : How did the fellow villagers react to Mike getting rich overnight? A) They were jealous of him B) They were very excited C) They followed his example D) They envied him Solution : B) They were very excited This article has been contributed by Nishant Arora Please write comments if you have any doubts related to the topic discussed above, or if you are facing difficulty in any question or if you would like to discuss a question other than those mentioned above. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above hareeshwarc rkbhola5 English - Placements Placements Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n04 May, 2022" }, { "code": null, "e": 5104, "s": 52, "text": "Comprehension passages are sure shot scoring questions. We are given a passage and some questions that follow the passage. The questions are to be answered by using the data given in the passage, even if it differs from real life facts. Example : Read the passage and answer the questions that follow : Mike and Morris lived in the same village. While Morris owned the largest jewellery shop in the village, Mike was a poor farmer. Both had large families with many sons, daughters-in-law and grandchildren. One fine day, Mike, tired of not being able to feed his family, decided to leave the village and move to the city where he was certain to earn enough to feed everyone. Along with his family, he left the village for the city. At night, they stopped under a large tree. There was a stream running nearby where they could freshen up themselves. He told his sons to clear the area below the tree, he told his wife to fetch water and he instructed his daughters-in-law to make up the fire and started cutting wood from the tree himself. They didn’t know that in the branches of the tree, there was a thief hiding. He watched as Mike’s family worked together and also noticed that they had nothing to cook. Mike’s wife also thought the same and asked her husband ” Everything is ready but what shall we eat?”. Mike raised his hands to heaven and said ” Don’t worry. He is watching all of this from above. He will help us.” The thief got worried as he had seen that the family was large and worked well together. Taking advantage of the fact that they did not know he was hiding in the branches, he decided to make a quick escape. He climbed down safely when they were not looking and ran for his life. But, he left behind the bundle of stolen jewels and money which dropped into Mike’s lap. Mike opened it and jumped with joy when he saw the contents. The family gathered all their belongings and returned to the village. There was great excitement when they told everyone how they got rich. Morris thought that the tree was miraculous and this was a nice and quick way to earn some money. He ordered his family to pack some clothes and they set off as if on a journey. They also stopped under the same tree and Morris started commanding everyone as Mike had done. But no one in his family was willing to obey his orders. Being a rich family, they were used to having servants all around. So, the one who went to the river to fetch water enjoyed a nice bath. The one who went to get wood for fire went off to sleep. Morris’s wife said ” Everything is ready but what shall we eat ?” Morris raised his hands and said, ” Don’t worry. He is watching all of this from above. He will help us.” As soon as he finished saying, the thief jumped down from the tree with a knife in hand. Seeing him, everyone started running around to save their lives. The thief stole everything they had and Morris and his family had to return to the village empty handed, having lost all their valuables that they had taken with them. Question 1 : Why did Mike and his family decide to rest under the thief’s tree ? A) Being a large family, they knew that they could easily defeat the thief B) It was a convenient spot for taking a halt at night C) There was a stream nearby and wood enough to build a house D) That was the only large tree that could shelter their large family Solution : B) It was a convenient spot for taking a halt at night A is incorrect as they didn’t know that a thief was hiding on the tree. C is incorrect as nothing has been mentioned in the passage about the amount of wood D is incorrect as nothing has been mentioned about the number of trees. Question 2 : Which of the following best describes Morris ? A) He was a rich businessman B) He bullied his wife C) He paid his servants well D) He was greedy and imitated Mike Solution : D) He was greedy and imitated Mike Question 3 : What did Mike mean when he said “He is watching all this from above”? A) He had spotted the thief and wanted to scare him B) He was telling his wife to have faith in god C) It was just a warning for his family members to stick together D) He was begging the thief to help his family Solution : B) He was telling his wife to have faith in god Question 4 : Why did the thief return to the tree? A) To wait for Mike to return B) To set up a trap C) To wait for Morris’s family D) Not mentioned in the passage Solution : D) Not mentioned in the passage Question 5 : How did the fellow villagers react to Mike getting rich overnight? A) They were jealous of him B) They were very excited C) They followed his example D) They envied him Solution : B) They were very excited This article has been contributed by Nishant Arora Please write comments if you have any doubts related to the topic discussed above, or if you are facing difficulty in any question or if you would like to discuss a question other than those mentioned above. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 5116, "s": 5104, "text": "hareeshwarc" }, { "code": null, "e": 5125, "s": 5116, "text": "rkbhola5" }, { "code": null, "e": 5146, "s": 5125, "text": "English - Placements" }, { "code": null, "e": 5157, "s": 5146, "text": "Placements" } ]
Write an JDBC example for inserting value for Clob data type into a table?
Assume we already have a table named MyData in the database with the following description. +---------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +---------+--------------+------+-----+---------+-------+ | Name | varchar(255) | YES | | NULL | | | Article | longtext | YES | | NULL | | +---------+--------------+------+-----+---------+-------+ If you need to insert value int to the clob data type using a JDBC program you need to use the methods which reads the contents of a file and sets to the database rows. PreparedStatement interface provides such methods. The void setCharacterStream(int parameterIndex, Reader reader) method sets the contents of the reader object as a value to the parameter at the given index. Other variant of this method are: void setCharacterStream(int parameterIndex, Reader reader, int length) void setCharacterStream(int parameterIndex, Reader reader, int length) void setCharacterStream(int parameterIndex, Reader reader, long length) void setCharacterStream(int parameterIndex, Reader reader, long length) The void setClob(int parameterIndex, Clob x) method sets the given java.sql.Clob object as a value to the parameter at the given index. Other variant of this method are: void setClob(int parameterIndex, Reader reader) void setClob(int parameterIndex, Reader reader) void setClob(int parameterIndex, Reader reader, long length) void setClob(int parameterIndex, Reader reader, long length) You can set value to the Clob data type using either of these methods. Following example sets value to a Clob datatype using the setClob() method. import java.io.FileReader; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; public class InsertingValueInClob { public static void main(String args[]) throws Exception { //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://localhost/sampleDB"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //Inserting values String query = "INSERT INTO MyData(Name, Article ) VALUES (?, ?)"; PreparedStatement pstmt = con.prepareStatement(query); pstmt.setString(1, "JavaFX"); FileReader reader = new FileReader("E:\\images\\javafx.txt"); pstmt.setClob(2, reader); pstmt.execute(); System.out.println("Data inserted"); } } Connection established...... Table Created...... Contents of the table are: JavaFX E:\images\MyData_clob_output1.txt If you try to view the clob value in the record using the MySQL work bench you can see the inserted text data as shown below:
[ { "code": null, "e": 1154, "s": 1062, "text": "Assume we already have a table named MyData in the database with the following description." }, { "code": null, "e": 1502, "s": 1154, "text": "+---------+--------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+---------+--------------+------+-----+---------+-------+\n| Name | varchar(255) | YES | | NULL | |\n| Article | longtext | YES | | NULL | |\n+---------+--------------+------+-----+---------+-------+" }, { "code": null, "e": 1722, "s": 1502, "text": "If you need to insert value int to the clob data type using a JDBC program you need to use the methods which reads the contents of a file and sets to the database rows. PreparedStatement interface provides such methods." }, { "code": null, "e": 1913, "s": 1722, "text": "The void setCharacterStream(int parameterIndex, Reader reader) method sets the contents of the reader object as a value to the parameter at the given index. Other variant of this method are:" }, { "code": null, "e": 1984, "s": 1913, "text": "void setCharacterStream(int parameterIndex, Reader reader, int length)" }, { "code": null, "e": 2055, "s": 1984, "text": "void setCharacterStream(int parameterIndex, Reader reader, int length)" }, { "code": null, "e": 2127, "s": 2055, "text": "void setCharacterStream(int parameterIndex, Reader reader, long length)" }, { "code": null, "e": 2199, "s": 2127, "text": "void setCharacterStream(int parameterIndex, Reader reader, long length)" }, { "code": null, "e": 2369, "s": 2199, "text": "The void setClob(int parameterIndex, Clob x) method sets the given java.sql.Clob object as a value to the parameter at the given index. Other variant of this method are:" }, { "code": null, "e": 2417, "s": 2369, "text": "void setClob(int parameterIndex, Reader reader)" }, { "code": null, "e": 2465, "s": 2417, "text": "void setClob(int parameterIndex, Reader reader)" }, { "code": null, "e": 2526, "s": 2465, "text": "void setClob(int parameterIndex, Reader reader, long length)" }, { "code": null, "e": 2587, "s": 2526, "text": "void setClob(int parameterIndex, Reader reader, long length)" }, { "code": null, "e": 2658, "s": 2587, "text": "You can set value to the Clob data type using either of these methods." }, { "code": null, "e": 2734, "s": 2658, "text": "Following example sets value to a Clob datatype using the setClob() method." }, { "code": null, "e": 3646, "s": 2734, "text": "import java.io.FileReader;\nimport java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\npublic class InsertingValueInClob {\n public static void main(String args[]) throws Exception {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/sampleDB\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Inserting values\n String query = \"INSERT INTO MyData(Name, Article ) VALUES (?, ?)\";\n PreparedStatement pstmt = con.prepareStatement(query);\n pstmt.setString(1, \"JavaFX\");\n FileReader reader = new FileReader(\"E:\\\\images\\\\javafx.txt\");\n pstmt.setClob(2, reader);\n pstmt.execute();\n System.out.println(\"Data inserted\");\n }\n}" }, { "code": null, "e": 3763, "s": 3646, "text": "Connection established......\nTable Created......\nContents of the table are:\nJavaFX\nE:\\images\\MyData_clob_output1.txt" }, { "code": null, "e": 3889, "s": 3763, "text": "If you try to view the clob value in the record using the MySQL work bench you can see the inserted text data as shown below:" } ]
Explain the conversions of expressions of stacks in C language
Stack is a linear data structure, where data is inserted and removed only at one end. Given below is an algorithm for Push ( ) − Check for stack overflow. if (top = = n-1) printf("stack over flow"); Otherwise, insert an element into the stack. top ++ a[top] = item Given below is an algorithm for Pop ( ) − Check for stack underflow. if (top = = -1) printf("stack under flow"); Otherwise, delete an element from the stack. item = a[top] top -- Given below is an algorithm for Display ( ) − if (top == -1) printf ("stack is empty"); Otherwise, follow the below mentioned algorithm. for (i=0; i<top; i++) printf ("%d", a[i]); Let us understand the conversions of expressions of stacks in C language. Expression − It is a legal combination of operands and operations. Types of expressions There are three types of expressions in C language on which the conversions and evaluations can be carried out. They are explained below − Infix expression − Operator is in between the operands. For example, A+B Infix expression − Operator is in between the operands. For example, A+B Prefix expression − Operator is before the operands. For example, +AB Prefix expression − Operator is before the operands. For example, +AB Postfix expression − Operator is after the operands. For example, AB+ Postfix expression − Operator is after the operands. For example, AB+ Conversion of infix to postfix and infix to prefix is explained below − Infix to postfix Infix to prefix A+ B*C A+ B*C A+ BC * A+ *BC ABC* + +A*BC For example, Convert A+B*C / D-E+F infix to postfix and prefix. Infix to prefix Infix to postfix A +B*C / D-E+F A +B*C / D-E+F A +*BC / D-E+F A +BC* / D-E+F A + / *BCD -E+F A +BC*D /-E+F +A /*BCD -E +F ABC *D /+ -E+F -+A/*BCDE +F ABC *D/ +E- +F + - +A/*BCDEF ABC *D / +E –F+ Scan the input string from left to right and follow the steps given below − Step 1 − If the input symbol is an operand, print it on to the monitor. Step 1 − If the input symbol is an operand, print it on to the monitor. Step 2 − If the input symbol is ‘(‘then, push it on to the stack. Step 2 − If the input symbol is ‘(‘then, push it on to the stack. Step 3 − If the input the symbol is ‘)’ then, pop out all the contents of the stack until you get ‘(‘. Step 3 − If the input the symbol is ‘)’ then, pop out all the contents of the stack until you get ‘(‘. Step 4 − If the input symbol is an operator, check with the priority of the operator on top of the stack with the current input symbol. Step 4 − If the input symbol is an operator, check with the priority of the operator on top of the stack with the current input symbol. If the top priority of top of the stack is greater than or equal to the priority of the current symbol, then pop out the content of the stack and put the current symbol in to the stack. Otherwise, push the operator on to the stack. Step 5 − If the input symbol is ‘\0’ then, pop out the contents of the stack until it becomes empty. Step 5 − If the input symbol is ‘\0’ then, pop out the contents of the stack until it becomes empty. Conversion of infix to post fix with the help of stacks is given below −
[ { "code": null, "e": 1148, "s": 1062, "text": "Stack is a linear data structure, where data is inserted and removed only at one end." }, { "code": null, "e": 1191, "s": 1148, "text": "Given below is an algorithm for Push ( ) −" }, { "code": null, "e": 1217, "s": 1191, "text": "Check for stack overflow." }, { "code": null, "e": 1261, "s": 1217, "text": "if (top = = n-1)\nprintf(\"stack over flow\");" }, { "code": null, "e": 1306, "s": 1261, "text": "Otherwise, insert an element into the stack." }, { "code": null, "e": 1327, "s": 1306, "text": "top ++\na[top] = item" }, { "code": null, "e": 1369, "s": 1327, "text": "Given below is an algorithm for Pop ( ) −" }, { "code": null, "e": 1396, "s": 1369, "text": "Check for stack underflow." }, { "code": null, "e": 1440, "s": 1396, "text": "if (top = = -1)\nprintf(\"stack under flow\");" }, { "code": null, "e": 1485, "s": 1440, "text": "Otherwise, delete an element from the stack." }, { "code": null, "e": 1506, "s": 1485, "text": "item = a[top]\ntop --" }, { "code": null, "e": 1552, "s": 1506, "text": "Given below is an algorithm for Display ( ) −" }, { "code": null, "e": 1594, "s": 1552, "text": "if (top == -1)\nprintf (\"stack is empty\");" }, { "code": null, "e": 1643, "s": 1594, "text": "Otherwise, follow the below mentioned algorithm." }, { "code": null, "e": 1686, "s": 1643, "text": "for (i=0; i<top; i++)\nprintf (\"%d\", a[i]);" }, { "code": null, "e": 1760, "s": 1686, "text": "Let us understand the conversions of expressions of stacks in C language." }, { "code": null, "e": 1827, "s": 1760, "text": "Expression − It is a legal combination of operands and operations." }, { "code": null, "e": 1848, "s": 1827, "text": "Types of expressions" }, { "code": null, "e": 1987, "s": 1848, "text": "There are three types of expressions in C language on which the conversions and evaluations can be carried out. They are explained below −" }, { "code": null, "e": 2060, "s": 1987, "text": "Infix expression − Operator is in between the operands. For example, A+B" }, { "code": null, "e": 2133, "s": 2060, "text": "Infix expression − Operator is in between the operands. For example, A+B" }, { "code": null, "e": 2203, "s": 2133, "text": "Prefix expression − Operator is before the operands. For example, +AB" }, { "code": null, "e": 2273, "s": 2203, "text": "Prefix expression − Operator is before the operands. For example, +AB" }, { "code": null, "e": 2343, "s": 2273, "text": "Postfix expression − Operator is after the operands. For example, AB+" }, { "code": null, "e": 2413, "s": 2343, "text": "Postfix expression − Operator is after the operands. For example, AB+" }, { "code": null, "e": 2485, "s": 2413, "text": "Conversion of infix to postfix and infix to prefix is explained below −" }, { "code": null, "e": 2604, "s": 2485, "text": "Infix to postfix Infix to prefix\nA+ B*C A+ B*C\nA+ BC * A+ *BC\nABC* + +A*BC" }, { "code": null, "e": 2617, "s": 2604, "text": "For example," }, { "code": null, "e": 2668, "s": 2617, "text": "Convert A+B*C / D-E+F infix to postfix and prefix." }, { "code": null, "e": 2958, "s": 2668, "text": "Infix to prefix Infix to postfix\nA +B*C / D-E+F A +B*C / D-E+F\nA +*BC / D-E+F A +BC* / D-E+F\nA + / *BCD -E+F A +BC*D /-E+F\n+A /*BCD -E +F ABC *D /+ -E+F\n-+A/*BCDE +F ABC *D/ +E- +F\n+ - +A/*BCDEF ABC *D / +E –F+" }, { "code": null, "e": 3034, "s": 2958, "text": "Scan the input string from left to right and follow the steps given below −" }, { "code": null, "e": 3106, "s": 3034, "text": "Step 1 − If the input symbol is an operand, print it on to the monitor." }, { "code": null, "e": 3178, "s": 3106, "text": "Step 1 − If the input symbol is an operand, print it on to the monitor." }, { "code": null, "e": 3244, "s": 3178, "text": "Step 2 − If the input symbol is ‘(‘then, push it on to the stack." }, { "code": null, "e": 3310, "s": 3244, "text": "Step 2 − If the input symbol is ‘(‘then, push it on to the stack." }, { "code": null, "e": 3413, "s": 3310, "text": "Step 3 − If the input the symbol is ‘)’ then, pop out all the contents of the stack until you get ‘(‘." }, { "code": null, "e": 3516, "s": 3413, "text": "Step 3 − If the input the symbol is ‘)’ then, pop out all the contents of the stack until you get ‘(‘." }, { "code": null, "e": 3652, "s": 3516, "text": "Step 4 − If the input symbol is an operator, check with the priority of the operator on top of the stack with the current input symbol." }, { "code": null, "e": 3788, "s": 3652, "text": "Step 4 − If the input symbol is an operator, check with the priority of the operator on top of the stack with the current input symbol." }, { "code": null, "e": 3974, "s": 3788, "text": "If the top priority of top of the stack is greater than or equal to the priority of the current symbol, then pop out the content of the stack and put the current symbol in to the stack." }, { "code": null, "e": 4020, "s": 3974, "text": "Otherwise, push the operator on to the stack." }, { "code": null, "e": 4121, "s": 4020, "text": "Step 5 − If the input symbol is ‘\\0’ then, pop out the contents of the stack until it becomes empty." }, { "code": null, "e": 4222, "s": 4121, "text": "Step 5 − If the input symbol is ‘\\0’ then, pop out the contents of the stack until it becomes empty." }, { "code": null, "e": 4295, "s": 4222, "text": "Conversion of infix to post fix with the help of stacks is given below −" } ]
jQuery | ready() with Examples
26 Sep, 2018 The ready() method is an inbuilt method in jQuery which helps to load the whole page then execute the rest code. This method specify the function to execute when the DOM is fully loaded. Syntax: $(document).ready(function) Parameters: This method accepts single parameter function which is mandatory. It is used to specify the function to run after the document is loaded. Return Value: This method returns the document after performing the ready() method.Below example illustrates the ready() method in jQuery: Example: <!DOCTYpe html><html> <head> <title>The ready Method</title> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <!-- jQuery code to show the working of this method --> <script> $(document).ready(function(){ $("button").click(function(){ $("p").css("color", "green"); $("p").css("font-size", "40px"); $("p").css("font-weight","bold") }); }); </script> <style> div { text-align:center; width: 60%; min-height: 100px; padding: 10px; border: 2px solid green; } </style> </head> <body> <div> <p>Welcome to</p> <p>GeeksforGeeks!</p> <!-- click on this button --> <button>Click Here!</button> </div> </body></html> Output: JavaScript JQuery Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Sep, 2018" }, { "code": null, "e": 215, "s": 28, "text": "The ready() method is an inbuilt method in jQuery which helps to load the whole page then execute the rest code. This method specify the function to execute when the DOM is fully loaded." }, { "code": null, "e": 223, "s": 215, "text": "Syntax:" }, { "code": null, "e": 251, "s": 223, "text": "$(document).ready(function)" }, { "code": null, "e": 401, "s": 251, "text": "Parameters: This method accepts single parameter function which is mandatory. It is used to specify the function to run after the document is loaded." }, { "code": null, "e": 540, "s": 401, "text": "Return Value: This method returns the document after performing the ready() method.Below example illustrates the ready() method in jQuery:" }, { "code": null, "e": 549, "s": 540, "text": "Example:" }, { "code": "<!DOCTYpe html><html> <head> <title>The ready Method</title> <script src= \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <!-- jQuery code to show the working of this method --> <script> $(document).ready(function(){ $(\"button\").click(function(){ $(\"p\").css(\"color\", \"green\"); $(\"p\").css(\"font-size\", \"40px\"); $(\"p\").css(\"font-weight\",\"bold\") }); }); </script> <style> div { text-align:center; width: 60%; min-height: 100px; padding: 10px; border: 2px solid green; } </style> </head> <body> <div> <p>Welcome to</p> <p>GeeksforGeeks!</p> <!-- click on this button --> <button>Click Here!</button> </div> </body></html>", "e": 1501, "s": 549, "text": null }, { "code": null, "e": 1509, "s": 1501, "text": "Output:" }, { "code": null, "e": 1520, "s": 1509, "text": "JavaScript" }, { "code": null, "e": 1527, "s": 1520, "text": "JQuery" } ]
How can I create custom button in Android using XML Styles?
This example demonstrates how do I create custom button in Android using XML Styles. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/customButton" android:layout_width="200dp" android:layout_height="wrap_content" android:layout_centerInParent="true" android:background="@drawable/custom_button" android:text="My Custom button"/> <Button android:id="@+id/customButton2" android:layout_width="200dp" android:layout_height="wrap_content" android:layout_centerInParent="true" android:layout_below="@id/customButton" android:layout_marginTop="24sp" android:background="@drawable/custom_button2" android:text="My Custom button"/> <Button android:id="@+id/customButton3" android:layout_width="200dp" android:layout_height="200dp" android:layout_centerInParent="true" android:layout_above="@id/customButton" android:layout_marginBottom="24sp" android:layout_marginTop="24sp" android:background="@drawable/custom_button3" android:text="My Custom button"/> </RelativeLayout> Step 3 – Right Click on res/drawable, Select new → Drawable resource file and add the following code in custom_dialog.xml <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <stroke android:color="#66F9B9" android:width="4dp"/> <corners android:radius="16sp"/> </shape> Step 4 – Right Click on res/drawable, Select new → Drawable resource file and add the following code in custom_dialog2.xml <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <gradient android:startColor="#2AF598" android:centerColor="#ff1493" android:endColor="@color/colorPrimary"/> <corners android:radius="50dp"/> </shape> Step 5 – Right Click on res/drawable, Select new → Drawable resource file and add the following code in custom_dialog3.xml <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <solid android:color="#80121a" /> <corners android:radius="999dp"/> </shape> Step 6 − Add the following code to src/MainActivity.java package app.com.sample; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } } Step 7 - Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run Icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
[ { "code": null, "e": 1272, "s": 1187, "text": "This example demonstrates how do I create custom button in Android using XML Styles." }, { "code": null, "e": 1401, "s": 1272, "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": 1466, "s": 1401, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2750, "s": 1466, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n\n <Button\n android:id=\"@+id/customButton\"\n android:layout_width=\"200dp\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:background=\"@drawable/custom_button\"\n android:text=\"My Custom button\"/>\n\n <Button\n android:id=\"@+id/customButton2\"\n android:layout_width=\"200dp\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:layout_below=\"@id/customButton\"\n android:layout_marginTop=\"24sp\"\n android:background=\"@drawable/custom_button2\"\n android:text=\"My Custom button\"/>\n\n <Button\n android:id=\"@+id/customButton3\"\n android:layout_width=\"200dp\"\n android:layout_height=\"200dp\"\n android:layout_centerInParent=\"true\"\n android:layout_above=\"@id/customButton\"\n android:layout_marginBottom=\"24sp\"\n android:layout_marginTop=\"24sp\"\n android:background=\"@drawable/custom_button3\"\n android:text=\"My Custom button\"/>\n</RelativeLayout>" }, { "code": null, "e": 2872, "s": 2750, "text": "Step 3 – Right Click on res/drawable, Select new → Drawable resource file and add the following code in custom_dialog.xml" }, { "code": null, "e": 3110, "s": 2872, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<shape xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:shape=\"rectangle\">\n\n <stroke android:color=\"#66F9B9\" android:width=\"4dp\"/>\n <corners android:radius=\"16sp\"/>\n</shape>" }, { "code": null, "e": 3233, "s": 3110, "text": "Step 4 – Right Click on res/drawable, Select new → Drawable resource file and add the following code in custom_dialog2.xml" }, { "code": null, "e": 3533, "s": 3233, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<shape xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:shape=\"rectangle\">\n\n <gradient android:startColor=\"#2AF598\" android:centerColor=\"#ff1493\"\n android:endColor=\"@color/colorPrimary\"/>\n <corners android:radius=\"50dp\"/>\n</shape>" }, { "code": null, "e": 3656, "s": 3533, "text": "Step 5 – Right Click on res/drawable, Select new → Drawable resource file and add the following code in custom_dialog3.xml" }, { "code": null, "e": 3875, "s": 3656, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<shape xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:shape=\"rectangle\">\n\n <solid android:color=\"#80121a\" />\n <corners android:radius=\"999dp\"/>\n</shape>" }, { "code": null, "e": 3932, "s": 3875, "text": "Step 6 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 4251, "s": 3932, "text": "package app.com.sample;\n\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\n\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n }\n}" }, { "code": null, "e": 4306, "s": 4251, "text": "Step 7 - Add the following code to androidManifest.xml" }, { "code": null, "e": 4980, "s": 4306, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.sample\">\n\n <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": 5327, "s": 4980, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run Icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" } ]
Java Program for Anagram Substring Search (Or Search for all permutations)
07 Jul, 2021 Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all occurrences of pat[] and its permutations (or anagrams) in txt[]. You may assume that n > m.Expected time complexity is O(n) Examples: 1) Input: txt[] = "BACDGABCDA" pat[] = "ABCD" Output: Found at Index 0 Found at Index 5 Found at Index 6 2) Input: txt[] = "AAABABAA" pat[] = "AABA" Output: Found at Index 0 Found at Index 1 Found at Index 4 A simple idea is to modify Rabin Karp Algorithm. For example we can keep the hash value as sum of ASCII values of all characters under modulo of a big prime number. For every character of text, we can add the current character to hash value and subtract the first character of previous window. This solution looks good, but like standard Rabin Karp, the worst case time complexity of this solution is O(mn). The worst case occurs when all hash values match and we one by one match all characters.We can achieve O(n) time complexity under the assumption that alphabet size is fixed which is typically true as we have maximum 256 possible characters in ASCII. The idea is to use two count arrays: 1) The first count array store frequencies of characters in pattern.2) The second count array stores frequencies of characters in current window of text. The important thing to note is, time complexity to compare two count arrays is O(1) as the number of elements in them are fixed (independent of pattern and text sizes). Following are steps of this algorithm.1) Store counts of frequencies of pattern in first count array countP[]. Also store counts of frequencies of characters in first window of text in array countTW[]. 2) Now run a loop from i = M to N-1. Do following in loop......a) If the two count arrays are identical, we found an occurrence......b) Increment count of current character of text in countTW[].....c) Decrement count of first character in previous window in countWT[] 3) The last window is not checked by above loop, so explicitly check it. Java // Java program to search all anagrams// of a pattern in a textpublic class GFG { static final int MAX = 256; // This function returns true if contents // of arr1[] and arr2[] are same, otherwise // false. static boolean compare(char arr1[], char arr2[]) { for (int i = 0; i < MAX; i++) if (arr1[i] != arr2[i]) return false; return true; } // This function search for all permutations // of pat[] in txt[] static void search(String pat, String txt) { int M = pat.length(); int N = txt.length(); // countP[]: Store count of all // characters of pattern // countTW[]: Store count of current // window of text char[] countP = new char[MAX]; char[] countTW = new char[MAX]; for (int i = 0; i < M; i++) { (countP[pat.charAt(i)])++; (countTW[txt.charAt(i)])++; } // Traverse through remaining characters // of pattern for (int i = M; i < N; i++) { // Compare counts of current window // of text with counts of pattern[] if (compare(countP, countTW)) System.out.println("Found at Index " + (i - M)); // Add current character to current // window (countTW[txt.charAt(i)])++; // Remove the first character of previous // window countTW[txt.charAt(i - M)]--; } // Check for the last window in text if (compare(countP, countTW)) System.out.println("Found at Index " + (N - M)); } /* Driver program to test above function */ public static void main(String args[]) { String txt = "BACDGABCDA"; String pat = "ABCD"; search(pat, txt); }}// This code is contributed by Sumit Ghosh Found at Index 0 Found at Index 5 Found at Index 6 Please refer complete article on Anagram Substring Search (Or Search for all permutations) for more details! Java Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Iterate Over the Characters of a String in Java How to Convert Char to String in Java? How to Get Elements By Index from HashSet in Java? Java Program to Write into a File How to Write Data into Excel Sheet using Java? Java Program to Read a File to String Comparing two ArrayList In Java Java Program to Convert File to a Byte Array SHA-1 Hash Java Program to Find Sum of Array Elements
[ { "code": null, "e": 54, "s": 26, "text": "\n07 Jul, 2021" }, { "code": null, "e": 295, "s": 54, "text": "Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all occurrences of pat[] and its permutations (or anagrams) in txt[]. You may assume that n > m.Expected time complexity is O(n)" }, { "code": null, "e": 305, "s": 295, "text": "Examples:" }, { "code": null, "e": 578, "s": 305, "text": "1) Input: txt[] = \"BACDGABCDA\" pat[] = \"ABCD\"\n Output: Found at Index 0\n Found at Index 5\n Found at Index 6\n2) Input: txt[] = \"AAABABAA\" pat[] = \"AABA\"\n Output: Found at Index 0\n Found at Index 1\n Found at Index 4" }, { "code": null, "e": 1273, "s": 578, "text": "A simple idea is to modify Rabin Karp Algorithm. For example we can keep the hash value as sum of ASCII values of all characters under modulo of a big prime number. For every character of text, we can add the current character to hash value and subtract the first character of previous window. This solution looks good, but like standard Rabin Karp, the worst case time complexity of this solution is O(mn). The worst case occurs when all hash values match and we one by one match all characters.We can achieve O(n) time complexity under the assumption that alphabet size is fixed which is typically true as we have maximum 256 possible characters in ASCII. The idea is to use two count arrays:" }, { "code": null, "e": 1427, "s": 1273, "text": "1) The first count array store frequencies of characters in pattern.2) The second count array stores frequencies of characters in current window of text." }, { "code": null, "e": 1798, "s": 1427, "text": "The important thing to note is, time complexity to compare two count arrays is O(1) as the number of elements in them are fixed (independent of pattern and text sizes). Following are steps of this algorithm.1) Store counts of frequencies of pattern in first count array countP[]. Also store counts of frequencies of characters in first window of text in array countTW[]." }, { "code": null, "e": 2066, "s": 1798, "text": "2) Now run a loop from i = M to N-1. Do following in loop......a) If the two count arrays are identical, we found an occurrence......b) Increment count of current character of text in countTW[].....c) Decrement count of first character in previous window in countWT[]" }, { "code": null, "e": 2139, "s": 2066, "text": "3) The last window is not checked by above loop, so explicitly check it." }, { "code": null, "e": 2144, "s": 2139, "text": "Java" }, { "code": "// Java program to search all anagrams// of a pattern in a textpublic class GFG { static final int MAX = 256; // This function returns true if contents // of arr1[] and arr2[] are same, otherwise // false. static boolean compare(char arr1[], char arr2[]) { for (int i = 0; i < MAX; i++) if (arr1[i] != arr2[i]) return false; return true; } // This function search for all permutations // of pat[] in txt[] static void search(String pat, String txt) { int M = pat.length(); int N = txt.length(); // countP[]: Store count of all // characters of pattern // countTW[]: Store count of current // window of text char[] countP = new char[MAX]; char[] countTW = new char[MAX]; for (int i = 0; i < M; i++) { (countP[pat.charAt(i)])++; (countTW[txt.charAt(i)])++; } // Traverse through remaining characters // of pattern for (int i = M; i < N; i++) { // Compare counts of current window // of text with counts of pattern[] if (compare(countP, countTW)) System.out.println(\"Found at Index \" + (i - M)); // Add current character to current // window (countTW[txt.charAt(i)])++; // Remove the first character of previous // window countTW[txt.charAt(i - M)]--; } // Check for the last window in text if (compare(countP, countTW)) System.out.println(\"Found at Index \" + (N - M)); } /* Driver program to test above function */ public static void main(String args[]) { String txt = \"BACDGABCDA\"; String pat = \"ABCD\"; search(pat, txt); }}// This code is contributed by Sumit Ghosh", "e": 3994, "s": 2144, "text": null }, { "code": null, "e": 4046, "s": 3994, "text": "Found at Index 0\nFound at Index 5\nFound at Index 6\n" }, { "code": null, "e": 4155, "s": 4046, "text": "Please refer complete article on Anagram Substring Search (Or Search for all permutations) for more details!" }, { "code": null, "e": 4169, "s": 4155, "text": "Java Programs" }, { "code": null, "e": 4267, "s": 4169, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4315, "s": 4267, "text": "Iterate Over the Characters of a String in Java" }, { "code": null, "e": 4354, "s": 4315, "text": "How to Convert Char to String in Java?" }, { "code": null, "e": 4405, "s": 4354, "text": "How to Get Elements By Index from HashSet in Java?" }, { "code": null, "e": 4439, "s": 4405, "text": "Java Program to Write into a File" }, { "code": null, "e": 4486, "s": 4439, "text": "How to Write Data into Excel Sheet using Java?" }, { "code": null, "e": 4524, "s": 4486, "text": "Java Program to Read a File to String" }, { "code": null, "e": 4556, "s": 4524, "text": "Comparing two ArrayList In Java" }, { "code": null, "e": 4601, "s": 4556, "text": "Java Program to Convert File to a Byte Array" }, { "code": null, "e": 4612, "s": 4601, "text": "SHA-1 Hash" } ]
Find the smallest missing number
09 Jun, 2022 Given a sorted array of n distinct integers where each integer is in the range from 0 to m-1 and m > n. Find the smallest number that is missing from the array. Examples Input: {0, 1, 2, 6, 9}, n = 5, m = 10 Output: 3 Input: {4, 5, 10, 11}, n = 4, m = 12 Output: 0 Input: {0, 1, 2, 3}, n = 4, m = 5 Output: 4 Input: {0, 1, 2, 3, 4, 5, 6, 7, 10}, n = 9, m = 11 Output: 8 Thanks to Ravichandra for suggesting following two methods. Method 1 (Use Binary Search) For i = 0 to m-1, do binary search for i in the array. If i is not present in the array then return i.Time Complexity: O(m log n) Method 2 (Linear Search) If arr[0] is not 0, return 0. Otherwise traverse the input array starting from index 0, and for each pair of elements a[i] and a[i+1], find the difference between them. if the difference is greater than 1 then a[i]+1 is the missing number. Time Complexity: O(n) 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. Method 3 (Use Modified Binary Search) Thanks to yasein and Jams for suggesting this method. In the standard Binary Search process, the element to be searched is compared with the middle element and on the basis of comparison result, we decide whether to search is over or to go to left half or right half. In this method, we modify the standard Binary Search algorithm to compare the middle element with its index and make decision on the basis of this comparison. If the first element is not same as its index then return first index Else get the middle index say midIf arr[mid] greater than mid then the required element lies in left half.Else the required element lies in right half. If arr[mid] greater than mid then the required element lies in left half. Else the required element lies in right half. C++ C Java Python3 C# PHP Javascript // C++ program to find the smallest elements// missing in a sorted array.#include<bits/stdc++.h>using namespace std; int findFirstMissing(int array[], int start, int end){ if (start > end) return end + 1; if (start != array[start]) return start; int mid = (start + end) / 2; // Left half has all elements // from 0 to mid if (array[mid] == mid) return findFirstMissing(array, mid+1, end); return findFirstMissing(array, start, mid);} // Driver codeint main(){ int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 10}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Smallest missing element is " << findFirstMissing(arr, 0, n-1) << endl;} // This code is contributed by// Shivi_Aggarwal // C program to find the smallest elements missing// in a sorted array.#include<stdio.h> int findFirstMissing(int array[], int start, int end){ if (start > end) return end + 1; if (start != array[start]) return start; int mid = (start + end) / 2; // Left half has all elements from 0 to mid if (array[mid] == mid) return findFirstMissing(array, mid+1, end); return findFirstMissing(array, start, mid);} // driver program to test above functionint main(){ int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 10}; int n = sizeof(arr)/sizeof(arr[0]); printf("Smallest missing element is %d", findFirstMissing(arr, 0, n-1)); return 0;} class SmallestMissing{ int findFirstMissing(int array[], int start, int end) { if (start > end) return end + 1; if (start != array[start]) return start; int mid = (start + end) / 2; // Left half has all elements from 0 to mid if (array[mid] == mid) return findFirstMissing(array, mid+1, end); return findFirstMissing(array, start, mid); } // Driver program to test the above function public static void main(String[] args) { SmallestMissing small = new SmallestMissing(); int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 10}; int n = arr.length; System.out.println("First Missing element is : " + small.findFirstMissing(arr, 0, n - 1)); }} # Python3 program to find the smallest# elements missing in a sorted array. def findFirstMissing(array, start, end): if (start > end): return end + 1 if (start != array[start]): return start; mid = int((start + end) / 2) # Left half has all elements # from 0 to mid if (array[mid] == mid): return findFirstMissing(array, mid+1, end) return findFirstMissing(array, start, mid) # driver program to test above functionarr = [0, 1, 2, 3, 4, 5, 6, 7, 10]n = len(arr)print("Smallest missing element is", findFirstMissing(arr, 0, n-1)) # This code is contributed by Smitha Dinesh Semwal // C# program to find the smallest// elements missing in a sorted array.using System; class GFG{ static int findFirstMissing(int []array, int start, int end) { if (start > end) return end + 1; if (start != array[start]) return start; int mid = (start + end) / 2; // Left half has all elements from 0 to mid if (array[mid] == mid) return findFirstMissing(array, mid+1, end); return findFirstMissing(array, start, mid); } // Driver program to test the above function public static void Main() { int []arr = {0, 1, 2, 3, 4, 5, 6, 7, 10}; int n = arr.Length; Console.Write("smallest Missing element is : " + findFirstMissing(arr, 0, n - 1)); }} // This code is contributed by Sam007 <?php// PHP program to find the// smallest elements missing// in a sorted array. // function that returns// smallest elements missing// in a sorted array.function findFirstMissing($array, $start, $end){ if ($start > $end) return $end + 1; if ($start != $array[$start]) return $start; $mid = ($start + $end) / 2; // Left half has all // elements from 0 to mid if ($array[$mid] == $mid) return findFirstMissing($array, $mid + 1, $end); return findFirstMissing($array, $start, $mid);} // Driver Code $arr = array (0, 1, 2, 3, 4, 5, 6, 7, 10); $n = count($arr); echo "Smallest missing element is " , findFirstMissing($arr, 2, $n - 1); // This code Contributed by Ajit.?> <script> // Javascript program to find the smallest // elements missing in a sorted array. function findFirstMissing(array, start, end) { if (start > end) return end + 1; if (start != array[start]) return start; let mid = parseInt((start + end) / 2, 10); // Left half has all elements from 0 to mid if (array[mid] == mid) return findFirstMissing(array, mid+1, end); return findFirstMissing(array, start, mid); } let arr = [0, 1, 2, 3, 4, 5, 6, 7, 10]; let n = arr.length; document.write("smallest Missing element is " + findFirstMissing(arr, 0, n - 1)); </script> Smallest missing element is 8 Note: This method doesn’t work if there are duplicate elements in the array.Time Complexity: O(Log n) Auxiliary Space : O(Log n) Another Method: The idea is to use Recursive Binary Search to find the smallest missing number. Below is the illustration with the help of steps: If the first element of the array is not 0, then the smallest missing number is 0. If the last elements of the array is N-1, then the smallest missing number is N. Otherwise, find the middle element from the first and last index and check if the middle element is equal to the desired element. i.e. first + middle_index.If the middle element is the desired element, then the smallest missing element is in the right search space of the middle.Otherwise, the smallest missing number is in the left search space of the middle. If the middle element is the desired element, then the smallest missing element is in the right search space of the middle. Otherwise, the smallest missing number is in the left search space of the middle. Below is the implementation of the above approach: C++ Java Python3 C# Javascript //C++ program for the above approach#include <bits/stdc++.h> using namespace std; // Program to find missing elementint findFirstMissing(vector<int> arr , int start , int end,int first){ if (start < end) { int mid = (start + end) / 2; /** Index matches with value at that index, means missing element cannot be upto that po*/ if (arr[mid] != mid+first) return findFirstMissing(arr, start, mid , first); else return findFirstMissing(arr, mid + 1, end , first); } return start + first; } // Program to find Smallest// Missing in Sorted Arrayint findSmallestMissinginSortedArray(vector<int> arr){ // Check if 0 is missing // in the array if(arr[0] != 0) return 0; // Check is all numbers 0 to n - 1 // are present in array if(arr[arr.size() - 1] == arr.size() - 1) return arr.size(); int first = arr[0]; return findFirstMissing(arr, 0, arr.size() - 1, first);} // Driver program to test the above functionint main(){ vector<int> arr = {0, 1, 2, 3, 4, 5, 7}; int n = arr.size(); // Function Call cout<<"First Missing element is : "<<findSmallestMissinginSortedArray(arr);} // This code is contributed by mohit kumar 29. // Java Program for above approachimport java.io.*; class GFG{ // Program to find Smallest // Missing in Sorted Array int findSmallestMissinginSortedArray( int[] arr) { // Check if 0 is missing // in the array if(arr[0] != 0) return 0; // Check is all numbers 0 to n - 1 // are present in array if(arr[arr.length-1] == arr.length - 1) return arr.length; int first = arr[0]; return findFirstMissing(arr,0, arr.length-1,first); } // Program to find missing element int findFirstMissing(int[] arr , int start , int end, int first) { if (start < end) { int mid = (start+end)/2; /** Index matches with value at that index, means missing element cannot be upto that point */ if (arr[mid] != mid+first) return findFirstMissing(arr, start, mid , first); else return findFirstMissing(arr, mid+1, end , first); } return start+first; } // Driver program to test the above function public static void main(String[] args) { GFG small = new GFG(); int arr[] = {0, 1, 2, 3, 4, 5, 7}; int n = arr.length; // Function Call System.out.println("First Missing element is : " + small.findSmallestMissinginSortedArray(arr)); }} # Python3 program for above approach # Function to find Smallest # Missing in Sorted Arraydef findSmallestMissinginSortedArray(arr): # Check if 0 is missing # in the array if (arr[0] != 0): return 0 # Check is all numbers 0 to n - 1 # are present in array if (arr[-1] == len(arr) - 1): return len(arr) first = arr[0] return findFirstMissing(arr, 0, len(arr) - 1, first) # Function to find missing element def findFirstMissing(arr, start, end, first): if (start < end): mid = int((start + end) / 2) # Index matches with value # at that index, means missing # element cannot be upto that point if (arr[mid] != mid + first): return findFirstMissing(arr, start, mid, first) else: return findFirstMissing(arr, mid + 1, end, first) return start + first # Driver codearr = [ 0, 1, 2, 3, 4, 5, 7 ]n = len(arr) # Function Callprint("First Missing element is :", findSmallestMissinginSortedArray(arr)) # This code is contributed by rag2127 // C# program for above approachusing System; class GFG{ // Program to find Smallest // Missing in Sorted Arrayint findSmallestMissinginSortedArray(int[] arr) { // Check if 0 is missing // in the array if (arr[0] != 0) return 0; // Check is all numbers 0 to n - 1 // are present in array if (arr[arr.Length - 1] == arr.Length - 1) return arr.Length; int first = arr[0]; return findFirstMissing(arr, 0, arr.Length - 1,first);} // Program to find missing element int findFirstMissing(int[] arr , int start , int end, int first) { if (start < end) { int mid = (start + end) / 2; /*Index matches with value at that index, means missing element cannot be upto that point */ if (arr[mid] != mid+first) return findFirstMissing(arr, start, mid, first); else return findFirstMissing(arr, mid + 1, end, first); } return start + first;} // Driver codestatic public void Main (){ GFG small = new GFG(); int[] arr = {0, 1, 2, 3, 4, 5, 7}; int n = arr.Length; // Function Call Console.WriteLine("First Missing element is : " + small.findSmallestMissinginSortedArray(arr));}} // This code is contributed by avanitrachhadiya2155 <script> // Javascript program for the above approach // Program to find missing elementfunction findFirstMissing(arr, start, end, first){ if (start < end) { let mid = (start + end) / 2; /** Index matches with value at that index, means missing element cannot be upto that po*/ if (arr[mid] != mid + first) return findFirstMissing(arr, start, mid, first); else return findFirstMissing(arr, mid + 1, end, first); } return start + first;} // Program to find Smallest// Missing in Sorted Arrayfunction findSmallestMissinginSortedArray(arr){ // Check if 0 is missing // in the array if (arr[0] != 0) return 0; // Check is all numbers 0 to n - 1 // are present in array if (arr[arr.length - 1] == arr.length - 1) return arr.length; let first = arr[0]; return findFirstMissing( arr, 0, arr.length - 1, first);} // Driver codelet arr = [ 0, 1, 2, 3, 4, 5, 7 ];let n = arr.length; // Function Calldocument.write("First Missing element is : " + findSmallestMissinginSortedArray(arr)); // This code is contributed by Mayank Tyagi </script> First Missing element is : 6 Time Complexity: O(Log n) Auxiliary Space : O(Log n) Find the smallest missing number | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersFind the smallest missing number | GeeksforGeeksWatch laterShareCopy link81/101InfoShoppingTap 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 / 3:26•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=s60sUkWh7TI" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Please write comments if you find the above codes/algorithms incorrect, or find other ways to solve the same problem. jit_t Shivi_Aggarwal amitbhatia.ab ukasp avanitrachhadiya2155 rag2127 rameshtravel07 mohit kumar 29 mayanktyagi1709 rajeev0719singh _shinchancode Binary Search Arrays Arrays Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Introduction to Arrays Subset Sum Problem | DP-25 Introduction to Data Structures Python | Using 2D arrays/lists the right way
[ { "code": null, "e": 54, "s": 26, "text": "\n09 Jun, 2022" }, { "code": null, "e": 216, "s": 54, "text": "Given a sorted array of n distinct integers where each integer is in the range from 0 to m-1 and m > n. Find the smallest number that is missing from the array. " }, { "code": null, "e": 226, "s": 216, "text": "Examples " }, { "code": null, "e": 433, "s": 226, "text": "Input: {0, 1, 2, 6, 9}, n = 5, m = 10 \nOutput: 3\n\nInput: {4, 5, 10, 11}, n = 4, m = 12 \nOutput: 0\n\nInput: {0, 1, 2, 3}, n = 4, m = 5 \nOutput: 4\n\nInput: {0, 1, 2, 3, 4, 5, 6, 7, 10}, n = 9, m = 11 \nOutput: 8" }, { "code": null, "e": 493, "s": 433, "text": "Thanks to Ravichandra for suggesting following two methods." }, { "code": null, "e": 653, "s": 493, "text": "Method 1 (Use Binary Search) For i = 0 to m-1, do binary search for i in the array. If i is not present in the array then return i.Time Complexity: O(m log n) " }, { "code": null, "e": 940, "s": 653, "text": "Method 2 (Linear Search) If arr[0] is not 0, return 0. Otherwise traverse the input array starting from index 0, and for each pair of elements a[i] and a[i+1], find the difference between them. if the difference is greater than 1 then a[i]+1 is the missing number. Time Complexity: O(n)" }, { "code": null, "e": 949, "s": 940, "text": "Chapters" }, { "code": null, "e": 976, "s": 949, "text": "descriptions off, selected" }, { "code": null, "e": 1026, "s": 976, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 1049, "s": 1026, "text": "captions off, selected" }, { "code": null, "e": 1057, "s": 1049, "text": "English" }, { "code": null, "e": 1081, "s": 1057, "text": "This is a modal window." }, { "code": null, "e": 1150, "s": 1081, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 1172, "s": 1150, "text": "End of dialog window." }, { "code": null, "e": 1637, "s": 1172, "text": "Method 3 (Use Modified Binary Search) Thanks to yasein and Jams for suggesting this method. In the standard Binary Search process, the element to be searched is compared with the middle element and on the basis of comparison result, we decide whether to search is over or to go to left half or right half. In this method, we modify the standard Binary Search algorithm to compare the middle element with its index and make decision on the basis of this comparison." }, { "code": null, "e": 1707, "s": 1637, "text": "If the first element is not same as its index then return first index" }, { "code": null, "e": 1859, "s": 1707, "text": "Else get the middle index say midIf arr[mid] greater than mid then the required element lies in left half.Else the required element lies in right half." }, { "code": null, "e": 1933, "s": 1859, "text": "If arr[mid] greater than mid then the required element lies in left half." }, { "code": null, "e": 1979, "s": 1933, "text": "Else the required element lies in right half." }, { "code": null, "e": 1983, "s": 1979, "text": "C++" }, { "code": null, "e": 1985, "s": 1983, "text": "C" }, { "code": null, "e": 1990, "s": 1985, "text": "Java" }, { "code": null, "e": 1998, "s": 1990, "text": "Python3" }, { "code": null, "e": 2001, "s": 1998, "text": "C#" }, { "code": null, "e": 2005, "s": 2001, "text": "PHP" }, { "code": null, "e": 2016, "s": 2005, "text": "Javascript" }, { "code": "// C++ program to find the smallest elements// missing in a sorted array.#include<bits/stdc++.h>using namespace std; int findFirstMissing(int array[], int start, int end){ if (start > end) return end + 1; if (start != array[start]) return start; int mid = (start + end) / 2; // Left half has all elements // from 0 to mid if (array[mid] == mid) return findFirstMissing(array, mid+1, end); return findFirstMissing(array, start, mid);} // Driver codeint main(){ int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 10}; int n = sizeof(arr)/sizeof(arr[0]); cout << \"Smallest missing element is \" << findFirstMissing(arr, 0, n-1) << endl;} // This code is contributed by// Shivi_Aggarwal", "e": 2792, "s": 2016, "text": null }, { "code": "// C program to find the smallest elements missing// in a sorted array.#include<stdio.h> int findFirstMissing(int array[], int start, int end){ if (start > end) return end + 1; if (start != array[start]) return start; int mid = (start + end) / 2; // Left half has all elements from 0 to mid if (array[mid] == mid) return findFirstMissing(array, mid+1, end); return findFirstMissing(array, start, mid);} // driver program to test above functionint main(){ int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 10}; int n = sizeof(arr)/sizeof(arr[0]); printf(\"Smallest missing element is %d\", findFirstMissing(arr, 0, n-1)); return 0;}", "e": 3475, "s": 2792, "text": null }, { "code": "class SmallestMissing{ int findFirstMissing(int array[], int start, int end) { if (start > end) return end + 1; if (start != array[start]) return start; int mid = (start + end) / 2; // Left half has all elements from 0 to mid if (array[mid] == mid) return findFirstMissing(array, mid+1, end); return findFirstMissing(array, start, mid); } // Driver program to test the above function public static void main(String[] args) { SmallestMissing small = new SmallestMissing(); int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 10}; int n = arr.length; System.out.println(\"First Missing element is : \" + small.findFirstMissing(arr, 0, n - 1)); }}", "e": 4247, "s": 3475, "text": null }, { "code": "# Python3 program to find the smallest# elements missing in a sorted array. def findFirstMissing(array, start, end): if (start > end): return end + 1 if (start != array[start]): return start; mid = int((start + end) / 2) # Left half has all elements # from 0 to mid if (array[mid] == mid): return findFirstMissing(array, mid+1, end) return findFirstMissing(array, start, mid) # driver program to test above functionarr = [0, 1, 2, 3, 4, 5, 6, 7, 10]n = len(arr)print(\"Smallest missing element is\", findFirstMissing(arr, 0, n-1)) # This code is contributed by Smitha Dinesh Semwal", "e": 4930, "s": 4247, "text": null }, { "code": "// C# program to find the smallest// elements missing in a sorted array.using System; class GFG{ static int findFirstMissing(int []array, int start, int end) { if (start > end) return end + 1; if (start != array[start]) return start; int mid = (start + end) / 2; // Left half has all elements from 0 to mid if (array[mid] == mid) return findFirstMissing(array, mid+1, end); return findFirstMissing(array, start, mid); } // Driver program to test the above function public static void Main() { int []arr = {0, 1, 2, 3, 4, 5, 6, 7, 10}; int n = arr.Length; Console.Write(\"smallest Missing element is : \" + findFirstMissing(arr, 0, n - 1)); }} // This code is contributed by Sam007", "e": 5786, "s": 4930, "text": null }, { "code": "<?php// PHP program to find the// smallest elements missing// in a sorted array. // function that returns// smallest elements missing// in a sorted array.function findFirstMissing($array, $start, $end){ if ($start > $end) return $end + 1; if ($start != $array[$start]) return $start; $mid = ($start + $end) / 2; // Left half has all // elements from 0 to mid if ($array[$mid] == $mid) return findFirstMissing($array, $mid + 1, $end); return findFirstMissing($array, $start, $mid);} // Driver Code $arr = array (0, 1, 2, 3, 4, 5, 6, 7, 10); $n = count($arr); echo \"Smallest missing element is \" , findFirstMissing($arr, 2, $n - 1); // This code Contributed by Ajit.?>", "e": 6645, "s": 5786, "text": null }, { "code": "<script> // Javascript program to find the smallest // elements missing in a sorted array. function findFirstMissing(array, start, end) { if (start > end) return end + 1; if (start != array[start]) return start; let mid = parseInt((start + end) / 2, 10); // Left half has all elements from 0 to mid if (array[mid] == mid) return findFirstMissing(array, mid+1, end); return findFirstMissing(array, start, mid); } let arr = [0, 1, 2, 3, 4, 5, 6, 7, 10]; let n = arr.length; document.write(\"smallest Missing element is \" + findFirstMissing(arr, 0, n - 1)); </script>", "e": 7339, "s": 6645, "text": null }, { "code": null, "e": 7369, "s": 7339, "text": "Smallest missing element is 8" }, { "code": null, "e": 7471, "s": 7369, "text": "Note: This method doesn’t work if there are duplicate elements in the array.Time Complexity: O(Log n)" }, { "code": null, "e": 7498, "s": 7471, "text": "Auxiliary Space : O(Log n)" }, { "code": null, "e": 7644, "s": 7498, "text": "Another Method: The idea is to use Recursive Binary Search to find the smallest missing number. Below is the illustration with the help of steps:" }, { "code": null, "e": 7727, "s": 7644, "text": "If the first element of the array is not 0, then the smallest missing number is 0." }, { "code": null, "e": 7808, "s": 7727, "text": "If the last elements of the array is N-1, then the smallest missing number is N." }, { "code": null, "e": 8169, "s": 7808, "text": "Otherwise, find the middle element from the first and last index and check if the middle element is equal to the desired element. i.e. first + middle_index.If the middle element is the desired element, then the smallest missing element is in the right search space of the middle.Otherwise, the smallest missing number is in the left search space of the middle." }, { "code": null, "e": 8293, "s": 8169, "text": "If the middle element is the desired element, then the smallest missing element is in the right search space of the middle." }, { "code": null, "e": 8375, "s": 8293, "text": "Otherwise, the smallest missing number is in the left search space of the middle." }, { "code": null, "e": 8426, "s": 8375, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 8430, "s": 8426, "text": "C++" }, { "code": null, "e": 8435, "s": 8430, "text": "Java" }, { "code": null, "e": 8443, "s": 8435, "text": "Python3" }, { "code": null, "e": 8446, "s": 8443, "text": "C#" }, { "code": null, "e": 8457, "s": 8446, "text": "Javascript" }, { "code": "//C++ program for the above approach#include <bits/stdc++.h> using namespace std; // Program to find missing elementint findFirstMissing(vector<int> arr , int start , int end,int first){ if (start < end) { int mid = (start + end) / 2; /** Index matches with value at that index, means missing element cannot be upto that po*/ if (arr[mid] != mid+first) return findFirstMissing(arr, start, mid , first); else return findFirstMissing(arr, mid + 1, end , first); } return start + first; } // Program to find Smallest// Missing in Sorted Arrayint findSmallestMissinginSortedArray(vector<int> arr){ // Check if 0 is missing // in the array if(arr[0] != 0) return 0; // Check is all numbers 0 to n - 1 // are present in array if(arr[arr.size() - 1] == arr.size() - 1) return arr.size(); int first = arr[0]; return findFirstMissing(arr, 0, arr.size() - 1, first);} // Driver program to test the above functionint main(){ vector<int> arr = {0, 1, 2, 3, 4, 5, 7}; int n = arr.size(); // Function Call cout<<\"First Missing element is : \"<<findSmallestMissinginSortedArray(arr);} // This code is contributed by mohit kumar 29.", "e": 9733, "s": 8457, "text": null }, { "code": "// Java Program for above approachimport java.io.*; class GFG{ // Program to find Smallest // Missing in Sorted Array int findSmallestMissinginSortedArray( int[] arr) { // Check if 0 is missing // in the array if(arr[0] != 0) return 0; // Check is all numbers 0 to n - 1 // are present in array if(arr[arr.length-1] == arr.length - 1) return arr.length; int first = arr[0]; return findFirstMissing(arr,0, arr.length-1,first); } // Program to find missing element int findFirstMissing(int[] arr , int start , int end, int first) { if (start < end) { int mid = (start+end)/2; /** Index matches with value at that index, means missing element cannot be upto that point */ if (arr[mid] != mid+first) return findFirstMissing(arr, start, mid , first); else return findFirstMissing(arr, mid+1, end , first); } return start+first; } // Driver program to test the above function public static void main(String[] args) { GFG small = new GFG(); int arr[] = {0, 1, 2, 3, 4, 5, 7}; int n = arr.length; // Function Call System.out.println(\"First Missing element is : \" + small.findSmallestMissinginSortedArray(arr)); }}", "e": 11258, "s": 9733, "text": null }, { "code": "# Python3 program for above approach # Function to find Smallest # Missing in Sorted Arraydef findSmallestMissinginSortedArray(arr): # Check if 0 is missing # in the array if (arr[0] != 0): return 0 # Check is all numbers 0 to n - 1 # are present in array if (arr[-1] == len(arr) - 1): return len(arr) first = arr[0] return findFirstMissing(arr, 0, len(arr) - 1, first) # Function to find missing element def findFirstMissing(arr, start, end, first): if (start < end): mid = int((start + end) / 2) # Index matches with value # at that index, means missing # element cannot be upto that point if (arr[mid] != mid + first): return findFirstMissing(arr, start, mid, first) else: return findFirstMissing(arr, mid + 1, end, first) return start + first # Driver codearr = [ 0, 1, 2, 3, 4, 5, 7 ]n = len(arr) # Function Callprint(\"First Missing element is :\", findSmallestMissinginSortedArray(arr)) # This code is contributed by rag2127", "e": 12425, "s": 11258, "text": null }, { "code": "// C# program for above approachusing System; class GFG{ // Program to find Smallest // Missing in Sorted Arrayint findSmallestMissinginSortedArray(int[] arr) { // Check if 0 is missing // in the array if (arr[0] != 0) return 0; // Check is all numbers 0 to n - 1 // are present in array if (arr[arr.Length - 1] == arr.Length - 1) return arr.Length; int first = arr[0]; return findFirstMissing(arr, 0, arr.Length - 1,first);} // Program to find missing element int findFirstMissing(int[] arr , int start , int end, int first) { if (start < end) { int mid = (start + end) / 2; /*Index matches with value at that index, means missing element cannot be upto that point */ if (arr[mid] != mid+first) return findFirstMissing(arr, start, mid, first); else return findFirstMissing(arr, mid + 1, end, first); } return start + first;} // Driver codestatic public void Main (){ GFG small = new GFG(); int[] arr = {0, 1, 2, 3, 4, 5, 7}; int n = arr.Length; // Function Call Console.WriteLine(\"First Missing element is : \" + small.findSmallestMissinginSortedArray(arr));}} // This code is contributed by avanitrachhadiya2155", "e": 13825, "s": 12425, "text": null }, { "code": "<script> // Javascript program for the above approach // Program to find missing elementfunction findFirstMissing(arr, start, end, first){ if (start < end) { let mid = (start + end) / 2; /** Index matches with value at that index, means missing element cannot be upto that po*/ if (arr[mid] != mid + first) return findFirstMissing(arr, start, mid, first); else return findFirstMissing(arr, mid + 1, end, first); } return start + first;} // Program to find Smallest// Missing in Sorted Arrayfunction findSmallestMissinginSortedArray(arr){ // Check if 0 is missing // in the array if (arr[0] != 0) return 0; // Check is all numbers 0 to n - 1 // are present in array if (arr[arr.length - 1] == arr.length - 1) return arr.length; let first = arr[0]; return findFirstMissing( arr, 0, arr.length - 1, first);} // Driver codelet arr = [ 0, 1, 2, 3, 4, 5, 7 ];let n = arr.length; // Function Calldocument.write(\"First Missing element is : \" + findSmallestMissinginSortedArray(arr)); // This code is contributed by Mayank Tyagi </script>", "e": 15075, "s": 13825, "text": null }, { "code": null, "e": 15104, "s": 15075, "text": "First Missing element is : 6" }, { "code": null, "e": 15131, "s": 15104, "text": "Time Complexity: O(Log n) " }, { "code": null, "e": 15158, "s": 15131, "text": "Auxiliary Space : O(Log n)" }, { "code": null, "e": 16046, "s": 15158, "text": "Find the smallest missing number | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersFind the smallest missing number | GeeksforGeeksWatch laterShareCopy link81/101InfoShoppingTap 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 / 3:26•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=s60sUkWh7TI\" 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": 16164, "s": 16046, "text": "Please write comments if you find the above codes/algorithms incorrect, or find other ways to solve the same problem." }, { "code": null, "e": 16170, "s": 16164, "text": "jit_t" }, { "code": null, "e": 16185, "s": 16170, "text": "Shivi_Aggarwal" }, { "code": null, "e": 16199, "s": 16185, "text": "amitbhatia.ab" }, { "code": null, "e": 16205, "s": 16199, "text": "ukasp" }, { "code": null, "e": 16226, "s": 16205, "text": "avanitrachhadiya2155" }, { "code": null, "e": 16234, "s": 16226, "text": "rag2127" }, { "code": null, "e": 16249, "s": 16234, "text": "rameshtravel07" }, { "code": null, "e": 16264, "s": 16249, "text": "mohit kumar 29" }, { "code": null, "e": 16280, "s": 16264, "text": "mayanktyagi1709" }, { "code": null, "e": 16296, "s": 16280, "text": "rajeev0719singh" }, { "code": null, "e": 16310, "s": 16296, "text": "_shinchancode" }, { "code": null, "e": 16324, "s": 16310, "text": "Binary Search" }, { "code": null, "e": 16331, "s": 16324, "text": "Arrays" }, { "code": null, "e": 16338, "s": 16331, "text": "Arrays" }, { "code": null, "e": 16352, "s": 16338, "text": "Binary Search" }, { "code": null, "e": 16450, "s": 16352, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 16518, "s": 16450, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 16562, "s": 16518, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 16594, "s": 16562, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 16642, "s": 16594, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 16656, "s": 16642, "text": "Linear Search" }, { "code": null, "e": 16741, "s": 16656, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 16764, "s": 16741, "text": "Introduction to Arrays" }, { "code": null, "e": 16791, "s": 16764, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 16823, "s": 16791, "text": "Introduction to Data Structures" } ]
Node.js Readline() Module
08 Oct, 2021 Readline Module in Node.js allows the reading of input stream line by line. This module wraps up the process standard output and process standard input objects. Readline module makes it easier for input and reading the output given by the user. To use this module, create a new JavaScript file and write the following code at the starting of the application – var readline = require('readline'); The Readline module comes with different methods to interact with the user.Interaction with the user: For the interaction, we will first create an interface for the input and output. For creating an interface, write the following code – javascript var readline = require('readline'); var rl = readline.createInterface( process.stdin, process.stdout); Here, the createInterface() method takes two arguments. The first argument will be for the standard input and the second one will be for reading the standard output. javascript rl.question('What is your age? ', (age) => { console.log('Your age is: ' + age);}); Here, rl.question() method is used for asking questions from the user and reading their reply (output). The first parameter is used to ask the question and the second parameter is a callback function which will take the output from the user as the parameter and return it on the console. The output for the above code will be – What is your age? 20 Your age is: 20 Here, the problem is it will not exit the application and it will keep asking for the inputs. To resolve this issue, rl.close() method is used. This method will close the interface. To use it in the application, write the following – javascript rl.question('What is your age? ', (age) => { console.log('Your age is: ' + age); rl.close();}); We can also use a setPrompt() method is used to set the particular statement to the console. prompt() method for displaying the statement which is set in setPrompt() Method. Therefore, write the following code – javascript var readline = require('readline'); var rl = readline.createInterface( process.stdin, process.stdout); rl.setPrompt(`What is your age? `);rl.prompt() This code will take input from the user. Now, we need a listener for reading the input from the user and displaying it to the console. For this purpose, Readline Module has a listener method called on that will take two parameters. The first parameter will the event and the second parameter will be a callback function that will return the output to the console. For example – javascript var readline = require('readline'); var rl = readline.createInterface( process.stdin, process.stdout); rl.setPrompt(`What is your age? `);rl.prompt();rl.on('line', (age) => { console.log(`Age received by the user: ${age}`); rl.close();}); Here, rl.on() method takes the first argument as line event. This event is invoked whenever the user presse Enter key. The output for the above code will be – What is your age? 20 Age received by the user: 20 Events: Along with the listener, readline module also comes with the events properties. Let us learn about the various events. close: This event is invoked when either rl.close() method is called or when the user presses ctrl + c to close the interface. line: This event is invoked whenever the user presses Enter or return keys. This event is called in the listener function. For example – javascript rl.on('line', (input) => { console.log(`Input Received: ${input}`); rl.close();}); pause: This event is invoked when the input stream is paused. For example – javascript rl.on('pause', () => { console.log('Paused Event is invoked');}); The output for the above code will be – Paused Event is invoked resume: This event is invoked whenever the input is resumed. For example – javascript rl.on('resume', () => { console.log('Resume Event is invoked.');}); SIGINT: This event is invoked whenever the user press ctrl + c button. If there is no event listeners registered when the SIGINT is invoked, then pause event will be invoked. For example – javascript rl.on('SIGINT', () => { rl.question('Exit (y or n)? ', (input) => { if (input.match(/^y(es)?$/i)) { rl.pause(); } });}); This code will ask the given question if ctrl + c key is pressed by the user. Here, if the provided input will match with y or yes, then the pause() method will be called on the interface. SIGTSTP: This event is invoked whenever user gives ctrl + z input. This input is known as SIGTSTP. If a user does not provide the SIGTSTP input, then the current running process will be sent to the background. For example – javascript rl.on('SIGTSTP', () => { console.log('SIGTSTP event is invoked.');}) SIGCONT: This event is invoked when a process that was sent to background using SIGTSTP is again brought back to the front running process. For example – javascript rl.on('SIGCONT', () => { console.log('SIGCONT event is invoked.'); rl.prompt();}) Conclusion: In this article, we learned about the Readline Module in Node.js. Also, we learned about its various implementations using methods, variables, events, and listeners. zack_aayush sagar0719kumar Node.js-Basics Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to install the previous version of node.js and npm ? Difference between promise and async await in Node.js Mongoose | findByIdAndUpdate() Function JWT Authentication with Node.js Installation of Node.js on Windows Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Oct, 2021" }, { "code": null, "e": 390, "s": 28, "text": "Readline Module in Node.js allows the reading of input stream line by line. This module wraps up the process standard output and process standard input objects. Readline module makes it easier for input and reading the output given by the user. To use this module, create a new JavaScript file and write the following code at the starting of the application – " }, { "code": null, "e": 426, "s": 390, "text": "var readline = require('readline');" }, { "code": null, "e": 664, "s": 426, "text": "The Readline module comes with different methods to interact with the user.Interaction with the user: For the interaction, we will first create an interface for the input and output. For creating an interface, write the following code – " }, { "code": null, "e": 675, "s": 664, "text": "javascript" }, { "code": "var readline = require('readline'); var rl = readline.createInterface( process.stdin, process.stdout);", "e": 783, "s": 675, "text": null }, { "code": null, "e": 951, "s": 783, "text": "Here, the createInterface() method takes two arguments. The first argument will be for the standard input and the second one will be for reading the standard output. " }, { "code": null, "e": 962, "s": 951, "text": "javascript" }, { "code": "rl.question('What is your age? ', (age) => { console.log('Your age is: ' + age);});", "e": 1049, "s": 962, "text": null }, { "code": null, "e": 1379, "s": 1049, "text": "Here, rl.question() method is used for asking questions from the user and reading their reply (output). The first parameter is used to ask the question and the second parameter is a callback function which will take the output from the user as the parameter and return it on the console. The output for the above code will be – " }, { "code": null, "e": 1416, "s": 1379, "text": "What is your age? 20\nYour age is: 20" }, { "code": null, "e": 1651, "s": 1416, "text": "Here, the problem is it will not exit the application and it will keep asking for the inputs. To resolve this issue, rl.close() method is used. This method will close the interface. To use it in the application, write the following – " }, { "code": null, "e": 1662, "s": 1651, "text": "javascript" }, { "code": "rl.question('What is your age? ', (age) => { console.log('Your age is: ' + age); rl.close();});", "e": 1764, "s": 1662, "text": null }, { "code": null, "e": 1977, "s": 1764, "text": "We can also use a setPrompt() method is used to set the particular statement to the console. prompt() method for displaying the statement which is set in setPrompt() Method. Therefore, write the following code – " }, { "code": null, "e": 1988, "s": 1977, "text": "javascript" }, { "code": "var readline = require('readline'); var rl = readline.createInterface( process.stdin, process.stdout); rl.setPrompt(`What is your age? `);rl.prompt()", "e": 2147, "s": 1988, "text": null }, { "code": null, "e": 2527, "s": 2147, "text": "This code will take input from the user. Now, we need a listener for reading the input from the user and displaying it to the console. For this purpose, Readline Module has a listener method called on that will take two parameters. The first parameter will the event and the second parameter will be a callback function that will return the output to the console. For example – " }, { "code": null, "e": 2538, "s": 2527, "text": "javascript" }, { "code": "var readline = require('readline'); var rl = readline.createInterface( process.stdin, process.stdout); rl.setPrompt(`What is your age? `);rl.prompt();rl.on('line', (age) => { console.log(`Age received by the user: ${age}`); rl.close();});", "e": 2792, "s": 2538, "text": null }, { "code": null, "e": 2952, "s": 2792, "text": "Here, rl.on() method takes the first argument as line event. This event is invoked whenever the user presse Enter key. The output for the above code will be – " }, { "code": null, "e": 3002, "s": 2952, "text": "What is your age? 20\nAge received by the user: 20" }, { "code": null, "e": 3130, "s": 3002, "text": "Events: Along with the listener, readline module also comes with the events properties. Let us learn about the various events. " }, { "code": null, "e": 3257, "s": 3130, "text": "close: This event is invoked when either rl.close() method is called or when the user presses ctrl + c to close the interface." }, { "code": null, "e": 3395, "s": 3257, "text": "line: This event is invoked whenever the user presses Enter or return keys. This event is called in the listener function. For example – " }, { "code": null, "e": 3406, "s": 3395, "text": "javascript" }, { "code": "rl.on('line', (input) => { console.log(`Input Received: ${input}`); rl.close();});", "e": 3495, "s": 3406, "text": null }, { "code": null, "e": 3572, "s": 3495, "text": "pause: This event is invoked when the input stream is paused. For example – " }, { "code": null, "e": 3583, "s": 3572, "text": "javascript" }, { "code": "rl.on('pause', () => { console.log('Paused Event is invoked');});", "e": 3652, "s": 3583, "text": null }, { "code": null, "e": 3693, "s": 3652, "text": "The output for the above code will be – " }, { "code": null, "e": 3717, "s": 3693, "text": "Paused Event is invoked" }, { "code": null, "e": 3793, "s": 3717, "text": "resume: This event is invoked whenever the input is resumed. For example – " }, { "code": null, "e": 3804, "s": 3793, "text": "javascript" }, { "code": "rl.on('resume', () => { console.log('Resume Event is invoked.');});", "e": 3879, "s": 3804, "text": null }, { "code": null, "e": 4069, "s": 3879, "text": "SIGINT: This event is invoked whenever the user press ctrl + c button. If there is no event listeners registered when the SIGINT is invoked, then pause event will be invoked. For example – " }, { "code": null, "e": 4080, "s": 4069, "text": "javascript" }, { "code": "rl.on('SIGINT', () => { rl.question('Exit (y or n)? ', (input) => { if (input.match(/^y(es)?$/i)) { rl.pause(); } });});", "e": 4212, "s": 4080, "text": null }, { "code": null, "e": 4401, "s": 4212, "text": "This code will ask the given question if ctrl + c key is pressed by the user. Here, if the provided input will match with y or yes, then the pause() method will be called on the interface." }, { "code": null, "e": 4626, "s": 4401, "text": "SIGTSTP: This event is invoked whenever user gives ctrl + z input. This input is known as SIGTSTP. If a user does not provide the SIGTSTP input, then the current running process will be sent to the background. For example – " }, { "code": null, "e": 4637, "s": 4626, "text": "javascript" }, { "code": "rl.on('SIGTSTP', () => { console.log('SIGTSTP event is invoked.');})", "e": 4709, "s": 4637, "text": null }, { "code": null, "e": 4865, "s": 4709, "text": "SIGCONT: This event is invoked when a process that was sent to background using SIGTSTP is again brought back to the front running process. For example – " }, { "code": null, "e": 4876, "s": 4865, "text": "javascript" }, { "code": "rl.on('SIGCONT', () => { console.log('SIGCONT event is invoked.'); rl.prompt();})", "e": 4966, "s": 4876, "text": null }, { "code": null, "e": 5145, "s": 4966, "text": "Conclusion: In this article, we learned about the Readline Module in Node.js. Also, we learned about its various implementations using methods, variables, events, and listeners. " }, { "code": null, "e": 5157, "s": 5145, "text": "zack_aayush" }, { "code": null, "e": 5172, "s": 5157, "text": "sagar0719kumar" }, { "code": null, "e": 5187, "s": 5172, "text": "Node.js-Basics" }, { "code": null, "e": 5195, "s": 5187, "text": "Node.js" }, { "code": null, "e": 5212, "s": 5195, "text": "Web Technologies" }, { "code": null, "e": 5310, "s": 5212, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5367, "s": 5310, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 5421, "s": 5367, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 5461, "s": 5421, "text": "Mongoose | findByIdAndUpdate() Function" }, { "code": null, "e": 5493, "s": 5461, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 5528, "s": 5493, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 5590, "s": 5528, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 5651, "s": 5590, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5701, "s": 5651, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 5744, "s": 5701, "text": "How to fetch data from an API in ReactJS ?" } ]
Maximum profit from sale of wines
27 May, 2021 Given n wines in a row, with integers denoting the cost of each wine respectively. Each year you can sale the first or the last wine in the row. However, the price of wines increases over time. Let the initial profits from the wines be P1, P2, P3...Pn. On the Yth year, the profit from the ith wine will be Y*Pi. For each year, your task is to print “beg” or “end” denoting whether first or last wine should be sold. Also, calculate the maximum profit from all the wines.Examples : Input: Price of wines: 2 4 6 2 5 Output: beg end end beg beg 64 Explanation : Approach : It is a standard Dynamic Programming problem. It initially looks like a greedy problem in which we should sell the cheaper of the wines each year but the example case (year 2) clearly proves the approach is wrong. Sometimes we need to sell an expensive wine earlier to save relatively costly wines for later years (Here, if 4 was sold in the 2nd year, in the 4th year we had to sell 2 which would be waste of a heavy coefficient).The second problem is to “store the strategy” to obtain the calculated price which has a fairly standard method that can be used in other problems as well. The idea is to store the optimal action for each state and use that to navigate through the optimal states starting from the initial state. C++ Java Python3 C# Javascript // Program to calculate maximum price of wines#include <bits/stdc++.h>using namespace std; #define N 1000 int dp[N][N]; // This array stores the "optimal action"// for each state i, jint sell[N][N]; // Function to maximize profitint maxProfitUtil(int price[], int begin, int end, int n) { if (dp[begin][end] != -1) return dp[begin][end]; int year = n - (end - begin); if (begin == end) return year * price[begin]; // x = maximum profit on selling the // wine from the front this year int x = price[begin] * year + maxProfitUtil(price, begin + 1, end, n); // y = maximum profit on selling the // wine from the end this year int y = price[end] * year + maxProfitUtil(price, begin, end - 1, n); int ans = max(x, y); dp[begin][end] = ans; if (x >= y) sell[begin][end] = 0; else sell[begin][end] = 1; return ans;} // Util Function to calculate maxProfitint maxProfit(int price[], int n) { // reseting the dp table for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) dp[i][j] = -1; int ans = maxProfitUtil(price, 0, n - 1, n); int i = 0, j = n - 1; while (i <= j) { // sell[i][j]=0 implies selling the // wine from beginning will be more // profitable in the long run if (sell[i][j] == 0) { cout << "beg "; i++; } else { cout << "end "; j--; } } cout << endl; return ans;} // Driver codeint main() { // Price array int price[] = { 2, 4, 6, 2, 5 }; int n = sizeof(price) / sizeof(price[0]); int ans = maxProfit(price, n); cout << ans << endl; return 0;} // Program to calculate maximum price of winesimport java.io.*; class GFG { static int N = 1000; static int [][]dp = new int[N][N]; // This array stores the "optimal action" // for each state i, j static int [][]sell = new int[N][N]; // Function to maximize profit static int maxProfitUtil(int price[], int begin, int end, int n) { if (dp[begin][end] != -1) return dp[begin][end]; int year = n - (end - begin); if (begin == end) return year * price[begin]; // x = maximum profit on selling the // wine from the front this year int x = price[begin] * year + maxProfitUtil(price, begin + 1, end, n); // y = maximum profit on selling the // wine from the end this year int y = price[end] * year + maxProfitUtil(price, begin, end - 1, n); int ans = Math.max(x, y); dp[begin][end] = ans; if (x >= y) sell[begin][end] = 0; else sell[begin][end] = 1; return ans; } // Util Function to calculate maxProfit static int maxProfit(int price[], int n) { // reseting the dp table for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) dp[i][j] = -1; int ans = maxProfitUtil(price, 0, n - 1, n); int i = 0, j = n - 1; while (i <= j) { // sell[i][j]=0 implies selling // the wine from beginning will // be more profitable in the // long run if(sell[i][j] == 0){ System.out.print( "beg "); i++; } else { System.out.print( "end "); j--; } } System.out.println(); return ans; } // Driver code public static void main (String[] args) { // Price array int price[] = { 2, 4, 6, 2, 5 }; int n = price.length; int ans = maxProfit(price, n); System.out.println( ans ); }} // This code is contributed by anuj_67. # Python3 Program to calculate# maximum price of winesN = 1000dp = [ [-1 for col in range(N)] for row in range(N)] # This array stores the "optimal action"# for each state i, jsell = [ [0 for col in range(N)] for row in range(N)] # Function to maximize profitdef maxProfitUtil(price, begin, end, n): if (dp[begin][end] != -1): return dp[begin][end] year = n - (end - begin) if (begin == end): return year * price[begin] # x = maximum profit on selling the # wine from the front this year x = price[begin] * year + \ maxProfitUtil(price, begin + 1, end, n) # y = maximum profit on selling the # wine from the end this year y = price[end] * year + \ maxProfitUtil(price, begin, end - 1, n) ans = max(x, y) dp[begin][end] = ans if (x >= y): sell[begin][end] = 0 else: sell[begin][end] = 1 return ans # Util Function to calculate maxProfitdef maxProfit(price, n): ans = maxProfitUtil(price, 0, n - 1, n) i = 0 j = n - 1 while (i <= j): # sell[i][j]=0 implies selling the # wine from beginning will be more # profitable in the long run if (sell[i][j] == 0): print("beg", end = " ") i = i + 1 else: print("end", end = " ") j = j - 1 print(" ") return ans # Driver code # Price arrayprice = [ 2, 4, 6, 2, 5 ] size = 5 ans = maxProfit(price, size); print(ans) # This code is contributed by ashutosh450 // C# Program to calculate maximum// price of winesusing System;class GFG { static int N = 1000; static int [,]dp = new int[N, N]; // This array stores the "optimal action" // for each state i, j static int [,]sell = new int[N,N]; // Function to maximize profit static int maxProfitUtil(int []price, int begin, int end, int n) { if (dp[begin,end] != -1) return dp[begin,end]; int year = n - (end - begin); if (begin == end) return year * price[begin]; // x = maximum profit on selling the // wine from the front this year int x = price[begin] * year + maxProfitUtil(price, begin + 1, end, n); // y = maximum profit on selling the // wine from the end this year int y = price[end] * year + maxProfitUtil(price, begin, end - 1, n); int ans = Math.Max(x, y); dp[begin,end] = ans; if (x >= y) sell[begin,end] = 0; else sell[begin,end] = 1; return ans; } // Util Function to calculate maxProfit static int maxProfit(int []price, int n) { int i, j; // reseting the dp table for(i = 0; i < N; i++) for(j = 0; j < N; j++) dp[i, j] = -1; int ans = maxProfitUtil(price, 0, n - 1, n); i = 0; j = n - 1; while (i <= j) { // sell[i][j]=0 implies selling // the wine from beginning will // be more profitable in the // long run if(sell[i, j] == 0){ Console.Write( "beg "); i++; } else { Console.Write( "end "); j--; } } Console.WriteLine(); return ans; } // Driver Code public static void Main () { // Price array int []price = {2, 4, 6, 2, 5}; int n = price.Length; int ans = maxProfit(price, n); Console.WriteLine( ans ); }} // This code is contributed by anuj_67. <script> // Program to calculate maximum price of wines let N = 1000; let dp = new Array(N); // This array stores the "optimal action" // for each state i, j let sell = new Array(N); for(let i = 0; i < N; i++) { dp[i] = new Array(N); sell[i] = new Array(N); for(let j = 0; j < N; j++) { dp[i][j] = 0; sell[i][j] = 0; } } // Function to maximize profit function maxProfitUtil(price, begin, end, n) { if (dp[begin][end] != -1) return dp[begin][end]; let year = n - (end - begin); if (begin == end) return year * price[begin]; // x = maximum profit on selling the // wine from the front this year let x = price[begin] * year + maxProfitUtil(price, begin + 1, end, n); // y = maximum profit on selling the // wine from the end this year let y = price[end] * year + maxProfitUtil(price, begin, end - 1, n); let ans = Math.max(x, y); dp[begin][end] = ans; if (x >= y) sell[begin][end] = 0; else sell[begin][end] = 1; return ans; } // Util Function to calculate maxProfit function maxProfit(price, n) { // reseting the dp table for (let i = 0; i < N; i++) for (let j = 0; j < N; j++) dp[i][j] = -1; let ans = maxProfitUtil(price, 0, n - 1, n); let i = 0, j = n - 1; while (i <= j) { // sell[i][j]=0 implies selling // the wine from beginning will // be more profitable in the // long run if(sell[i][j] == 0){ document.write( "beg "); i++; } else { document.write( "end "); j--; } } document.write("</br>"); return ans; } // Price array let price = [ 2, 4, 6, 2, 5 ]; let n = price.length; let ans = maxProfit(price, n); document.write( ans ); // This code is contributed by divyeshrabadiya07.</script> beg end end beg beg 64 Time Complexity: O(n2) vt_m ASHUTOSH_GUPTA ashutosh450 divyeshrabadiya07 Dynamic Programming Dynamic Programming 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 an undirected graph Count number of binary strings without consecutive 1's Find if a string is interleaved of two other strings | DP-33 Optimal Substructure Property in Dynamic Programming | DP-2 Maximum sum such that no two elements are adjacent How to solve a Dynamic Programming Problem ? Unique paths in a Grid with Obstacles Maximum profit by buying and selling a share at most twice Word Break Problem | DP-32 Optimal Binary Search Tree | DP-24
[ { "code": null, "e": 54, "s": 26, "text": "\n27 May, 2021" }, { "code": null, "e": 538, "s": 54, "text": "Given n wines in a row, with integers denoting the cost of each wine respectively. Each year you can sale the first or the last wine in the row. However, the price of wines increases over time. Let the initial profits from the wines be P1, P2, P3...Pn. On the Yth year, the profit from the ith wine will be Y*Pi. For each year, your task is to print “beg” or “end” denoting whether first or last wine should be sold. Also, calculate the maximum profit from all the wines.Examples : " }, { "code": null, "e": 626, "s": 538, "text": "Input: Price of wines: 2 4 6 2 5\nOutput: beg end end beg beg \n 64\nExplanation :" }, { "code": null, "e": 1367, "s": 628, "text": "Approach : It is a standard Dynamic Programming problem. It initially looks like a greedy problem in which we should sell the cheaper of the wines each year but the example case (year 2) clearly proves the approach is wrong. Sometimes we need to sell an expensive wine earlier to save relatively costly wines for later years (Here, if 4 was sold in the 2nd year, in the 4th year we had to sell 2 which would be waste of a heavy coefficient).The second problem is to “store the strategy” to obtain the calculated price which has a fairly standard method that can be used in other problems as well. The idea is to store the optimal action for each state and use that to navigate through the optimal states starting from the initial state. " }, { "code": null, "e": 1371, "s": 1367, "text": "C++" }, { "code": null, "e": 1376, "s": 1371, "text": "Java" }, { "code": null, "e": 1384, "s": 1376, "text": "Python3" }, { "code": null, "e": 1387, "s": 1384, "text": "C#" }, { "code": null, "e": 1398, "s": 1387, "text": "Javascript" }, { "code": "// Program to calculate maximum price of wines#include <bits/stdc++.h>using namespace std; #define N 1000 int dp[N][N]; // This array stores the \"optimal action\"// for each state i, jint sell[N][N]; // Function to maximize profitint maxProfitUtil(int price[], int begin, int end, int n) { if (dp[begin][end] != -1) return dp[begin][end]; int year = n - (end - begin); if (begin == end) return year * price[begin]; // x = maximum profit on selling the // wine from the front this year int x = price[begin] * year + maxProfitUtil(price, begin + 1, end, n); // y = maximum profit on selling the // wine from the end this year int y = price[end] * year + maxProfitUtil(price, begin, end - 1, n); int ans = max(x, y); dp[begin][end] = ans; if (x >= y) sell[begin][end] = 0; else sell[begin][end] = 1; return ans;} // Util Function to calculate maxProfitint maxProfit(int price[], int n) { // reseting the dp table for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) dp[i][j] = -1; int ans = maxProfitUtil(price, 0, n - 1, n); int i = 0, j = n - 1; while (i <= j) { // sell[i][j]=0 implies selling the // wine from beginning will be more // profitable in the long run if (sell[i][j] == 0) { cout << \"beg \"; i++; } else { cout << \"end \"; j--; } } cout << endl; return ans;} // Driver codeint main() { // Price array int price[] = { 2, 4, 6, 2, 5 }; int n = sizeof(price) / sizeof(price[0]); int ans = maxProfit(price, n); cout << ans << endl; return 0;}", "e": 3124, "s": 1398, "text": null }, { "code": "// Program to calculate maximum price of winesimport java.io.*; class GFG { static int N = 1000; static int [][]dp = new int[N][N]; // This array stores the \"optimal action\" // for each state i, j static int [][]sell = new int[N][N]; // Function to maximize profit static int maxProfitUtil(int price[], int begin, int end, int n) { if (dp[begin][end] != -1) return dp[begin][end]; int year = n - (end - begin); if (begin == end) return year * price[begin]; // x = maximum profit on selling the // wine from the front this year int x = price[begin] * year + maxProfitUtil(price, begin + 1, end, n); // y = maximum profit on selling the // wine from the end this year int y = price[end] * year + maxProfitUtil(price, begin, end - 1, n); int ans = Math.max(x, y); dp[begin][end] = ans; if (x >= y) sell[begin][end] = 0; else sell[begin][end] = 1; return ans; } // Util Function to calculate maxProfit static int maxProfit(int price[], int n) { // reseting the dp table for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) dp[i][j] = -1; int ans = maxProfitUtil(price, 0, n - 1, n); int i = 0, j = n - 1; while (i <= j) { // sell[i][j]=0 implies selling // the wine from beginning will // be more profitable in the // long run if(sell[i][j] == 0){ System.out.print( \"beg \"); i++; } else { System.out.print( \"end \"); j--; } } System.out.println(); return ans; } // Driver code public static void main (String[] args) { // Price array int price[] = { 2, 4, 6, 2, 5 }; int n = price.length; int ans = maxProfit(price, n); System.out.println( ans ); }} // This code is contributed by anuj_67.", "e": 5452, "s": 3124, "text": null }, { "code": "# Python3 Program to calculate# maximum price of winesN = 1000dp = [ [-1 for col in range(N)] for row in range(N)] # This array stores the \"optimal action\"# for each state i, jsell = [ [0 for col in range(N)] for row in range(N)] # Function to maximize profitdef maxProfitUtil(price, begin, end, n): if (dp[begin][end] != -1): return dp[begin][end] year = n - (end - begin) if (begin == end): return year * price[begin] # x = maximum profit on selling the # wine from the front this year x = price[begin] * year + \\ maxProfitUtil(price, begin + 1, end, n) # y = maximum profit on selling the # wine from the end this year y = price[end] * year + \\ maxProfitUtil(price, begin, end - 1, n) ans = max(x, y) dp[begin][end] = ans if (x >= y): sell[begin][end] = 0 else: sell[begin][end] = 1 return ans # Util Function to calculate maxProfitdef maxProfit(price, n): ans = maxProfitUtil(price, 0, n - 1, n) i = 0 j = n - 1 while (i <= j): # sell[i][j]=0 implies selling the # wine from beginning will be more # profitable in the long run if (sell[i][j] == 0): print(\"beg\", end = \" \") i = i + 1 else: print(\"end\", end = \" \") j = j - 1 print(\" \") return ans # Driver code # Price arrayprice = [ 2, 4, 6, 2, 5 ] size = 5 ans = maxProfit(price, size); print(ans) # This code is contributed by ashutosh450", "e": 6981, "s": 5452, "text": null }, { "code": "// C# Program to calculate maximum// price of winesusing System;class GFG { static int N = 1000; static int [,]dp = new int[N, N]; // This array stores the \"optimal action\" // for each state i, j static int [,]sell = new int[N,N]; // Function to maximize profit static int maxProfitUtil(int []price, int begin, int end, int n) { if (dp[begin,end] != -1) return dp[begin,end]; int year = n - (end - begin); if (begin == end) return year * price[begin]; // x = maximum profit on selling the // wine from the front this year int x = price[begin] * year + maxProfitUtil(price, begin + 1, end, n); // y = maximum profit on selling the // wine from the end this year int y = price[end] * year + maxProfitUtil(price, begin, end - 1, n); int ans = Math.Max(x, y); dp[begin,end] = ans; if (x >= y) sell[begin,end] = 0; else sell[begin,end] = 1; return ans; } // Util Function to calculate maxProfit static int maxProfit(int []price, int n) { int i, j; // reseting the dp table for(i = 0; i < N; i++) for(j = 0; j < N; j++) dp[i, j] = -1; int ans = maxProfitUtil(price, 0, n - 1, n); i = 0; j = n - 1; while (i <= j) { // sell[i][j]=0 implies selling // the wine from beginning will // be more profitable in the // long run if(sell[i, j] == 0){ Console.Write( \"beg \"); i++; } else { Console.Write( \"end \"); j--; } } Console.WriteLine(); return ans; } // Driver Code public static void Main () { // Price array int []price = {2, 4, 6, 2, 5}; int n = price.Length; int ans = maxProfit(price, n); Console.WriteLine( ans ); }} // This code is contributed by anuj_67.", "e": 9251, "s": 6981, "text": null }, { "code": "<script> // Program to calculate maximum price of wines let N = 1000; let dp = new Array(N); // This array stores the \"optimal action\" // for each state i, j let sell = new Array(N); for(let i = 0; i < N; i++) { dp[i] = new Array(N); sell[i] = new Array(N); for(let j = 0; j < N; j++) { dp[i][j] = 0; sell[i][j] = 0; } } // Function to maximize profit function maxProfitUtil(price, begin, end, n) { if (dp[begin][end] != -1) return dp[begin][end]; let year = n - (end - begin); if (begin == end) return year * price[begin]; // x = maximum profit on selling the // wine from the front this year let x = price[begin] * year + maxProfitUtil(price, begin + 1, end, n); // y = maximum profit on selling the // wine from the end this year let y = price[end] * year + maxProfitUtil(price, begin, end - 1, n); let ans = Math.max(x, y); dp[begin][end] = ans; if (x >= y) sell[begin][end] = 0; else sell[begin][end] = 1; return ans; } // Util Function to calculate maxProfit function maxProfit(price, n) { // reseting the dp table for (let i = 0; i < N; i++) for (let j = 0; j < N; j++) dp[i][j] = -1; let ans = maxProfitUtil(price, 0, n - 1, n); let i = 0, j = n - 1; while (i <= j) { // sell[i][j]=0 implies selling // the wine from beginning will // be more profitable in the // long run if(sell[i][j] == 0){ document.write( \"beg \"); i++; } else { document.write( \"end \"); j--; } } document.write(\"</br>\"); return ans; } // Price array let price = [ 2, 4, 6, 2, 5 ]; let n = price.length; let ans = maxProfit(price, n); document.write( ans ); // This code is contributed by divyeshrabadiya07.</script>", "e": 11606, "s": 9251, "text": null }, { "code": null, "e": 11630, "s": 11606, "text": "beg end end beg beg \n64" }, { "code": null, "e": 11656, "s": 11632, "text": "Time Complexity: O(n2) " }, { "code": null, "e": 11661, "s": 11656, "text": "vt_m" }, { "code": null, "e": 11676, "s": 11661, "text": "ASHUTOSH_GUPTA" }, { "code": null, "e": 11688, "s": 11676, "text": "ashutosh450" }, { "code": null, "e": 11706, "s": 11688, "text": "divyeshrabadiya07" }, { "code": null, "e": 11726, "s": 11706, "text": "Dynamic Programming" }, { "code": null, "e": 11746, "s": 11726, "text": "Dynamic Programming" }, { "code": null, "e": 11844, "s": 11746, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11912, "s": 11844, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 11967, "s": 11912, "text": "Count number of binary strings without consecutive 1's" }, { "code": null, "e": 12028, "s": 11967, "text": "Find if a string is interleaved of two other strings | DP-33" }, { "code": null, "e": 12088, "s": 12028, "text": "Optimal Substructure Property in Dynamic Programming | DP-2" }, { "code": null, "e": 12139, "s": 12088, "text": "Maximum sum such that no two elements are adjacent" }, { "code": null, "e": 12184, "s": 12139, "text": "How to solve a Dynamic Programming Problem ?" }, { "code": null, "e": 12222, "s": 12184, "text": "Unique paths in a Grid with Obstacles" }, { "code": null, "e": 12281, "s": 12222, "text": "Maximum profit by buying and selling a share at most twice" }, { "code": null, "e": 12308, "s": 12281, "text": "Word Break Problem | DP-32" } ]
MOD() Function in MySQL
01 Oct, 2020 The MOD() function in MySQL is used to find the remainder of one number divided by another. The MOD() function returns the remainder of dividend divided by divisor. if the divisor is zero, it returns NULL. Syntax : MOD(N, M) or N % M or N MOD M Parameter :MOD() function accepts two parameter as mentioned above and described below. N –The dividend i.e. a number or a numeric expression that will be divided by M. M –The divisor i.e. a number or a numeric expression by which to divide the dividend. Returns :It returns the remainder of dividend divided by divisor. Example-1 :Finding the remainder of 36 when it is divided by 6 using MOD Function. SELECT MOD( 36, 6) AS Remainder; Output : Example-2 :Finding the remainder of 27 when it is divided by 4 using the modulus operator(%). SELECT 27 % 4 AS Remainder; Output : Example-3 :Finding the remainder of a floating number using MOD Function. SELECT 10.15 MOD 3 AS Remainder; Output : Example-4 :Finding the remainder of a number using MOD Function when the divisor is 0. SELECT MOD( 6, 0) AS Remainder; Output : Example-5 :MOD Function can also be used to find the Remainder values for the column data. In this example, we are going to find whether a student has appeared a total odd number of exams or even with the help of the MOD function. To demonstrate create a table namedStudent. CREATE TABLE Student ( Student_id INT AUTO_INCREMENT, Student_name VARCHAR(100) NOT NULL, Student_Class VARCHAR(20) NOT NULL, TotalExamGiven INT NOT NULL, PRIMARY KEY(Student_id ) ); Now inserting some data to the Student table : INSERT INTO Student (Student_name, Student_Class, TotalExamGiven ) VALUES ('Sayan', 'IX', 8 ), ('Nitin', 'X', 5 ), ('Aniket', 'XI', 6 ), ('Abdur', 'X', 7 ), ('Riya', 'IX', 4 ), ('Jony', 'X', 10 ), ('Deepak', 'X', 7 ), ('Ankana', 'XII', 5 ), ('Shreya', 'X', 8 ) ; So, the Student Table is as follows. mysql> SELECT * FROM Student; +------------+--------------+---------------+----------------+ | Student_id | Student_name | Student_Class | TotalExamGiven | +------------+--------------+---------------+----------------+ | 1 | Sayan | IX | 8 | | 2 | Nitin | X | 5 | | 3 | Aniket | XI | 6 | | 4 | Abdur | X | 7 | | 5 | Riya | IX | 4 | | 6 | Jony | X | 10 | | 7 | Deepak | X | 7 | | 8 | Ankana | XII | 5 | | 9 | Shreya | X | 8 | +------------+--------------+---------------+----------------+ 9 rows in set (0.00 sec) Now, we are going to find whether a student has appeared total odd number of exam or even. SELECT Student_name, Student_Class, TotalExamGiven, IF(MOD(TotalExamGiven, 2), 'Odd','Even') OddOrEven FROM Student ; Output : +--------------+---------------+----------------+-----------+ | Student_name | Student_Class | TotalExamGiven | OddOrEven | +--------------+---------------+----------------+-----------+ | Sayan | IX | 8 | Even | | Nitin | X | 5 | Odd | | Aniket | XI | 6 | Even | | Abdur | X | 7 | Odd | | Riya | IX | 4 | Even | | Jony | X | 10 | Even | | Deepak | X | 7 | Odd | | Ankana | XII | 5 | Odd | | Shreya | X | 8 | Even | +--------------+---------------+----------------+-----------+ DBMS-SQL mysql SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. CTE in SQL How to Update Multiple Columns in Single Update Statement in SQL? SQL Trigger | Student Database SQL Interview Questions SQL | Views Difference between DELETE, DROP and TRUNCATE MySQL | Group_CONCAT() Function Window functions in SQL Difference between DDL and DML in DBMS Difference between DELETE and TRUNCATE
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Oct, 2020" }, { "code": null, "e": 234, "s": 28, "text": "The MOD() function in MySQL is used to find the remainder of one number divided by another. The MOD() function returns the remainder of dividend divided by divisor. if the divisor is zero, it returns NULL." }, { "code": null, "e": 243, "s": 234, "text": "Syntax :" }, { "code": null, "e": 274, "s": 243, "text": "MOD(N, M)\nor\nN % M\nor\nN MOD M\n" }, { "code": null, "e": 362, "s": 274, "text": "Parameter :MOD() function accepts two parameter as mentioned above and described below." }, { "code": null, "e": 445, "s": 362, "text": "N –The dividend i.e. a number or a numeric expression that will be divided by M." }, { "code": null, "e": 531, "s": 445, "text": "M –The divisor i.e. a number or a numeric expression by which to divide the dividend." }, { "code": null, "e": 597, "s": 531, "text": "Returns :It returns the remainder of dividend divided by divisor." }, { "code": null, "e": 680, "s": 597, "text": "Example-1 :Finding the remainder of 36 when it is divided by 6 using MOD Function." }, { "code": null, "e": 714, "s": 680, "text": "SELECT MOD( 36, 6) AS Remainder;\n" }, { "code": null, "e": 723, "s": 714, "text": "Output :" }, { "code": null, "e": 817, "s": 723, "text": "Example-2 :Finding the remainder of 27 when it is divided by 4 using the modulus operator(%)." }, { "code": null, "e": 846, "s": 817, "text": "SELECT 27 % 4 AS Remainder;\n" }, { "code": null, "e": 855, "s": 846, "text": "Output :" }, { "code": null, "e": 929, "s": 855, "text": "Example-3 :Finding the remainder of a floating number using MOD Function." }, { "code": null, "e": 964, "s": 929, "text": "SELECT 10.15 MOD 3 AS Remainder;\n" }, { "code": null, "e": 973, "s": 964, "text": "Output :" }, { "code": null, "e": 1062, "s": 973, "text": "Example-4 :Finding the remainder of a number using MOD Function when the divisor is 0." }, { "code": null, "e": 1095, "s": 1062, "text": "SELECT MOD( 6, 0) AS Remainder;\n" }, { "code": null, "e": 1104, "s": 1095, "text": "Output :" }, { "code": null, "e": 1379, "s": 1104, "text": "Example-5 :MOD Function can also be used to find the Remainder values for the column data. In this example, we are going to find whether a student has appeared a total odd number of exams or even with the help of the MOD function. To demonstrate create a table namedStudent." }, { "code": null, "e": 1588, "s": 1379, "text": "CREATE TABLE Student\n(\n Student_id INT AUTO_INCREMENT, \n Student_name VARCHAR(100) NOT NULL,\n Student_Class VARCHAR(20) NOT NULL,\n TotalExamGiven INT NOT NULL,\n PRIMARY KEY(Student_id )\n\n);\n" }, { "code": null, "e": 1635, "s": 1588, "text": "Now inserting some data to the Student table :" }, { "code": null, "e": 1939, "s": 1635, "text": "INSERT INTO Student\n(Student_name, Student_Class, TotalExamGiven )\nVALUES\n ('Sayan', 'IX', 8 ),\n ('Nitin', 'X', 5 ),\n ('Aniket', 'XI', 6 ),\n ('Abdur', 'X', 7 ),\n ('Riya', 'IX', 4 ),\n ('Jony', 'X', 10 ),\n ('Deepak', 'X', 7 ),\n ('Ankana', 'XII', 5 ),\n ('Shreya', 'X', 8 ) ;\n" }, { "code": null, "e": 1976, "s": 1939, "text": "So, the Student Table is as follows." }, { "code": null, "e": 2851, "s": 1976, "text": "mysql> SELECT * FROM Student;\n+------------+--------------+---------------+----------------+\n| Student_id | Student_name | Student_Class | TotalExamGiven |\n+------------+--------------+---------------+----------------+\n| 1 | Sayan | IX | 8 |\n| 2 | Nitin | X | 5 |\n| 3 | Aniket | XI | 6 |\n| 4 | Abdur | X | 7 |\n| 5 | Riya | IX | 4 |\n| 6 | Jony | X | 10 |\n| 7 | Deepak | X | 7 |\n| 8 | Ankana | XII | 5 |\n| 9 | Shreya | X | 8 |\n+------------+--------------+---------------+----------------+\n9 rows in set (0.00 sec)\n" }, { "code": null, "e": 2942, "s": 2851, "text": "Now, we are going to find whether a student has appeared total odd number of exam or even." }, { "code": null, "e": 3091, "s": 2942, "text": "SELECT \n Student_name,\n Student_Class,\n TotalExamGiven,\n IF(MOD(TotalExamGiven, 2),\n 'Odd','Even') \n OddOrEven FROM Student ; \n" }, { "code": null, "e": 3100, "s": 3091, "text": "Output :" }, { "code": null, "e": 3907, "s": 3100, "text": "+--------------+---------------+----------------+-----------+\n| Student_name | Student_Class | TotalExamGiven | OddOrEven |\n+--------------+---------------+----------------+-----------+\n| Sayan | IX | 8 | Even |\n| Nitin | X | 5 | Odd |\n| Aniket | XI | 6 | Even |\n| Abdur | X | 7 | Odd |\n| Riya | IX | 4 | Even |\n| Jony | X | 10 | Even |\n| Deepak | X | 7 | Odd |\n| Ankana | XII | 5 | Odd |\n| Shreya | X | 8 | Even |\n+--------------+---------------+----------------+-----------+\n" }, { "code": null, "e": 3916, "s": 3907, "text": "DBMS-SQL" }, { "code": null, "e": 3922, "s": 3916, "text": "mysql" }, { "code": null, "e": 3926, "s": 3922, "text": "SQL" }, { "code": null, "e": 3930, "s": 3926, "text": "SQL" }, { "code": null, "e": 4028, "s": 3930, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4039, "s": 4028, "text": "CTE in SQL" }, { "code": null, "e": 4105, "s": 4039, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 4136, "s": 4105, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 4160, "s": 4136, "text": "SQL Interview Questions" }, { "code": null, "e": 4172, "s": 4160, "text": "SQL | Views" }, { "code": null, "e": 4217, "s": 4172, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 4249, "s": 4217, "text": "MySQL | Group_CONCAT() Function" }, { "code": null, "e": 4273, "s": 4249, "text": "Window functions in SQL" }, { "code": null, "e": 4312, "s": 4273, "text": "Difference between DDL and DML in DBMS" } ]
Python | Fast Walsh Hadamard Transform
31 Jan, 2022 Fast Walsh Hadamard Transform, is an Hadamard ordered efficient algorithm to compute the Walsh Hadamard transform (WHT). Normal WHT computation has N = 2m complexity but using FWHT reduces the computation to O(n2). The FWHT requires O(n logn) additions and subtraction operations. It is a divide and conquer algorithm which breaks down the WHT recursively. sympy.discrete.transforms.fwht( ) : It can perform Walsh Hadamard Transform (WHT). This method uses Hadamard sequence ordering. Automatically the sequence is padded with zero to the right because the radix-2 FWHT requires the sample point number as a power of 2. Parameters : -> seq : [iterable] sequence on which WHT is to be applied. Returns : Fast Walsh Hadamard Transform Transform Example #1 : Python3 # import sympyfrom sympy import fwht # sequenceseq = [23, 56, 12, 555] # hwhttransform = fwht(seq)print ("Transform : ", transform) Output : Transform : [646, -576, -488, 510] Example #2 : Python3 # import sympyfrom sympy import fwht # sequenceseq = [15, 21, 13, 44] # hwhttransform = fwht(seq)print ("Transform : ", transform) Output : Transform : [93, -37, -21, 25] varshagumber28 Maths 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 Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Convert integer to string in Python Introduction To PYTHON
[ { "code": null, "e": 53, "s": 25, "text": "\n31 Jan, 2022" }, { "code": null, "e": 412, "s": 53, "text": "Fast Walsh Hadamard Transform, is an Hadamard ordered efficient algorithm to compute the Walsh Hadamard transform (WHT). Normal WHT computation has N = 2m complexity but using FWHT reduces the computation to O(n2). The FWHT requires O(n logn) additions and subtraction operations. It is a divide and conquer algorithm which breaks down the WHT recursively. " }, { "code": null, "e": 677, "s": 412, "text": "sympy.discrete.transforms.fwht( ) : It can perform Walsh Hadamard Transform (WHT). This method uses Hadamard sequence ordering. Automatically the sequence is padded with zero to the right because the radix-2 FWHT requires the sample point number as a power of 2. " }, { "code": null, "e": 803, "s": 677, "text": "Parameters : \n-> seq : [iterable] sequence on which WHT is to be applied.\n\nReturns : \nFast Walsh Hadamard Transform Transform" }, { "code": null, "e": 818, "s": 803, "text": "Example #1 : " }, { "code": null, "e": 826, "s": 818, "text": "Python3" }, { "code": "# import sympyfrom sympy import fwht # sequenceseq = [23, 56, 12, 555] # hwhttransform = fwht(seq)print (\"Transform : \", transform)", "e": 977, "s": 826, "text": null }, { "code": null, "e": 988, "s": 977, "text": "Output : " }, { "code": null, "e": 1025, "s": 988, "text": "Transform : [646, -576, -488, 510]" }, { "code": null, "e": 1040, "s": 1025, "text": "Example #2 : " }, { "code": null, "e": 1048, "s": 1040, "text": "Python3" }, { "code": "# import sympyfrom sympy import fwht # sequenceseq = [15, 21, 13, 44] # hwhttransform = fwht(seq)print (\"Transform : \", transform)", "e": 1180, "s": 1048, "text": null }, { "code": null, "e": 1191, "s": 1180, "text": "Output : " }, { "code": null, "e": 1224, "s": 1191, "text": "Transform : [93, -37, -21, 25]" }, { "code": null, "e": 1241, "s": 1226, "text": "varshagumber28" }, { "code": null, "e": 1247, "s": 1241, "text": "Maths" }, { "code": null, "e": 1254, "s": 1247, "text": "Python" }, { "code": null, "e": 1352, "s": 1254, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1370, "s": 1352, "text": "Python Dictionary" }, { "code": null, "e": 1412, "s": 1370, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1434, "s": 1412, "text": "Enumerate() in Python" }, { "code": null, "e": 1460, "s": 1434, "text": "Python String | replace()" }, { "code": null, "e": 1492, "s": 1460, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1521, "s": 1492, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1548, "s": 1521, "text": "Python Classes and Objects" }, { "code": null, "e": 1569, "s": 1548, "text": "Python OOPs Concepts" }, { "code": null, "e": 1605, "s": 1569, "text": "Convert integer to string in Python" } ]
How to choose background color through color picker?
05 Mar, 2021 In this project, we are going to change the background color with the help of the Color Picker. Glimpse of the Project: Approach: Create an HTML file in which we are going to add the text and a color picker which helps to change the background color of our web-page. Create a CSS style to give some animation effects to the web-page elements. Create a JavaScript file for adding event-listeners that can detect the movement of the mouse. Example: HTML: Firstly, create an HTML file (index.html). Then we link the CSS (style.css) file that provides all the animations effect to our HTML page. This is also placed in between the <head> tag. We add a link from Google Fonts to use a different type of font family in our project. Then we have to add an input tag so that we can use a color picker! At the end of the body tag, we have to add 2 <script> tags. One for our index.js file and the other for the icon that we have used on our webpage. index.html <!DOCTYPE html><html lang="en"><head> <link rel="stylesheet" href="style.css"> <script src="index.js"></script> <script src="https://kit.fontawesome.com/704ff50790.js" crossorigin="anonymous"> </script></head><body> <h1 class="head"> Choose the color from the selector to change the bg-color <i class="fas fa-arrow-right"> </i> </h1> <input type="color" id="clr"></body></html> CSS: The following is the code for the “style.css” file used above in the HTML code. CSS is used to give different types of animations and effects to our HTML page so that it looks interactive to all users. Restore all the browser effects. Use classes and ids to give effects to HTML elements. Use of :hover to use hover effects. Use of @keyframes to use animations on our webpage. style.css /* restoring all the default properties of the browser */*{ margin: 0; padding: 0; box-sizing: border-box;} /* all similar effects of the web page so we applied them to the body */body{ height: 100vh; display: flex; justify-content: center; align-items: center;} /* css effects for the color picker */input{ margin: 2em; width: 3em; height: 3em; border: .4em solid black; border-radius: 20%; outline: none; cursor: pointer; box-shadow: 0 0 .5em #111;} /* for the icon that we have added */.fas{ margin: 1em;} /* hover effects on color picker */input:hover{ animation: round 2s infinite;} /* animation for our color picker */@keyframes round{ 0%{ transform: rotate(0deg); } 10%{ transform: rotate(60deg); } 20%{ transform: rotate(120deg); } 40%{ transform: rotate(180deg); } 60%{ transform: rotate(240deg); } 80%{ transform: rotate(300deg); } 100%{ transform: rotate(360deg); }} JavaScript: In this, we write code for the detection of mouse movement for changing the background color. Returns the first element that matches with specified CSS selector:document.querySelector(‘css_selector’) => Returns all the elements that matches with specified HTML ID:document.getElementbyId(‘html_id’) => index.js // Selection of id's and classes from html documentconst bgclr = document.getElementById("clr");const headingg = document.querySelector(".head"); // Here we are adding event listener which // is used to detect the mouse movementbgclr.addEventListener("input", () => { // This updates the background color which is // picked by the user from the picker document.body.style.backgroundColor = bgclr.value; // This is the conditional statement that is used // to change the text color from BLACK to WHITE // when the background color changes to dark! if ( bgclr.value.includes("00") || bgclr.value.includes("0a") || bgclr.value.includes("0b") || bgclr.value.includes("0c") || bgclr.value.includes("0d") || bgclr.value.includes("0e") || bgclr.value.includes("0f") ) { headingg.style.color = "#fff"; } else { headingg.style.color = "#000"; }}); Output: CSS-Properties CSS-Selectors Technical Scripter 2020 CSS HTML JavaScript Technical Scripter HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n05 Mar, 2021" }, { "code": null, "e": 150, "s": 54, "text": "In this project, we are going to change the background color with the help of the Color Picker." }, { "code": null, "e": 174, "s": 150, "text": "Glimpse of the Project:" }, { "code": null, "e": 184, "s": 174, "text": "Approach:" }, { "code": null, "e": 321, "s": 184, "text": "Create an HTML file in which we are going to add the text and a color picker which helps to change the background color of our web-page." }, { "code": null, "e": 397, "s": 321, "text": "Create a CSS style to give some animation effects to the web-page elements." }, { "code": null, "e": 492, "s": 397, "text": "Create a JavaScript file for adding event-listeners that can detect the movement of the mouse." }, { "code": null, "e": 501, "s": 492, "text": "Example:" }, { "code": null, "e": 507, "s": 501, "text": "HTML:" }, { "code": null, "e": 550, "s": 507, "text": "Firstly, create an HTML file (index.html)." }, { "code": null, "e": 693, "s": 550, "text": "Then we link the CSS (style.css) file that provides all the animations effect to our HTML page. This is also placed in between the <head> tag." }, { "code": null, "e": 780, "s": 693, "text": "We add a link from Google Fonts to use a different type of font family in our project." }, { "code": null, "e": 848, "s": 780, "text": "Then we have to add an input tag so that we can use a color picker!" }, { "code": null, "e": 995, "s": 848, "text": "At the end of the body tag, we have to add 2 <script> tags. One for our index.js file and the other for the icon that we have used on our webpage." }, { "code": null, "e": 1006, "s": 995, "text": "index.html" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <link rel=\"stylesheet\" href=\"style.css\"> <script src=\"index.js\"></script> <script src=\"https://kit.fontawesome.com/704ff50790.js\" crossorigin=\"anonymous\"> </script></head><body> <h1 class=\"head\"> Choose the color from the selector to change the bg-color <i class=\"fas fa-arrow-right\"> </i> </h1> <input type=\"color\" id=\"clr\"></body></html>", "e": 1441, "s": 1006, "text": null }, { "code": null, "e": 1648, "s": 1441, "text": "CSS: The following is the code for the “style.css” file used above in the HTML code. CSS is used to give different types of animations and effects to our HTML page so that it looks interactive to all users." }, { "code": null, "e": 1681, "s": 1648, "text": "Restore all the browser effects." }, { "code": null, "e": 1735, "s": 1681, "text": "Use classes and ids to give effects to HTML elements." }, { "code": null, "e": 1771, "s": 1735, "text": "Use of :hover to use hover effects." }, { "code": null, "e": 1823, "s": 1771, "text": "Use of @keyframes to use animations on our webpage." }, { "code": null, "e": 1833, "s": 1823, "text": "style.css" }, { "code": "/* restoring all the default properties of the browser */*{ margin: 0; padding: 0; box-sizing: border-box;} /* all similar effects of the web page so we applied them to the body */body{ height: 100vh; display: flex; justify-content: center; align-items: center;} /* css effects for the color picker */input{ margin: 2em; width: 3em; height: 3em; border: .4em solid black; border-radius: 20%; outline: none; cursor: pointer; box-shadow: 0 0 .5em #111;} /* for the icon that we have added */.fas{ margin: 1em;} /* hover effects on color picker */input:hover{ animation: round 2s infinite;} /* animation for our color picker */@keyframes round{ 0%{ transform: rotate(0deg); } 10%{ transform: rotate(60deg); } 20%{ transform: rotate(120deg); } 40%{ transform: rotate(180deg); } 60%{ transform: rotate(240deg); } 80%{ transform: rotate(300deg); } 100%{ transform: rotate(360deg); }}", "e": 2864, "s": 1833, "text": null }, { "code": null, "e": 2970, "s": 2864, "text": "JavaScript: In this, we write code for the detection of mouse movement for changing the background color." }, { "code": null, "e": 3079, "s": 2970, "text": "Returns the first element that matches with specified CSS selector:document.querySelector(‘css_selector’) =>" }, { "code": null, "e": 3178, "s": 3079, "text": "Returns all the elements that matches with specified HTML ID:document.getElementbyId(‘html_id’) =>" }, { "code": null, "e": 3187, "s": 3178, "text": "index.js" }, { "code": "// Selection of id's and classes from html documentconst bgclr = document.getElementById(\"clr\");const headingg = document.querySelector(\".head\"); // Here we are adding event listener which // is used to detect the mouse movementbgclr.addEventListener(\"input\", () => { // This updates the background color which is // picked by the user from the picker document.body.style.backgroundColor = bgclr.value; // This is the conditional statement that is used // to change the text color from BLACK to WHITE // when the background color changes to dark! if ( bgclr.value.includes(\"00\") || bgclr.value.includes(\"0a\") || bgclr.value.includes(\"0b\") || bgclr.value.includes(\"0c\") || bgclr.value.includes(\"0d\") || bgclr.value.includes(\"0e\") || bgclr.value.includes(\"0f\") ) { headingg.style.color = \"#fff\"; } else { headingg.style.color = \"#000\"; }});", "e": 4067, "s": 3187, "text": null }, { "code": null, "e": 4075, "s": 4067, "text": "Output:" }, { "code": null, "e": 4090, "s": 4075, "text": "CSS-Properties" }, { "code": null, "e": 4104, "s": 4090, "text": "CSS-Selectors" }, { "code": null, "e": 4128, "s": 4104, "text": "Technical Scripter 2020" }, { "code": null, "e": 4132, "s": 4128, "text": "CSS" }, { "code": null, "e": 4137, "s": 4132, "text": "HTML" }, { "code": null, "e": 4148, "s": 4137, "text": "JavaScript" }, { "code": null, "e": 4167, "s": 4148, "text": "Technical Scripter" }, { "code": null, "e": 4172, "s": 4167, "text": "HTML" } ]
HTML | Flip a card
22 Aug, 2019 Flip cards are the cards in your website that will flip when you hover your mouse over them. There will be information, links or images in the back face of the card which will be visible when you hover over the cards. In this article, you’re going to learn how to make Flip cards on your website using only HTML and CSS. HTML file for card: <div class="card"> <h2>HTML | Flip a Card</h2> <div class="card-inner"> <div class="card-front"> <!-- adding picture in the card --> <img src="" style="width:250px;height:250px;"> </div> <!-- Decorate card back side --> <div class="card-back"> <h1>GeeksforGeeks</h1> <p>A Computer Science Portal for Geeks</p> <a href=""> Try our ide </a> </div> </div></div> Decorating the front and back of the card using CSS: Built the structure of both faces of the card in the HTML part. Now we need to hide the back face initially. So we do that by backface-visibility: hidden property of CSS and this to the card-front and card-back classes so that when the front face is visible the back face is hidden and vice-versa. The key is to use the transform property of CSS and rotate the element by 180 degree i.e. transform: rotateY(180deg). <style> .card { width: 250px; height: 250px; perspective: 1000px;}.card-inner { position: relative; text-align: center; transition: transform 0.6s; transform-style: preserve-3d;}.card:hover .card-inner { transform: rotateY(180deg);}.card-front, .card-back { position: absolute; backface-visibility: hidden;}.card-back { transform: rotateY(180deg);}</style> Note: You can rotate your cards as much as possible depending on the transform: rotateY(180deg). If you decrease the deg and increase the deg rotation is depending on that also you can flip the card vertically. Example: This example uses transform: rotateY(180deg) property to flip/rotate the image. If you change the axis Y to X then cards will change the flip direction. <!DOCTYPE html><html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- CSS code --> <style> h1 { color: green; } a { color: purple; text-decoration: none; } .card { background-color: transparent; width: 250px; height: 250px; perspective: 1000px; } .card-inner { position: relative; width: 100%; height: 100%; text-align: center; transition: transform 0.6s; transform-style: preserve-3d; box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2); } .card:hover .card-inner { transform: rotateY(180deg); } .card-front, .card-back { position: absolute; width: 100%; height: 100%; backface-visibility: hidden; } .card-front { background-color: #bbb; color: black; } .card-back { background-color: white; transform: rotateY(180deg); } </style></head> <body> <center> <div class="card"> <h2>HTML | Flip Card</h2> <div class="card-inner"> <div class="card-front"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20190722122630/GFG48.png" style="width:250px;height:250px;"> </div> <div class="card-back"> <h1>GeeksforGeeks</h1> <p>A Computer Science Portal for Geeks</p> <a href="https://ide.geeksforgeeks.org/tryit.php"> Try our ide </a> </div> </div> </div> </center></body> </html> Output: Web technologies CSS HTML HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Aug, 2019" }, { "code": null, "e": 246, "s": 28, "text": "Flip cards are the cards in your website that will flip when you hover your mouse over them. There will be information, links or images in the back face of the card which will be visible when you hover over the cards." }, { "code": null, "e": 349, "s": 246, "text": "In this article, you’re going to learn how to make Flip cards on your website using only HTML and CSS." }, { "code": null, "e": 369, "s": 349, "text": "HTML file for card:" }, { "code": "<div class=\"card\"> <h2>HTML | Flip a Card</h2> <div class=\"card-inner\"> <div class=\"card-front\"> <!-- adding picture in the card --> <img src=\"\" style=\"width:250px;height:250px;\"> </div> <!-- Decorate card back side --> <div class=\"card-back\"> <h1>GeeksforGeeks</h1> <p>A Computer Science Portal for Geeks</p> <a href=\"\"> Try our ide </a> </div> </div></div>", "e": 896, "s": 369, "text": null }, { "code": null, "e": 1365, "s": 896, "text": "Decorating the front and back of the card using CSS: Built the structure of both faces of the card in the HTML part. Now we need to hide the back face initially. So we do that by backface-visibility: hidden property of CSS and this to the card-front and card-back classes so that when the front face is visible the back face is hidden and vice-versa. The key is to use the transform property of CSS and rotate the element by 180 degree i.e. transform: rotateY(180deg)." }, { "code": "<style> .card { width: 250px; height: 250px; perspective: 1000px;}.card-inner { position: relative; text-align: center; transition: transform 0.6s; transform-style: preserve-3d;}.card:hover .card-inner { transform: rotateY(180deg);}.card-front, .card-back { position: absolute; backface-visibility: hidden;}.card-back { transform: rotateY(180deg);}</style>", "e": 1755, "s": 1365, "text": null }, { "code": null, "e": 1966, "s": 1755, "text": "Note: You can rotate your cards as much as possible depending on the transform: rotateY(180deg). If you decrease the deg and increase the deg rotation is depending on that also you can flip the card vertically." }, { "code": null, "e": 2128, "s": 1966, "text": "Example: This example uses transform: rotateY(180deg) property to flip/rotate the image. If you change the axis Y to X then cards will change the flip direction." }, { "code": "<!DOCTYPE html><html> <head> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <!-- CSS code --> <style> h1 { color: green; } a { color: purple; text-decoration: none; } .card { background-color: transparent; width: 250px; height: 250px; perspective: 1000px; } .card-inner { position: relative; width: 100%; height: 100%; text-align: center; transition: transform 0.6s; transform-style: preserve-3d; box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2); } .card:hover .card-inner { transform: rotateY(180deg); } .card-front, .card-back { position: absolute; width: 100%; height: 100%; backface-visibility: hidden; } .card-front { background-color: #bbb; color: black; } .card-back { background-color: white; transform: rotateY(180deg); } </style></head> <body> <center> <div class=\"card\"> <h2>HTML | Flip Card</h2> <div class=\"card-inner\"> <div class=\"card-front\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190722122630/GFG48.png\" style=\"width:250px;height:250px;\"> </div> <div class=\"card-back\"> <h1>GeeksforGeeks</h1> <p>A Computer Science Portal for Geeks</p> <a href=\"https://ide.geeksforgeeks.org/tryit.php\"> Try our ide </a> </div> </div> </div> </center></body> </html>", "e": 4027, "s": 2128, "text": null }, { "code": null, "e": 4035, "s": 4027, "text": "Output:" }, { "code": null, "e": 4052, "s": 4035, "text": "Web technologies" }, { "code": null, "e": 4056, "s": 4052, "text": "CSS" }, { "code": null, "e": 4061, "s": 4056, "text": "HTML" }, { "code": null, "e": 4066, "s": 4061, "text": "HTML" } ]
How to add text to Matplotlib?
16 Feb, 2022 Matplotlib is a plotting library in Python to visualize data, inspired by MATLAB, meaning that the terms used (Axis, Figure, Plots) will be similar to those used in MATLAB. Pyplot is a module within the Matplotlib library which is a shell-like interface to Matplotlib module. It provides almost any kind of plot that we can think of. In this post, we will focus on a more specific topic which is adding text on matplotlib plot. The following commands are used to create text in the matplotlib plot. We will see each of the commands one by one, first, let’s create a basic plot of Day v/s Question on which we will add various text objects. Code: Python3 # Code to add text on matplotlib # Importing libraryimport matplotlib.pyplot as plt # Creating x-value and y-value of datax = [1, 2, 3, 4, 5]y = [5, 8, 4, 7, 5] # Creating figurefig = plt.figure() # Adding axes on the figureax = fig.add_subplot(111) # Plotting data on the axesax.plot(x, y) plt.show() Output: The output plot looks very simple. Now, let’s see some text commands to add it on our plot. set_title() is used to add the title of axes. The first and mandatory argument is the title you want to give and the rest are optional to format it. Similarly, set_xlabel() and set_ylabel() are used to add titles to x-axis and y-axis. It also takes title as an argument. It is better to adjust the range on y-axis so that we can have some space to add text later on. For this, we will use ax.axis() which allows specifying value ranges (the first two for x-axis and the other two for y-axis). Now, let’s add its title and names of x-axis and y-axis. Code: Python3 # Adding titleax.set_title('Day v/s No of Questions on GFG', fontsize=15) # Adding axis titleax.set_xlabel('Day', fontsize=12)ax.set_ylabel('No of Questions', fontsize=12) # Setting axis limitsax.axis([0, 10, 0, 15]) Output: Now, it looks better than the previous version. It’s the time to add text to our plot. First, let’s see about them. axes.text() is used to add text at an arbitrary location of the Axes. For this we need to specify the location of the text and of course what the text is. For instance, the following code will add “Practice on GFG” text. It will located according to the point whose coordinates are specified ([1,13] in this case). The parameter bbox is used to capture the text with a box. As argument to bbox parameter, we pass a dictionary which includes formatting styles. Code: Python3 # Adding text on the plot.ax.text(1, 13, 'Practice on GFG', style='italic', bbox={ 'facecolor': 'grey', 'alpha': 0.5, 'pad': 10}) If we want to do not have to box the text then simply do not assign anything to the bbox parameter. The following code adds the specified text without a box. Code: Python3 # Adding text without box on the plot.ax.text(8, 13, 'December', style='italic') We can also add text with annotations. axes.annotate() is used to add an annotation, with an optional arrow, at an arbitrary location of the Axes. Its xy parameter contains the coordinates for arrow and xytext parameter specifies the location of the text. Arrowprops parameter is used to style the arrow. For instance, we can mark the peak value of the Day-Question data with an annotation. Code: Python3 # Adding annotation on the plot.ax.annotate('Peak', xy=(2, 8), xytext=(4, 10), fontsize=12, arrowprops=dict(facecolor='green', shrink=0.05)) Let’s put all this together and see the final code. Code: Python3 # Code to add text on matplotlib # Importing libraryimport matplotlib.pyplot as plt # Creating x-value and y-value of datax = [1, 2, 3, 4, 5]y = [5, 8, 4, 7, 5] # Creating figurefig = plt.figure() # Adding axes on the figureax = fig.add_subplot(111) # Plotting data on the axesax.plot(x, y) # Adding titleax.set_title('Day v/s No of Questions on GFG', fontsize=15) # Adding axis titleax.set_xlabel('Day', fontsize=12)ax.set_ylabel('No of Questions', fontsize=12) # Setting axis limitsax.axis([0, 10, 0, 15]) # Adding text on the plot.ax.text(1, 13, 'Practice on GFG', style='italic', bbox={ 'facecolor': 'green', 'alpha': 0.5, 'pad': 10}) # Adding text without box on the plot.ax.text(8, 13, 'December', style='italic') # Adding annotation on the plot.ax.annotate('Peak', xy=(2, 8), xytext=(4, 10), fontsize=12, arrowprops=dict(facecolor='green', shrink=0.05)) plt.show() Output: simranarora5sos Picked Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Feb, 2022" }, { "code": null, "e": 304, "s": 28, "text": "Matplotlib is a plotting library in Python to visualize data, inspired by MATLAB, meaning that the terms used (Axis, Figure, Plots) will be similar to those used in MATLAB. Pyplot is a module within the Matplotlib library which is a shell-like interface to Matplotlib module." }, { "code": null, "e": 528, "s": 304, "text": " It provides almost any kind of plot that we can think of. In this post, we will focus on a more specific topic which is adding text on matplotlib plot. The following commands are used to create text in the matplotlib plot." }, { "code": null, "e": 670, "s": 528, "text": "We will see each of the commands one by one, first, let’s create a basic plot of Day v/s Question on which we will add various text objects. " }, { "code": null, "e": 676, "s": 670, "text": "Code:" }, { "code": null, "e": 684, "s": 676, "text": "Python3" }, { "code": "# Code to add text on matplotlib # Importing libraryimport matplotlib.pyplot as plt # Creating x-value and y-value of datax = [1, 2, 3, 4, 5]y = [5, 8, 4, 7, 5] # Creating figurefig = plt.figure() # Adding axes on the figureax = fig.add_subplot(111) # Plotting data on the axesax.plot(x, y) plt.show()", "e": 986, "s": 684, "text": null }, { "code": null, "e": 994, "s": 986, "text": "Output:" }, { "code": null, "e": 1086, "s": 994, "text": "The output plot looks very simple. Now, let’s see some text commands to add it on our plot." }, { "code": null, "e": 1235, "s": 1086, "text": "set_title() is used to add the title of axes. The first and mandatory argument is the title you want to give and the rest are optional to format it." }, { "code": null, "e": 1357, "s": 1235, "text": "Similarly, set_xlabel() and set_ylabel() are used to add titles to x-axis and y-axis. It also takes title as an argument." }, { "code": null, "e": 1579, "s": 1357, "text": "It is better to adjust the range on y-axis so that we can have some space to add text later on. For this, we will use ax.axis() which allows specifying value ranges (the first two for x-axis and the other two for y-axis)." }, { "code": null, "e": 1636, "s": 1579, "text": "Now, let’s add its title and names of x-axis and y-axis." }, { "code": null, "e": 1642, "s": 1636, "text": "Code:" }, { "code": null, "e": 1650, "s": 1642, "text": "Python3" }, { "code": "# Adding titleax.set_title('Day v/s No of Questions on GFG', fontsize=15) # Adding axis titleax.set_xlabel('Day', fontsize=12)ax.set_ylabel('No of Questions', fontsize=12) # Setting axis limitsax.axis([0, 10, 0, 15])", "e": 1867, "s": 1650, "text": null }, { "code": null, "e": 1875, "s": 1867, "text": "Output:" }, { "code": null, "e": 1991, "s": 1875, "text": "Now, it looks better than the previous version. It’s the time to add text to our plot. First, let’s see about them." }, { "code": null, "e": 2451, "s": 1991, "text": "axes.text() is used to add text at an arbitrary location of the Axes. For this we need to specify the location of the text and of course what the text is. For instance, the following code will add “Practice on GFG” text. It will located according to the point whose coordinates are specified ([1,13] in this case). The parameter bbox is used to capture the text with a box. As argument to bbox parameter, we pass a dictionary which includes formatting styles." }, { "code": null, "e": 2458, "s": 2451, "text": " Code:" }, { "code": null, "e": 2466, "s": 2458, "text": "Python3" }, { "code": "# Adding text on the plot.ax.text(1, 13, 'Practice on GFG', style='italic', bbox={ 'facecolor': 'grey', 'alpha': 0.5, 'pad': 10})", "e": 2603, "s": 2466, "text": null }, { "code": null, "e": 2761, "s": 2603, "text": "If we want to do not have to box the text then simply do not assign anything to the bbox parameter. The following code adds the specified text without a box." }, { "code": null, "e": 2767, "s": 2761, "text": "Code:" }, { "code": null, "e": 2775, "s": 2767, "text": "Python3" }, { "code": "# Adding text without box on the plot.ax.text(8, 13, 'December', style='italic')", "e": 2856, "s": 2775, "text": null }, { "code": null, "e": 2898, "s": 2859, "text": "We can also add text with annotations." }, { "code": null, "e": 3166, "s": 2900, "text": "axes.annotate() is used to add an annotation, with an optional arrow, at an arbitrary location of the Axes. Its xy parameter contains the coordinates for arrow and xytext parameter specifies the location of the text. Arrowprops parameter is used to style the arrow." }, { "code": null, "e": 3254, "s": 3168, "text": "For instance, we can mark the peak value of the Day-Question data with an annotation." }, { "code": null, "e": 3262, "s": 3256, "text": "Code:" }, { "code": null, "e": 3272, "s": 3264, "text": "Python3" }, { "code": "# Adding annotation on the plot.ax.annotate('Peak', xy=(2, 8), xytext=(4, 10), fontsize=12, arrowprops=dict(facecolor='green', shrink=0.05))", "e": 3424, "s": 3272, "text": null }, { "code": null, "e": 3476, "s": 3424, "text": "Let’s put all this together and see the final code." }, { "code": null, "e": 3482, "s": 3476, "text": "Code:" }, { "code": null, "e": 3490, "s": 3482, "text": "Python3" }, { "code": "# Code to add text on matplotlib # Importing libraryimport matplotlib.pyplot as plt # Creating x-value and y-value of datax = [1, 2, 3, 4, 5]y = [5, 8, 4, 7, 5] # Creating figurefig = plt.figure() # Adding axes on the figureax = fig.add_subplot(111) # Plotting data on the axesax.plot(x, y) # Adding titleax.set_title('Day v/s No of Questions on GFG', fontsize=15) # Adding axis titleax.set_xlabel('Day', fontsize=12)ax.set_ylabel('No of Questions', fontsize=12) # Setting axis limitsax.axis([0, 10, 0, 15]) # Adding text on the plot.ax.text(1, 13, 'Practice on GFG', style='italic', bbox={ 'facecolor': 'green', 'alpha': 0.5, 'pad': 10}) # Adding text without box on the plot.ax.text(8, 13, 'December', style='italic') # Adding annotation on the plot.ax.annotate('Peak', xy=(2, 8), xytext=(4, 10), fontsize=12, arrowprops=dict(facecolor='green', shrink=0.05)) plt.show()", "e": 4380, "s": 3490, "text": null }, { "code": null, "e": 4388, "s": 4380, "text": "Output:" }, { "code": null, "e": 4404, "s": 4388, "text": "simranarora5sos" }, { "code": null, "e": 4411, "s": 4404, "text": "Picked" }, { "code": null, "e": 4429, "s": 4411, "text": "Python-matplotlib" }, { "code": null, "e": 4436, "s": 4429, "text": "Python" }, { "code": null, "e": 4534, "s": 4436, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4566, "s": 4534, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4593, "s": 4566, "text": "Python Classes and Objects" }, { "code": null, "e": 4614, "s": 4593, "text": "Python OOPs Concepts" }, { "code": null, "e": 4637, "s": 4614, "text": "Introduction To PYTHON" }, { "code": null, "e": 4693, "s": 4637, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 4724, "s": 4693, "text": "Python | os.path.join() method" }, { "code": null, "e": 4766, "s": 4724, "text": "Check if element exists in list in Python" }, { "code": null, "e": 4808, "s": 4766, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 4847, "s": 4808, "text": "Python | Get unique values from a list" } ]
Difference between string and StringBuffer in Java.
Strings, which are widely used in Java programming, are a sequence of characters. In Java programming language, strings are treated as objects. The Java platform provides the String class to create and manipulate strings. Whereas, StringBuffer class is a thread-safe, mutable sequence of characters. A string buffer is like a String, but can be modified. It contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls. They are safe for use by multiple threads. Every string buffer has a capacity. Live Demo public class Sample { public static void main(String args[]) { String str = new String("Hi welcome to tutorialspoint"); System.out.println(str);StringBuffer sBuffer = new StringBuffer("test"); sBuffer.append(" String Buffer"); System.out.println(sBuffer); } } Hi welcome to tutorialspoint test String Buffer
[ { "code": null, "e": 1409, "s": 1187, "text": "Strings, which are widely used in Java programming, are a sequence of characters. In Java programming language, strings are treated as objects. The Java platform provides the String class to create and manipulate strings." }, { "code": null, "e": 1487, "s": 1409, "text": "Whereas, StringBuffer class is a thread-safe, mutable sequence of characters." }, { "code": null, "e": 1542, "s": 1487, "text": "A string buffer is like a String, but can be modified." }, { "code": null, "e": 1682, "s": 1542, "text": "It contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls." }, { "code": null, "e": 1725, "s": 1682, "text": "They are safe for use by multiple threads." }, { "code": null, "e": 1761, "s": 1725, "text": "Every string buffer has a capacity." }, { "code": null, "e": 1771, "s": 1761, "text": "Live Demo" }, { "code": null, "e": 2061, "s": 1771, "text": "public class Sample {\n public static void main(String args[]) {\n String str = new String(\"Hi welcome to tutorialspoint\");\n System.out.println(str);StringBuffer sBuffer = new StringBuffer(\"test\");\n sBuffer.append(\" String Buffer\");\n System.out.println(sBuffer);\n }\n}" }, { "code": null, "e": 2109, "s": 2061, "text": "Hi welcome to tutorialspoint\ntest String Buffer" } ]
HTML | placeholder Attribute
08 Dec, 2021 The placeholder attribute specifies a short hint that describes the expected value of an input field/text area. The short hint is displayed in the field before the user enters a value.Syntax: <element placeholder=""> Elements: This method can have following attributes: <input> placeholder Attribute <textarea> placeholder Attribute Attribute: The attribute for each of the above element is placeholder. Example: With <input> element html <!DOCTYPE html><html> <body> <center> <h1 style="font-size:25px;font-style:italic;"> GeeksforGeeks </h1> <h2 style="font-size:25px;font-style:italic;"> Placeholder Attribute in Input Element </h2> <form action=" "> <input type="text" name="fname" placeholder="First name"> <br> <input type="text" name="lname" placeholder="Last name"> <br> <input type="submit" value="Submit"> </form></center></body> </html> Output: Example: With <textarea> element html <!DOCTYPE html><html> <body> <center> <h1 style="font-size:25px;font-style:italic;"> GeeksForGeeks </h1> <h2 style="font-size:25px;font-style:italic;"> Placeholder Attribute in Textarea Element </h2> Give your Intro: <textarea rows="4" cols="40" placeholder="Write something here about yourself..."> </textarea></center></body> </html> Output: Supported Browsers: The browser supported by placeholder Attribute are listed below: Google Chrome Internet Explorer Firefox Opera Safari hritikbhatnagar2182 HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? REST API (Introduction) Hide or show elements in HTML using display property Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 53, "s": 25, "text": "\n08 Dec, 2021" }, { "code": null, "e": 247, "s": 53, "text": "The placeholder attribute specifies a short hint that describes the expected value of an input field/text area. The short hint is displayed in the field before the user enters a value.Syntax: " }, { "code": null, "e": 272, "s": 247, "text": "<element placeholder=\"\">" }, { "code": null, "e": 327, "s": 272, "text": "Elements: This method can have following attributes: " }, { "code": null, "e": 357, "s": 327, "text": "<input> placeholder Attribute" }, { "code": null, "e": 390, "s": 357, "text": "<textarea> placeholder Attribute" }, { "code": null, "e": 493, "s": 390, "text": "Attribute: The attribute for each of the above element is placeholder. Example: With <input> element " }, { "code": null, "e": 498, "s": 493, "text": "html" }, { "code": "<!DOCTYPE html><html> <body> <center> <h1 style=\"font-size:25px;font-style:italic;\"> GeeksforGeeks </h1> <h2 style=\"font-size:25px;font-style:italic;\"> Placeholder Attribute in Input Element </h2> <form action=\" \"> <input type=\"text\" name=\"fname\" placeholder=\"First name\"> <br> <input type=\"text\" name=\"lname\" placeholder=\"Last name\"> <br> <input type=\"submit\" value=\"Submit\"> </form></center></body> </html>", "e": 1079, "s": 498, "text": null }, { "code": null, "e": 1089, "s": 1079, "text": "Output: " }, { "code": null, "e": 1124, "s": 1089, "text": "Example: With <textarea> element " }, { "code": null, "e": 1129, "s": 1124, "text": "html" }, { "code": "<!DOCTYPE html><html> <body> <center> <h1 style=\"font-size:25px;font-style:italic;\"> GeeksForGeeks </h1> <h2 style=\"font-size:25px;font-style:italic;\"> Placeholder Attribute in Textarea Element </h2> Give your Intro: <textarea rows=\"4\" cols=\"40\" placeholder=\"Write something here about yourself...\"> </textarea></center></body> </html>", "e": 1538, "s": 1129, "text": null }, { "code": null, "e": 1548, "s": 1538, "text": "Output: " }, { "code": null, "e": 1635, "s": 1548, "text": "Supported Browsers: The browser supported by placeholder Attribute are listed below: " }, { "code": null, "e": 1649, "s": 1635, "text": "Google Chrome" }, { "code": null, "e": 1667, "s": 1649, "text": "Internet Explorer" }, { "code": null, "e": 1675, "s": 1667, "text": "Firefox" }, { "code": null, "e": 1681, "s": 1675, "text": "Opera" }, { "code": null, "e": 1688, "s": 1681, "text": "Safari" }, { "code": null, "e": 1710, "s": 1690, "text": "hritikbhatnagar2182" }, { "code": null, "e": 1726, "s": 1710, "text": "HTML-Attributes" }, { "code": null, "e": 1731, "s": 1726, "text": "HTML" }, { "code": null, "e": 1748, "s": 1731, "text": "Web Technologies" }, { "code": null, "e": 1753, "s": 1748, "text": "HTML" }, { "code": null, "e": 1851, "s": 1753, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1899, "s": 1851, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 1961, "s": 1899, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2011, "s": 1961, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 2035, "s": 2011, "text": "REST API (Introduction)" }, { "code": null, "e": 2088, "s": 2035, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 2150, "s": 2088, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2183, "s": 2150, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2244, "s": 2183, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2294, "s": 2244, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
GATE | GATE CS 2019 | Question 30
15 Feb, 2019 An array of 25 distinct elements is to be sorted using quicksort. Assume that the pivot element is chosen uniformly at random. The probability that the pivot element gets placed in the worst possible location in the first round of partitioning (rounded off to 2 decimal places) is _________. Note: This was Numerical Type question.(A) 0.08(B) 0.0016(C) 0.04(D) 0.0008Answer: (A)Explanation: Given an array of 25 distinct elements, and pivot element is chosen uniformly randomly. So, there are only 2 worst case position in the pivot element is either first (or) last. Therefore, required probability is, = 2/25 = 0.08 So, option (A) is correct.Quiz of this Question GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Feb, 2019" }, { "code": null, "e": 320, "s": 28, "text": "An array of 25 distinct elements is to be sorted using quicksort. Assume that the pivot element is chosen uniformly at random. The probability that the pivot element gets placed in the worst possible location in the first round of partitioning (rounded off to 2 decimal places) is _________." }, { "code": null, "e": 596, "s": 320, "text": "Note: This was Numerical Type question.(A) 0.08(B) 0.0016(C) 0.04(D) 0.0008Answer: (A)Explanation: Given an array of 25 distinct elements, and pivot element is chosen uniformly randomly. So, there are only 2 worst case position in the pivot element is either first (or) last." }, { "code": null, "e": 632, "s": 596, "text": "Therefore, required probability is," }, { "code": null, "e": 646, "s": 632, "text": "= 2/25\n= 0.08" }, { "code": null, "e": 694, "s": 646, "text": "So, option (A) is correct.Quiz of this Question" }, { "code": null, "e": 699, "s": 694, "text": "GATE" } ]
Largest number having both positive and negative values present in the array - GeeksforGeeks
28 Jul, 2021 Given an array arr[] consisting of N integers, the task is to find the largest number K (> 0) such that both the values K and -K are present in the given array arr[]. If no such number exists, then print -1. Examples: Input: arr[] = {3, 2, -2, 5, -3}Output: 3 Input: arr[] = {1, 2, 3, -4}Output: -1 Naive Approach: The simplest approach to solve the given problem is to iterate over the array and for each element, traverse the remaining array to check if its negative value exists in the array or not. After complete traversal of the array, print the maximum such number obtained. Time Complexity: O(N2)Auxiliary Space: O(1) Efficient Approach: The above approach can be optimized by using Sorting and Two Pointers. Follow the steps below to solve this problem: Initialize a variable, say res as -1 that stores the maximum element obtained. Sort the given array arr[]. Initialize two variables, say l and r as 0 and (N – 1), and perform the following steps:If the value of (arr[l] + arr[r]) is equal to 0, then return the absolute value of arr[l] and arr[r].Otherwise, if the value of (arr[l] + arr[r]) is less than 0, then increment the value of l by 1.Otherwise, decrement the value of r by 1. If the value of (arr[l] + arr[r]) is equal to 0, then return the absolute value of arr[l] and arr[r]. Otherwise, if the value of (arr[l] + arr[r]) is less than 0, then increment the value of l by 1. Otherwise, decrement the value of r by 1. After completing the above steps, print the value of res as the result. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include<bits/stdc++.h>using namespace std; // Function to find the largest// number k such that both k and// -k are present in the arrayint largestNum(vector<int>arr){ // Stores the resultant value // of K int res = 0; // Sort the array arr[] sort(arr.begin(), arr.end()); // Initialize two variables to // use two pointers technique int l = 0, r = arr.size() - 1; // Iterate until the value of // l is less than r while (l < r) { // Find the value of the sum int sum = arr[l] + arr[r]; // If the sum is 0, then the // resultant element is found if (sum == 0) { res = max(res, max(arr[l], arr[r])); return res; } // If the sum is negative else if (sum < 0) { l++; } // Otherwise, decrement r else { r--; } } return res;} // Driver Codeint main(){ vector<int>arr = { 3, 2, -2, 5, -3 }; cout << (largestNum(arr));} // This code is contributed by amreshkumar3 // Java program for the above approach import java.io.*;import java.util.*; public class GFG { // Function to find the largest // number k such that both k and // -k are present in the array public static int largestNum(int[] arr) { // Stores the resultant value // of K int res = 0; // Sort the array arr[] Arrays.sort(arr); // Initialize two variables to // use two pointers technique int l = 0, r = arr.length - 1; // Iterate until the value of // l is less than r while (l < r) { // Find the value of the sum int sum = arr[l] + arr[r]; // If the sum is 0, then the // resultant element is found if (sum == 0) { res = Math.max( res, Math.max( arr[l], arr[r])); return res; } // If the sum is negative else if (sum < 0) { l++; } // Otherwise, decrement r else { r--; } } return res; } // Driver Code public static void main(String[] args) { int[] arr = { 3, 2, -2, 5, -3 }; System.out.println( largestNum(arr)); }} # Python3 program for the above approach # Function to find the largest# number k such that both k and# -k are present in the arraydef largestNum(arr): # Stores the resultant value # of K res = 0 # Sort the array arr[] arr = sorted(arr) # Initialize two variables to # use two pointers technique l = 0 r = len(arr) - 1 # Iterate until the value of # l is less than r while (l < r): # Find the value of the sum sum = arr[l] + arr[r] # If the sum is 0, then the # resultant element is found if (sum == 0): res = max(res, max(arr[l], arr[r])) return res # If the sum is negative elif (sum < 0): l += 1 # Otherwise, decrement r else: r-=1 return res # Driver Codeif __name__ == '__main__': arr =[3, 2, -2, 5, -3] print(largestNum(arr)) # This code is contributed by mohit kumar 29. // C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to find the largest// number k such that both k and// -k are present in the arraystatic int largestNum(List<int>arr){ // Stores the resultant value // of K int res = 0; // Sort the array arr[] arr.Sort(); // Initialize two variables to // use two pointers technique int l = 0, r = arr.Count - 1; // Iterate until the value of // l is less than r while (l < r) { // Find the value of the sum int sum = arr[l] + arr[r]; // If the sum is 0, then the // resultant element is found if (sum == 0) { res = Math.Max(res, Math.Max(arr[l], arr[r])); return res; } // If the sum is negative else if (sum < 0) { l++; } // Otherwise, decrement r else { r--; } } return res;} // Driver Codepublic static void Main(){ List<int>arr = new List<int>(){ 3, 2, -2, 5, -3 }; Console.Write(largestNum(arr));}} // This code is contributed by bgangwar59 <script>// Javascript program for the above approach // Function to find the largest// number k such that both k and// -k are present in the arrayfunction largestNum(arr) { // Stores the resultant value // of K let res = 0; // Sort the array arr[] arr.sort((a, b) => a - b); // Initialize two variables to // use two pointers technique let l = 0, r = arr.length - 1; // Iterate until the value of // l is less than r while (l < r) { // Find the value of the sum let sum = arr[l] + arr[r]; // If the sum is 0, then the // resultant element is found if (sum == 0) { res = Math.max(res, Math.max(arr[l], arr[r])); return res; } // If the sum is negative else if (sum < 0) { l++; } // Otherwise, decrement r else { r--; } } return res;} // Driver Code let arr = [3, 2, -2, 5, -3];document.write((largestNum(arr))); // This code is contributed by _saurabh_jaiswal</script> 3 Time Complexity: O(N*log N)Auxiliary Space: O(1) Optimized Approach: The above approach can be further optimized by storing the elements into a Set. Follow the steps below to solve this problem: Initialize a set S that stores the array elements. Initialize a variable, say res as -1 to store the maximum element while traversing the array. Iterate over the range [0, N – 1] using the variable i and perform the following steps:Add the current element to the set S.If the element is present, then update the value of res to the current element. Add the current element to the set S. If the element is present, then update the value of res to the current element. After completing the above steps, print the value of res as the result. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include<bits/stdc++.h>using namespace std; // Function to find the largest// number k such that both k and// -k are present in the arrayint largestNum(int arr[] ,int n){ // Stores the array elements set<int> st; // Initialize a variable res as // 0 to store maximum element // while traversing the array int res = 0; // Iterate through array arr for(int i = 0; i < n; i++) { // Add the current element // into the st st.insert(arr[i]); // Check if the negative of // this element is also // present in the st or not if (st.find(-1 * arr[i]) != st.end()) { res = max(res, abs(arr[i])); } } // Return the resultant element return res;} // Drive Codeint main(){ int arr[] = { 3, 2, -2, 5, -3 }; int n = sizeof(arr) / sizeof(arr[0]); cout << largestNum(arr, n);} // This code is contributed by SURENDRA_GANGWAR // Java program for the above approach import java.io.*;import java.util.*; class GFG { // Function to find the largest // number k such that both k and // -k are present in the array public static int largestNum(int[] arr) { // Stores the array elements Set<Integer> set = new HashSet<>(); // Initialize a variable res as // 0 to store maximum element // while traversing the array int res = 0; // Iterate through array arr for (int i = 0; i < arr.length; i++) { // Add the current element // into the set set.add(arr[i]); // Check if the negative of // this element is also // present in the set or not if (set.contains(-1 * arr[i])) { res = Math.max( res, Math.abs(arr[i])); } } // Return the resultant element return res; } // Drive Code public static void main(String[] args) { int[] arr = { 3, 2, -2, 5, -3 }; System.out.println( largestNum(arr)); }} # Python3 program for the above approach # Function to find the largest# number k such that both k and# -k are present in the arraydef largestNum(arr, n) : # Stores the array elements st = set([]) # Initialize a variable res as # 0 to store maximum element # while traversing the array res = 0 # Iterate through array arr for i in range(n): # Add the current element # into the st st.add(arr[i]) # Check if the negative of # this element is also # present in the st or not if (-1 * arr[i]) in st: res = max(res, abs(arr[i])) # Return the resultant element return res arr = [ 3, 2, -2, 5, -3 ]n = len(arr) print(largestNum(arr, n)) # This code is contributed by divyeshrabadiya07 // C# program for the above approachusing System;using System.Collections.Generic; public class GFG{ // Function to find the largest // number k such that both k and // -k are present in the array public static int largestNum(int[] arr) { // Stores the array elements HashSet<int> set = new HashSet<int>(); // Initialize a variable res as // 0 to store maximum element // while traversing the array int res = 0; // Iterate through array arr for (int i = 0; i < arr.Length; i++) { // Add the current element // into the set set.Add(arr[i]); // Check if the negative of // this element is also // present in the set or not if (set.Contains(-1 * arr[i])) { res = Math.Max( res, Math.Abs(arr[i])); } } // Return the resultant element return res; } // Drive Code static public void Main (){ int[] arr = { 3, 2, -2, 5, -3 }; Console.WriteLine( largestNum(arr)); }} // This code is contributed by unknown2108 <script> // JavaScript program for the above approach // Function to find the largest // number k such that both k and // -k are present in the arrayfunction largestNum(arr){ // Stores the array elements let set = new Set(); // Initialize a variable res as // 0 to store maximum element // while traversing the array let res = 0; // Iterate through array arr for (let i = 0; i < arr.length; i++) { // Add the current element // into the set set.add(arr[i]); // Check if the negative of // this element is also // present in the set or not if (set.has(-1 * arr[i])) { res = Math.max( res, Math.abs(arr[i])); } } // Return the resultant element return res;} // Drive Codelet arr=[3, 2, -2, 5, -3 ];document.write(largestNum(arr)); // This code is contributed by patel2127 </script> 3 Time Complexity: O(N)Auxiliary Space: O(N) mohit kumar 29 amreshkumar3 bgangwar59 _saurabh_jaiswal SURENDRA_GANGWAR patel2127 unknown2108 divyeshrabadiya07 HashSet two-pointer-algorithm Arrays Hash Mathematical Searching Sorting two-pointer-algorithm Arrays Searching Hash Mathematical Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count pairs with given sum Chocolate Distribution Problem Window Sliding Technique Reversal algorithm for array rotation Next Greater Element Internal Working of HashMap in Java Count pairs with given sum Hashing | Set 1 (Introduction) Hashing | Set 3 (Open Addressing) Hashing | Set 2 (Separate Chaining)
[ { "code": null, "e": 26041, "s": 26013, "text": "\n28 Jul, 2021" }, { "code": null, "e": 26249, "s": 26041, "text": "Given an array arr[] consisting of N integers, the task is to find the largest number K (> 0) such that both the values K and -K are present in the given array arr[]. If no such number exists, then print -1." }, { "code": null, "e": 26259, "s": 26249, "text": "Examples:" }, { "code": null, "e": 26301, "s": 26259, "text": "Input: arr[] = {3, 2, -2, 5, -3}Output: 3" }, { "code": null, "e": 26340, "s": 26301, "text": "Input: arr[] = {1, 2, 3, -4}Output: -1" }, { "code": null, "e": 26623, "s": 26340, "text": "Naive Approach: The simplest approach to solve the given problem is to iterate over the array and for each element, traverse the remaining array to check if its negative value exists in the array or not. After complete traversal of the array, print the maximum such number obtained." }, { "code": null, "e": 26667, "s": 26623, "text": "Time Complexity: O(N2)Auxiliary Space: O(1)" }, { "code": null, "e": 26804, "s": 26667, "text": "Efficient Approach: The above approach can be optimized by using Sorting and Two Pointers. Follow the steps below to solve this problem:" }, { "code": null, "e": 26883, "s": 26804, "text": "Initialize a variable, say res as -1 that stores the maximum element obtained." }, { "code": null, "e": 26911, "s": 26883, "text": "Sort the given array arr[]." }, { "code": null, "e": 27238, "s": 26911, "text": "Initialize two variables, say l and r as 0 and (N – 1), and perform the following steps:If the value of (arr[l] + arr[r]) is equal to 0, then return the absolute value of arr[l] and arr[r].Otherwise, if the value of (arr[l] + arr[r]) is less than 0, then increment the value of l by 1.Otherwise, decrement the value of r by 1." }, { "code": null, "e": 27340, "s": 27238, "text": "If the value of (arr[l] + arr[r]) is equal to 0, then return the absolute value of arr[l] and arr[r]." }, { "code": null, "e": 27437, "s": 27340, "text": "Otherwise, if the value of (arr[l] + arr[r]) is less than 0, then increment the value of l by 1." }, { "code": null, "e": 27479, "s": 27437, "text": "Otherwise, decrement the value of r by 1." }, { "code": null, "e": 27551, "s": 27479, "text": "After completing the above steps, print the value of res as the result." }, { "code": null, "e": 27602, "s": 27551, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27606, "s": 27602, "text": "C++" }, { "code": null, "e": 27611, "s": 27606, "text": "Java" }, { "code": null, "e": 27619, "s": 27611, "text": "Python3" }, { "code": null, "e": 27622, "s": 27619, "text": "C#" }, { "code": null, "e": 27633, "s": 27622, "text": "Javascript" }, { "code": "// C++ program for the above approach#include<bits/stdc++.h>using namespace std; // Function to find the largest// number k such that both k and// -k are present in the arrayint largestNum(vector<int>arr){ // Stores the resultant value // of K int res = 0; // Sort the array arr[] sort(arr.begin(), arr.end()); // Initialize two variables to // use two pointers technique int l = 0, r = arr.size() - 1; // Iterate until the value of // l is less than r while (l < r) { // Find the value of the sum int sum = arr[l] + arr[r]; // If the sum is 0, then the // resultant element is found if (sum == 0) { res = max(res, max(arr[l], arr[r])); return res; } // If the sum is negative else if (sum < 0) { l++; } // Otherwise, decrement r else { r--; } } return res;} // Driver Codeint main(){ vector<int>arr = { 3, 2, -2, 5, -3 }; cout << (largestNum(arr));} // This code is contributed by amreshkumar3", "e": 28745, "s": 27633, "text": null }, { "code": "// Java program for the above approach import java.io.*;import java.util.*; public class GFG { // Function to find the largest // number k such that both k and // -k are present in the array public static int largestNum(int[] arr) { // Stores the resultant value // of K int res = 0; // Sort the array arr[] Arrays.sort(arr); // Initialize two variables to // use two pointers technique int l = 0, r = arr.length - 1; // Iterate until the value of // l is less than r while (l < r) { // Find the value of the sum int sum = arr[l] + arr[r]; // If the sum is 0, then the // resultant element is found if (sum == 0) { res = Math.max( res, Math.max( arr[l], arr[r])); return res; } // If the sum is negative else if (sum < 0) { l++; } // Otherwise, decrement r else { r--; } } return res; } // Driver Code public static void main(String[] args) { int[] arr = { 3, 2, -2, 5, -3 }; System.out.println( largestNum(arr)); }}", "e": 30058, "s": 28745, "text": null }, { "code": "# Python3 program for the above approach # Function to find the largest# number k such that both k and# -k are present in the arraydef largestNum(arr): # Stores the resultant value # of K res = 0 # Sort the array arr[] arr = sorted(arr) # Initialize two variables to # use two pointers technique l = 0 r = len(arr) - 1 # Iterate until the value of # l is less than r while (l < r): # Find the value of the sum sum = arr[l] + arr[r] # If the sum is 0, then the # resultant element is found if (sum == 0): res = max(res, max(arr[l], arr[r])) return res # If the sum is negative elif (sum < 0): l += 1 # Otherwise, decrement r else: r-=1 return res # Driver Codeif __name__ == '__main__': arr =[3, 2, -2, 5, -3] print(largestNum(arr)) # This code is contributed by mohit kumar 29.", "e": 31004, "s": 30058, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to find the largest// number k such that both k and// -k are present in the arraystatic int largestNum(List<int>arr){ // Stores the resultant value // of K int res = 0; // Sort the array arr[] arr.Sort(); // Initialize two variables to // use two pointers technique int l = 0, r = arr.Count - 1; // Iterate until the value of // l is less than r while (l < r) { // Find the value of the sum int sum = arr[l] + arr[r]; // If the sum is 0, then the // resultant element is found if (sum == 0) { res = Math.Max(res, Math.Max(arr[l], arr[r])); return res; } // If the sum is negative else if (sum < 0) { l++; } // Otherwise, decrement r else { r--; } } return res;} // Driver Codepublic static void Main(){ List<int>arr = new List<int>(){ 3, 2, -2, 5, -3 }; Console.Write(largestNum(arr));}} // This code is contributed by bgangwar59", "e": 32197, "s": 31004, "text": null }, { "code": "<script>// Javascript program for the above approach // Function to find the largest// number k such that both k and// -k are present in the arrayfunction largestNum(arr) { // Stores the resultant value // of K let res = 0; // Sort the array arr[] arr.sort((a, b) => a - b); // Initialize two variables to // use two pointers technique let l = 0, r = arr.length - 1; // Iterate until the value of // l is less than r while (l < r) { // Find the value of the sum let sum = arr[l] + arr[r]; // If the sum is 0, then the // resultant element is found if (sum == 0) { res = Math.max(res, Math.max(arr[l], arr[r])); return res; } // If the sum is negative else if (sum < 0) { l++; } // Otherwise, decrement r else { r--; } } return res;} // Driver Code let arr = [3, 2, -2, 5, -3];document.write((largestNum(arr))); // This code is contributed by _saurabh_jaiswal</script>", "e": 33242, "s": 32197, "text": null }, { "code": null, "e": 33244, "s": 33242, "text": "3" }, { "code": null, "e": 33295, "s": 33246, "text": "Time Complexity: O(N*log N)Auxiliary Space: O(1)" }, { "code": null, "e": 33441, "s": 33295, "text": "Optimized Approach: The above approach can be further optimized by storing the elements into a Set. Follow the steps below to solve this problem:" }, { "code": null, "e": 33492, "s": 33441, "text": "Initialize a set S that stores the array elements." }, { "code": null, "e": 33586, "s": 33492, "text": "Initialize a variable, say res as -1 to store the maximum element while traversing the array." }, { "code": null, "e": 33790, "s": 33586, "text": "Iterate over the range [0, N – 1] using the variable i and perform the following steps:Add the current element to the set S.If the element is present, then update the value of res to the current element." }, { "code": null, "e": 33828, "s": 33790, "text": "Add the current element to the set S." }, { "code": null, "e": 33908, "s": 33828, "text": "If the element is present, then update the value of res to the current element." }, { "code": null, "e": 33980, "s": 33908, "text": "After completing the above steps, print the value of res as the result." }, { "code": null, "e": 34031, "s": 33980, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 34035, "s": 34031, "text": "C++" }, { "code": null, "e": 34040, "s": 34035, "text": "Java" }, { "code": null, "e": 34048, "s": 34040, "text": "Python3" }, { "code": null, "e": 34051, "s": 34048, "text": "C#" }, { "code": null, "e": 34062, "s": 34051, "text": "Javascript" }, { "code": "// C++ program for the above approach#include<bits/stdc++.h>using namespace std; // Function to find the largest// number k such that both k and// -k are present in the arrayint largestNum(int arr[] ,int n){ // Stores the array elements set<int> st; // Initialize a variable res as // 0 to store maximum element // while traversing the array int res = 0; // Iterate through array arr for(int i = 0; i < n; i++) { // Add the current element // into the st st.insert(arr[i]); // Check if the negative of // this element is also // present in the st or not if (st.find(-1 * arr[i]) != st.end()) { res = max(res, abs(arr[i])); } } // Return the resultant element return res;} // Drive Codeint main(){ int arr[] = { 3, 2, -2, 5, -3 }; int n = sizeof(arr) / sizeof(arr[0]); cout << largestNum(arr, n);} // This code is contributed by SURENDRA_GANGWAR", "e": 35049, "s": 34062, "text": null }, { "code": "// Java program for the above approach import java.io.*;import java.util.*; class GFG { // Function to find the largest // number k such that both k and // -k are present in the array public static int largestNum(int[] arr) { // Stores the array elements Set<Integer> set = new HashSet<>(); // Initialize a variable res as // 0 to store maximum element // while traversing the array int res = 0; // Iterate through array arr for (int i = 0; i < arr.length; i++) { // Add the current element // into the set set.add(arr[i]); // Check if the negative of // this element is also // present in the set or not if (set.contains(-1 * arr[i])) { res = Math.max( res, Math.abs(arr[i])); } } // Return the resultant element return res; } // Drive Code public static void main(String[] args) { int[] arr = { 3, 2, -2, 5, -3 }; System.out.println( largestNum(arr)); }}", "e": 36188, "s": 35049, "text": null }, { "code": "# Python3 program for the above approach # Function to find the largest# number k such that both k and# -k are present in the arraydef largestNum(arr, n) : # Stores the array elements st = set([]) # Initialize a variable res as # 0 to store maximum element # while traversing the array res = 0 # Iterate through array arr for i in range(n): # Add the current element # into the st st.add(arr[i]) # Check if the negative of # this element is also # present in the st or not if (-1 * arr[i]) in st: res = max(res, abs(arr[i])) # Return the resultant element return res arr = [ 3, 2, -2, 5, -3 ]n = len(arr) print(largestNum(arr, n)) # This code is contributed by divyeshrabadiya07", "e": 36991, "s": 36188, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic; public class GFG{ // Function to find the largest // number k such that both k and // -k are present in the array public static int largestNum(int[] arr) { // Stores the array elements HashSet<int> set = new HashSet<int>(); // Initialize a variable res as // 0 to store maximum element // while traversing the array int res = 0; // Iterate through array arr for (int i = 0; i < arr.Length; i++) { // Add the current element // into the set set.Add(arr[i]); // Check if the negative of // this element is also // present in the set or not if (set.Contains(-1 * arr[i])) { res = Math.Max( res, Math.Abs(arr[i])); } } // Return the resultant element return res; } // Drive Code static public void Main (){ int[] arr = { 3, 2, -2, 5, -3 }; Console.WriteLine( largestNum(arr)); }} // This code is contributed by unknown2108", "e": 38198, "s": 36991, "text": null }, { "code": "<script> // JavaScript program for the above approach // Function to find the largest // number k such that both k and // -k are present in the arrayfunction largestNum(arr){ // Stores the array elements let set = new Set(); // Initialize a variable res as // 0 to store maximum element // while traversing the array let res = 0; // Iterate through array arr for (let i = 0; i < arr.length; i++) { // Add the current element // into the set set.add(arr[i]); // Check if the negative of // this element is also // present in the set or not if (set.has(-1 * arr[i])) { res = Math.max( res, Math.abs(arr[i])); } } // Return the resultant element return res;} // Drive Codelet arr=[3, 2, -2, 5, -3 ];document.write(largestNum(arr)); // This code is contributed by patel2127 </script>", "e": 39205, "s": 38198, "text": null }, { "code": null, "e": 39207, "s": 39205, "text": "3" }, { "code": null, "e": 39252, "s": 39209, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 39267, "s": 39252, "text": "mohit kumar 29" }, { "code": null, "e": 39280, "s": 39267, "text": "amreshkumar3" }, { "code": null, "e": 39291, "s": 39280, "text": "bgangwar59" }, { "code": null, "e": 39308, "s": 39291, "text": "_saurabh_jaiswal" }, { "code": null, "e": 39325, "s": 39308, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 39335, "s": 39325, "text": "patel2127" }, { "code": null, "e": 39347, "s": 39335, "text": "unknown2108" }, { "code": null, "e": 39365, "s": 39347, "text": "divyeshrabadiya07" }, { "code": null, "e": 39373, "s": 39365, "text": "HashSet" }, { "code": null, "e": 39395, "s": 39373, "text": "two-pointer-algorithm" }, { "code": null, "e": 39402, "s": 39395, "text": "Arrays" }, { "code": null, "e": 39407, "s": 39402, "text": "Hash" }, { "code": null, "e": 39420, "s": 39407, "text": "Mathematical" }, { "code": null, "e": 39430, "s": 39420, "text": "Searching" }, { "code": null, "e": 39438, "s": 39430, "text": "Sorting" }, { "code": null, "e": 39460, "s": 39438, "text": "two-pointer-algorithm" }, { "code": null, "e": 39467, "s": 39460, "text": "Arrays" }, { "code": null, "e": 39477, "s": 39467, "text": "Searching" }, { "code": null, "e": 39482, "s": 39477, "text": "Hash" }, { "code": null, "e": 39495, "s": 39482, "text": "Mathematical" }, { "code": null, "e": 39503, "s": 39495, "text": "Sorting" }, { "code": null, "e": 39601, "s": 39503, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39628, "s": 39601, "text": "Count pairs with given sum" }, { "code": null, "e": 39659, "s": 39628, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 39684, "s": 39659, "text": "Window Sliding Technique" }, { "code": null, "e": 39722, "s": 39684, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 39743, "s": 39722, "text": "Next Greater Element" }, { "code": null, "e": 39779, "s": 39743, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 39806, "s": 39779, "text": "Count pairs with given sum" }, { "code": null, "e": 39837, "s": 39806, "text": "Hashing | Set 1 (Introduction)" }, { "code": null, "e": 39871, "s": 39837, "text": "Hashing | Set 3 (Open Addressing)" } ]
Python | Find depth of a dictionary - GeeksforGeeks
27 Nov, 2018 Prerequisite: Nested dictionary The task is to find the depth of given dictionary in Python. Let’s discuss all different methods to do this task. Examples: Input : {1:'a', 2: {3: {4: {}}}} Output : 4 Input : {'a':1, 'b': {'c':'geek'}} Output : 3 Approach #1 : Naive Alpproach A naive approach in order to find the depth of a dictionary is to count the number of opening curly braces. But, one drawback of this approach is that it would only work if the input is correct. # Python3 Program to find depth of a dictionarydef dict_depth(dic, level = 1): str_dic = str(dic) counter = 0 for i in str_dic: if i == "{": counter += 1 return(counter) # Driver code dic = {1:'Geek', 2: {3: {4: {}}}}print(dict_depth(dic)) 4 Approach #2: Using recursion In this method we use recursion with max() function which picks the greatest depth for the current dictionary under scrutiny at each level. # Python3 Program to find depth of a dictionarydef dict_depth(dic, level = 1): if not isinstance(dic, dict) or not dic: return level return max(dict_depth(dic[key], level + 1) for key in dic) # Driver code dic = {1:'a', 2: {3: {4: {}}}} print(dict_depth(dic)) 4 Another version of the recursive solution is to use map() function by which the values of the inner dictionary is mapped to the called function. # Python3 Program to find depth of a dictionarydef dict_depth(my_dict): if isinstance(my_dict, dict): return 1 + (max(map(dict_depth, my_dict.values())) if my_dict else 0) return 0 # Driver code my_dict = {1:'a', 2: {3: {4: {}}}}print(dict_depth(my_dict)) 4 Approach #3: Iterative Solution In this approach, we save the nested key and its initial depth in a variable, say p_dict. Now, start a loop for p_dict, and keep popping values while digging deeper for nested dictionaries. # Python3 Program to find depth of a dictionarydef dict_depth(myDict): Ddepth = 1 obj = [(k, Ddepth + 1) for k in myDict.values() if isinstance(k, dict)] max_depth = 0 while(obj): n, Ddepth = obj.pop() max_depth = max(max_depth, Ddepth) obj = obj + [(k, Ddepth + 1) for k in n.values() if isinstance(k, dict)] return max_depth # Driver code myDict = {1:'a', 2: {3: {4:{}}}}print(dict_depth(myDict)) 4 Python dictionary-programs python-dict Python python-dict Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n27 Nov, 2018" }, { "code": null, "e": 25569, "s": 25537, "text": "Prerequisite: Nested dictionary" }, { "code": null, "e": 25683, "s": 25569, "text": "The task is to find the depth of given dictionary in Python. Let’s discuss all different methods to do this task." }, { "code": null, "e": 25693, "s": 25683, "text": "Examples:" }, { "code": null, "e": 25785, "s": 25693, "text": "Input : {1:'a', 2: {3: {4: {}}}}\nOutput : 4\n\nInput : {'a':1, 'b': {'c':'geek'}}\nOutput : 3\n" }, { "code": null, "e": 25815, "s": 25785, "text": "Approach #1 : Naive Alpproach" }, { "code": null, "e": 26010, "s": 25815, "text": "A naive approach in order to find the depth of a dictionary is to count the number of opening curly braces. But, one drawback of this approach is that it would only work if the input is correct." }, { "code": "# Python3 Program to find depth of a dictionarydef dict_depth(dic, level = 1): str_dic = str(dic) counter = 0 for i in str_dic: if i == \"{\": counter += 1 return(counter) # Driver code dic = {1:'Geek', 2: {3: {4: {}}}}print(dict_depth(dic))", "e": 26289, "s": 26010, "text": null }, { "code": null, "e": 26292, "s": 26289, "text": "4\n" }, { "code": null, "e": 26322, "s": 26292, "text": " Approach #2: Using recursion" }, { "code": null, "e": 26462, "s": 26322, "text": "In this method we use recursion with max() function which picks the greatest depth for the current dictionary under scrutiny at each level." }, { "code": "# Python3 Program to find depth of a dictionarydef dict_depth(dic, level = 1): if not isinstance(dic, dict) or not dic: return level return max(dict_depth(dic[key], level + 1) for key in dic) # Driver code dic = {1:'a', 2: {3: {4: {}}}} print(dict_depth(dic))", "e": 26773, "s": 26462, "text": null }, { "code": null, "e": 26776, "s": 26773, "text": "4\n" }, { "code": null, "e": 26921, "s": 26776, "text": "Another version of the recursive solution is to use map() function by which the values of the inner dictionary is mapped to the called function." }, { "code": "# Python3 Program to find depth of a dictionarydef dict_depth(my_dict): if isinstance(my_dict, dict): return 1 + (max(map(dict_depth, my_dict.values())) if my_dict else 0) return 0 # Driver code my_dict = {1:'a', 2: {3: {4: {}}}}print(dict_depth(my_dict))", "e": 27246, "s": 26921, "text": null }, { "code": null, "e": 27249, "s": 27246, "text": "4\n" }, { "code": null, "e": 27282, "s": 27249, "text": " Approach #3: Iterative Solution" }, { "code": null, "e": 27472, "s": 27282, "text": "In this approach, we save the nested key and its initial depth in a variable, say p_dict. Now, start a loop for p_dict, and keep popping values while digging deeper for nested dictionaries." }, { "code": "# Python3 Program to find depth of a dictionarydef dict_depth(myDict): Ddepth = 1 obj = [(k, Ddepth + 1) for k in myDict.values() if isinstance(k, dict)] max_depth = 0 while(obj): n, Ddepth = obj.pop() max_depth = max(max_depth, Ddepth) obj = obj + [(k, Ddepth + 1) for k in n.values() if isinstance(k, dict)] return max_depth # Driver code myDict = {1:'a', 2: {3: {4:{}}}}print(dict_depth(myDict))", "e": 27997, "s": 27472, "text": null }, { "code": null, "e": 28000, "s": 27997, "text": "4\n" }, { "code": null, "e": 28027, "s": 28000, "text": "Python dictionary-programs" }, { "code": null, "e": 28039, "s": 28027, "text": "python-dict" }, { "code": null, "e": 28046, "s": 28039, "text": "Python" }, { "code": null, "e": 28058, "s": 28046, "text": "python-dict" }, { "code": null, "e": 28156, "s": 28058, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28188, "s": 28156, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28230, "s": 28188, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28272, "s": 28230, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28299, "s": 28272, "text": "Python Classes and Objects" }, { "code": null, "e": 28355, "s": 28299, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28377, "s": 28355, "text": "Defaultdict in Python" }, { "code": null, "e": 28416, "s": 28377, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28447, "s": 28416, "text": "Python | os.path.join() method" }, { "code": null, "e": 28476, "s": 28447, "text": "Create a directory in Python" } ]
Remove Multiple Columns from data.table in R - GeeksforGeeks
31 Aug, 2021 In this article, we are going to see how to remove multiple columns from data.table in the R Programming language. Create data.table for demonstration: R # load the data.table packagelibrary("data.table") # create a data.table with 4 columns# they are id,name,age and address data = data.table(id = c(1,2,3) , name = c("sravan","bobby","satwik"), age = c(23,21,17), address = c("kakumanu","ponnur","hyd")) # displaydata Output: Here we are going to remove multiple columns by using the index operator [] Syntax: data[ ,’:='(column1 = NULL, column2 = NULL, column n=NULL)] where data is the input data.table column is the columns to be removed := is the operator to be loaded in the data.table Example 1: R program to remove multiple columns from data.table R # load the data.table packagelibrary("data.table") # create a data.table with 4 columns# they are id,name,age and address data = data.table(id = c(1,2,3), name = c("sravan","bobby","satwik"), age = c(23,21,17), address = c("kakumanu","ponnur","hyd")) # remove age , name and address columnsdata[ ,':='(age = NULL, address = NULL, name=NULL)] # displaydata Output: Example 2: Remove only one column from data.table R # load the data.table packagelibrary("data.table") # create a data.table with 4 columns# they are id,name,age and address data = data.table(id = c(1,2,3), name = c("sravan","bobby","satwik"), age = c(23,21,17), address = c("kakumanu","ponnur","hyd")) # remove id columndata[ ,':='(id=NULL)] # displaydata Output: Example 3: R program to remove all columns R # load the data.table packagelibrary("data.table") # create a data.table with 4 columns# they are id,name,age and address data = data.table(id = c(1,2,3), name = c("sravan","bobby","satwik"), age = c(23,21,17), address = c("kakumanu","ponnur","hyd")) # remove all columnsdata[ ,':='(id=NULL,age = NULL, address = NULL, name=NULL)] # displaydata Output: Null data.table (0 rows and 0 cols) Picked R DataTable R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? How to import an Excel File into R ? Time Series Analysis in R R - if statement How to filter R dataframe by multiple conditions?
[ { "code": null, "e": 26487, "s": 26459, "text": "\n31 Aug, 2021" }, { "code": null, "e": 26602, "s": 26487, "text": "In this article, we are going to see how to remove multiple columns from data.table in the R Programming language." }, { "code": null, "e": 26639, "s": 26602, "text": "Create data.table for demonstration:" }, { "code": null, "e": 26641, "s": 26639, "text": "R" }, { "code": "# load the data.table packagelibrary(\"data.table\") # create a data.table with 4 columns# they are id,name,age and address data = data.table(id = c(1,2,3) , name = c(\"sravan\",\"bobby\",\"satwik\"), age = c(23,21,17), address = c(\"kakumanu\",\"ponnur\",\"hyd\")) # displaydata", "e": 26961, "s": 26641, "text": null }, { "code": null, "e": 26969, "s": 26961, "text": "Output:" }, { "code": null, "e": 27045, "s": 26969, "text": "Here we are going to remove multiple columns by using the index operator []" }, { "code": null, "e": 27115, "s": 27045, "text": "Syntax: data[ ,’:='(column1 = NULL, column2 = NULL, column n=NULL)] " }, { "code": null, "e": 27121, "s": 27115, "text": "where" }, { "code": null, "e": 27150, "s": 27121, "text": "data is the input data.table" }, { "code": null, "e": 27186, "s": 27150, "text": "column is the columns to be removed" }, { "code": null, "e": 27236, "s": 27186, "text": ":= is the operator to be loaded in the data.table" }, { "code": null, "e": 27300, "s": 27236, "text": "Example 1: R program to remove multiple columns from data.table" }, { "code": null, "e": 27302, "s": 27300, "text": "R" }, { "code": "# load the data.table packagelibrary(\"data.table\") # create a data.table with 4 columns# they are id,name,age and address data = data.table(id = c(1,2,3), name = c(\"sravan\",\"bobby\",\"satwik\"), age = c(23,21,17), address = c(\"kakumanu\",\"ponnur\",\"hyd\")) # remove age , name and address columnsdata[ ,':='(age = NULL, address = NULL, name=NULL)] # displaydata", "e": 27715, "s": 27302, "text": null }, { "code": null, "e": 27723, "s": 27715, "text": "Output:" }, { "code": null, "e": 27773, "s": 27723, "text": "Example 2: Remove only one column from data.table" }, { "code": null, "e": 27775, "s": 27773, "text": "R" }, { "code": "# load the data.table packagelibrary(\"data.table\") # create a data.table with 4 columns# they are id,name,age and address data = data.table(id = c(1,2,3), name = c(\"sravan\",\"bobby\",\"satwik\"), age = c(23,21,17), address = c(\"kakumanu\",\"ponnur\",\"hyd\")) # remove id columndata[ ,':='(id=NULL)] # displaydata", "e": 28137, "s": 27775, "text": null }, { "code": null, "e": 28145, "s": 28137, "text": "Output:" }, { "code": null, "e": 28188, "s": 28145, "text": "Example 3: R program to remove all columns" }, { "code": null, "e": 28190, "s": 28188, "text": "R" }, { "code": "# load the data.table packagelibrary(\"data.table\") # create a data.table with 4 columns# they are id,name,age and address data = data.table(id = c(1,2,3), name = c(\"sravan\",\"bobby\",\"satwik\"), age = c(23,21,17), address = c(\"kakumanu\",\"ponnur\",\"hyd\")) # remove all columnsdata[ ,':='(id=NULL,age = NULL, address = NULL, name=NULL)] # displaydata", "e": 28592, "s": 28190, "text": null }, { "code": null, "e": 28600, "s": 28592, "text": "Output:" }, { "code": null, "e": 28636, "s": 28600, "text": "Null data.table (0 rows and 0 cols)" }, { "code": null, "e": 28643, "s": 28636, "text": "Picked" }, { "code": null, "e": 28655, "s": 28643, "text": "R DataTable" }, { "code": null, "e": 28666, "s": 28655, "text": "R Language" }, { "code": null, "e": 28764, "s": 28666, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28816, "s": 28764, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 28851, "s": 28816, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 28889, "s": 28851, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 28947, "s": 28889, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 28990, "s": 28947, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 29039, "s": 28990, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 29076, "s": 29039, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 29102, "s": 29076, "text": "Time Series Analysis in R" }, { "code": null, "e": 29119, "s": 29102, "text": "R - if statement" } ]
Python | Langton's Ant - GeeksforGeeks
16 Oct, 2018 Langton’s Ant is a 4-state two-dimensional universal Turing machine. It was invented by Chris Langton in 1986. It is basically an ant, sitting on a square lattice of cells, which are initially white. The ant moves on the plane and changes the color of cells creating patterns on it. But the movement of the ant is not random; it follows the following set of rules : If the ant is on a black square, it turns right 90 degrees and moves forward one unit. If the ant is on a white square, it turns left 90 degrees and moves forward one unit. When the ant leaves a square, it inverts the color. As the ant starts, it creates a black and white pattern while moving. Initially, the changes are not distinctive but as we iterate it over and over again, a beautiful pattern emerges. But if we further increase the number of iterations (say ~ 10000), the ant starts repeating its path with a gradual shift, instead of making new patterns. Thus, we obtain a highway like pattern that is infinite. The ant keeps moving on that highway and gives the following pattern. Refer the visual explanation of Langton’s Ant from here. It helps to visualize how exactly the ant works. The Python-3 code for Langton’s Ant is given below : # importing turtle moduleimport turtle def langton(): # Initializing the Window window = turtle.Screen() window.bgcolor('white') window.screensize(1000,1000) # Contains the coordinate and colour maps = {} # Initializing the Ant ant = turtle.Turtle() # shape of the ant ant.shape('square') # size of the ant ant.shapesize(0.5) # speed of the ant ant.speed(10000) # gives the coordinate of the ant pos = coordinate(ant) while True: # distance the ant will move step = 10 if pos not in maps or maps[pos] == "white": #inverts the colour ant.fillcolor("black") #stamps a copy of the ant on the canvas ant.stamp() invert(maps, ant, "black") ant.right(90) #moves the ant forward ant.forward(step) pos = coordinate(ant) elif maps[pos] == "black": ant.fillcolor("white") invert(maps, ant, "white") ant.stamp() ant.left(90) ant.forward(step) pos = coordinate(ant) def invert(graph, ant, color): graph[coordinate(ant)] = color def coordinate(ant): return (round(ant.xcor()), round(ant.ycor())) langton() Output :Here, the white cells are denoted by ‘ ‘ (space) and the black cells are denoted by ‘•’ (dot). python-utility 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 ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25537, "s": 25509, "text": "\n16 Oct, 2018" }, { "code": null, "e": 25903, "s": 25537, "text": "Langton’s Ant is a 4-state two-dimensional universal Turing machine. It was invented by Chris Langton in 1986. It is basically an ant, sitting on a square lattice of cells, which are initially white. The ant moves on the plane and changes the color of cells creating patterns on it. But the movement of the ant is not random; it follows the following set of rules :" }, { "code": null, "e": 25990, "s": 25903, "text": "If the ant is on a black square, it turns right 90 degrees and moves forward one unit." }, { "code": null, "e": 26076, "s": 25990, "text": "If the ant is on a white square, it turns left 90 degrees and moves forward one unit." }, { "code": null, "e": 26128, "s": 26076, "text": "When the ant leaves a square, it inverts the color." }, { "code": null, "e": 26594, "s": 26128, "text": "As the ant starts, it creates a black and white pattern while moving. Initially, the changes are not distinctive but as we iterate it over and over again, a beautiful pattern emerges. But if we further increase the number of iterations (say ~ 10000), the ant starts repeating its path with a gradual shift, instead of making new patterns. Thus, we obtain a highway like pattern that is infinite. The ant keeps moving on that highway and gives the following pattern." }, { "code": null, "e": 26700, "s": 26594, "text": "Refer the visual explanation of Langton’s Ant from here. It helps to visualize how exactly the ant works." }, { "code": null, "e": 26753, "s": 26700, "text": "The Python-3 code for Langton’s Ant is given below :" }, { "code": "# importing turtle moduleimport turtle def langton(): # Initializing the Window window = turtle.Screen() window.bgcolor('white') window.screensize(1000,1000) # Contains the coordinate and colour maps = {} # Initializing the Ant ant = turtle.Turtle() # shape of the ant ant.shape('square') # size of the ant ant.shapesize(0.5) # speed of the ant ant.speed(10000) # gives the coordinate of the ant pos = coordinate(ant) while True: # distance the ant will move step = 10 if pos not in maps or maps[pos] == \"white\": #inverts the colour ant.fillcolor(\"black\") #stamps a copy of the ant on the canvas ant.stamp() invert(maps, ant, \"black\") ant.right(90) #moves the ant forward ant.forward(step) pos = coordinate(ant) elif maps[pos] == \"black\": ant.fillcolor(\"white\") invert(maps, ant, \"white\") ant.stamp() ant.left(90) ant.forward(step) pos = coordinate(ant) def invert(graph, ant, color): graph[coordinate(ant)] = color def coordinate(ant): return (round(ant.xcor()), round(ant.ycor())) langton()", "e": 28301, "s": 26753, "text": null }, { "code": null, "e": 28404, "s": 28301, "text": "Output :Here, the white cells are denoted by ‘ ‘ (space) and the black cells are denoted by ‘•’ (dot)." }, { "code": null, "e": 28419, "s": 28404, "text": "python-utility" }, { "code": null, "e": 28426, "s": 28419, "text": "Python" }, { "code": null, "e": 28442, "s": 28426, "text": "Python Programs" }, { "code": null, "e": 28540, "s": 28442, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28572, "s": 28540, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28614, "s": 28572, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28656, "s": 28614, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28683, "s": 28656, "text": "Python Classes and Objects" }, { "code": null, "e": 28739, "s": 28683, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28761, "s": 28739, "text": "Defaultdict in Python" }, { "code": null, "e": 28800, "s": 28761, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28846, "s": 28800, "text": "Python | Split string into list of characters" }, { "code": null, "e": 28884, "s": 28846, "text": "Python | Convert a list to dictionary" } ]
Different ways to fetch data using API in React - GeeksforGeeks
23 Nov, 2021 ReactJS: ReactJS is a declarative, efficient, and flexible JavaScript library for building user interfaces. It’s ‘V’ in MVC. ReactJS is an open-source, component-based front-end library responsible only for the view layer of the application. It is maintained by Facebook. API: API is an abbreviation for Application Programming Interface which is a collection of communication protocols and subroutines used by various programs to communicate between them. A programmer can make use of various API tools to make its program easier and simpler. Also, an API facilitates the programmers with an efficient way to develop their software programs. In this article, we will know how we fetch the data from API (Application Programming Interface). For the data, we have used the API endpoint from http://jsonplaceholder.typicode.com/users Approach: In this article, we will know how we fetch the data from API (Application Programming Interface). For the data, we have used the API endpoint from https://jsonplaceholder.typicode.com/todos we have created the component in App.js. From the API we have target “userId”, “id”, “title”, “completed” and fetch the data from API endpoints. Below is the stepwise implementation of how we fetch the data from an API using 3 different ways in react. Step 1: Create React Project npx create-react-app apis Step 2: Change your directory and enter your main folder charting as cd apis Step 3: Write code in App.js to fetch data from API. Project Structure: It will look the following. Project Structure Now we have 3 ways to fetch data from an API 1. fetch method: The fetch() method in JavaScript is used to request to the server and load the information in the webpages. The request can be of any APIs that return the data of the format JSON or XML. This method returns a promise. App.js import {useEffect} from "react"; function App() { useEffect(() => { fetch('https://jsonplaceholder.typicode.com/todos') .then(response => response.json()) .then(json => console.log(json)) }, []); return ( <div> Different ways to fetch Data </div> );} export default App; Step to run the application: Open the terminal and type the following command. npm start Output: Now open localhost:300 and in the console, the data is fetched. 2. Axios Package: Axios is a promise-based HTTP client designed for Node.js and browsers. With Axios, we can easily send asynchronous HTTP requests to REST APIs and perform create, read, update and delete operations. It is an open-source collaboration project hosted on Github. It can be imported in plain Javascript or with any library accordingly. To install Axios write the following command npm i axios App.js import {useEffect} from "react";import axios from "axios" function App() { useEffect(() => { axios.get("https://jsonplaceholder.typicode.com/todos") .then((response) => console.log(response.data)); }, []); return ( <div> Different ways to fetch Data </div> );} export default App; Step to run the application: Open the terminal and type the following command. npm start Output: Now open localhost:300 and in the console, the data is fetched. 3. Async-Await: This is the preferred way of fetching the data from an API. Async: It simply allows us to write promise-based code as if it was synchronous and it checks that we are not breaking the execution thread. It operates asynchronously via the event loop. Async functions will always return a value. Await: Await function is used to wait for the promise. It could be used within the async block only. It makes the code wait until the promise returns a result. It is used to prevent call-back hell and we can use it with Axios rather than the fetch method as Axios makes our code look cleaner and also makes it shorter(as we don’t need to convert to JSON format). App.js import {useEffect} from "react";import axios from "axios" function App() { useEffect(() => { (async () => { try { const result = await axios.get("https://jsonplaceholder.typicode.com/todos") console.log(result.data); } catch (error) { console.error(error); } })() }) return ( <div > Different ways to fetch Data </div> );} export default App; Step to run the application: Open the terminal and type the following command. npm start Output: Now open localhost:300 and in the console, the data is fetched. 4. Using Custom hook: Create one file(useFetch.js) for your custom hook which returns the state of important parameters like data, loading, and error. App.js file will import this hook Now write the following code: useFetch.js import { useEffect, useState } from "react";import axios from "axios"; function useFetch(url) { const [data, setData] = useState(""); const [loading, setLoading] = useState(false); const [error, setError] = useState(""); useEffect(() => { setLoading(true); axios .get(url) .then((response) => { setData(response.data); }) .catch((err) => { setError(err); }) .finally(() => { setLoading(false); }); }, [url]); const refetch = () => { setLoading(true); axios .get(url) .then((response) => { setData(response.data); }) .catch((err) => { setError(err); }) .finally(() => { setLoading(false); }); }; return { data, loading, error, refetch };} export default useFetch; Import the useFetch hook and pass the URL of the API endpoint from where you want to fetch data. App.js import {useEffect} from "react";import axios from "axios" function App() { const { data: dataInfo, loading, error, refetch } = useFetch( https://jsonplaceholder.typicode.com/todos ); return ( <div > Different ways to fetch data {console.log(data)} </div> );} export default App; Step to run the application: Open the terminal and type the following command. npm start Output: Now open localhost:300 and in the console, the data is fetched. React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ReactJS useNavigate() Hook How to set background images in ReactJS ? Axios in React: A Guide for Beginners How to create a table in ReactJS ? How to navigate on path by button click in react router ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26071, "s": 26043, "text": "\n23 Nov, 2021" }, { "code": null, "e": 26343, "s": 26071, "text": "ReactJS: ReactJS is a declarative, efficient, and flexible JavaScript library for building user interfaces. It’s ‘V’ in MVC. ReactJS is an open-source, component-based front-end library responsible only for the view layer of the application. It is maintained by Facebook." }, { "code": null, "e": 26861, "s": 26343, "text": "API: API is an abbreviation for Application Programming Interface which is a collection of communication protocols and subroutines used by various programs to communicate between them. A programmer can make use of various API tools to make its program easier and simpler. Also, an API facilitates the programmers with an efficient way to develop their software programs. In this article, we will know how we fetch the data from API (Application Programming Interface). For the data, we have used the API endpoint from" }, { "code": null, "e": 26903, "s": 26861, "text": "http://jsonplaceholder.typicode.com/users" }, { "code": null, "e": 27249, "s": 26903, "text": "Approach: In this article, we will know how we fetch the data from API (Application Programming Interface). For the data, we have used the API endpoint from https://jsonplaceholder.typicode.com/todos we have created the component in App.js. From the API we have target “userId”, “id”, “title”, “completed” and fetch the data from API endpoints." }, { "code": null, "e": 27357, "s": 27249, "text": "Below is the stepwise implementation of how we fetch the data from an API using 3 different ways in react. " }, { "code": null, "e": 27388, "s": 27357, "text": "Step 1: Create React Project " }, { "code": null, "e": 27414, "s": 27388, "text": "npx create-react-app apis" }, { "code": null, "e": 27483, "s": 27414, "text": "Step 2: Change your directory and enter your main folder charting as" }, { "code": null, "e": 27491, "s": 27483, "text": "cd apis" }, { "code": null, "e": 27544, "s": 27491, "text": "Step 3: Write code in App.js to fetch data from API." }, { "code": null, "e": 27592, "s": 27544, "text": "Project Structure: It will look the following." }, { "code": null, "e": 27610, "s": 27592, "text": "Project Structure" }, { "code": null, "e": 27655, "s": 27610, "text": "Now we have 3 ways to fetch data from an API" }, { "code": null, "e": 27890, "s": 27655, "text": "1. fetch method: The fetch() method in JavaScript is used to request to the server and load the information in the webpages. The request can be of any APIs that return the data of the format JSON or XML. This method returns a promise." }, { "code": null, "e": 27897, "s": 27890, "text": "App.js" }, { "code": "import {useEffect} from \"react\"; function App() { useEffect(() => { fetch('https://jsonplaceholder.typicode.com/todos') .then(response => response.json()) .then(json => console.log(json)) }, []); return ( <div> Different ways to fetch Data </div> );} export default App;", "e": 28203, "s": 27897, "text": null }, { "code": null, "e": 28282, "s": 28203, "text": "Step to run the application: Open the terminal and type the following command." }, { "code": null, "e": 28292, "s": 28282, "text": "npm start" }, { "code": null, "e": 28364, "s": 28292, "text": "Output: Now open localhost:300 and in the console, the data is fetched." }, { "code": null, "e": 28715, "s": 28364, "text": "2. Axios Package: Axios is a promise-based HTTP client designed for Node.js and browsers. With Axios, we can easily send asynchronous HTTP requests to REST APIs and perform create, read, update and delete operations. It is an open-source collaboration project hosted on Github. It can be imported in plain Javascript or with any library accordingly. " }, { "code": null, "e": 28760, "s": 28715, "text": "To install Axios write the following command" }, { "code": null, "e": 28772, "s": 28760, "text": "npm i axios" }, { "code": null, "e": 28779, "s": 28772, "text": "App.js" }, { "code": "import {useEffect} from \"react\";import axios from \"axios\" function App() { useEffect(() => { axios.get(\"https://jsonplaceholder.typicode.com/todos\") .then((response) => console.log(response.data)); }, []); return ( <div> Different ways to fetch Data </div> );} export default App;", "e": 29093, "s": 28779, "text": null }, { "code": null, "e": 29172, "s": 29093, "text": "Step to run the application: Open the terminal and type the following command." }, { "code": null, "e": 29183, "s": 29172, "text": "npm start " }, { "code": null, "e": 29255, "s": 29183, "text": "Output: Now open localhost:300 and in the console, the data is fetched." }, { "code": null, "e": 29331, "s": 29255, "text": "3. Async-Await: This is the preferred way of fetching the data from an API." }, { "code": null, "e": 29563, "s": 29331, "text": "Async: It simply allows us to write promise-based code as if it was synchronous and it checks that we are not breaking the execution thread. It operates asynchronously via the event loop. Async functions will always return a value." }, { "code": null, "e": 29926, "s": 29563, "text": "Await: Await function is used to wait for the promise. It could be used within the async block only. It makes the code wait until the promise returns a result. It is used to prevent call-back hell and we can use it with Axios rather than the fetch method as Axios makes our code look cleaner and also makes it shorter(as we don’t need to convert to JSON format)." }, { "code": null, "e": 29933, "s": 29926, "text": "App.js" }, { "code": "import {useEffect} from \"react\";import axios from \"axios\" function App() { useEffect(() => { (async () => { try { const result = await axios.get(\"https://jsonplaceholder.typicode.com/todos\") console.log(result.data); } catch (error) { console.error(error); } })() }) return ( <div > Different ways to fetch Data </div> );} export default App;", "e": 30342, "s": 29933, "text": null }, { "code": null, "e": 30421, "s": 30342, "text": "Step to run the application: Open the terminal and type the following command." }, { "code": null, "e": 30431, "s": 30421, "text": "npm start" }, { "code": null, "e": 30503, "s": 30431, "text": "Output: Now open localhost:300 and in the console, the data is fetched." }, { "code": null, "e": 30688, "s": 30503, "text": "4. Using Custom hook: Create one file(useFetch.js) for your custom hook which returns the state of important parameters like data, loading, and error. App.js file will import this hook" }, { "code": null, "e": 30718, "s": 30688, "text": "Now write the following code:" }, { "code": null, "e": 30730, "s": 30718, "text": "useFetch.js" }, { "code": "import { useEffect, useState } from \"react\";import axios from \"axios\"; function useFetch(url) { const [data, setData] = useState(\"\"); const [loading, setLoading] = useState(false); const [error, setError] = useState(\"\"); useEffect(() => { setLoading(true); axios .get(url) .then((response) => { setData(response.data); }) .catch((err) => { setError(err); }) .finally(() => { setLoading(false); }); }, [url]); const refetch = () => { setLoading(true); axios .get(url) .then((response) => { setData(response.data); }) .catch((err) => { setError(err); }) .finally(() => { setLoading(false); }); }; return { data, loading, error, refetch };} export default useFetch;", "e": 31533, "s": 30730, "text": null }, { "code": null, "e": 31630, "s": 31533, "text": "Import the useFetch hook and pass the URL of the API endpoint from where you want to fetch data." }, { "code": null, "e": 31637, "s": 31630, "text": "App.js" }, { "code": "import {useEffect} from \"react\";import axios from \"axios\" function App() { const { data: dataInfo, loading, error, refetch } = useFetch( https://jsonplaceholder.typicode.com/todos ); return ( <div > Different ways to fetch data {console.log(data)} </div> );} export default App;", "e": 31949, "s": 31637, "text": null }, { "code": null, "e": 32028, "s": 31949, "text": "Step to run the application: Open the terminal and type the following command." }, { "code": null, "e": 32038, "s": 32028, "text": "npm start" }, { "code": null, "e": 32110, "s": 32038, "text": "Output: Now open localhost:300 and in the console, the data is fetched." }, { "code": null, "e": 32126, "s": 32110, "text": "React-Questions" }, { "code": null, "e": 32134, "s": 32126, "text": "ReactJS" }, { "code": null, "e": 32151, "s": 32134, "text": "Web Technologies" }, { "code": null, "e": 32249, "s": 32151, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32276, "s": 32249, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 32318, "s": 32276, "text": "How to set background images in ReactJS ?" }, { "code": null, "e": 32356, "s": 32318, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 32391, "s": 32356, "text": "How to create a table in ReactJS ?" }, { "code": null, "e": 32449, "s": 32391, "text": "How to navigate on path by button click in react router ?" }, { "code": null, "e": 32489, "s": 32449, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 32522, "s": 32489, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 32567, "s": 32522, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 32617, "s": 32567, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Difference between Relative and Absolute Deadline of Real-time Task - GeeksforGeeks
28 Jan, 2022 1. Relative Deadline :The time interval between the start of the task and the completion of the real-time task is known as Relative deadline. It is basically the time interval between arrival and corresponding deadline of the real-time task.If the arrival time of task is ‘t’ and corresponding deadline of task is ‘t+d’ then, Relative deadline = d 2. Absolute Deadline :The time interval between the time 0 and the completion of the real-time task is known as Absolute deadline. It is basically the time interval between time 0 and corresponding deadline of the real-time task.If the arrival time is ‘t’ and corresponding deadline of task is ‘t+d’ then, Absolute deadline = t+d Difference between Relative and Absolute Deadline of Real-time task : shivambhat45 Difference Between Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Difference between Prim's and Kruskal's algorithm for MST Difference between Internal and External fragmentation Difference between Compile-time and Run-time Polymorphism in Java Banker's Algorithm in Operating System Types of Operating Systems Page Replacement Algorithms in Operating Systems Program for FCFS CPU Scheduling | Set 1 Paging in Operating System
[ { "code": null, "e": 26103, "s": 26075, "text": "\n28 Jan, 2022" }, { "code": null, "e": 26429, "s": 26103, "text": "1. Relative Deadline :The time interval between the start of the task and the completion of the real-time task is known as Relative deadline. It is basically the time interval between arrival and corresponding deadline of the real-time task.If the arrival time of task is ‘t’ and corresponding deadline of task is ‘t+d’ then," }, { "code": null, "e": 26452, "s": 26429, "text": "Relative deadline = d " }, { "code": null, "e": 26758, "s": 26452, "text": "2. Absolute Deadline :The time interval between the time 0 and the completion of the real-time task is known as Absolute deadline. It is basically the time interval between time 0 and corresponding deadline of the real-time task.If the arrival time is ‘t’ and corresponding deadline of task is ‘t+d’ then," }, { "code": null, "e": 26783, "s": 26758, "text": "Absolute deadline = t+d " }, { "code": null, "e": 26853, "s": 26783, "text": "Difference between Relative and Absolute Deadline of Real-time task :" }, { "code": null, "e": 26866, "s": 26853, "text": "shivambhat45" }, { "code": null, "e": 26885, "s": 26866, "text": "Difference Between" }, { "code": null, "e": 26903, "s": 26885, "text": "Operating Systems" }, { "code": null, "e": 26921, "s": 26903, "text": "Operating Systems" }, { "code": null, "e": 27019, "s": 26921, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27080, "s": 27019, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27148, "s": 27080, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 27206, "s": 27148, "text": "Difference between Prim's and Kruskal's algorithm for MST" }, { "code": null, "e": 27261, "s": 27206, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 27327, "s": 27261, "text": "Difference between Compile-time and Run-time Polymorphism in Java" }, { "code": null, "e": 27366, "s": 27327, "text": "Banker's Algorithm in Operating System" }, { "code": null, "e": 27393, "s": 27366, "text": "Types of Operating Systems" }, { "code": null, "e": 27442, "s": 27393, "text": "Page Replacement Algorithms in Operating Systems" }, { "code": null, "e": 27482, "s": 27442, "text": "Program for FCFS CPU Scheduling | Set 1" } ]
Python | Pandas dataframe.at_time() - GeeksforGeeks
06 Aug, 2021 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.Pandasdataframe.at_time() function is used to select all the values in a row corresponding to the input time of the day. If the input time is not present in the dataframe then an empty dataframe is returned. Syntax: DataFrame.at_time(time, asof=False)Parameters: time : datetime.time or stringReturns: values_at_time : type of caller Note: at_time() function raises exception when the index of the dataframe is not a DatetimeIndexExample #1: Create a datetime indexed dataframe and retrieve the values at any specific time Python3 # importing pandas as pdimport pandas as pd # Creating row index values for dataframe# Taken time frequency to be of 12 hours interval # Generating five index value using "period = 5" parameterind = pd.date_range('01/ 01/2000', periods = 5, freq ='12H') # Creating a dataframe with 2 columns# using "ind" as the index for our dataframe df = pd.DataFrame({"A":[1, 2, 3, 4, 5], "B":[10, 20, 30, 40, 50]}, index = ind) # Printing the dataframe# for visualizationdf Now find out the values at time “12:00” Python3 df.at_time('12:00') Output : Example #2: Set the frequency of date_time index for 30 minute duration and query for both valid and invalid time (Not present in the dataframe) . Python3 # importing pandas as pdimport pandas as pd # Creating row index values for our data frame# We have taken time frequency to be of 30 minutes interval# We are generating eight index value using "period = 8" parameter ind = pd.date_range('01/01/2000', periods = 8, freq ='30T') # Creating a dataframe with 2 columns# using "ind" as the index for our dataframedf = pd.DataFrame({"A":[1, 2, 3, 4, 5, 6, 7, 8], "B":[10, 20, 30, 40, 50, 60, 70, 80]}, index = ind) # Printing the dataframedf Now let’s query for time “02:00” Python3 # Find the row values at time "02:00"df.at_time('02:00') Output : saurabh1990aror Python pandas-dataFrame Python pandas-dataFrame-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Convert integer to string in Python Check if element exists in list in Python
[ { "code": null, "e": 25701, "s": 25673, "text": "\n06 Aug, 2021" }, { "code": null, "e": 26123, "s": 25701, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.Pandasdataframe.at_time() function is used to select all the values in a row corresponding to the input time of the day. If the input time is not present in the dataframe then an empty dataframe is returned. " }, { "code": null, "e": 26250, "s": 26123, "text": "Syntax: DataFrame.at_time(time, asof=False)Parameters: time : datetime.time or stringReturns: values_at_time : type of caller " }, { "code": null, "e": 26441, "s": 26250, "text": "Note: at_time() function raises exception when the index of the dataframe is not a DatetimeIndexExample #1: Create a datetime indexed dataframe and retrieve the values at any specific time " }, { "code": null, "e": 26449, "s": 26441, "text": "Python3" }, { "code": "# importing pandas as pdimport pandas as pd # Creating row index values for dataframe# Taken time frequency to be of 12 hours interval # Generating five index value using \"period = 5\" parameterind = pd.date_range('01/ 01/2000', periods = 5, freq ='12H') # Creating a dataframe with 2 columns# using \"ind\" as the index for our dataframe df = pd.DataFrame({\"A\":[1, 2, 3, 4, 5], \"B\":[10, 20, 30, 40, 50]}, index = ind) # Printing the dataframe# for visualizationdf", "e": 26961, "s": 26449, "text": null }, { "code": null, "e": 27002, "s": 26961, "text": "Now find out the values at time “12:00” " }, { "code": null, "e": 27010, "s": 27002, "text": "Python3" }, { "code": "df.at_time('12:00')", "e": 27030, "s": 27010, "text": null }, { "code": null, "e": 27041, "s": 27030, "text": "Output : " }, { "code": null, "e": 27190, "s": 27041, "text": " Example #2: Set the frequency of date_time index for 30 minute duration and query for both valid and invalid time (Not present in the dataframe) . " }, { "code": null, "e": 27198, "s": 27190, "text": "Python3" }, { "code": "# importing pandas as pdimport pandas as pd # Creating row index values for our data frame# We have taken time frequency to be of 30 minutes interval# We are generating eight index value using \"period = 8\" parameter ind = pd.date_range('01/01/2000', periods = 8, freq ='30T') # Creating a dataframe with 2 columns# using \"ind\" as the index for our dataframedf = pd.DataFrame({\"A\":[1, 2, 3, 4, 5, 6, 7, 8], \"B\":[10, 20, 30, 40, 50, 60, 70, 80]}, index = ind) # Printing the dataframedf", "e": 27745, "s": 27198, "text": null }, { "code": null, "e": 27779, "s": 27745, "text": "Now let’s query for time “02:00” " }, { "code": null, "e": 27787, "s": 27779, "text": "Python3" }, { "code": "# Find the row values at time \"02:00\"df.at_time('02:00')", "e": 27844, "s": 27787, "text": null }, { "code": null, "e": 27855, "s": 27844, "text": "Output : " }, { "code": null, "e": 27873, "s": 27857, "text": "saurabh1990aror" }, { "code": null, "e": 27897, "s": 27873, "text": "Python pandas-dataFrame" }, { "code": null, "e": 27929, "s": 27897, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 27943, "s": 27929, "text": "Python-pandas" }, { "code": null, "e": 27950, "s": 27943, "text": "Python" }, { "code": null, "e": 28048, "s": 27950, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28066, "s": 28048, "text": "Python Dictionary" }, { "code": null, "e": 28098, "s": 28066, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28120, "s": 28098, "text": "Enumerate() in Python" }, { "code": null, "e": 28162, "s": 28120, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28188, "s": 28162, "text": "Python String | replace()" }, { "code": null, "e": 28217, "s": 28188, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28261, "s": 28217, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 28298, "s": 28261, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28334, "s": 28298, "text": "Convert integer to string in Python" } ]
restore command in Linux with Examples - GeeksforGeeks
24 May, 2019 restore command in Linux system is used for restoring files from a backup created using dump. The restore command performs the exact inverse function of dump. A full backup of a file system is being restored and subsequent incremental backups layered is being kept on top of it. Single files and directory subtrees can easily be restored from full or partial backups. Restore simply works across a network. Other arguments which need to be pass to the command are file or directory names specifying the files that need to be restored. Syntax: restore -C [-cdHklMvVy] [-b blocksize] [-D filesystem] [-f file] [-F script] [-L limit] [-s fileno] [-T directory] Example: It will be going to print the general syntax of the command along with the various options that can be used with the restore command. Options: restore -a: In -i o -x mode, restore will ask the user for the volume number on which the files needs to be extracted. The -a option simply disables this behavior and reads all the volumes starting with 1. restore -c: Normally, restore will try to determine dynamically whether the dump was made out of an old or from a new format file system. The -c flag simply disables this check, and it only allows reading a dump with the method of the old format. restore -d: The -d (debug) flag causes the restore to print all the debug information. restore -f: This option read the backup from the file that can be a special device file like /devfffrrr5/st0, /dev/sda1 (a disk drive) etc. restore -h: Extract the actual directory, rather than the files which is being referencing. This prevents the hierarchical restoration of complete subtrees from the dump. restore -C: This flag allows comparison of files from a dump. Restore command reads the backup and compares it’s with the contents of files present on the disk. restore -i: This flag allows the interactive restoration of files from a dump. After reading the directory information from the dump, restore command provides a shell-like interface which simply allows the user to move around the directory tree selecting files to be extracted. restore -P file: Restore creates a new Quickly File Access file from an existing dump file without any kind of restoring its contents. restore -R: Restore requests a particular tape of the multi-volume set to restart a full restore (see the -r flag below). This is proven useful if the restore has been interrupted. restore -r: Restore a file system. The target file system needs to be made pristine with mke2fs(8), mounted, and the user cd’d into a pristine file system before starting the restoration of the initial level 0 backup. restore -t: The names of the specified files are being listed if they occur on the backup. If no file argument is already given, the root directory is listed by default. restore -x: The names of the files are read from the given media. If a named file matches a particular directory whose contents are on the backup and the -h flag is not specified, the directory is then recursively extracted. restore -k: Uses the Kerberos authentication when contacting the remote tape server (Only available if this option was already enabled when restore was compiled). restore -l: When we are doing remote restores, then assume the remote file is a regular file (instead of a tape device). If you’re supposed to be restoring a remote compressed file, then you will need to specify this option or restore will fail to access it correctly. restore -m: Extracted by the inode numbers rather than by file name. This is proven useful if only a few files are being extracted, and one wants to avoid the regenerating to be completed pathname to the file. restore -m: Simply enables the multi-volume feature (for reading dumps made using the -M option of dump). The name must be specified with -f which is treated as a prefix and restore tries to read in the sequence from 001, 002 etc. restore -N: The -N flag causes the restore to perform a full execution as requested by one of the -i, -R, -r, t or x command without actually writing any file on the disk. restore -o: The -o flag causes the restore to automatically restore the current directory permissions without asking for the operator whether he needs to do so in one of -i or -x modes. restore -Q file: Use the file in order to read the tape position. restore -u: Whenever certain types of files are created, restore may generate a warning diagnostic if they already exist in the target directory. To prevent this, the -u (unlink) flag can causes restore to remove the old entries before attempting to create new ones. restore -v: Normally restore does his work silently under the hood. The -v (verbose) flag causes it to type the name each of file it simply treats preceded by its file type. restore -V: Enables reading a multi-volume non-tape mediums like CDROMs. restore -y: Do not ask for the user whether to abort the restore in the event of an error. It always tries to skip over the bad block and then continue. Example: Let’s create a dumpsudo tar -xvpzf /home/server/backup.tar.gz -C / --numeric-owner sudo tar -xvpzf /home/server/backup.tar.gz -C / --numeric-owner Dump in progress. Let’s restore from the dump filesudo tar -cvpzf backup.tar.gz --exclude=/home/server/backup.tar.gz --one-file-system / sudo tar -cvpzf backup.tar.gz --exclude=/home/server/backup.tar.gz --one-file-system / Restore under progress. linux-command Linux-file-commands Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C curl command in Linux with Examples Conditional Statements | Shell Script UDP Server-Client implementation in C Tail command in Linux with examples Cat command in Linux with examples touch command in Linux with Examples echo command in Linux with Examples Compiling with g++ scp command in Linux with Examples
[ { "code": null, "e": 25293, "s": 25265, "text": "\n24 May, 2019" }, { "code": null, "e": 25828, "s": 25293, "text": "restore command in Linux system is used for restoring files from a backup created using dump. The restore command performs the exact inverse function of dump. A full backup of a file system is being restored and subsequent incremental backups layered is being kept on top of it. Single files and directory subtrees can easily be restored from full or partial backups. Restore simply works across a network. Other arguments which need to be pass to the command are file or directory names specifying the files that need to be restored." }, { "code": null, "e": 25836, "s": 25828, "text": "Syntax:" }, { "code": null, "e": 25951, "s": 25836, "text": "restore -C [-cdHklMvVy] [-b blocksize] [-D filesystem] [-f file] [-F script] [-L limit] [-s fileno] [-T directory]" }, { "code": null, "e": 26094, "s": 25951, "text": "Example: It will be going to print the general syntax of the command along with the various options that can be used with the restore command." }, { "code": null, "e": 26103, "s": 26094, "text": "Options:" }, { "code": null, "e": 26309, "s": 26103, "text": "restore -a: In -i o -x mode, restore will ask the user for the volume number on which the files needs to be extracted. The -a option simply disables this behavior and reads all the volumes starting with 1." }, { "code": null, "e": 26556, "s": 26309, "text": "restore -c: Normally, restore will try to determine dynamically whether the dump was made out of an old or from a new format file system. The -c flag simply disables this check, and it only allows reading a dump with the method of the old format." }, { "code": null, "e": 26643, "s": 26556, "text": "restore -d: The -d (debug) flag causes the restore to print all the debug information." }, { "code": null, "e": 26783, "s": 26643, "text": "restore -f: This option read the backup from the file that can be a special device file like /devfffrrr5/st0, /dev/sda1 (a disk drive) etc." }, { "code": null, "e": 26954, "s": 26783, "text": "restore -h: Extract the actual directory, rather than the files which is being referencing. This prevents the hierarchical restoration of complete subtrees from the dump." }, { "code": null, "e": 27115, "s": 26954, "text": "restore -C: This flag allows comparison of files from a dump. Restore command reads the backup and compares it’s with the contents of files present on the disk." }, { "code": null, "e": 27393, "s": 27115, "text": "restore -i: This flag allows the interactive restoration of files from a dump. After reading the directory information from the dump, restore command provides a shell-like interface which simply allows the user to move around the directory tree selecting files to be extracted." }, { "code": null, "e": 27528, "s": 27393, "text": "restore -P file: Restore creates a new Quickly File Access file from an existing dump file without any kind of restoring its contents." }, { "code": null, "e": 27709, "s": 27528, "text": "restore -R: Restore requests a particular tape of the multi-volume set to restart a full restore (see the -r flag below). This is proven useful if the restore has been interrupted." }, { "code": null, "e": 27927, "s": 27709, "text": "restore -r: Restore a file system. The target file system needs to be made pristine with mke2fs(8), mounted, and the user cd’d into a pristine file system before starting the restoration of the initial level 0 backup." }, { "code": null, "e": 28097, "s": 27927, "text": "restore -t: The names of the specified files are being listed if they occur on the backup. If no file argument is already given, the root directory is listed by default." }, { "code": null, "e": 28322, "s": 28097, "text": "restore -x: The names of the files are read from the given media. If a named file matches a particular directory whose contents are on the backup and the -h flag is not specified, the directory is then recursively extracted." }, { "code": null, "e": 28485, "s": 28322, "text": "restore -k: Uses the Kerberos authentication when contacting the remote tape server (Only available if this option was already enabled when restore was compiled)." }, { "code": null, "e": 28754, "s": 28485, "text": "restore -l: When we are doing remote restores, then assume the remote file is a regular file (instead of a tape device). If you’re supposed to be restoring a remote compressed file, then you will need to specify this option or restore will fail to access it correctly." }, { "code": null, "e": 28964, "s": 28754, "text": "restore -m: Extracted by the inode numbers rather than by file name. This is proven useful if only a few files are being extracted, and one wants to avoid the regenerating to be completed pathname to the file." }, { "code": null, "e": 29195, "s": 28964, "text": "restore -m: Simply enables the multi-volume feature (for reading dumps made using the -M option of dump). The name must be specified with -f which is treated as a prefix and restore tries to read in the sequence from 001, 002 etc." }, { "code": null, "e": 29367, "s": 29195, "text": "restore -N: The -N flag causes the restore to perform a full execution as requested by one of the -i, -R, -r, t or x command without actually writing any file on the disk." }, { "code": null, "e": 29553, "s": 29367, "text": "restore -o: The -o flag causes the restore to automatically restore the current directory permissions without asking for the operator whether he needs to do so in one of -i or -x modes." }, { "code": null, "e": 29619, "s": 29553, "text": "restore -Q file: Use the file in order to read the tape position." }, { "code": null, "e": 29886, "s": 29619, "text": "restore -u: Whenever certain types of files are created, restore may generate a warning diagnostic if they already exist in the target directory. To prevent this, the -u (unlink) flag can causes restore to remove the old entries before attempting to create new ones." }, { "code": null, "e": 30060, "s": 29886, "text": "restore -v: Normally restore does his work silently under the hood. The -v (verbose) flag causes it to type the name each of file it simply treats preceded by its file type." }, { "code": null, "e": 30133, "s": 30060, "text": "restore -V: Enables reading a multi-volume non-tape mediums like CDROMs." }, { "code": null, "e": 30286, "s": 30133, "text": "restore -y: Do not ask for the user whether to abort the restore in the event of an error. It always tries to skip over the bad block and then continue." }, { "code": null, "e": 30295, "s": 30286, "text": "Example:" }, { "code": null, "e": 30378, "s": 30295, "text": "Let’s create a dumpsudo tar -xvpzf /home/server/backup.tar.gz -C / --numeric-owner" }, { "code": null, "e": 30442, "s": 30378, "text": "sudo tar -xvpzf /home/server/backup.tar.gz -C / --numeric-owner" }, { "code": null, "e": 30460, "s": 30442, "text": "Dump in progress." }, { "code": null, "e": 30579, "s": 30460, "text": "Let’s restore from the dump filesudo tar -cvpzf backup.tar.gz --exclude=/home/server/backup.tar.gz --one-file-system /" }, { "code": null, "e": 30666, "s": 30579, "text": "sudo tar -cvpzf backup.tar.gz --exclude=/home/server/backup.tar.gz --one-file-system /" }, { "code": null, "e": 30690, "s": 30666, "text": "Restore under progress." }, { "code": null, "e": 30704, "s": 30690, "text": "linux-command" }, { "code": null, "e": 30724, "s": 30704, "text": "Linux-file-commands" }, { "code": null, "e": 30735, "s": 30724, "text": "Linux-Unix" }, { "code": null, "e": 30833, "s": 30735, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30871, "s": 30833, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 30907, "s": 30871, "text": "curl command in Linux with Examples" }, { "code": null, "e": 30945, "s": 30907, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 30983, "s": 30945, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 31019, "s": 30983, "text": "Tail command in Linux with examples" }, { "code": null, "e": 31054, "s": 31019, "text": "Cat command in Linux with examples" }, { "code": null, "e": 31091, "s": 31054, "text": "touch command in Linux with Examples" }, { "code": null, "e": 31127, "s": 31091, "text": "echo command in Linux with Examples" }, { "code": null, "e": 31146, "s": 31127, "text": "Compiling with g++" } ]
Numpy | Iterating Over Array - GeeksforGeeks
15 Nov, 2018 NumPy package contains an iterator object numpy.nditer. It is an efficient multidimensional iterator object using which it is possible to iterate over an array. Each element of an array is visited using Python’s standard Iterator interface. Output: Original array is: [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] Modified array is: 0 1 2 3 4 5 6 7 8 9 10 11 The order of iteration is chosen to match the memory layout of an array, without considering a particular ordering. This can be seen by iterating over the transpose of the above array. Output: Original array is: [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] Modified array is: 0 1 2 3 4 5 6 7 8 9 10 11 Controlling Iteration Order:There are times when it is important to visit the elements of an array in a specific order, irrespective of the layout of the elements in memory. The nditer object provides an order parameter to control this aspect of iteration. The default, having the behavior described above, is order=’K’ to keep the existing order. This can be overridden with order=’C’ for C order and order=’F’ for Fortran order. Code #1: Output: Original array is: [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] Modified array in C-style order: 0 1 2 3 4 5 6 7 8 9 10 11 Code #2: Output: Original array is: [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] Modified array in F-style order: 0 4 8 1 5 9 2 6 10 3 7 11 Modifying Array Values:The nditer object has another optional parameter called op_flags. Its default value is read-only, but can be set to read-write or write-only mode. This will enable modifying array elements using this iterator. Output: Original array is: [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] Modified array is: [[ 0 5 10 15] [20 25 30 35] [40 45 50 55]] External Loop: The nditer class constructor has a flags parameter, which can take the following values Code #1: Output: Original array is: [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] Modified array is: [ 0 1 2 3] [ 4 5 6 7] [8 9 10 11] Code #2: Output: Original array is: [[ 0 1 2] [ 3 4 5]] 0 <0> 1 <2> 2 <4> 3 <1> 4 <3> 5 <5> Broadcasting Iteration:If two arrays are broadcastable, a combined nditer object is able to iterate upon them concurrently. Assuming that an array a has dimension 3X4, and there is another array b of dimension 1X4, the iterator of following type is used (array b is broadcast to size of a). Output: First array is: [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] Second array is: [5 6 7 8] Modified array is: 0:5 1:6 2:7 3:8 4:5 5:6 6:7 7:8 8:5 9:6 10:7 11:8 Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Java Program for Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph) Python Program for Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph) Java Program for Depth First Search or DFS for a Graph Python Program for Depth First Search or DFS for a Graph Java Program for Breadth First Search or BFS for a Graph Python Program for Breadth First Search or BFS for a Graph C Program for Coin Change | DP-7 Java Program for Coin Change | DP-7 PHP Program for Coin Change | DP-7 C Program for Find the number of islands | Set 1 (Using DFS)
[ { "code": null, "e": 42651, "s": 42623, "text": "\n15 Nov, 2018" }, { "code": null, "e": 42892, "s": 42651, "text": "NumPy package contains an iterator object numpy.nditer. It is an efficient multidimensional iterator object using which it is possible to iterate over an array. Each element of an array is visited using Python’s standard Iterator interface." }, { "code": null, "e": 42900, "s": 42892, "text": "Output:" }, { "code": null, "e": 43005, "s": 42900, "text": "Original array is:\n[[ 0 1 2 3]\n [ 4 5 6 7]\n [ 8 9 10 11]]\n\nModified array is:\n0 1 2 3 4 5 6 7 8 9 10 11\n" }, { "code": null, "e": 43190, "s": 43005, "text": "The order of iteration is chosen to match the memory layout of an array, without considering a particular ordering. This can be seen by iterating over the transpose of the above array." }, { "code": null, "e": 43198, "s": 43190, "text": "Output:" }, { "code": null, "e": 43303, "s": 43198, "text": "Original array is:\n[[ 0 1 2 3]\n [ 4 5 6 7]\n [ 8 9 10 11]]\n\nModified array is:\n0 1 2 3 4 5 6 7 8 9 10 11\n" }, { "code": null, "e": 43736, "s": 43305, "text": "Controlling Iteration Order:There are times when it is important to visit the elements of an array in a specific order, irrespective of the layout of the elements in memory. The nditer object provides an order parameter to control this aspect of iteration. The default, having the behavior described above, is order=’K’ to keep the existing order. This can be overridden with order=’C’ for C order and order=’F’ for Fortran order." }, { "code": null, "e": 43745, "s": 43736, "text": "Code #1:" }, { "code": null, "e": 43753, "s": 43745, "text": "Output:" }, { "code": null, "e": 43872, "s": 43753, "text": "Original array is:\n[[ 0 1 2 3]\n [ 4 5 6 7]\n [ 8 9 10 11]]\n\nModified array in C-style order:\n0 1 2 3 4 5 6 7 8 9 10 11\n" }, { "code": null, "e": 43882, "s": 43872, "text": " Code #2:" }, { "code": null, "e": 43890, "s": 43882, "text": "Output:" }, { "code": null, "e": 44009, "s": 43890, "text": "Original array is:\n[[ 0 1 2 3]\n [ 4 5 6 7]\n [ 8 9 10 11]]\n\nModified array in F-style order:\n0 4 8 1 5 9 2 6 10 3 7 11\n" }, { "code": null, "e": 44244, "s": 44011, "text": "Modifying Array Values:The nditer object has another optional parameter called op_flags. Its default value is read-only, but can be set to read-write or write-only mode. This will enable modifying array elements using this iterator." }, { "code": null, "e": 44252, "s": 44244, "text": "Output:" }, { "code": null, "e": 44376, "s": 44252, "text": "Original array is:\n[[ 0 1 2 3]\n [ 4 5 6 7]\n [ 8 9 10 11]]\n\nModified array is:\n[[ 0 5 10 15]\n [20 25 30 35]\n [40 45 50 55]]\n" }, { "code": null, "e": 44393, "s": 44378, "text": "External Loop:" }, { "code": null, "e": 44481, "s": 44393, "text": "The nditer class constructor has a flags parameter, which can take the following values" }, { "code": null, "e": 44490, "s": 44481, "text": "Code #1:" }, { "code": null, "e": 44498, "s": 44490, "text": "Output:" }, { "code": null, "e": 44612, "s": 44498, "text": "Original array is:\n[[ 0 1 2 3]\n [ 4 5 6 7]\n [ 8 9 10 11]]\n\nModified array is:\n[ 0 1 2 3] [ 4 5 6 7] [8 9 10 11] \n" }, { "code": null, "e": 44623, "s": 44614, "text": "Code #2:" }, { "code": null, "e": 44631, "s": 44623, "text": "Output:" }, { "code": null, "e": 44709, "s": 44631, "text": "Original array is:\n[[ 0 1 2]\n [ 3 4 5]]\n\n0 <0> 1 <2> 2 <4> 3 <1> 4 <3> 5 <5>\n" }, { "code": null, "e": 45002, "s": 44711, "text": "Broadcasting Iteration:If two arrays are broadcastable, a combined nditer object is able to iterate upon them concurrently. Assuming that an array a has dimension 3X4, and there is another array b of dimension 1X4, the iterator of following type is used (array b is broadcast to size of a)." }, { "code": null, "e": 45010, "s": 45002, "text": "Output:" }, { "code": null, "e": 45164, "s": 45010, "text": "First array is:\n[[ 0 1 2 3]\n [ 4 5 6 7]\n [ 8 9 10 11]]\n\nSecond array is:\n[5 6 7 8]\n\nModified array is:\n0:5 1:6 2:7 3:8 4:5 5:6 6:7 7:8 8:5 9:6 10:7 11:8\n" }, { "code": null, "e": 45264, "s": 45166, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 45356, "s": 45264, "text": "Java Program for Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)" }, { "code": null, "e": 45450, "s": 45356, "text": "Python Program for Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)" }, { "code": null, "e": 45505, "s": 45450, "text": "Java Program for Depth First Search or DFS for a Graph" }, { "code": null, "e": 45562, "s": 45505, "text": "Python Program for Depth First Search or DFS for a Graph" }, { "code": null, "e": 45619, "s": 45562, "text": "Java Program for Breadth First Search or BFS for a Graph" }, { "code": null, "e": 45678, "s": 45619, "text": "Python Program for Breadth First Search or BFS for a Graph" }, { "code": null, "e": 45711, "s": 45678, "text": "C Program for Coin Change | DP-7" }, { "code": null, "e": 45747, "s": 45711, "text": "Java Program for Coin Change | DP-7" }, { "code": null, "e": 45782, "s": 45747, "text": "PHP Program for Coin Change | DP-7" } ]
How to Install Numpy on Linux? - GeeksforGeeks
30 Sep, 2021 Python NumPy is a general-purpose array processing package that provides tools for handling n-dimensional arrays. It provides various computing tools such as comprehensive mathematical functions, linear algebra routines. NumPy provides both the flexibility of Python and the speed of well-optimized compiled C code. Its easy-to-use syntax makes it highly accessible and productive for programmers from any background. The only thing that you need for installing Numpy on Windows are: Python PIP or Conda (Depending upon the user preference) If you want the installation to be done through conda, you can use the below command: conda install -c anaconda numpy Type in “y” for yes when prompted. You will get a similar message once the installation is complete Make sure you follow the best practices for installation using conda as: Use an environment for installation rather than in the base environment using the below command: conda create -n my-env conda activate my-env Note: If your preferred method of installation is conda-forge, use the below command: conda config --env --add channels conda-forge Use the below command to verify if the above package has successfully installed: conda list numpy You will get a similar message as shown below if the installation has been successful: Users who prefer to use pip can use the below command to install NumPy: pip install numpy You will get a similar message once the installation is complete: It is a good programming practice to install packages in a virtual environment rather than installing them globally. PIP users can use the below command to create a virtual environment: python3 -m venv my-env Activate the virtual environment (ie, my-env) using the below command: source my-env/bin/activate Use the below command to check if the package has been successfully installed: python3 -m pip show numpy You will get a similar message as shown below if the installation is successful: how-to-install Picked How To Installation Guide Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install FFmpeg on Windows? How to Add External JAR File to an IntelliJ IDEA Project? How to Set Git Username and Password in GitBash? How to create a nested RecyclerView in Android How to Install Jupyter Notebook on MacOS? Installation of Node.js on Linux How to Install FFmpeg on Windows? How to Install Pygame on Windows ? How to Add External JAR File to an IntelliJ IDEA Project? How to Install Jupyter Notebook on MacOS?
[ { "code": null, "e": 26197, "s": 26169, "text": "\n30 Sep, 2021" }, { "code": null, "e": 26615, "s": 26197, "text": "Python NumPy is a general-purpose array processing package that provides tools for handling n-dimensional arrays. It provides various computing tools such as comprehensive mathematical functions, linear algebra routines. NumPy provides both the flexibility of Python and the speed of well-optimized compiled C code. Its easy-to-use syntax makes it highly accessible and productive for programmers from any background." }, { "code": null, "e": 26681, "s": 26615, "text": "The only thing that you need for installing Numpy on Windows are:" }, { "code": null, "e": 26688, "s": 26681, "text": "Python" }, { "code": null, "e": 26738, "s": 26688, "text": "PIP or Conda (Depending upon the user preference)" }, { "code": null, "e": 26824, "s": 26738, "text": "If you want the installation to be done through conda, you can use the below command:" }, { "code": null, "e": 26856, "s": 26824, "text": "conda install -c anaconda numpy" }, { "code": null, "e": 26891, "s": 26856, "text": "Type in “y” for yes when prompted." }, { "code": null, "e": 26956, "s": 26891, "text": "You will get a similar message once the installation is complete" }, { "code": null, "e": 27029, "s": 26956, "text": "Make sure you follow the best practices for installation using conda as:" }, { "code": null, "e": 27126, "s": 27029, "text": "Use an environment for installation rather than in the base environment using the below command:" }, { "code": null, "e": 27171, "s": 27126, "text": "conda create -n my-env\nconda activate my-env" }, { "code": null, "e": 27257, "s": 27171, "text": "Note: If your preferred method of installation is conda-forge, use the below command:" }, { "code": null, "e": 27303, "s": 27257, "text": "conda config --env --add channels conda-forge" }, { "code": null, "e": 27384, "s": 27303, "text": "Use the below command to verify if the above package has successfully installed:" }, { "code": null, "e": 27402, "s": 27384, "text": "conda list numpy " }, { "code": null, "e": 27489, "s": 27402, "text": "You will get a similar message as shown below if the installation has been successful:" }, { "code": null, "e": 27561, "s": 27489, "text": "Users who prefer to use pip can use the below command to install NumPy:" }, { "code": null, "e": 27579, "s": 27561, "text": "pip install numpy" }, { "code": null, "e": 27645, "s": 27579, "text": "You will get a similar message once the installation is complete:" }, { "code": null, "e": 27831, "s": 27645, "text": "It is a good programming practice to install packages in a virtual environment rather than installing them globally. PIP users can use the below command to create a virtual environment:" }, { "code": null, "e": 27854, "s": 27831, "text": "python3 -m venv my-env" }, { "code": null, "e": 27925, "s": 27854, "text": "Activate the virtual environment (ie, my-env) using the below command:" }, { "code": null, "e": 27952, "s": 27925, "text": "source my-env/bin/activate" }, { "code": null, "e": 28031, "s": 27952, "text": "Use the below command to check if the package has been successfully installed:" }, { "code": null, "e": 28057, "s": 28031, "text": "python3 -m pip show numpy" }, { "code": null, "e": 28138, "s": 28057, "text": "You will get a similar message as shown below if the installation is successful:" }, { "code": null, "e": 28153, "s": 28138, "text": "how-to-install" }, { "code": null, "e": 28160, "s": 28153, "text": "Picked" }, { "code": null, "e": 28167, "s": 28160, "text": "How To" }, { "code": null, "e": 28186, "s": 28167, "text": "Installation Guide" }, { "code": null, "e": 28284, "s": 28186, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28318, "s": 28284, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 28376, "s": 28318, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" }, { "code": null, "e": 28425, "s": 28376, "text": "How to Set Git Username and Password in GitBash?" }, { "code": null, "e": 28472, "s": 28425, "text": "How to create a nested RecyclerView in Android" }, { "code": null, "e": 28514, "s": 28472, "text": "How to Install Jupyter Notebook on MacOS?" }, { "code": null, "e": 28547, "s": 28514, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28581, "s": 28547, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 28616, "s": 28581, "text": "How to Install Pygame on Windows ?" }, { "code": null, "e": 28674, "s": 28616, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" } ]
Python | Using 2D arrays/lists the right way - GeeksforGeeks
15 Mar, 2021 Python provides many ways to create 2-dimensional lists/arrays. However one must know the differences between these ways because they can create complications in code that can be very difficult to trace out. Lets start by looking at common ways of creating 1d array of size N initialized with 0s. Method 1a Python3 # First method to create a 1 D arrayN = 5arr = [0]*Nprint(arr) [0, 0, 0, 0, 0] Method 1b Python3 # Second method to create a 1 D arrayN = 5arr = [0 for i in range(N)]print(arr) [0, 0, 0, 0, 0] Extending the above we can define 2-dimensional arrays in the following ways. Method 2a Python3 # Using above first method to create a# 2D arrayrows, cols = (5, 5)arr = [[0]*cols]*rowsprint(arr) [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] Method 2b Python3 # Using above second method to create a# 2D arrayrows, cols = (5, 5)arr = [[0 for i in range(cols)] for j in range(rows)]print(arr) [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] Method 2c Python3 # Using above second method to create a# 2D arrayrows, cols = (5, 5)arr=[]for i in range(rows): col = [] for j in range(cols): col.append(0) arr.append(col)print(arr) [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] Both the ways give seemingly same output as of now. Lets change one of the elements in the array of method 2a and method 2b. Python3 # Python 3 program to demonstrate working# of method 1 and method 2. rows, cols = (5, 5) # method 2aarr = [[0]*cols]*rows # lets change the first element of the# first row to 1 and print the arrayarr[0][0] = 1 for row in arr: print(row)# outputs the following#[1, 0, 0, 0, 0]#[1, 0, 0, 0, 0]#[1, 0, 0, 0, 0]#[1, 0, 0, 0, 0]#[1, 0, 0, 0, 0] # method 2barr = [[0 for i in range(cols)] for j in range(rows)] # again in this new array lets change# the first element of the first row# to 1 and print the arrayarr[0][0] = 1for row in arr: print(row) # outputs the following as expected#[1, 0, 0, 0, 0]#[0, 0, 0, 0, 0]#[0, 0, 0, 0, 0]#[0, 0, 0, 0, 0]#[0, 0, 0, 0, 0] [1, 0, 0, 0, 0] [1, 0, 0, 0, 0] [1, 0, 0, 0, 0] [1, 0, 0, 0, 0] [1, 0, 0, 0, 0] [1, 0, 0, 0, 0] [0, 0, 0, 0, 0] [0, 0, 0, 0, 0] [0, 0, 0, 0, 0] [0, 0, 0, 0, 0] We expect only the first element of first row to change to 1 but the first element of every row gets changed to 1 in method 2a. This peculiar functioning is because Python uses shallow lists which we will try to understand.In method 1a, Python doesn’t create 5 integer objects but creates only one integer object and all the indices of the array arr point to the same int object as shown. If we assign the 0th index to a another integer say 1, then a new integer object is created with the value of 1 and then the 0th index now points to this new int object as shown below Similarly, when we create a 2d array as “arr = [[0]*cols]*rows” we are essentially the extending the above analogy. 1. Only one integer object is created. 2. A single 1d list is created and all its indices point to the same int object in point 1. 3. Now, arr[0], arr[1], arr[2] .... arr[n-1] all point to the same list object above in point 2.The above setup can be visualized in the image below. Now lets change the first element in first row of “arr” as arr[0][0] = 1=> arr[0] points to the single list object we created we above.(Remember arr[1], arr[2] ...arr[n-1] all point to the same list object too) => The assignment of arr[0][0] will create a new int object with the value 1 and arr[0][0] will now point to this new int object.(and so will arr[1][0], arr[2][0] ...arr[n-1][0])This can be clearly seen in the below image. So when 2d arrays are created like this, changing values at a certain row will effect all the rows since there is essentially only one integer object and only one list object being referenced by the all the rows of the array.As you would expect, tracing out errors caused by such usage of shallow lists is difficult. Hence the better way to declare a 2d array is Python3 rows, cols = (5, 5)arr = [[0 for i in range(cols)] for j in range(rows)] This method creates 5 separate list objects unlike method 2a. One way to check this is using the ‘is’ operator which checks if the two operands refer to the same object. Python3 rows, cols = (5, 5)# method 2barr = [[0 for i in range(cols)] for j in range(rows)] # check if arr[0] and arr[1] refer to# the same objectprint(arr[0] is arr[1]) # prints False # method 2aarr = [[0]*cols]*rows # check if arr[0] and arr[1] refer to# the same object# prints True because there is only one# list object being created.print(arr[0] is arr[1]) False True amainaster ragulravi Python matrix-program Python-array Arrays Python Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Arrays Multidimensional Arrays in Java Linked List vs Array Search an element in a sorted and rotated array Array of Strings in C++ (5 Different Ways to Create) Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Taking input in Python
[ { "code": null, "e": 25625, "s": 25597, "text": "\n15 Mar, 2021" }, { "code": null, "e": 25934, "s": 25625, "text": "Python provides many ways to create 2-dimensional lists/arrays. However one must know the differences between these ways because they can create complications in code that can be very difficult to trace out. Lets start by looking at common ways of creating 1d array of size N initialized with 0s. Method 1a " }, { "code": null, "e": 25942, "s": 25934, "text": "Python3" }, { "code": "# First method to create a 1 D arrayN = 5arr = [0]*Nprint(arr)", "e": 26005, "s": 25942, "text": null }, { "code": null, "e": 26021, "s": 26005, "text": "[0, 0, 0, 0, 0]" }, { "code": null, "e": 26035, "s": 26023, "text": "Method 1b " }, { "code": null, "e": 26043, "s": 26035, "text": "Python3" }, { "code": "# Second method to create a 1 D arrayN = 5arr = [0 for i in range(N)]print(arr)", "e": 26123, "s": 26043, "text": null }, { "code": null, "e": 26139, "s": 26123, "text": "[0, 0, 0, 0, 0]" }, { "code": null, "e": 26231, "s": 26141, "text": "Extending the above we can define 2-dimensional arrays in the following ways. Method 2a " }, { "code": null, "e": 26239, "s": 26231, "text": "Python3" }, { "code": "# Using above first method to create a# 2D arrayrows, cols = (5, 5)arr = [[0]*cols]*rowsprint(arr)", "e": 26338, "s": 26239, "text": null }, { "code": null, "e": 26424, "s": 26338, "text": "[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]" }, { "code": null, "e": 26438, "s": 26426, "text": "Method 2b " }, { "code": null, "e": 26446, "s": 26438, "text": "Python3" }, { "code": "# Using above second method to create a# 2D arrayrows, cols = (5, 5)arr = [[0 for i in range(cols)] for j in range(rows)]print(arr)", "e": 26578, "s": 26446, "text": null }, { "code": null, "e": 26664, "s": 26578, "text": "[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]" }, { "code": null, "e": 26678, "s": 26666, "text": "Method 2c " }, { "code": null, "e": 26686, "s": 26678, "text": "Python3" }, { "code": "# Using above second method to create a# 2D arrayrows, cols = (5, 5)arr=[]for i in range(rows): col = [] for j in range(cols): col.append(0) arr.append(col)print(arr)", "e": 26869, "s": 26686, "text": null }, { "code": null, "e": 26955, "s": 26869, "text": "[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]" }, { "code": null, "e": 27084, "s": 26957, "text": "Both the ways give seemingly same output as of now. Lets change one of the elements in the array of method 2a and method 2b. " }, { "code": null, "e": 27092, "s": 27084, "text": "Python3" }, { "code": "# Python 3 program to demonstrate working# of method 1 and method 2. rows, cols = (5, 5) # method 2aarr = [[0]*cols]*rows # lets change the first element of the# first row to 1 and print the arrayarr[0][0] = 1 for row in arr: print(row)# outputs the following#[1, 0, 0, 0, 0]#[1, 0, 0, 0, 0]#[1, 0, 0, 0, 0]#[1, 0, 0, 0, 0]#[1, 0, 0, 0, 0] # method 2barr = [[0 for i in range(cols)] for j in range(rows)] # again in this new array lets change# the first element of the first row# to 1 and print the arrayarr[0][0] = 1for row in arr: print(row) # outputs the following as expected#[1, 0, 0, 0, 0]#[0, 0, 0, 0, 0]#[0, 0, 0, 0, 0]#[0, 0, 0, 0, 0]#[0, 0, 0, 0, 0]", "e": 27758, "s": 27092, "text": null }, { "code": null, "e": 27918, "s": 27758, "text": "[1, 0, 0, 0, 0]\n[1, 0, 0, 0, 0]\n[1, 0, 0, 0, 0]\n[1, 0, 0, 0, 0]\n[1, 0, 0, 0, 0]\n[1, 0, 0, 0, 0]\n[0, 0, 0, 0, 0]\n[0, 0, 0, 0, 0]\n[0, 0, 0, 0, 0]\n[0, 0, 0, 0, 0]" }, { "code": null, "e": 28311, "s": 27920, "text": "We expect only the first element of first row to change to 1 but the first element of every row gets changed to 1 in method 2a. This peculiar functioning is because Python uses shallow lists which we will try to understand.In method 1a, Python doesn’t create 5 integer objects but creates only one integer object and all the indices of the array arr point to the same int object as shown. " }, { "code": null, "e": 28496, "s": 28311, "text": "If we assign the 0th index to a another integer say 1, then a new integer object is created with the value of 1 and then the 0th index now points to this new int object as shown below " }, { "code": null, "e": 28894, "s": 28496, "text": "Similarly, when we create a 2d array as “arr = [[0]*cols]*rows” we are essentially the extending the above analogy. 1. Only one integer object is created. 2. A single 1d list is created and all its indices point to the same int object in point 1. 3. Now, arr[0], arr[1], arr[2] .... arr[n-1] all point to the same list object above in point 2.The above setup can be visualized in the image below. " }, { "code": null, "e": 29329, "s": 28894, "text": "Now lets change the first element in first row of “arr” as arr[0][0] = 1=> arr[0] points to the single list object we created we above.(Remember arr[1], arr[2] ...arr[n-1] all point to the same list object too) => The assignment of arr[0][0] will create a new int object with the value 1 and arr[0][0] will now point to this new int object.(and so will arr[1][0], arr[2][0] ...arr[n-1][0])This can be clearly seen in the below image. " }, { "code": null, "e": 29694, "s": 29329, "text": "So when 2d arrays are created like this, changing values at a certain row will effect all the rows since there is essentially only one integer object and only one list object being referenced by the all the rows of the array.As you would expect, tracing out errors caused by such usage of shallow lists is difficult. Hence the better way to declare a 2d array is " }, { "code": null, "e": 29702, "s": 29694, "text": "Python3" }, { "code": "rows, cols = (5, 5)arr = [[0 for i in range(cols)] for j in range(rows)]", "e": 29775, "s": 29702, "text": null }, { "code": null, "e": 29951, "s": 29779, "text": "This method creates 5 separate list objects unlike method 2a. One way to check this is using the ‘is’ operator which checks if the two operands refer to the same object. " }, { "code": null, "e": 29959, "s": 29951, "text": "Python3" }, { "code": "rows, cols = (5, 5)# method 2barr = [[0 for i in range(cols)] for j in range(rows)] # check if arr[0] and arr[1] refer to# the same objectprint(arr[0] is arr[1]) # prints False # method 2aarr = [[0]*cols]*rows # check if arr[0] and arr[1] refer to# the same object# prints True because there is only one# list object being created.print(arr[0] is arr[1])", "e": 30314, "s": 29959, "text": null }, { "code": null, "e": 30325, "s": 30314, "text": "False\nTrue" }, { "code": null, "e": 30338, "s": 30327, "text": "amainaster" }, { "code": null, "e": 30348, "s": 30338, "text": "ragulravi" }, { "code": null, "e": 30370, "s": 30348, "text": "Python matrix-program" }, { "code": null, "e": 30383, "s": 30370, "text": "Python-array" }, { "code": null, "e": 30390, "s": 30383, "text": "Arrays" }, { "code": null, "e": 30397, "s": 30390, "text": "Python" }, { "code": null, "e": 30404, "s": 30397, "text": "Arrays" }, { "code": null, "e": 30502, "s": 30404, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30525, "s": 30502, "text": "Introduction to Arrays" }, { "code": null, "e": 30557, "s": 30525, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 30578, "s": 30557, "text": "Linked List vs Array" }, { "code": null, "e": 30626, "s": 30578, "text": "Search an element in a sorted and rotated array" }, { "code": null, "e": 30679, "s": 30626, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 30707, "s": 30679, "text": "Read JSON file using Python" }, { "code": null, "e": 30757, "s": 30707, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 30779, "s": 30757, "text": "Python map() function" }, { "code": null, "e": 30823, "s": 30779, "text": "How to get column names in Pandas dataframe" } ]
Lambda Function - Ruby - GeeksforGeeks
16 Aug, 2021 In Computer Programming, Lambda functions are anonymous functions. Lambda functions in Ruby are no different. Since everything in Ruby is treated as an object, lambdas are also objects in Ruby. Lambdas in Ruby allow us to wrap data and logic in a portable package. Syntax to create Lambda function in Ruby: lambda = lambda {} Alternatively, we can also use literal lambda. lambda = ->() {} Lambda function is an instance of the Proc class of Ruby. # Creating a lambda function my_lambda_function = lambda { puts " GeeksforGeeks " } # Getting class of lambda my_lambda_function.class On Execution : Proc Let’s define a lambda function my_lambda_function = lambda { puts "Hello, Geeks !" } We have different ways to call this function. We can use my_lambda.call, my_lambda.() , my_lambda.[] or my_lambda.=== to call the lambda function . Example : Ruby # Creating a lambda functionmy_lambda_function = lambda { puts "Hello, Geeks" } # Different ways to call a lambda functionmy_lambda_function.call my_lambda_function.() my_lambda_function.[] my_lambda_function.=== Output: Hello, Geeks Hello, Geeks Hello, Geeks Hello, Geeks To pass arguments in the lambda function, we can either use normal lambda syntax or use the literal lambda operator ” -> ” Example 1: # Creating lambda function with arguments # Using lambda keyword lambda_with_args = lambda {| s | puts "Hello "+ s } # Calling lambda function by passing arguments lambda_with_args.call("Geeks") Output: Hello Geeks Example 2: Ruby # Creating lambda function with arguments# Using literal lambda function lambda_with_args = -> (s) { puts "Hello "+ s } # Calling lambda function by passing argumentslambda_with_args.call("Geeks") Output: Hello Geeks To use lambda functions along with a normal function, we can pass lambda function as an argument. Example: Ruby # Lambda function to add 10add_10 = lambda { |num| num + 10 } # Lambda function to multiply with 2multiply_2 = lambda { |num| num * 2 } # A Function using lambdadef using_lambda_with_functions(lambda, number) puts lambda.call(number) end # Passing lambda to functionusing_lambda_with_functions(add_10, 10) using_lambda_with_functions(multiply_2, 20) Output: 20 40 simmytarika5 Picked Ruby Function Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Include v/s Extend in Ruby Ruby | Hash delete() function Ruby | Types of Variables Ruby | Enumerator each_with_index function Ruby | Case Statement Ruby | Array select() function Ruby | Data Types Ruby | Numeric round() function Ruby | String capitalize() Method Ruby | String gsub! Method
[ { "code": null, "e": 24873, "s": 24845, "text": "\n16 Aug, 2021" }, { "code": null, "e": 25140, "s": 24873, "text": "In Computer Programming, Lambda functions are anonymous functions. Lambda functions in Ruby are no different. Since everything in Ruby is treated as an object, lambdas are also objects in Ruby. Lambdas in Ruby allow us to wrap data and logic in a portable package. " }, { "code": null, "e": 25182, "s": 25140, "text": "Syntax to create Lambda function in Ruby:" }, { "code": null, "e": 25203, "s": 25182, "text": "lambda = lambda {} " }, { "code": null, "e": 25252, "s": 25203, "text": "Alternatively, we can also use literal lambda. " }, { "code": null, "e": 25271, "s": 25252, "text": "lambda = ->() {} " }, { "code": null, "e": 25330, "s": 25271, "text": "Lambda function is an instance of the Proc class of Ruby. " }, { "code": null, "e": 25466, "s": 25330, "text": "# Creating a lambda function\nmy_lambda_function = lambda { puts \" GeeksforGeeks \" }\n\n# Getting class of lambda\nmy_lambda_function.class" }, { "code": null, "e": 25482, "s": 25466, "text": "On Execution : " }, { "code": null, "e": 25487, "s": 25482, "text": "Proc" }, { "code": null, "e": 25519, "s": 25487, "text": "Let’s define a lambda function " }, { "code": null, "e": 25573, "s": 25519, "text": "my_lambda_function = lambda { puts \"Hello, Geeks !\" }" }, { "code": null, "e": 25732, "s": 25573, "text": "We have different ways to call this function. We can use my_lambda.call, my_lambda.() , my_lambda.[] or my_lambda.=== to call the lambda function . Example : " }, { "code": null, "e": 25737, "s": 25732, "text": "Ruby" }, { "code": "# Creating a lambda functionmy_lambda_function = lambda { puts \"Hello, Geeks\" } # Different ways to call a lambda functionmy_lambda_function.call my_lambda_function.() my_lambda_function.[] my_lambda_function.===", "e": 25951, "s": 25737, "text": null }, { "code": null, "e": 25959, "s": 25951, "text": "Output:" }, { "code": null, "e": 26011, "s": 25959, "text": "Hello, Geeks\nHello, Geeks\nHello, Geeks\nHello, Geeks" }, { "code": null, "e": 26146, "s": 26011, "text": "To pass arguments in the lambda function, we can either use normal lambda syntax or use the literal lambda operator ” -> ” Example 1: " }, { "code": null, "e": 26344, "s": 26146, "text": "# Creating lambda function with arguments \n# Using lambda keyword\n\nlambda_with_args = lambda {| s | puts \"Hello \"+ s }\n\n# Calling lambda function by passing arguments\nlambda_with_args.call(\"Geeks\")" }, { "code": null, "e": 26353, "s": 26344, "text": "Output: " }, { "code": null, "e": 26365, "s": 26353, "text": "Hello Geeks" }, { "code": null, "e": 26377, "s": 26365, "text": "Example 2: " }, { "code": null, "e": 26382, "s": 26377, "text": "Ruby" }, { "code": "# Creating lambda function with arguments# Using literal lambda function lambda_with_args = -> (s) { puts \"Hello \"+ s } # Calling lambda function by passing argumentslambda_with_args.call(\"Geeks\")", "e": 26579, "s": 26382, "text": null }, { "code": null, "e": 26587, "s": 26579, "text": "Output:" }, { "code": null, "e": 26599, "s": 26587, "text": "Hello Geeks" }, { "code": null, "e": 26707, "s": 26599, "text": "To use lambda functions along with a normal function, we can pass lambda function as an argument. Example: " }, { "code": null, "e": 26712, "s": 26707, "text": "Ruby" }, { "code": "# Lambda function to add 10add_10 = lambda { |num| num + 10 } # Lambda function to multiply with 2multiply_2 = lambda { |num| num * 2 } # A Function using lambdadef using_lambda_with_functions(lambda, number) puts lambda.call(number) end # Passing lambda to functionusing_lambda_with_functions(add_10, 10) using_lambda_with_functions(multiply_2, 20)", "e": 27065, "s": 26712, "text": null }, { "code": null, "e": 27074, "s": 27065, "text": "Output: " }, { "code": null, "e": 27080, "s": 27074, "text": "20\n40" }, { "code": null, "e": 27093, "s": 27080, "text": "simmytarika5" }, { "code": null, "e": 27100, "s": 27093, "text": "Picked" }, { "code": null, "e": 27114, "s": 27100, "text": "Ruby Function" }, { "code": null, "e": 27119, "s": 27114, "text": "Ruby" }, { "code": null, "e": 27217, "s": 27119, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27244, "s": 27217, "text": "Include v/s Extend in Ruby" }, { "code": null, "e": 27274, "s": 27244, "text": "Ruby | Hash delete() function" }, { "code": null, "e": 27300, "s": 27274, "text": "Ruby | Types of Variables" }, { "code": null, "e": 27343, "s": 27300, "text": "Ruby | Enumerator each_with_index function" }, { "code": null, "e": 27365, "s": 27343, "text": "Ruby | Case Statement" }, { "code": null, "e": 27396, "s": 27365, "text": "Ruby | Array select() function" }, { "code": null, "e": 27414, "s": 27396, "text": "Ruby | Data Types" }, { "code": null, "e": 27446, "s": 27414, "text": "Ruby | Numeric round() function" }, { "code": null, "e": 27480, "s": 27446, "text": "Ruby | String capitalize() Method" } ]
User Registration in Android using Back4App - GeeksforGeeks
06 Nov, 2021 Prerequisite: How to Connect Android App with Back4App? We have seen adding Back4App in our Android App. In this article, we will take a look at adding a User Registration form in Android App so that users can register themselves in the app. We will be building a simple application in which we will be adding a simple user registration form so that users can register themselves with their username and password. Below is the video in which we will get to see what we are going to build in this article. This article is the continuation of How to Connect Android App with Back4App. Step 1: Working with the activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. 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" tools:context=".MainActivity"> <!--text view for heading--> <TextView android:id="@+id/idTVHeader" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="30dp" android:gravity="center_horizontal" android:padding="5dp" android:text="Welcome to Geeks for Geeks \n Register Form" android:textAlignment="center" android:textColor="@color/purple_700" android:textSize="18sp" /> <!--edit text for user name--> <EditText android:id="@+id/idEdtUserName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idTVHeader" android:layout_marginStart="10dp" android:layout_marginTop="50dp" android:layout_marginEnd="10dp" android:hint="Enter UserName" android:inputType="textEmailAddress" /> <!--edit text for user password--> <EditText android:id="@+id/idEdtPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idEdtUserName" android:layout_marginStart="10dp" android:layout_marginTop="20dp" android:layout_marginEnd="10dp" android:hint="Enter Password" android:inputType="textPassword" /> <!--button to register our new user--> <Button android:id="@+id/idBtnRegister" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idEdtPassword" android:layout_marginStart="10dp" android:layout_marginTop="20dp" android:layout_marginEnd="10dp" android:text="Register User" android:textAllCaps="false" /> </RelativeLayout> Step 2: Creating a new activity to redirect our user after registration Navigate to the app > java > your app’s package name > Right-click on it > New > Empty Activity and name it as HomeActivity. or you may also refer to this article How to Create New Activity in Android Studio? Step 3: Working with the activity_home.xml file Navigate to the app > res > layout > activity_home.xml file and add the below code to it. 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" tools:context=".HomeActivity"> <!--text view for displaying heading--> <TextView android:id="@+id/idTVHeader" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:gravity="center_horizontal" android:text="Welcome to Geeks for Geeks" android:textAlignment="center" android:textColor="@color/purple_700" android:textSize="18sp" /> <!--text view for displaying user name--> <TextView android:id="@+id/idTVUserName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idTVHeader" android:layout_centerInParent="true" android:layout_marginTop="20dp" android:gravity="center_horizontal" android:text="UserName" android:textAlignment="center" android:textColor="@color/purple_700" android:textSize="25sp" /> </RelativeLayout> Step 4: Working with the HomeActivity.java file Navigate to the app > java > your app’s package name > HomeActivity.java file and add the below code to it. Comments are added inside the code to understand the code in more detail. Java import android.os.Bundle;import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class HomeActivity extends AppCompatActivity { // creating a variable for our text view.. private TextView userNameTV; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); // initializing our variables userNameTV = findViewById(R.id.idTVUserName); // getting data from intent. String name = getIntent().getStringExtra("username"); // setting data to our text view. userNameTV.setText(name); }} Step 5: Working with the MainActivity.java file Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.content.Intent;import android.os.Bundle;import android.text.TextUtils;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.parse.ParseException;import com.parse.ParseUser;import com.parse.SignUpCallback; public class MainActivity extends AppCompatActivity { // creating variables for our edit text and buttons. private EditText userNameEdt, passwordEdt; private Button registerBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our edit text and buttons. userNameEdt = findViewById(R.id.idEdtUserName); passwordEdt = findViewById(R.id.idEdtPassword); registerBtn = findViewById(R.id.idBtnRegister); // adding on click listener for our button. registerBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // on below line we are getting data from our edit text. String userName = userNameEdt.getText().toString(); String password = passwordEdt.getText().toString(); // checking if the entered text is empty or not. if (TextUtils.isEmpty(userName) && TextUtils.isEmpty(password)) { Toast.makeText(MainActivity.this, "Please enter user name and password", Toast.LENGTH_SHORT).show(); } // calling a method to register a user. registerUser(userName, password); } }); } private void registerUser(String userName, String password) { // on below line we are creating // a new user using parse user. ParseUser user = new ParseUser(); // Set the user's username and password, // which can be obtained from edit text user.setUsername(userName); user.setPassword(password); // calling a method to register the user. user.signUpInBackground(new SignUpCallback() { @Override public void done(ParseException e) { // on user registration checking if // the error is null or not. if (e == null) { // if the error is null we are displaying a toast message and // redirecting our user to new activity and passing the user name. Toast.makeText(MainActivity.this, "User Registered successfully", Toast.LENGTH_SHORT).show(); Intent i = new Intent(MainActivity.this, HomeActivity.class); i.putExtra("username", userName); startActivity(i); } else { // if we get any error then we are logging out // our user and displaying an error message ParseUser.logOut(); Toast.makeText(MainActivity.this, "Fail to Register User..", Toast.LENGTH_SHORT).show(); } } }); }} Now run your app and see the output of the app. Output: Check out the project on the below link: https://github.com/ChaitanyaMunje/GFG-Back4App/tree/RegisterUser surindertarika1234 kalrap615 Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Create and Add Data to SQLite Database in Android? Broadcast Receiver in Android With Example Resource Raw Folder in Android Studio Services in Android with Example Android RecyclerView in Kotlin Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples
[ { "code": null, "e": 25729, "s": 25701, "text": "\n06 Nov, 2021" }, { "code": null, "e": 25785, "s": 25729, "text": "Prerequisite: How to Connect Android App with Back4App?" }, { "code": null, "e": 25972, "s": 25785, "text": "We have seen adding Back4App in our Android App. In this article, we will take a look at adding a User Registration form in Android App so that users can register themselves in the app. " }, { "code": null, "e": 26236, "s": 25972, "text": "We will be building a simple application in which we will be adding a simple user registration form so that users can register themselves with their username and password. Below is the video in which we will get to see what we are going to build in this article. " }, { "code": null, "e": 26315, "s": 26236, "text": "This article is the continuation of How to Connect Android App with Back4App. " }, { "code": null, "e": 26363, "s": 26315, "text": "Step 1: Working with the activity_main.xml file" }, { "code": null, "e": 26506, "s": 26363, "text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. " }, { "code": null, "e": 26510, "s": 26506, "text": "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\" tools:context=\".MainActivity\"> <!--text view for heading--> <TextView android:id=\"@+id/idTVHeader\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"30dp\" android:gravity=\"center_horizontal\" android:padding=\"5dp\" android:text=\"Welcome to Geeks for Geeks \\n Register Form\" android:textAlignment=\"center\" android:textColor=\"@color/purple_700\" android:textSize=\"18sp\" /> <!--edit text for user name--> <EditText android:id=\"@+id/idEdtUserName\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idTVHeader\" android:layout_marginStart=\"10dp\" android:layout_marginTop=\"50dp\" android:layout_marginEnd=\"10dp\" android:hint=\"Enter UserName\" android:inputType=\"textEmailAddress\" /> <!--edit text for user password--> <EditText android:id=\"@+id/idEdtPassword\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idEdtUserName\" android:layout_marginStart=\"10dp\" android:layout_marginTop=\"20dp\" android:layout_marginEnd=\"10dp\" android:hint=\"Enter Password\" android:inputType=\"textPassword\" /> <!--button to register our new user--> <Button android:id=\"@+id/idBtnRegister\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idEdtPassword\" android:layout_marginStart=\"10dp\" android:layout_marginTop=\"20dp\" android:layout_marginEnd=\"10dp\" android:text=\"Register User\" android:textAllCaps=\"false\" /> </RelativeLayout>", "e": 28538, "s": 26510, "text": null }, { "code": null, "e": 28610, "s": 28538, "text": "Step 2: Creating a new activity to redirect our user after registration" }, { "code": null, "e": 28819, "s": 28610, "text": "Navigate to the app > java > your app’s package name > Right-click on it > New > Empty Activity and name it as HomeActivity. or you may also refer to this article How to Create New Activity in Android Studio?" }, { "code": null, "e": 28867, "s": 28819, "text": "Step 3: Working with the activity_home.xml file" }, { "code": null, "e": 28958, "s": 28867, "text": "Navigate to the app > res > layout > activity_home.xml file and add the below code to it. " }, { "code": null, "e": 28962, "s": 28958, "text": "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\" tools:context=\".HomeActivity\"> <!--text view for displaying heading--> <TextView android:id=\"@+id/idTVHeader\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:gravity=\"center_horizontal\" android:text=\"Welcome to Geeks for Geeks\" android:textAlignment=\"center\" android:textColor=\"@color/purple_700\" android:textSize=\"18sp\" /> <!--text view for displaying user name--> <TextView android:id=\"@+id/idTVUserName\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idTVHeader\" android:layout_centerInParent=\"true\" android:layout_marginTop=\"20dp\" android:gravity=\"center_horizontal\" android:text=\"UserName\" android:textAlignment=\"center\" android:textColor=\"@color/purple_700\" android:textSize=\"25sp\" /> </RelativeLayout>", "e": 30203, "s": 28962, "text": null }, { "code": null, "e": 30251, "s": 30203, "text": "Step 4: Working with the HomeActivity.java file" }, { "code": null, "e": 30433, "s": 30251, "text": "Navigate to the app > java > your app’s package name > HomeActivity.java file and add the below code to it. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 30438, "s": 30433, "text": "Java" }, { "code": "import android.os.Bundle;import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class HomeActivity extends AppCompatActivity { // creating a variable for our text view.. private TextView userNameTV; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); // initializing our variables userNameTV = findViewById(R.id.idTVUserName); // getting data from intent. String name = getIntent().getStringExtra(\"username\"); // setting data to our text view. userNameTV.setText(name); }}", "e": 31131, "s": 30438, "text": null }, { "code": null, "e": 31179, "s": 31131, "text": "Step 5: Working with the MainActivity.java file" }, { "code": null, "e": 31369, "s": 31179, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 31374, "s": 31369, "text": "Java" }, { "code": "import android.content.Intent;import android.os.Bundle;import android.text.TextUtils;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.parse.ParseException;import com.parse.ParseUser;import com.parse.SignUpCallback; public class MainActivity extends AppCompatActivity { // creating variables for our edit text and buttons. private EditText userNameEdt, passwordEdt; private Button registerBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our edit text and buttons. userNameEdt = findViewById(R.id.idEdtUserName); passwordEdt = findViewById(R.id.idEdtPassword); registerBtn = findViewById(R.id.idBtnRegister); // adding on click listener for our button. registerBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // on below line we are getting data from our edit text. String userName = userNameEdt.getText().toString(); String password = passwordEdt.getText().toString(); // checking if the entered text is empty or not. if (TextUtils.isEmpty(userName) && TextUtils.isEmpty(password)) { Toast.makeText(MainActivity.this, \"Please enter user name and password\", Toast.LENGTH_SHORT).show(); } // calling a method to register a user. registerUser(userName, password); } }); } private void registerUser(String userName, String password) { // on below line we are creating // a new user using parse user. ParseUser user = new ParseUser(); // Set the user's username and password, // which can be obtained from edit text user.setUsername(userName); user.setPassword(password); // calling a method to register the user. user.signUpInBackground(new SignUpCallback() { @Override public void done(ParseException e) { // on user registration checking if // the error is null or not. if (e == null) { // if the error is null we are displaying a toast message and // redirecting our user to new activity and passing the user name. Toast.makeText(MainActivity.this, \"User Registered successfully\", Toast.LENGTH_SHORT).show(); Intent i = new Intent(MainActivity.this, HomeActivity.class); i.putExtra(\"username\", userName); startActivity(i); } else { // if we get any error then we are logging out // our user and displaying an error message ParseUser.logOut(); Toast.makeText(MainActivity.this, \"Fail to Register User..\", Toast.LENGTH_SHORT).show(); } } }); }}", "e": 34626, "s": 31374, "text": null }, { "code": null, "e": 34675, "s": 34626, "text": "Now run your app and see the output of the app. " }, { "code": null, "e": 34683, "s": 34675, "text": "Output:" }, { "code": null, "e": 34789, "s": 34683, "text": "Check out the project on the below link: https://github.com/ChaitanyaMunje/GFG-Back4App/tree/RegisterUser" }, { "code": null, "e": 34808, "s": 34789, "text": "surindertarika1234" }, { "code": null, "e": 34818, "s": 34808, "text": "kalrap615" }, { "code": null, "e": 34826, "s": 34818, "text": "Android" }, { "code": null, "e": 34831, "s": 34826, "text": "Java" }, { "code": null, "e": 34836, "s": 34831, "text": "Java" }, { "code": null, "e": 34844, "s": 34836, "text": "Android" }, { "code": null, "e": 34942, "s": 34844, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35000, "s": 34942, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 35043, "s": 35000, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 35081, "s": 35043, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 35114, "s": 35081, "text": "Services in Android with Example" }, { "code": null, "e": 35145, "s": 35114, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 35160, "s": 35145, "text": "Arrays in Java" }, { "code": null, "e": 35204, "s": 35160, "text": "Split() String method in Java with examples" }, { "code": null, "e": 35226, "s": 35204, "text": "For-each loop in Java" }, { "code": null, "e": 35277, "s": 35226, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
Any All in Python - GeeksforGeeks
25 Nov, 2020 Any and All are two built ins provided in python used for successive And/Or. AnyReturns true if any of the items is True. It returns False if empty or all are false. Any can be thought of as a sequence of OR operations on the provided iterables.It short circuit the execution i.e. stop the execution as soon as the result is known. Syntax : any(list of iterables) # Since all are false, false is returnedprint (any([False, False, False, False])) # Here the method will short-circuit at the# second item (True) and will return True.print (any([False, True, False, False])) # Here the method will short-circuit at the# first (True) and will return True.print (any([True, False, False, False])) Output : False True True AllReturns true if all of the items are True (or if the iterable is empty). All can be thought of as a sequence of AND operations on the provided iterables. It also short circuit the execution i.e. stop the execution as soon as the result is known. Syntax : all(list of iterables) # Here all the iterables are True so all# will return True and the same will be printedprint (all([True, True, True, True])) # Here the method will short-circuit at the # first item (False) and will return False.print (all([False, True, True, False])) # This statement will return False, as no# True is found in the iterablesprint (all([False, False, False])) Output : True False False Practical Examples # This code explains how can we # use 'any' function on list list1 = []list2 = [] # Index ranges from 1 to 10 to multiplyfor i in range(1,11): list1.append(4*i) # Index to access the list2 is from 0 to 9for i in range(0,10): list2.append(list1[i]%5==0) print('See whether at least one number is divisible by 5 in list 1=>')print(any(list2)) Output: See whether at least one number is divisible by 5 in list 1=> True # Illustration of 'all' function in python 3 # Take two lists list1=[]list2=[] # All numbers in list1 are in form: 4*i-3for i in range(1,21): list1.append(4*i-3) # list2 stores info of odd numbers in list1for i in range(0,20): list2.append(list1[i]%2==1) print('See whether all numbers in list1 are odd =>')print(all(list2)) Output: See whether all numbers in list1 are odd => True Truth table :- This article is contributed by Mayank Rawat .If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@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. pintusaini Python-Built-in-functions Python School Programming 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 Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects Interfaces in Java
[ { "code": null, "e": 42713, "s": 42685, "text": "\n25 Nov, 2020" }, { "code": null, "e": 42790, "s": 42713, "text": "Any and All are two built ins provided in python used for successive And/Or." }, { "code": null, "e": 43045, "s": 42790, "text": "AnyReturns true if any of the items is True. It returns False if empty or all are false. Any can be thought of as a sequence of OR operations on the provided iterables.It short circuit the execution i.e. stop the execution as soon as the result is known." }, { "code": null, "e": 43077, "s": 43045, "text": "Syntax : any(list of iterables)" }, { "code": "# Since all are false, false is returnedprint (any([False, False, False, False])) # Here the method will short-circuit at the# second item (True) and will return True.print (any([False, True, False, False])) # Here the method will short-circuit at the# first (True) and will return True.print (any([True, False, False, False]))", "e": 43407, "s": 43077, "text": null }, { "code": null, "e": 43416, "s": 43407, "text": "Output :" }, { "code": null, "e": 43433, "s": 43416, "text": "False\nTrue\nTrue\n" }, { "code": null, "e": 43684, "s": 43435, "text": "AllReturns true if all of the items are True (or if the iterable is empty). All can be thought of as a sequence of AND operations on the provided iterables. It also short circuit the execution i.e. stop the execution as soon as the result is known." }, { "code": null, "e": 43716, "s": 43684, "text": "Syntax : all(list of iterables)" }, { "code": "# Here all the iterables are True so all# will return True and the same will be printedprint (all([True, True, True, True])) # Here the method will short-circuit at the # first item (False) and will return False.print (all([False, True, True, False])) # This statement will return False, as no# True is found in the iterablesprint (all([False, False, False]))", "e": 44078, "s": 43716, "text": null }, { "code": null, "e": 44087, "s": 44078, "text": "Output :" }, { "code": null, "e": 44105, "s": 44087, "text": "True\nFalse\nFalse\n" }, { "code": null, "e": 44124, "s": 44105, "text": "Practical Examples" }, { "code": "# This code explains how can we # use 'any' function on list list1 = []list2 = [] # Index ranges from 1 to 10 to multiplyfor i in range(1,11): list1.append(4*i) # Index to access the list2 is from 0 to 9for i in range(0,10): list2.append(list1[i]%5==0) print('See whether at least one number is divisible by 5 in list 1=>')print(any(list2))", "e": 44475, "s": 44124, "text": null }, { "code": null, "e": 44483, "s": 44475, "text": "Output:" }, { "code": null, "e": 44551, "s": 44483, "text": "See whether at least one number is divisible by 5 in list 1=>\nTrue\n" }, { "code": "# Illustration of 'all' function in python 3 # Take two lists list1=[]list2=[] # All numbers in list1 are in form: 4*i-3for i in range(1,21): list1.append(4*i-3) # list2 stores info of odd numbers in list1for i in range(0,20): list2.append(list1[i]%2==1) print('See whether all numbers in list1 are odd =>')print(all(list2))", "e": 44887, "s": 44551, "text": null }, { "code": null, "e": 44895, "s": 44887, "text": "Output:" }, { "code": null, "e": 44945, "s": 44895, "text": "See whether all numbers in list1 are odd =>\nTrue\n" }, { "code": null, "e": 44960, "s": 44945, "text": "Truth table :-" }, { "code": null, "e": 45260, "s": 44960, "text": "This article is contributed by Mayank Rawat .If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 45385, "s": 45260, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 45396, "s": 45385, "text": "pintusaini" }, { "code": null, "e": 45422, "s": 45396, "text": "Python-Built-in-functions" }, { "code": null, "e": 45429, "s": 45422, "text": "Python" }, { "code": null, "e": 45448, "s": 45429, "text": "School Programming" }, { "code": null, "e": 45546, "s": 45448, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 45574, "s": 45546, "text": "Read JSON file using Python" }, { "code": null, "e": 45624, "s": 45574, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 45646, "s": 45624, "text": "Python map() function" }, { "code": null, "e": 45690, "s": 45646, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 45725, "s": 45690, "text": "Read a file line by line in Python" }, { "code": null, "e": 45741, "s": 45725, "text": "Arrays in C/C++" }, { "code": null, "e": 45760, "s": 45741, "text": "Inheritance in C++" }, { "code": null, "e": 45785, "s": 45760, "text": "Reverse a string in Java" }, { "code": null, "e": 45809, "s": 45785, "text": "C++ Classes and Objects" } ]
NFA machines accepting all strings that ends or not ends with substring 'ab' - GeeksforGeeks
24 Jun, 2019 Prerequisite: Finite Automata Introduction Problem-1:Construction of a minimal NFA accepting a set of strings over {a, b} in which each string of the language ends with ‘ab’. Explanation:The desired language will be like: L1 = {ab, abbab, abaab, ...........} Here as we can see that each string of the above language ends with ‘ab’ but the below language is not accepted by this NFA because some of the string of below language does not end with ‘ab’. L2 = {bba, abb, aaabbbb, .............} The state transition diagram of the desired language will be like below: In the above NFA, the initial state ‘X’ on getting ‘a’ as the input it either remains in the state of itself or transit to a state ‘Y’ and on getting ‘b’ as the input it remains in the state of itself. The state ‘Y’ on getting ‘b’ as the input it transmits to a final state ‘Z’. Problem-2:Construction of a minimal NFA accepting a set of strings over {a, b} in which each string of the language is not ending with ‘ab’. Explanation: The desired language will be like: L1 = {bba, abb, aaabbbb, .............} Here as we can see that each string of the above language is not ending with ‘ab’ but the below language is not accepted by this NFA because some of the string of below language is ending with ‘ab’. L2 = {ab, abab, ababaab..............} The state transition diagram of the desired language will be like below: In the above NFA, the initial state ‘X’ on getting ‘a’ as the input it remains in the state of itself and on getting ‘b’ as the input it transmits to a state ‘Y’. The state ‘Y’ on getting ‘b’ as the input it either remains in the state of itself or transmits to a final state ‘Z’. The final state ‘Z’ on getting ‘a’ as the input it remains in the state of itself. GATE CS Theory of Computation & Automata Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Differences between IPv4 and IPv6 Preemptive and Non-Preemptive Scheduling Difference between Clustered and Non-clustered index Phases of a Compiler Introduction of Process Synchronization Turing Machine in TOC Introduction of Pushdown Automata Difference between DFA and NFA Introduction of Finite Automata Construct Pushdown Automata for given languages
[ { "code": null, "e": 25652, "s": 25624, "text": "\n24 Jun, 2019" }, { "code": null, "e": 25695, "s": 25652, "text": "Prerequisite: Finite Automata Introduction" }, { "code": null, "e": 25827, "s": 25695, "text": "Problem-1:Construction of a minimal NFA accepting a set of strings over {a, b} in which each string of the language ends with ‘ab’." }, { "code": null, "e": 25874, "s": 25827, "text": "Explanation:The desired language will be like:" }, { "code": null, "e": 25911, "s": 25874, "text": "L1 = {ab, abbab, abaab, ...........}" }, { "code": null, "e": 26104, "s": 25911, "text": "Here as we can see that each string of the above language ends with ‘ab’ but the below language is not accepted by this NFA because some of the string of below language does not end with ‘ab’." }, { "code": null, "e": 26144, "s": 26104, "text": "L2 = {bba, abb, aaabbbb, .............}" }, { "code": null, "e": 26217, "s": 26144, "text": "The state transition diagram of the desired language will be like below:" }, { "code": null, "e": 26496, "s": 26217, "text": "In the above NFA, the initial state ‘X’ on getting ‘a’ as the input it either remains in the state of itself or transit to a state ‘Y’ and on getting ‘b’ as the input it remains in the state of itself. The state ‘Y’ on getting ‘b’ as the input it transmits to a final state ‘Z’." }, { "code": null, "e": 26637, "s": 26496, "text": "Problem-2:Construction of a minimal NFA accepting a set of strings over {a, b} in which each string of the language is not ending with ‘ab’." }, { "code": null, "e": 26685, "s": 26637, "text": "Explanation: The desired language will be like:" }, { "code": null, "e": 26725, "s": 26685, "text": "L1 = {bba, abb, aaabbbb, .............}" }, { "code": null, "e": 26924, "s": 26725, "text": "Here as we can see that each string of the above language is not ending with ‘ab’ but the below language is not accepted by this NFA because some of the string of below language is ending with ‘ab’." }, { "code": null, "e": 26963, "s": 26924, "text": "L2 = {ab, abab, ababaab..............}" }, { "code": null, "e": 27036, "s": 26963, "text": "The state transition diagram of the desired language will be like below:" }, { "code": null, "e": 27400, "s": 27036, "text": "In the above NFA, the initial state ‘X’ on getting ‘a’ as the input it remains in the state of itself and on getting ‘b’ as the input it transmits to a state ‘Y’. The state ‘Y’ on getting ‘b’ as the input it either remains in the state of itself or transmits to a final state ‘Z’. The final state ‘Z’ on getting ‘a’ as the input it remains in the state of itself." }, { "code": null, "e": 27408, "s": 27400, "text": "GATE CS" }, { "code": null, "e": 27441, "s": 27408, "text": "Theory of Computation & Automata" }, { "code": null, "e": 27539, "s": 27441, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27573, "s": 27539, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 27614, "s": 27573, "text": "Preemptive and Non-Preemptive Scheduling" }, { "code": null, "e": 27667, "s": 27614, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 27688, "s": 27667, "text": "Phases of a Compiler" }, { "code": null, "e": 27728, "s": 27688, "text": "Introduction of Process Synchronization" }, { "code": null, "e": 27750, "s": 27728, "text": "Turing Machine in TOC" }, { "code": null, "e": 27784, "s": 27750, "text": "Introduction of Pushdown Automata" }, { "code": null, "e": 27815, "s": 27784, "text": "Difference between DFA and NFA" }, { "code": null, "e": 27847, "s": 27815, "text": "Introduction of Finite Automata" } ]
How to Right-align flex item? - GeeksforGeeks
01 Dec, 2020 CSS | flex-box Flex-box is simply a web layout method that allows developers to align the elements easily and much more. The whole concept of flex-box depends on two major pillars: main-axis and cross-axis. Representation of flex-box To align the flex items left/right, We need to deal with the main-axis, which can be done using flex-box properties. A detailed explanation is given below: Example 1: Right aligning flex item using flex-direction property <!DOCTYPE html><html><head><title>Right Alignment</title><style> #container { width:600px; height: 300px; border: 5px solid black; display: flex; flex-direction: row-reverse; } #container div { width: 100px; height: 50px; } </style> </head><body><div id="container"> <div style="background-color:#389900;">one</div> <div style="background-color:#08ebb2;">two</div> <div style="background-color:#dd2289;">three</div> <div style="background-color:#fcff66;">four</div> </div> </body></html> When flex-direction is set as “row-reverse” it not only right aligns the flex items but reverses the order of the items also. In simple words, flex-items now expand from right to left as shown in the given figure. Output: Figure-1 Example 2: Right aligning flex item using justify-content property <!DOCTYPE html><html><head><title>Right alignment</title><style> #container { width:600px; height: 300px; border: 5px solid black; display: flex; justify-content: flex-end; } #container div { width: 100px; height: 50px; } </style></head><body><div id="container"> <div style="background-color:#389900;">one</div> <div style="background-color:#08ebb2;">two</div> <div style="background-color:#dd2289;">three</div> <div style="background-color:#fcff66;">four</div> </div></body></html> When justify-content is set to “flex-end”, it instantly shifts all the flex-items to the end of the flex-container along the main-axis, i.e flex items get right aligned. It is different from the above-used method in terms of direction only as in this, flex-items will expand from left to right only. It will be more clear with the given figure. Output: Figure-2 CSS-Misc Picked CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to set space between the flexbox ? Design a web page using HTML and CSS Form validation using jQuery Search Bar using HTML, CSS and JavaScript How to style a checkbox using CSS? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26621, "s": 26593, "text": "\n01 Dec, 2020" }, { "code": null, "e": 26636, "s": 26621, "text": "CSS | flex-box" }, { "code": null, "e": 26828, "s": 26636, "text": "Flex-box is simply a web layout method that allows developers to align the elements easily and much more. The whole concept of flex-box depends on two major pillars: main-axis and cross-axis." }, { "code": null, "e": 26855, "s": 26828, "text": "Representation of flex-box" }, { "code": null, "e": 27011, "s": 26855, "text": "To align the flex items left/right, We need to deal with the main-axis, which can be done using flex-box properties. A detailed explanation is given below:" }, { "code": null, "e": 27078, "s": 27011, "text": "Example 1: Right aligning flex item using flex-direction property" }, { "code": "<!DOCTYPE html><html><head><title>Right Alignment</title><style> #container { width:600px; height: 300px; border: 5px solid black; display: flex; flex-direction: row-reverse; } #container div { width: 100px; height: 50px; } </style> </head><body><div id=\"container\"> <div style=\"background-color:#389900;\">one</div> <div style=\"background-color:#08ebb2;\">two</div> <div style=\"background-color:#dd2289;\">three</div> <div style=\"background-color:#fcff66;\">four</div> </div> </body></html>", "e": 27720, "s": 27078, "text": null }, { "code": null, "e": 27934, "s": 27720, "text": "When flex-direction is set as “row-reverse” it not only right aligns the flex items but reverses the order of the items also. In simple words, flex-items now expand from right to left as shown in the given figure." }, { "code": null, "e": 27942, "s": 27934, "text": "Output:" }, { "code": null, "e": 27951, "s": 27942, "text": "Figure-1" }, { "code": null, "e": 28019, "s": 27951, "text": "Example 2: Right aligning flex item using justify-content property" }, { "code": "<!DOCTYPE html><html><head><title>Right alignment</title><style> #container { width:600px; height: 300px; border: 5px solid black; display: flex; justify-content: flex-end; } #container div { width: 100px; height: 50px; } </style></head><body><div id=\"container\"> <div style=\"background-color:#389900;\">one</div> <div style=\"background-color:#08ebb2;\">two</div> <div style=\"background-color:#dd2289;\">three</div> <div style=\"background-color:#fcff66;\">four</div> </div></body></html>", "e": 28650, "s": 28019, "text": null }, { "code": null, "e": 28995, "s": 28650, "text": "When justify-content is set to “flex-end”, it instantly shifts all the flex-items to the end of the flex-container along the main-axis, i.e flex items get right aligned. It is different from the above-used method in terms of direction only as in this, flex-items will expand from left to right only. It will be more clear with the given figure." }, { "code": null, "e": 29003, "s": 28995, "text": "Output:" }, { "code": null, "e": 29012, "s": 29003, "text": "Figure-2" }, { "code": null, "e": 29021, "s": 29012, "text": "CSS-Misc" }, { "code": null, "e": 29028, "s": 29021, "text": "Picked" }, { "code": null, "e": 29032, "s": 29028, "text": "CSS" }, { "code": null, "e": 29049, "s": 29032, "text": "Web Technologies" }, { "code": null, "e": 29147, "s": 29049, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29186, "s": 29147, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 29223, "s": 29186, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 29252, "s": 29223, "text": "Form validation using jQuery" }, { "code": null, "e": 29294, "s": 29252, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 29329, "s": 29294, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 29369, "s": 29329, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29402, "s": 29369, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29447, "s": 29402, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29490, "s": 29447, "text": "How to fetch data from an API in ReactJS ?" } ]
How to convert timestamp string to datetime object in Python? - GeeksforGeeks
29 Aug, 2020 Python has a module named DateTime to work with dates and times. We did not need to install it separately. It is pre-installed with the python package itself. A UNIX timestamp is several seconds between a particular date and January 1, 1970, at UTC. You can simply use the fromtimestamp function from the DateTime module to get a date from a UNIX timestamp. This function takes the timestamp as input and returns the corresponding DateTime object to timestamp. Syntax: fromtimestamp(timestamp, tz=None) Example: Python timestamp to DateTime Python3 from datetime import datetime timestamp = 1545730073dt_obj = datetime.fromtimestamp(1140825600) print("date_time:",dt_obj)print("type of dt:",type(dt_obj)) Output: date_time: 2006-02-25 05:30:00 type of dt_obj: <class 'datetime.datetime'> Here, we have imported the DateTime class from DateTime module. Then we have used datetime.fromtimestamp() class method which returns the local DateTime. To get a DateTime in a particular form in you can use strftime function. The strftime() function is used to convert date and time objects to their string representation. It takes one or more input of formatted code and returns the string representation. Example: Python3 from datetime import datetime timestamp = 1553367060dt_obj = datetime.fromtimestamp(timestamp).strftime('%d-%m-%y') print("date:",dt_obj) Output: date: 24-03-19 Python-datetime Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe *args and **kwargs in Python Create a Pandas DataFrame from Lists Convert integer to string in Python Check if element exists in list in Python How To Convert Python Dictionary To JSON? sum() function in Python
[ { "code": null, "e": 26191, "s": 26163, "text": "\n29 Aug, 2020" }, { "code": null, "e": 26441, "s": 26191, "text": "Python has a module named DateTime to work with dates and times. We did not need to install it separately. It is pre-installed with the python package itself. A UNIX timestamp is several seconds between a particular date and January 1, 1970, at UTC." }, { "code": null, "e": 26652, "s": 26441, "text": "You can simply use the fromtimestamp function from the DateTime module to get a date from a UNIX timestamp. This function takes the timestamp as input and returns the corresponding DateTime object to timestamp." }, { "code": null, "e": 26660, "s": 26652, "text": "Syntax:" }, { "code": null, "e": 26694, "s": 26660, "text": "fromtimestamp(timestamp, tz=None)" }, { "code": null, "e": 26732, "s": 26694, "text": "Example: Python timestamp to DateTime" }, { "code": null, "e": 26740, "s": 26732, "text": "Python3" }, { "code": "from datetime import datetime timestamp = 1545730073dt_obj = datetime.fromtimestamp(1140825600) print(\"date_time:\",dt_obj)print(\"type of dt:\",type(dt_obj))", "e": 26900, "s": 26740, "text": null }, { "code": null, "e": 26908, "s": 26900, "text": "Output:" }, { "code": null, "e": 26984, "s": 26908, "text": "date_time: 2006-02-25 05:30:00\ntype of dt_obj: <class 'datetime.datetime'>\n" }, { "code": null, "e": 27139, "s": 26984, "text": "Here, we have imported the DateTime class from DateTime module. Then we have used datetime.fromtimestamp() class method which returns the local DateTime. " }, { "code": null, "e": 27393, "s": 27139, "text": "To get a DateTime in a particular form in you can use strftime function. The strftime() function is used to convert date and time objects to their string representation. It takes one or more input of formatted code and returns the string representation." }, { "code": null, "e": 27402, "s": 27393, "text": "Example:" }, { "code": null, "e": 27410, "s": 27402, "text": "Python3" }, { "code": "from datetime import datetime timestamp = 1553367060dt_obj = datetime.fromtimestamp(timestamp).strftime('%d-%m-%y') print(\"date:\",dt_obj)", "e": 27552, "s": 27410, "text": null }, { "code": null, "e": 27560, "s": 27552, "text": "Output:" }, { "code": null, "e": 27576, "s": 27560, "text": "date: 24-03-19\n" }, { "code": null, "e": 27592, "s": 27576, "text": "Python-datetime" }, { "code": null, "e": 27599, "s": 27592, "text": "Python" }, { "code": null, "e": 27697, "s": 27599, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27715, "s": 27697, "text": "Python Dictionary" }, { "code": null, "e": 27747, "s": 27715, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27769, "s": 27747, "text": "Enumerate() in Python" }, { "code": null, "e": 27811, "s": 27769, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27840, "s": 27811, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27877, "s": 27840, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 27913, "s": 27877, "text": "Convert integer to string in Python" }, { "code": null, "e": 27955, "s": 27913, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27997, "s": 27955, "text": "How To Convert Python Dictionary To JSON?" } ]