title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
ReactJS | Calculator App ( Building UI )
08 Oct, 2020 In the previous article, we created our first app and deleted all those files we did not need and created some of the files that we will need in the future. Now as we stand in our current situation we have a blank canvas before us where we will have to create our calculator app. Before moving on to actually developing something let us first plan the direction we will cover in this article. The article will be covering the development of the basic structure of the calculator before moving on to developing the logic behind. To start with the Calculator, let us first create the Calculator component by creating a calculator class in the calculator.js after we import the react, we do not need to render anything in this file so we will not import react-dom. We will export the module as default as well. As a member function, we will create a dummy render() function. After the addition, the code will be as below. // Import React (Mandatory Step).import React from 'react'; // Create a Class Component Calculator.class Calculator extends React.Component { render() { return "GeeksforGeeks Calculator"; }} // Export Calculator.export default Calculator; Now that we have created the backbone of our Calculator, let us first create the small components first which will make it look a bit closer to being a calculator. Let us start with the Calculator Title component. This component will only display the title that will be passed by its parent using props. So for the sake of simplicity, we will be importing only react, we will be creating a functional component using the thick arrow method and we will finally export the whole module as default. For the title, we will be using a div and pass in the value. The following will be what we code in the calculatorTitle.js. // Import React (Mandatory Step).import React from 'react'; // Create Functional Component.// Takes title as props.value.const CalculatorTitle = (props) => { return ( <div className="calculator-title"> { props.value } </div> )} // Export Calculator Title.export default CalculatorTitle; Nextly we will be developing the OutputScreen itself. As we have discussed that we will need two segments of the screen one for each output and input we will require the component screen row.Now this screen row component is a fairly easy component that will show whatever is passed to it. So for simplicity we will be importing only react, we will be creating a functional component using the thick arrow method and we will finally export the whole module as default. For the screen row, we will be using an input field and make it readOnly so that the user can’t modify the value. The following will be what we code in the outputScreenRow.js file. // Import React (Mandatory Step).import React from 'react'; // Functional Component.// Used to show Question/Answer.const OutputScreenRow = () => { return ( <div className="screen-row"> <input type="text" readOnly/> </div> )} // Export Output Screen Row.export default OutputScreenRow; So we have created the OutputScreenRow component, now we know that our Screen will be a component itself that will consist of two OutputScreenRows. So we will be importing React and the OutputScreenRow component we just created, we don’t need to render anything in this file thus we will not require react-dom. The OutputScreen itself is just a simple component to be used as the container of the OutputScreeRows thus we will create it as a functional component using the thick arrow method and we will add a render function that will consist of two OutputScreenRow components and finally we will export it as default. After the coding is complete the file outputScreen.js will look like this. // Import React (Mandatory Step).import React from 'react';// Import Output Screen Row.import OutputScreenRow from './outputScreenRow.js'; // Functional Component.// Use to hold two Screen Rows.const OutputScreen = () => { return ( <div className="screen"> <OutputScreenRow/> <OutputScreenRow/> </div> )} // Export Output Screen.export default OutputScreen; Now that we have created the screen part what is left is the Keypad. The keypad will be a set of Buttons. Now, this Buttons each will be independent components thus now we require to develop the Button component. Similarly to the other Components, we will only import react, we will again create a functional component using the thick arrow method and will create the render function to return a Button type input with the value as sent from the parent, and finally we will export it as default export. After completion, the contents of file button.js will look like the following. // Import React (Mandatory Step).import React from 'react'; // Create our Button component as a functional component.const Button = (props) => { return ( <input type="button" value={props.label} /> );} // Export our button component.export default Button; Now that we have completed developing the smaller components it is expected to assemble and create the app to look more like a calculator. We will move back to the Calculator.js file we created and we will update the render function accordingly. Firstly, We will add the title of the calculator followed by the Screen component. Now we need to set up our keypad. For our Keypad, we will be using rows of Buttons and we will use the className button-row to distinguish each row from the other. Thus we need to import the user-defined components CalculatorTitle, OutputScreen, and Button. Hence after updating, the file calculator.js will look like the following. // Imports.import React from 'react';import CalculatorTitle from './calculatorTitle.js';import OutputScreen from './outputScreen.js';import Button from './button.js'; class Calculator extends React.Component { render() { return ( <div className="frame"> <CalculatorTitle value="GeeksforGeeks Calculator"/> <div class="mainCalc"> <OutputScreen/> <div className="button-row"> <Button label={'Clear'}/> <Button label={'Delete'}/> <Button label={'.'}/> <Button label={'/'}/> </div> <div className="button-row"> <Button label={'7'}/> <Button label={'8'}/> <Button label={'9'}/> <Button label={'*'}/> </div> <div className="button-row"> <Button label={'4'}/> <Button label={'5'}/> <Button label={'6'}/> <Button label={'-'}/> </div> <div className="button-row"> <Button label={'1'}/> <Button label={'2'}/> <Button label={'3'}/> <Button label={'+'}/> </div> <div className="button-row"> <Button label={'0'}/> <Button label={'='}/> </div> </div> </div> ); }} // Export Calculator Component.export default Calculator; So far we have created all the components and stacked them together to create the basic structure. Now we just need to import the calculator in the index.js file and render in there. So we will need to import react and react-dom and we will use the render method of ReactDOM to render the calculator component. The index.js file’s contents are shown below. import React from 'react';import ReactDOM from 'react-dom';import Calculator from './components/calculator.js'; // Render the Calculator to the Web page.ReactDOM.render(<Calculator />, document.getElementById('root')); Following each of the steps, the output that we get is shown in the figure below. So now we can finally see the output in our browser, but wait this is nothing like what we showed you in the introductory article! Yes, it is nowhere near to be the finished project, it is rather a barebone structure and all it needs is the CSS touch-ups that we will provide in one of the upcoming articles, but before that, we have to implement the working logic of this calculator so that at least it works before we transform this rigid design into some eye-catching masterpiece or at least a decent model. ReactJS | Calculator App ( Adding Functionality ) react-js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 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 ? Remove elements from a JavaScript Array REST API (Introduction) Node.js fs.readFileSync() Method How to set the default value for an HTML <select> element ? How to create footer to stay at the bottom of a Web page?
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Oct, 2020" }, { "code": null, "e": 334, "s": 54, "text": "In the previous article, we created our first app and deleted all those files we did not need and created some of the files that we will need in the future. Now as we stand in our current situation we have a blank canvas before us where we will have to create our calculator app." }, { "code": null, "e": 582, "s": 334, "text": "Before moving on to actually developing something let us first plan the direction we will cover in this article. The article will be covering the development of the basic structure of the calculator before moving on to developing the logic behind." }, { "code": null, "e": 973, "s": 582, "text": "To start with the Calculator, let us first create the Calculator component by creating a calculator class in the calculator.js after we import the react, we do not need to render anything in this file so we will not import react-dom. We will export the module as default as well. As a member function, we will create a dummy render() function. After the addition, the code will be as below." }, { "code": "// Import React (Mandatory Step).import React from 'react'; // Create a Class Component Calculator.class Calculator extends React.Component { render() { return \"GeeksforGeeks Calculator\"; }} // Export Calculator.export default Calculator;", "e": 1230, "s": 973, "text": null }, { "code": null, "e": 1849, "s": 1230, "text": "Now that we have created the backbone of our Calculator, let us first create the small components first which will make it look a bit closer to being a calculator. Let us start with the Calculator Title component. This component will only display the title that will be passed by its parent using props. So for the sake of simplicity, we will be importing only react, we will be creating a functional component using the thick arrow method and we will finally export the whole module as default. For the title, we will be using a div and pass in the value. The following will be what we code in the calculatorTitle.js." }, { "code": "// Import React (Mandatory Step).import React from 'react'; // Create Functional Component.// Takes title as props.value.const CalculatorTitle = (props) => { return ( <div className=\"calculator-title\"> { props.value } </div> )} // Export Calculator Title.export default CalculatorTitle;", "e": 2152, "s": 1849, "text": null }, { "code": null, "e": 2801, "s": 2152, "text": "Nextly we will be developing the OutputScreen itself. As we have discussed that we will need two segments of the screen one for each output and input we will require the component screen row.Now this screen row component is a fairly easy component that will show whatever is passed to it. So for simplicity we will be importing only react, we will be creating a functional component using the thick arrow method and we will finally export the whole module as default. For the screen row, we will be using an input field and make it readOnly so that the user can’t modify the value. The following will be what we code in the outputScreenRow.js file." }, { "code": "// Import React (Mandatory Step).import React from 'react'; // Functional Component.// Used to show Question/Answer.const OutputScreenRow = () => { return ( <div className=\"screen-row\"> <input type=\"text\" readOnly/> </div> )} // Export Output Screen Row.export default OutputScreenRow;", "e": 3102, "s": 2801, "text": null }, { "code": null, "e": 3796, "s": 3102, "text": "So we have created the OutputScreenRow component, now we know that our Screen will be a component itself that will consist of two OutputScreenRows. So we will be importing React and the OutputScreenRow component we just created, we don’t need to render anything in this file thus we will not require react-dom. The OutputScreen itself is just a simple component to be used as the container of the OutputScreeRows thus we will create it as a functional component using the thick arrow method and we will add a render function that will consist of two OutputScreenRow components and finally we will export it as default. After the coding is complete the file outputScreen.js will look like this." }, { "code": "// Import React (Mandatory Step).import React from 'react';// Import Output Screen Row.import OutputScreenRow from './outputScreenRow.js'; // Functional Component.// Use to hold two Screen Rows.const OutputScreen = () => { return ( <div className=\"screen\"> <OutputScreenRow/> <OutputScreenRow/> </div> )} // Export Output Screen.export default OutputScreen;", "e": 4174, "s": 3796, "text": null }, { "code": null, "e": 4756, "s": 4174, "text": "Now that we have created the screen part what is left is the Keypad. The keypad will be a set of Buttons. Now, this Buttons each will be independent components thus now we require to develop the Button component. Similarly to the other Components, we will only import react, we will again create a functional component using the thick arrow method and will create the render function to return a Button type input with the value as sent from the parent, and finally we will export it as default export. After completion, the contents of file button.js will look like the following." }, { "code": "// Import React (Mandatory Step).import React from 'react'; // Create our Button component as a functional component.const Button = (props) => { return ( <input type=\"button\" value={props.label} /> );} // Export our button component.export default Button;", "e": 5032, "s": 4756, "text": null }, { "code": null, "e": 5694, "s": 5032, "text": "Now that we have completed developing the smaller components it is expected to assemble and create the app to look more like a calculator. We will move back to the Calculator.js file we created and we will update the render function accordingly. Firstly, We will add the title of the calculator followed by the Screen component. Now we need to set up our keypad. For our Keypad, we will be using rows of Buttons and we will use the className button-row to distinguish each row from the other. Thus we need to import the user-defined components CalculatorTitle, OutputScreen, and Button. Hence after updating, the file calculator.js will look like the following." }, { "code": "// Imports.import React from 'react';import CalculatorTitle from './calculatorTitle.js';import OutputScreen from './outputScreen.js';import Button from './button.js'; class Calculator extends React.Component { render() { return ( <div className=\"frame\"> <CalculatorTitle value=\"GeeksforGeeks Calculator\"/> <div class=\"mainCalc\"> <OutputScreen/> <div className=\"button-row\"> <Button label={'Clear'}/> <Button label={'Delete'}/> <Button label={'.'}/> <Button label={'/'}/> </div> <div className=\"button-row\"> <Button label={'7'}/> <Button label={'8'}/> <Button label={'9'}/> <Button label={'*'}/> </div> <div className=\"button-row\"> <Button label={'4'}/> <Button label={'5'}/> <Button label={'6'}/> <Button label={'-'}/> </div> <div className=\"button-row\"> <Button label={'1'}/> <Button label={'2'}/> <Button label={'3'}/> <Button label={'+'}/> </div> <div className=\"button-row\"> <Button label={'0'}/> <Button label={'='}/> </div> </div> </div> ); }} // Export Calculator Component.export default Calculator;", "e": 6855, "s": 5694, "text": null }, { "code": null, "e": 7212, "s": 6855, "text": "So far we have created all the components and stacked them together to create the basic structure. Now we just need to import the calculator in the index.js file and render in there. So we will need to import react and react-dom and we will use the render method of ReactDOM to render the calculator component. The index.js file’s contents are shown below." }, { "code": "import React from 'react';import ReactDOM from 'react-dom';import Calculator from './components/calculator.js'; // Render the Calculator to the Web page.ReactDOM.render(<Calculator />, document.getElementById('root'));", "e": 7432, "s": 7212, "text": null }, { "code": null, "e": 7514, "s": 7432, "text": "Following each of the steps, the output that we get is shown in the figure below." }, { "code": null, "e": 8025, "s": 7514, "text": "So now we can finally see the output in our browser, but wait this is nothing like what we showed you in the introductory article! Yes, it is nowhere near to be the finished project, it is rather a barebone structure and all it needs is the CSS touch-ups that we will provide in one of the upcoming articles, but before that, we have to implement the working logic of this calculator so that at least it works before we transform this rigid design into some eye-catching masterpiece or at least a decent model." }, { "code": null, "e": 8075, "s": 8025, "text": "ReactJS | Calculator App ( Adding Functionality )" }, { "code": null, "e": 8084, "s": 8075, "text": "react-js" }, { "code": null, "e": 8101, "s": 8084, "text": "Web Technologies" }, { "code": null, "e": 8199, "s": 8101, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8232, "s": 8199, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 8294, "s": 8232, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 8355, "s": 8294, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 8405, "s": 8355, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 8448, "s": 8405, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 8488, "s": 8448, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 8512, "s": 8488, "text": "REST API (Introduction)" }, { "code": null, "e": 8545, "s": 8512, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 8605, "s": 8545, "text": "How to set the default value for an HTML <select> element ?" } ]
Game of N stones where each player can remove 1, 3 or 4 - GeeksforGeeks
26 Apr, 2021 Two players are playing a game with n stones where player 1 always plays first. The two players move in alternating turns and plays optimally. In a single move a player can remove either 1, 3 or 4 stones from the pile of stones. If a player is unable to make a move then that player loses the game. Given the number of stones where n is less than equal to 200, find and print the name of the winner.Examples: Input : 4 Output : player 1 Input : 7 Output : player 2 To solve this problem, we need to find each possible value of n as a winning or losing position. Since above game is one of the impartial combinatorial games, therefore the characterization of losing and winning position is valid.The characteristic properties of winning and losing states are: All terminal positions are losing positions. From every winning position, there is atleast one move to a losing position. From every losing position, every move is to a winning position. If a player is able to make a move such that the next move is the losing state than the player is at winning state. Find the state of player 1, if player1 is in winning state then player 1 wins the game otherwise player 2 will win. Consider the following base positions: position 0 is the losing state, if the number of stones is 0 than the player1 will unable to make a move therefore player1 loses.position 1 is the winning state, if the number of stones is 1 than the player1 will remove the stone and win the game.position 2 is the losing state, if the number of stones is 2 than the player1 will remove 1 stone and then player2 will remove the second stone and win the game.position 3 is the winning state, if the player is able to take a move such that the next move is the losing state than the player is at winning state, the palyer1 will remove all the 3 stonesposition 4 is the winning state, if the player is able to take a move such that the next move is the losing state than the player is at winning state, the palyer1 will remove all the 4 stonesposition 5 is the winning state, if the player is able to take a move such that the next move is the losing state than the player is at winning state, the palyer1 will remove 3 stones leaving 2 stones, which is the losing stateposition 6 is the winning state, if the player is able to take a move such that the next move is the losing state than the player is at winning state, the palyer1 will remove 4 stones leaving 2 stones, which is the losing stateposition 7 is the losing state, if the number of stones is 7 than the player1 can remove 1, 3 or 4 stones which all leads to the losing state, therefore player1 will lose. position 0 is the losing state, if the number of stones is 0 than the player1 will unable to make a move therefore player1 loses. position 1 is the winning state, if the number of stones is 1 than the player1 will remove the stone and win the game. position 2 is the losing state, if the number of stones is 2 than the player1 will remove 1 stone and then player2 will remove the second stone and win the game. position 3 is the winning state, if the player is able to take a move such that the next move is the losing state than the player is at winning state, the palyer1 will remove all the 3 stones position 4 is the winning state, if the player is able to take a move such that the next move is the losing state than the player is at winning state, the palyer1 will remove all the 4 stones position 5 is the winning state, if the player is able to take a move such that the next move is the losing state than the player is at winning state, the palyer1 will remove 3 stones leaving 2 stones, which is the losing state position 6 is the winning state, if the player is able to take a move such that the next move is the losing state than the player is at winning state, the palyer1 will remove 4 stones leaving 2 stones, which is the losing state position 7 is the losing state, if the number of stones is 7 than the player1 can remove 1, 3 or 4 stones which all leads to the losing state, therefore player1 will lose. Below is the implementation of above approach: CPP Java Python3 C# PHP Javascript // CPP program to find winner of// the game of N stones#include <bits/stdc++.h>using namespace std; const int MAX = 200; // finds the winning and losing// states for the 200 stones.void findStates(int position[]){ // 0 means losing state // 1 means winning state position[0] = 0; position[1] = 1; position[2] = 0; position[3] = 1; position[4] = 1; position[5] = 1; position[6] = 1; position[7] = 0; // find states for other positions for (int i = 8; i <= MAX; i++) { if (!position[i - 1] || !position[i - 3] || !position[i - 4]) position[i] = 1; else position[i] = 0; }} // driver functionint main(){ int N = 100; int position[MAX] = { 0 }; findStates(position); if (position[N] == 1) cout << "Player 1"; else cout << "Player 2"; return 0;} // Java program for the variation// in nim gameclass GFG { static final int MAX = 200; // finds the winning and losing // states for the 200 stones. static void findStates(int position[]) { // 0 means losing state // 1 means winning state position[0] = 0; position[1] = 1; position[2] = 0; position[3] = 1; position[4] = 1; position[5] = 1; position[6] = 1; position[7] = 0; // find states for other positions for (int i = 8; i < MAX; i++) { if (position[i - 1]!=1 || position[i - 3]!=1 || position[i - 4]!=1) position[i] = 1; else position[i] = 0; } } //Driver code public static void main (String[] args) { int N = 100; int position[]=new int[MAX]; findStates(position); if (position[N] == 1) System.out.print("Player 1"); else System.out.print("Player 2"); }} // This code is contributed by Anant Agarwal. # Python3 program to find winner of# the game of N stones MAX = 200 # finds the winning and losing# states for the 200 stones.def findStates(position): # 0 means losing state # 1 means winning state position[0] = 0; position[1] = 1; position[2] = 0; position[3] = 1; position[4] = 1; position[5] = 1; position[6] = 1; position[7] = 0 # find states for other positions for i in range(8,MAX+1): if not(position[i - 1]) or not(position[i - 3]) or not(position[i - 4]): position[i] = 1; else: position[i] = 0; #driver functionN = 100position = [0] * (MAX+1) findStates(position) if (position[N] == 1): print("Player 1")else: print("Player 2") # This code is contributed by# Smitha Dinesh Semwal // C# program for the variation// in nim gameusing System; class GFG { static int MAX = 200; // finds the winning and losing // states for the 200 stones. static void findStates(int []position) { // 0 means losing state // 1 means winning state position[0] = 0; position[1] = 1; position[2] = 0; position[3] = 1; position[4] = 1; position[5] = 1; position[6] = 1; position[7] = 0; // find states for other positions for (int i = 8; i < MAX; i++) { if (position[i - 1] != 1 || position[i - 3] != 1 || position[i - 4]!=1) position[i] = 1; else position[i] = 0; } } // Driver code public static void Main () { int N = 100; int []position = new int[MAX]; findStates(position); if (position[N] == 1) Console.WriteLine("Player 1"); else Console.WriteLine("Player 2"); }} // This code is contributed by vt_m. <?php// PHP program to find winner of// the game of N stones$MAX = 200; // finds the winning and losing// states for the 200 stones.function findStates($position){ global $MAX; // 0 means losing state // 1 means winning state $position[0] = 0; $position[1] = 1; $position[2] = 0; $position[3] = 1; $position[4] = 1; $position[5] = 1; $position[6] = 1; $position[7] = 0; // find states for other positions for ($i = 8; $i <= $MAX; $i++) { if (!$position[$i - 1] || !$position[$i - 3] || !$position[$i - 4]) $position[$i] = 1; else $position[$i] = 0; }} // driver function $N = 100; $position[$MAX] = array(0); findStates($position); if ($position == 1) echo "Player 1"; else echo "Player 2"; #This code is contributed by ajit?> <script> // Javascript program for the variation// in nim game let MAX = 200; // finds the winning and losing // states for the 200 stones. function findStates(position) { // 0 means losing state // 1 means winning state position[0] = 0; position[1] = 1; position[2] = 0; position[3] = 1; position[4] = 1; position[5] = 1; position[6] = 1; position[7] = 0; // find states for other positions for (let i = 8; i < MAX; i++) { if (position[i - 1] != 1 || position[i - 3] != 1 || position[i - 4]!=1) position[i] = 1; else position[i] = 0; } } // Driver code let N = 100; let position = []; findStates(position); if (position[N] == 1) document.write("Player 1"); else document.write("Player 2"); // This code is contributed by code_hunt.</script> Output: Player 2 This article is contributed by ARSHPREET_SINGH. 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. vt_m jit_t code_hunt Game Theory Game Theory Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Classification of Algorithms with Examples A Binary String Game Chessboard Pawn-Pawn game Minesweeper Solver Game Theory (Normal-form Game) | Set 4 (Dominance Property-Pure Strategy) Optimal Strategy for the Divisor game using Dynamic Programming Game of replacing array elements Find the winner of the Game to Win by erasing any two consecutive similar alphabets Game Theory (Normal-form Game) | Set 6 (Graphical Method [2 X N] Game) Game Theory (Normal-form Game) | Set 7 (Graphical Method [M X 2] Game)
[ { "code": null, "e": 25853, "s": 25825, "text": "\n26 Apr, 2021" }, { "code": null, "e": 26264, "s": 25853, "text": "Two players are playing a game with n stones where player 1 always plays first. The two players move in alternating turns and plays optimally. In a single move a player can remove either 1, 3 or 4 stones from the pile of stones. If a player is unable to make a move then that player loses the game. Given the number of stones where n is less than equal to 200, find and print the name of the winner.Examples: " }, { "code": null, "e": 26321, "s": 26264, "text": "Input : 4\nOutput : player 1\n\nInput : 7\nOutput : player 2" }, { "code": null, "e": 26619, "s": 26323, "text": "To solve this problem, we need to find each possible value of n as a winning or losing position. Since above game is one of the impartial combinatorial games, therefore the characterization of losing and winning position is valid.The characteristic properties of winning and losing states are: " }, { "code": null, "e": 26664, "s": 26619, "text": "All terminal positions are losing positions." }, { "code": null, "e": 26741, "s": 26664, "text": "From every winning position, there is atleast one move to a losing position." }, { "code": null, "e": 26806, "s": 26741, "text": "From every losing position, every move is to a winning position." }, { "code": null, "e": 27079, "s": 26806, "text": "If a player is able to make a move such that the next move is the losing state than the player is at winning state. Find the state of player 1, if player1 is in winning state then player 1 wins the game otherwise player 2 will win. Consider the following base positions: " }, { "code": null, "e": 28497, "s": 27079, "text": "position 0 is the losing state, if the number of stones is 0 than the player1 will unable to make a move therefore player1 loses.position 1 is the winning state, if the number of stones is 1 than the player1 will remove the stone and win the game.position 2 is the losing state, if the number of stones is 2 than the player1 will remove 1 stone and then player2 will remove the second stone and win the game.position 3 is the winning state, if the player is able to take a move such that the next move is the losing state than the player is at winning state, the palyer1 will remove all the 3 stonesposition 4 is the winning state, if the player is able to take a move such that the next move is the losing state than the player is at winning state, the palyer1 will remove all the 4 stonesposition 5 is the winning state, if the player is able to take a move such that the next move is the losing state than the player is at winning state, the palyer1 will remove 3 stones leaving 2 stones, which is the losing stateposition 6 is the winning state, if the player is able to take a move such that the next move is the losing state than the player is at winning state, the palyer1 will remove 4 stones leaving 2 stones, which is the losing stateposition 7 is the losing state, if the number of stones is 7 than the player1 can remove 1, 3 or 4 stones which all leads to the losing state, therefore player1 will lose. " }, { "code": null, "e": 28627, "s": 28497, "text": "position 0 is the losing state, if the number of stones is 0 than the player1 will unable to make a move therefore player1 loses." }, { "code": null, "e": 28746, "s": 28627, "text": "position 1 is the winning state, if the number of stones is 1 than the player1 will remove the stone and win the game." }, { "code": null, "e": 28908, "s": 28746, "text": "position 2 is the losing state, if the number of stones is 2 than the player1 will remove 1 stone and then player2 will remove the second stone and win the game." }, { "code": null, "e": 29100, "s": 28908, "text": "position 3 is the winning state, if the player is able to take a move such that the next move is the losing state than the player is at winning state, the palyer1 will remove all the 3 stones" }, { "code": null, "e": 29292, "s": 29100, "text": "position 4 is the winning state, if the player is able to take a move such that the next move is the losing state than the player is at winning state, the palyer1 will remove all the 4 stones" }, { "code": null, "e": 29520, "s": 29292, "text": "position 5 is the winning state, if the player is able to take a move such that the next move is the losing state than the player is at winning state, the palyer1 will remove 3 stones leaving 2 stones, which is the losing state" }, { "code": null, "e": 29748, "s": 29520, "text": "position 6 is the winning state, if the player is able to take a move such that the next move is the losing state than the player is at winning state, the palyer1 will remove 4 stones leaving 2 stones, which is the losing state" }, { "code": null, "e": 29922, "s": 29748, "text": "position 7 is the losing state, if the number of stones is 7 than the player1 can remove 1, 3 or 4 stones which all leads to the losing state, therefore player1 will lose. " }, { "code": null, "e": 29971, "s": 29922, "text": "Below is the implementation of above approach: " }, { "code": null, "e": 29975, "s": 29971, "text": "CPP" }, { "code": null, "e": 29980, "s": 29975, "text": "Java" }, { "code": null, "e": 29988, "s": 29980, "text": "Python3" }, { "code": null, "e": 29991, "s": 29988, "text": "C#" }, { "code": null, "e": 29995, "s": 29991, "text": "PHP" }, { "code": null, "e": 30006, "s": 29995, "text": "Javascript" }, { "code": "// CPP program to find winner of// the game of N stones#include <bits/stdc++.h>using namespace std; const int MAX = 200; // finds the winning and losing// states for the 200 stones.void findStates(int position[]){ // 0 means losing state // 1 means winning state position[0] = 0; position[1] = 1; position[2] = 0; position[3] = 1; position[4] = 1; position[5] = 1; position[6] = 1; position[7] = 0; // find states for other positions for (int i = 8; i <= MAX; i++) { if (!position[i - 1] || !position[i - 3] || !position[i - 4]) position[i] = 1; else position[i] = 0; }} // driver functionint main(){ int N = 100; int position[MAX] = { 0 }; findStates(position); if (position[N] == 1) cout << \"Player 1\"; else cout << \"Player 2\"; return 0;}", "e": 30869, "s": 30006, "text": null }, { "code": "// Java program for the variation// in nim gameclass GFG { static final int MAX = 200; // finds the winning and losing // states for the 200 stones. static void findStates(int position[]) { // 0 means losing state // 1 means winning state position[0] = 0; position[1] = 1; position[2] = 0; position[3] = 1; position[4] = 1; position[5] = 1; position[6] = 1; position[7] = 0; // find states for other positions for (int i = 8; i < MAX; i++) { if (position[i - 1]!=1 || position[i - 3]!=1 || position[i - 4]!=1) position[i] = 1; else position[i] = 0; } } //Driver code public static void main (String[] args) { int N = 100; int position[]=new int[MAX]; findStates(position); if (position[N] == 1) System.out.print(\"Player 1\"); else System.out.print(\"Player 2\"); }} // This code is contributed by Anant Agarwal.", "e": 32005, "s": 30869, "text": null }, { "code": "# Python3 program to find winner of# the game of N stones MAX = 200 # finds the winning and losing# states for the 200 stones.def findStates(position): # 0 means losing state # 1 means winning state position[0] = 0; position[1] = 1; position[2] = 0; position[3] = 1; position[4] = 1; position[5] = 1; position[6] = 1; position[7] = 0 # find states for other positions for i in range(8,MAX+1): if not(position[i - 1]) or not(position[i - 3]) or not(position[i - 4]): position[i] = 1; else: position[i] = 0; #driver functionN = 100position = [0] * (MAX+1) findStates(position) if (position[N] == 1): print(\"Player 1\")else: print(\"Player 2\") # This code is contributed by# Smitha Dinesh Semwal", "e": 32789, "s": 32005, "text": null }, { "code": "// C# program for the variation// in nim gameusing System; class GFG { static int MAX = 200; // finds the winning and losing // states for the 200 stones. static void findStates(int []position) { // 0 means losing state // 1 means winning state position[0] = 0; position[1] = 1; position[2] = 0; position[3] = 1; position[4] = 1; position[5] = 1; position[6] = 1; position[7] = 0; // find states for other positions for (int i = 8; i < MAX; i++) { if (position[i - 1] != 1 || position[i - 3] != 1 || position[i - 4]!=1) position[i] = 1; else position[i] = 0; } } // Driver code public static void Main () { int N = 100; int []position = new int[MAX]; findStates(position); if (position[N] == 1) Console.WriteLine(\"Player 1\"); else Console.WriteLine(\"Player 2\"); }} // This code is contributed by vt_m.", "e": 33902, "s": 32789, "text": null }, { "code": "<?php// PHP program to find winner of// the game of N stones$MAX = 200; // finds the winning and losing// states for the 200 stones.function findStates($position){ global $MAX; // 0 means losing state // 1 means winning state $position[0] = 0; $position[1] = 1; $position[2] = 0; $position[3] = 1; $position[4] = 1; $position[5] = 1; $position[6] = 1; $position[7] = 0; // find states for other positions for ($i = 8; $i <= $MAX; $i++) { if (!$position[$i - 1] || !$position[$i - 3] || !$position[$i - 4]) $position[$i] = 1; else $position[$i] = 0; }} // driver function $N = 100; $position[$MAX] = array(0); findStates($position); if ($position == 1) echo \"Player 1\"; else echo \"Player 2\"; #This code is contributed by ajit?>", "e": 34757, "s": 33902, "text": null }, { "code": "<script> // Javascript program for the variation// in nim game let MAX = 200; // finds the winning and losing // states for the 200 stones. function findStates(position) { // 0 means losing state // 1 means winning state position[0] = 0; position[1] = 1; position[2] = 0; position[3] = 1; position[4] = 1; position[5] = 1; position[6] = 1; position[7] = 0; // find states for other positions for (let i = 8; i < MAX; i++) { if (position[i - 1] != 1 || position[i - 3] != 1 || position[i - 4]!=1) position[i] = 1; else position[i] = 0; } } // Driver code let N = 100; let position = []; findStates(position); if (position[N] == 1) document.write(\"Player 1\"); else document.write(\"Player 2\"); // This code is contributed by code_hunt.</script>", "e": 35809, "s": 34757, "text": null }, { "code": null, "e": 35819, "s": 35809, "text": "Output: " }, { "code": null, "e": 35828, "s": 35819, "text": "Player 2" }, { "code": null, "e": 36256, "s": 35828, "text": "This article is contributed by ARSHPREET_SINGH. 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. " }, { "code": null, "e": 36261, "s": 36256, "text": "vt_m" }, { "code": null, "e": 36267, "s": 36261, "text": "jit_t" }, { "code": null, "e": 36277, "s": 36267, "text": "code_hunt" }, { "code": null, "e": 36289, "s": 36277, "text": "Game Theory" }, { "code": null, "e": 36301, "s": 36289, "text": "Game Theory" }, { "code": null, "e": 36399, "s": 36301, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36442, "s": 36399, "text": "Classification of Algorithms with Examples" }, { "code": null, "e": 36463, "s": 36442, "text": "A Binary String Game" }, { "code": null, "e": 36489, "s": 36463, "text": "Chessboard Pawn-Pawn game" }, { "code": null, "e": 36508, "s": 36489, "text": "Minesweeper Solver" }, { "code": null, "e": 36582, "s": 36508, "text": "Game Theory (Normal-form Game) | Set 4 (Dominance Property-Pure Strategy)" }, { "code": null, "e": 36646, "s": 36582, "text": "Optimal Strategy for the Divisor game using Dynamic Programming" }, { "code": null, "e": 36679, "s": 36646, "text": "Game of replacing array elements" }, { "code": null, "e": 36763, "s": 36679, "text": "Find the winner of the Game to Win by erasing any two consecutive similar alphabets" }, { "code": null, "e": 36834, "s": 36763, "text": "Game Theory (Normal-form Game) | Set 6 (Graphical Method [2 X N] Game)" } ]
Slow Start Backoff Algorithm for Ad-Hoc - GeeksforGeeks
17 Jan, 2022 If the receiver proclaims a large window-size, larger than what the network en-route can manage, then there will always be packet losses. So there will be re-transmissions as well. However, the sender can’t send all the packets for which ACK (Acknowledgement) has not been received. Because of this way, even more congestion in the network will be caused. Moreover, the sender cannot be sure about the packets that have been lost due to transmission. It might be that this is the only packet that has been lost. It will also be not know how many packets have been actually received and buffered by the receiver. In that case, the sender will have superfluously sent various packets.So the re-transmission of the packets also follows slow – start backoff mechanism. However, we do precisely need to keep an upper bound on the size of the packets as it gets increases in slow start, to prevent it from the increasing in unbounded and causing congestion. In slow – start backoff mechanism the threshold window size is half the value of the size of the congestion window.Prerequisite: Back-off Algorithm for CSMA/CD Algorithm of Slow-Start Mechanism:- repeat if ACK frame received then successful transmission if current backoff window size <= Wm then if current backoff window size = W0 then current backoff window size = W0 else current backoff window size = current backoff window size ÷ 2 else current backoff window size = current backoff window size-W0 else if current backoff window size < Wm then current backoff window size = current backoff window size × 2 else frame lost due to collision or interference if current backoff window size = Wn then current backoff window size = Wn else current backoff window size = current backoff window size +W0 until no more frame to transmit end Examples: This represents the successful transmission because Threshold window is lesser the current window. Input : Enter the Threshold value:–>512 Enter the Current backoff window size:–>64 Output : Backoff Window Size is:–>128 Backoff Window Size is:–>96 Successful transmission Backoff Window Size is:–>32 Successful transmission Backoff Window Size is:–>32 Backoff Window Size is:–>128 Backoff Window Size is:–>96 Successful transmission Backoff Window Size is:–>32This represents the unsuccessful transmission because the threshold window is greater the current window. Input : Enter the Threshold value:–>512 Enter the Current backoff window size:–>1024 Output : Frame lost due to collision or interferenceBackoff Window Size is:–>1056 Successful transmission Backoff Window Size is:–>512 Successful transmission Backoff Window Size is:–>512 Frame lost due to collision or interferenceBackoff Window Size is:–>1056 Successful transmission Backoff Window Size is:–>512 Notations:- W0 --> Initial backoff window size Wm --> Threshold Wn --> Maximum backoff window size ACK --> Acknowledgement Curr_BT --> Current backoff window size Implementation of the Slow-Start Mechanism:- CPP #include <cstdlib>#include <iostream>#include <math.h>#include <random>#include <string>#include <time.h> using namespace std; void signal(int array_ACK[]){ srand(time_t(0)); for (int i = 0; i < 5; i++) { array_ACK[i] = rand() % 2; }} void Slow_Start_Backoff(int Wm, int Wo, int Wn, int Curr_BT, int array_ACK[]){ // Taking ACK Binary values in // array by user one by one // backoff_win_size defines // backoff window size int backoff_win_size = 0; // Printing of backoff window size takes place for (int j = 0; j < 5; j++) { if (array_ACK[j] == 1) { cout << "Successful transmission" << endl; if (Curr_BT <= Wm) { if (Curr_BT == Wo) { Curr_BT = Wo; cout << "Backoff Window Size is:-->" << Curr_BT << endl; } else { Curr_B= Curr_BT / 2; cout << "Backoff Window Size is:-->" << Curr_BT << endl; } } else { Curr_BT = Curr_BT - Wo; cout << "Backoff Window Size is:-->" << Curr_BT << endl; } } else { if (Curr_BT < Wm) { Curr_BT = Curr_BT * 2; cout << "Backoff Window Size is:-->" << Curr_BT << endl; } else { cout << "Frame lost due to collision" <<" or interference"; } if (Curr_BT == Wn) { Curr_BT = Wn; cout << "Backoff Window Size is:-->" << Curr_BT << endl << endl; } else { Curr_BT = Curr_BT + Wo; cout << "Backoff Window Size is:-->" << Curr_BT << endl; } } }} // Driver Codeint main(){ int Wm, Wo, Wn, Curr_BT; int array_ACK[5]; Wo = 32; // Initial backoff window size Wn = 1024; // Maximum backoff window size // Curr_BT defines the current backoff window size cout << "Enter the Threshold value:-->"; cin >> Wm; // Threshold backoff window size cout << "Enter the Current backoff window size:-->"; cin >> Curr_BT; signal(array_ACK); Slow_Start_Backoff(Wm, Wo, Wn, Curr_BT, array_ACK); return 0;} How the data sent in the form of packets through the network:-Any type of data gets converted into the binary format and this binary format contains 0’s and 1’s bytes which gets divided into the small binary bit sequences called packets.Now, we are implementing code in which the random matrix of 0’s and 1’s generates and suppose the binary file bit sequence arranged in the matrix row-wise in fixed-length (Taking a Length 10). Then each row of the matrix represents a single data packet that is going to be transmitted.Implementation of the Random Matrix Generator:- CPP // C++ program to construct the// Random Matrix Generator.#include <iostream>#include <iterator>#include <list>#include <random>#include <string>using namespace std; void showlist(list<string> l1){ list<string>::iterator it; cout << "list of frame packets are " <<"show as below :-> " << endl; cout << endl; for (it = l1.begin(); it != l1.end(); ++it) cout << *it << endl; cout << '\n';} // Driver Codeint main(){ int x, y, k = 1; string s, s1, s2; list<string> l1; srand(time_t(0)); cout << "Rows: " << endl; cin >> x; cout << "Columns: " << endl; cin >> y; int randomNums[x][y]; std::string temp[x]; int random; for (int i = 0; i < x; i++) { // This loop is for the row for (int p = 0; p < y; p++) { // Here you would randomize each // element for the array. random = rand() % 2; randomNums[i][p] = random; } } for (int i = 0; i < x; i++) { // This loop is for the row for (int p = 0; p < y; p++) { // Here you would randomize each // element for the array. cout << randomNums[i][p] << "\t"; } cout << endl; } cout << endl; // concatenation of the bits in the matrix row // to form a single data packet for (int i = 0; i < x; i++) { temp[i] = to_string(randomNums[i][0]); for (int j = 0; j < y; ++j) { s1 = temp[i]; s2 = to_string(randomNums[i][j]); s = s1 + s2; temp[i] = s; k++; } temp[i].erase(temp[i].begin() + 1); l1.push_back(temp[i]); } showlist(l1); return 0;} Example: Input: Rows: 10 Columns: 10 Output: 0 1 1 0 1 1 0 1 0 1 0 0 0 0 0 0 1 1 0 0 0 1 1 0 1 1 0 1 1 1 0 1 0 0 0 0 1 0 0 0 0 0 1 1 0 0 1 0 0 0 0 0 0 0 1 0 1 1 1 0 0 0 1 1 0 0 1 1 0 1 1 1 0 0 1 1 0 0 0 1 1 1 0 0 1 0 1 1 1 1 0 1 0 1 1 0 0 1 1 1 list of frame packets are show as below :-> 0110110101 0000001100 0110110111 0100001000 0011001000 0000101110 0011001101 1100110001 1100101111 0101100111 Reference: Slow Start Backoff Algorithm for Ad-Hoc Wireless Networks devashishchoudhary kushagrabansal8755 clintra simmytarika5 Advanced Computer Subject Articles Computer Networks Mathematical Randomized Mathematical Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Copying Files to and from Docker Containers Fuzzy Logic | Introduction Basics of API Testing Using Postman Principal Component Analysis with Python Q-Learning in Python Tree Traversals (Inorder, Preorder and Postorder) SQL | Join (Inner, Left, Right and Full Joins) find command in Linux with examples Analysis of Algorithms | Set 1 (Asymptotic Analysis) SQL Interview Questions
[ { "code": null, "e": 25661, "s": 25633, "text": "\n17 Jan, 2022" }, { "code": null, "e": 26811, "s": 25661, "text": "If the receiver proclaims a large window-size, larger than what the network en-route can manage, then there will always be packet losses. So there will be re-transmissions as well. However, the sender can’t send all the packets for which ACK (Acknowledgement) has not been received. Because of this way, even more congestion in the network will be caused. Moreover, the sender cannot be sure about the packets that have been lost due to transmission. It might be that this is the only packet that has been lost. It will also be not know how many packets have been actually received and buffered by the receiver. In that case, the sender will have superfluously sent various packets.So the re-transmission of the packets also follows slow – start backoff mechanism. However, we do precisely need to keep an upper bound on the size of the packets as it gets increases in slow start, to prevent it from the increasing in unbounded and causing congestion. In slow – start backoff mechanism the threshold window size is half the value of the size of the congestion window.Prerequisite: Back-off Algorithm for CSMA/CD Algorithm of Slow-Start Mechanism:- " }, { "code": null, "e": 27483, "s": 26811, "text": "repeat\n if ACK frame received then successful transmission\n if current backoff window size <= Wm then\n if current backoff window size = W0 then\n current backoff window size = W0\n else\n current backoff window size = current backoff window size ÷ 2\n else\n current backoff window size = current backoff window size-W0\nelse\n if current backoff window size < Wm then\n current backoff window size = current backoff window size × 2\n else frame lost due to collision or interference\n if current backoff window size = Wn then\n current backoff window size = Wn\n else\n current backoff window size = current backoff window size +W0\nuntil no more frame to transmit\nend" }, { "code": null, "e": 27495, "s": 27483, "text": "Examples: " }, { "code": null, "e": 28462, "s": 27495, "text": "This represents the successful transmission because Threshold window is lesser the current window. Input : Enter the Threshold value:–>512 Enter the Current backoff window size:–>64 Output : Backoff Window Size is:–>128 Backoff Window Size is:–>96 Successful transmission Backoff Window Size is:–>32 Successful transmission Backoff Window Size is:–>32 Backoff Window Size is:–>128 Backoff Window Size is:–>96 Successful transmission Backoff Window Size is:–>32This represents the unsuccessful transmission because the threshold window is greater the current window. Input : Enter the Threshold value:–>512 Enter the Current backoff window size:–>1024 Output : Frame lost due to collision or interferenceBackoff Window Size is:–>1056 Successful transmission Backoff Window Size is:–>512 Successful transmission Backoff Window Size is:–>512 Frame lost due to collision or interferenceBackoff Window Size is:–>1056 Successful transmission Backoff Window Size is:–>512 " }, { "code": null, "e": 28475, "s": 28462, "text": "Notations:- " }, { "code": null, "e": 28630, "s": 28475, "text": "W0 --> Initial backoff window size\nWm --> Threshold\nWn --> Maximum backoff window size\nACK --> Acknowledgement\nCurr_BT --> Current backoff window size" }, { "code": null, "e": 28676, "s": 28630, "text": "Implementation of the Slow-Start Mechanism:- " }, { "code": null, "e": 28680, "s": 28676, "text": "CPP" }, { "code": "#include <cstdlib>#include <iostream>#include <math.h>#include <random>#include <string>#include <time.h> using namespace std; void signal(int array_ACK[]){ srand(time_t(0)); for (int i = 0; i < 5; i++) { array_ACK[i] = rand() % 2; }} void Slow_Start_Backoff(int Wm, int Wo, int Wn, int Curr_BT, int array_ACK[]){ // Taking ACK Binary values in // array by user one by one // backoff_win_size defines // backoff window size int backoff_win_size = 0; // Printing of backoff window size takes place for (int j = 0; j < 5; j++) { if (array_ACK[j] == 1) { cout << \"Successful transmission\" << endl; if (Curr_BT <= Wm) { if (Curr_BT == Wo) { Curr_BT = Wo; cout << \"Backoff Window Size is:-->\" << Curr_BT << endl; } else { Curr_B= Curr_BT / 2; cout << \"Backoff Window Size is:-->\" << Curr_BT << endl; } } else { Curr_BT = Curr_BT - Wo; cout << \"Backoff Window Size is:-->\" << Curr_BT << endl; } } else { if (Curr_BT < Wm) { Curr_BT = Curr_BT * 2; cout << \"Backoff Window Size is:-->\" << Curr_BT << endl; } else { cout << \"Frame lost due to collision\" <<\" or interference\"; } if (Curr_BT == Wn) { Curr_BT = Wn; cout << \"Backoff Window Size is:-->\" << Curr_BT << endl << endl; } else { Curr_BT = Curr_BT + Wo; cout << \"Backoff Window Size is:-->\" << Curr_BT << endl; } } }} // Driver Codeint main(){ int Wm, Wo, Wn, Curr_BT; int array_ACK[5]; Wo = 32; // Initial backoff window size Wn = 1024; // Maximum backoff window size // Curr_BT defines the current backoff window size cout << \"Enter the Threshold value:-->\"; cin >> Wm; // Threshold backoff window size cout << \"Enter the Current backoff window size:-->\"; cin >> Curr_BT; signal(array_ACK); Slow_Start_Backoff(Wm, Wo, Wn, Curr_BT, array_ACK); return 0;}", "e": 31129, "s": 28680, "text": null }, { "code": null, "e": 31699, "s": 31129, "text": "How the data sent in the form of packets through the network:-Any type of data gets converted into the binary format and this binary format contains 0’s and 1’s bytes which gets divided into the small binary bit sequences called packets.Now, we are implementing code in which the random matrix of 0’s and 1’s generates and suppose the binary file bit sequence arranged in the matrix row-wise in fixed-length (Taking a Length 10). Then each row of the matrix represents a single data packet that is going to be transmitted.Implementation of the Random Matrix Generator:-" }, { "code": null, "e": 31703, "s": 31699, "text": "CPP" }, { "code": "// C++ program to construct the// Random Matrix Generator.#include <iostream>#include <iterator>#include <list>#include <random>#include <string>using namespace std; void showlist(list<string> l1){ list<string>::iterator it; cout << \"list of frame packets are \" <<\"show as below :-> \" << endl; cout << endl; for (it = l1.begin(); it != l1.end(); ++it) cout << *it << endl; cout << '\\n';} // Driver Codeint main(){ int x, y, k = 1; string s, s1, s2; list<string> l1; srand(time_t(0)); cout << \"Rows: \" << endl; cin >> x; cout << \"Columns: \" << endl; cin >> y; int randomNums[x][y]; std::string temp[x]; int random; for (int i = 0; i < x; i++) { // This loop is for the row for (int p = 0; p < y; p++) { // Here you would randomize each // element for the array. random = rand() % 2; randomNums[i][p] = random; } } for (int i = 0; i < x; i++) { // This loop is for the row for (int p = 0; p < y; p++) { // Here you would randomize each // element for the array. cout << randomNums[i][p] << \"\\t\"; } cout << endl; } cout << endl; // concatenation of the bits in the matrix row // to form a single data packet for (int i = 0; i < x; i++) { temp[i] = to_string(randomNums[i][0]); for (int j = 0; j < y; ++j) { s1 = temp[i]; s2 = to_string(randomNums[i][j]); s = s1 + s2; temp[i] = s; k++; } temp[i].erase(temp[i].begin() + 1); l1.push_back(temp[i]); } showlist(l1); return 0;}", "e": 33527, "s": 31703, "text": null }, { "code": null, "e": 33538, "s": 33527, "text": "Example: " }, { "code": null, "e": 33930, "s": 33538, "text": "Input: Rows: 10 Columns: 10 Output: 0 1 1 0 1 1 0 1 0 1 0 0 0 0 0 0 1 1 0 0 0 1 1 0 1 1 0 1 1 1 0 1 0 0 0 0 1 0 0 0 0 0 1 1 0 0 1 0 0 0 0 0 0 0 1 0 1 1 1 0 0 0 1 1 0 0 1 1 0 1 1 1 0 0 1 1 0 0 0 1 1 1 0 0 1 0 1 1 1 1 0 1 0 1 1 0 0 1 1 1 list of frame packets are show as below :-> 0110110101 0000001100 0110110111 0100001000 0011001000 0000101110 0011001101 1100110001 1100101111 0101100111 " }, { "code": null, "e": 33999, "s": 33930, "text": "Reference: Slow Start Backoff Algorithm for Ad-Hoc Wireless Networks" }, { "code": null, "e": 34018, "s": 33999, "text": "devashishchoudhary" }, { "code": null, "e": 34037, "s": 34018, "text": "kushagrabansal8755" }, { "code": null, "e": 34045, "s": 34037, "text": "clintra" }, { "code": null, "e": 34058, "s": 34045, "text": "simmytarika5" }, { "code": null, "e": 34084, "s": 34058, "text": "Advanced Computer Subject" }, { "code": null, "e": 34093, "s": 34084, "text": "Articles" }, { "code": null, "e": 34111, "s": 34093, "text": "Computer Networks" }, { "code": null, "e": 34124, "s": 34111, "text": "Mathematical" }, { "code": null, "e": 34135, "s": 34124, "text": "Randomized" }, { "code": null, "e": 34148, "s": 34135, "text": "Mathematical" }, { "code": null, "e": 34166, "s": 34148, "text": "Computer Networks" }, { "code": null, "e": 34264, "s": 34166, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34308, "s": 34264, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 34335, "s": 34308, "text": "Fuzzy Logic | Introduction" }, { "code": null, "e": 34371, "s": 34335, "text": "Basics of API Testing Using Postman" }, { "code": null, "e": 34412, "s": 34371, "text": "Principal Component Analysis with Python" }, { "code": null, "e": 34433, "s": 34412, "text": "Q-Learning in Python" }, { "code": null, "e": 34483, "s": 34433, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 34530, "s": 34483, "text": "SQL | Join (Inner, Left, Right and Full Joins)" }, { "code": null, "e": 34566, "s": 34530, "text": "find command in Linux with examples" }, { "code": null, "e": 34619, "s": 34566, "text": "Analysis of Algorithms | Set 1 (Asymptotic Analysis)" } ]
Program to find size of Doubly Linked List - GeeksforGeeks
23 May, 2021 Given a doubly linked list, the task is to find the size of that doubly linked list. For example, size of below linked list is 4. A doubly linked list is a linked data structure that consists of a set of sequentially linked records called nodes. Each node contains two fields, called links, that are references to the previous and to the next node in the sequence of nodes.Traversal of a doubly linked list can be in either direction. In fact, the direction of traversal can change many times, if desired. For example the function should return 3 for the above doubly linked list. 1) Initialize size to 0. 2) Initialize a node pointer, temp = head. 3) Do following while temp is not NULL ......a) temp = temp -> next ......b) size++; 4) Return size. C++ Java Python3 C# Javascript // A complete working C++ program to// find size of doubly linked list.#include <bits/stdc++.h>using namespace std; // A linked list nodestruct Node{ int data; struct Node *next; struct Node *prev;}; /* Function to add a node to front of doubly linked list */void push(struct Node** head_ref, int new_data){ struct Node* new_node = new Node; new_node->data = new_data; new_node->next = (*head_ref); new_node->prev = NULL; if ((*head_ref) != NULL) (*head_ref)->prev = new_node ; (*head_ref) = new_node;} // This function returns size of linked listint findSize(struct Node *node){ int res = 0; while (node != NULL) { res++; node = node->next; } return res;} /* Driver program to test above functions*/int main(){ struct Node* head = NULL; push(&head, 4); push(&head, 3); push(&head, 2); push(&head, 1); cout << findSize(head); return 0;} // A complete working Java program to// find size of doubly linked list.import java.io.*;import java.util.*; // Represents a doubly linked list nodeclass Node{ int data; Node next, prev; Node(int val) { data = val; next = null; prev = null; }} class GFG{ /* Function to add a node to front of doubly linked list */ static Node push(Node head, int data) { Node new_node = new Node(data); new_node.next = head; new_node.prev = null; if (head != null) head.prev = new_node; head = new_node; return head; } // This function returns size of doubly linked list static int findSize(Node node) { int res = 0; while (node != null) { res++; node = node.next; } return res; } // Driver Code public static void main(String args[]) { Node head = null; head = push(head, 4); head = push(head, 3); head = push(head, 2); head = push(head, 1); System.out.println(findSize(head)); }} // This code is contributed by rachana soma # A complete working Python3 program to# find size of doubly linked list. # A linked list nodeclass Node: def __init__(self): self.data = None self.next = None self.prev = None # Function to add a node to front of doubly# linked listdef push( head_ref, new_data): new_node = Node() new_node.data = new_data new_node.next = (head_ref) new_node.prev = None if ((head_ref) != None): (head_ref).prev = new_node (head_ref) = new_node return head_ref # This function returns size of linked listdef findSize(node): res = 0 while (node != None): res = res + 1 node = node.next return res # Driver codehead = Nonehead = push(head, 4)head = push(head, 3)head = push(head, 2)head = push(head, 1)print(findSize(head)) # This code is contributed by Arnab Kundu // A complete working C# program to// find size of doubly linked list. using System; // Represents a doubly linked list nodepublic class Node{ public int data; public Node next, prev; public Node(int val) { data = val; next = null; prev = null; }} class GFG{ /* Function to add a node to front of doubly linked list */ static Node push(Node head, int data) { Node new_node = new Node(data); new_node.next = head; new_node.prev = null; if (head != null) head.prev = new_node; head = new_node; return head; } // This function returns size of doubly linked list static int findSize(Node node) { int res = 0; while (node != null) { res++; node = node.next; } return res; } // Driver Code public static void Main(String []args) { Node head = null; head = push(head, 4); head = push(head, 3); head = push(head, 2); head = push(head, 1); Console.WriteLine(findSize(head)); }} // This code is contributed by Arnab Kundu <script>// A complete working javascript program to// find size of doubly linked list.// Represents a doubly linked list node class Node { constructor(val) { this.data = val; this.prev = null; this.next = null; } } /* * Function to add a node to front of doubly linked list */ function push(head , data) {var new_node = new Node(data); new_node.next = head; new_node.prev = null; if (head != null) head.prev = new_node; head = new_node; return head; } // This function returns size of doubly linked list function findSize(node) { var res = 0; while (node != null) { res++; node = node.next; } return res; } // Driver Code var head = null; head = push(head, 4); head = push(head, 3); head = push(head, 2); head = push(head, 1); document.write(findSize(head)); // This code contributed by aashish1995</script> 4 rachana soma andrew1234 nidhi_biet aashish1995 doubly linked list Linked List Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Linked List | Set 1 (Introduction) Linked List | Set 2 (Inserting a node) Stack Data Structure (Introduction and Program) Linked List | Set 3 (Deleting a node) LinkedList in Java Linked List vs Array Detect loop in a linked list Merge two sorted linked lists Find the middle of a given linked list Delete a Linked List node at a given position
[ { "code": null, "e": 32366, "s": 32338, "text": "\n23 May, 2021" }, { "code": null, "e": 32497, "s": 32366, "text": "Given a doubly linked list, the task is to find the size of that doubly linked list. For example, size of below linked list is 4. " }, { "code": null, "e": 32877, "s": 32501, "text": "A doubly linked list is a linked data structure that consists of a set of sequentially linked records called nodes. Each node contains two fields, called links, that are references to the previous and to the next node in the sequence of nodes.Traversal of a doubly linked list can be in either direction. In fact, the direction of traversal can change many times, if desired." }, { "code": null, "e": 32953, "s": 32877, "text": "For example the function should return 3 for the above doubly linked list. " }, { "code": null, "e": 33123, "s": 32953, "text": "1) Initialize size to 0. 2) Initialize a node pointer, temp = head. 3) Do following while temp is not NULL ......a) temp = temp -> next ......b) size++; 4) Return size. " }, { "code": null, "e": 33127, "s": 33123, "text": "C++" }, { "code": null, "e": 33132, "s": 33127, "text": "Java" }, { "code": null, "e": 33140, "s": 33132, "text": "Python3" }, { "code": null, "e": 33143, "s": 33140, "text": "C#" }, { "code": null, "e": 33154, "s": 33143, "text": "Javascript" }, { "code": "// A complete working C++ program to// find size of doubly linked list.#include <bits/stdc++.h>using namespace std; // A linked list nodestruct Node{ int data; struct Node *next; struct Node *prev;}; /* Function to add a node to front of doubly linked list */void push(struct Node** head_ref, int new_data){ struct Node* new_node = new Node; new_node->data = new_data; new_node->next = (*head_ref); new_node->prev = NULL; if ((*head_ref) != NULL) (*head_ref)->prev = new_node ; (*head_ref) = new_node;} // This function returns size of linked listint findSize(struct Node *node){ int res = 0; while (node != NULL) { res++; node = node->next; } return res;} /* Driver program to test above functions*/int main(){ struct Node* head = NULL; push(&head, 4); push(&head, 3); push(&head, 2); push(&head, 1); cout << findSize(head); return 0;}", "e": 34073, "s": 33154, "text": null }, { "code": "// A complete working Java program to// find size of doubly linked list.import java.io.*;import java.util.*; // Represents a doubly linked list nodeclass Node{ int data; Node next, prev; Node(int val) { data = val; next = null; prev = null; }} class GFG{ /* Function to add a node to front of doubly linked list */ static Node push(Node head, int data) { Node new_node = new Node(data); new_node.next = head; new_node.prev = null; if (head != null) head.prev = new_node; head = new_node; return head; } // This function returns size of doubly linked list static int findSize(Node node) { int res = 0; while (node != null) { res++; node = node.next; } return res; } // Driver Code public static void main(String args[]) { Node head = null; head = push(head, 4); head = push(head, 3); head = push(head, 2); head = push(head, 1); System.out.println(findSize(head)); }} // This code is contributed by rachana soma", "e": 35235, "s": 34073, "text": null }, { "code": "# A complete working Python3 program to# find size of doubly linked list. # A linked list nodeclass Node: def __init__(self): self.data = None self.next = None self.prev = None # Function to add a node to front of doubly# linked listdef push( head_ref, new_data): new_node = Node() new_node.data = new_data new_node.next = (head_ref) new_node.prev = None if ((head_ref) != None): (head_ref).prev = new_node (head_ref) = new_node return head_ref # This function returns size of linked listdef findSize(node): res = 0 while (node != None): res = res + 1 node = node.next return res # Driver codehead = Nonehead = push(head, 4)head = push(head, 3)head = push(head, 2)head = push(head, 1)print(findSize(head)) # This code is contributed by Arnab Kundu", "e": 36065, "s": 35235, "text": null }, { "code": "// A complete working C# program to// find size of doubly linked list. using System; // Represents a doubly linked list nodepublic class Node{ public int data; public Node next, prev; public Node(int val) { data = val; next = null; prev = null; }} class GFG{ /* Function to add a node to front of doubly linked list */ static Node push(Node head, int data) { Node new_node = new Node(data); new_node.next = head; new_node.prev = null; if (head != null) head.prev = new_node; head = new_node; return head; } // This function returns size of doubly linked list static int findSize(Node node) { int res = 0; while (node != null) { res++; node = node.next; } return res; } // Driver Code public static void Main(String []args) { Node head = null; head = push(head, 4); head = push(head, 3); head = push(head, 2); head = push(head, 1); Console.WriteLine(findSize(head)); }} // This code is contributed by Arnab Kundu", "e": 37229, "s": 36065, "text": null }, { "code": "<script>// A complete working javascript program to// find size of doubly linked list.// Represents a doubly linked list node class Node { constructor(val) { this.data = val; this.prev = null; this.next = null; } } /* * Function to add a node to front of doubly linked list */ function push(head , data) {var new_node = new Node(data); new_node.next = head; new_node.prev = null; if (head != null) head.prev = new_node; head = new_node; return head; } // This function returns size of doubly linked list function findSize(node) { var res = 0; while (node != null) { res++; node = node.next; } return res; } // Driver Code var head = null; head = push(head, 4); head = push(head, 3); head = push(head, 2); head = push(head, 1); document.write(findSize(head)); // This code contributed by aashish1995</script>", "e": 38255, "s": 37229, "text": null }, { "code": null, "e": 38257, "s": 38255, "text": "4" }, { "code": null, "e": 38272, "s": 38259, "text": "rachana soma" }, { "code": null, "e": 38283, "s": 38272, "text": "andrew1234" }, { "code": null, "e": 38294, "s": 38283, "text": "nidhi_biet" }, { "code": null, "e": 38306, "s": 38294, "text": "aashish1995" }, { "code": null, "e": 38325, "s": 38306, "text": "doubly linked list" }, { "code": null, "e": 38337, "s": 38325, "text": "Linked List" }, { "code": null, "e": 38349, "s": 38337, "text": "Linked List" }, { "code": null, "e": 38447, "s": 38349, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38482, "s": 38447, "text": "Linked List | Set 1 (Introduction)" }, { "code": null, "e": 38521, "s": 38482, "text": "Linked List | Set 2 (Inserting a node)" }, { "code": null, "e": 38569, "s": 38521, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 38607, "s": 38569, "text": "Linked List | Set 3 (Deleting a node)" }, { "code": null, "e": 38626, "s": 38607, "text": "LinkedList in Java" }, { "code": null, "e": 38647, "s": 38626, "text": "Linked List vs Array" }, { "code": null, "e": 38676, "s": 38647, "text": "Detect loop in a linked list" }, { "code": null, "e": 38706, "s": 38676, "text": "Merge two sorted linked lists" }, { "code": null, "e": 38745, "s": 38706, "text": "Find the middle of a given linked list" } ]
Rust-Powered Command-Line Utilities to Increase Your Productivity | by Shinichi Okada | Towards Data Science
Table of ContentsIntroduction1. du alternatives: dust and dutree ∘ dust ∘ dutree2. time alternative: hyperfine3. A fuzzy finder: skim4. sed alternative: sd5. top/htop alternatives: ytop and bottom6. A Bonus TipConclusion Last month, I wrote an article sharing seven Rust-powered command-line utilities. Those are modern and fast tools you can use every day with your terminal. Since publishing that original article, I’ve been searching for more Rust-powered command-line utilities, and I discovered more gems that I’m excited to share with you today. These tools will help you be productive with your terminal work. I recommend installing Rust. When you install Rust, it will install Cargo as one of the toolchains. And you can install Rust-powered tools with Cargo. If you want to start learning Rust, this article can help you get started. Let’s dive in. In Linux, the du command estimates file space usage. dust and dutree are Rust-powered du alternatives. It is difficult to use du command for me. For example with du, listing files and folders and totaling the size including subfolders I use: $ du -sk * | sort -nr Dust gives you an instant overview of directories and its disk space and commands are simpler. For example $ dust$ dust <dir>$ dust <dir> <another_dir> <and_more>$ dust -p <dir> (full-path) You can find all the usage here. In the above image, you can see that the app directory occupies 57MB(29%) and the target directory occupies 139 MB (71%) of disk space. You can install dust with Cargo. $ cargo install du-dust$ dust --help You can find other installations here. dutreeis another du alternative to analyze disk usage. You can install dutree with Cargo. $ cargo install dutree You can find usage by dutree --help. dutree has also simple command options. For example, you can display directories using the -d option to different directory depth. $ dutree -d // the default is 1$ dutree -d2 // show directories up to depth 2 In Linux, the time command shows you how long a given command takes to run. It is useful for testing the performance of your scripts and commands. Let’s say you have two scripts or commands doing the same job. You can use the time command to compare the time required for these scripts. hyperfine is a Rust-powered, time alternative, command-line benchmarking tool. Installing it with Cargo: $ cargo install hyperfine If you run hyperfine with --warmup N, the hyperfine will perform the warmup N times before the actual measurement. // warmup run$ hyperfine --warmup 3 'dutree -d' 'dutree -d2' 'dust'// actual run$ hyperfine 'dutree -d' 'dutree -d2' 'dust' A fuzzy finder helps you to search and open files quickly. It is an interactive version of grep. skim is a fuzzy finder in Rust. (fzf is a fuzzy finder written in the Go language, and is an excellent alternative as well.) You can install it using Cargo. $ cargo install skim Please see this page for other installations. You can search for files. $ sk$ file-name Or using grep to find a line in files. sk --ansi -i -c 'grep -rI --color=always --line-number "{}" .' In Linux, you can use sed to perform basic text replacement. You can install sd using Cargo. cargo install sd sd uses simpler syntax. Using sd: $ sd before after Whereas using sed: $ sed s/before/after/g Replacing newlines with commas with sd: $ sd '\n' ',' And with sed: $ sed ':a;N;$!ba;s/\n/,/g' sd is faster than sed. htop in Linux is an interactive process viewer. ytop and bottom are graphical process monitors. You can install them with Cargo: $ cargo install ytop$ cargo install bottom You can run bottom using btm. When you use another computer, server, or system, you will be using Linux commands. It is a good idea to keep using Linux commands even if you are using Rust-powered alternatives. I suggest creating aliases. In my .zshrc I have the followings: If you are a Powershell user: I hope you start using these Rust-powered utility tools. You will find they are very fast and modern looking. If you know of more, please let me know! Get full access to every story on Medium by becoming a member.
[ { "code": null, "e": 394, "s": 171, "text": "Table of ContentsIntroduction1. du alternatives: dust and dutree ∘ dust ∘ dutree2. time alternative: hyperfine3. A fuzzy finder: skim4. sed alternative: sd5. top/htop alternatives: ytop and bottom6. A Bonus TipConclusion" }, { "code": null, "e": 476, "s": 394, "text": "Last month, I wrote an article sharing seven Rust-powered command-line utilities." }, { "code": null, "e": 550, "s": 476, "text": "Those are modern and fast tools you can use every day with your terminal." }, { "code": null, "e": 725, "s": 550, "text": "Since publishing that original article, I’ve been searching for more Rust-powered command-line utilities, and I discovered more gems that I’m excited to share with you today." }, { "code": null, "e": 790, "s": 725, "text": "These tools will help you be productive with your terminal work." }, { "code": null, "e": 941, "s": 790, "text": "I recommend installing Rust. When you install Rust, it will install Cargo as one of the toolchains. And you can install Rust-powered tools with Cargo." }, { "code": null, "e": 1016, "s": 941, "text": "If you want to start learning Rust, this article can help you get started." }, { "code": null, "e": 1031, "s": 1016, "text": "Let’s dive in." }, { "code": null, "e": 1134, "s": 1031, "text": "In Linux, the du command estimates file space usage. dust and dutree are Rust-powered du alternatives." }, { "code": null, "e": 1273, "s": 1134, "text": "It is difficult to use du command for me. For example with du, listing files and folders and totaling the size including subfolders I use:" }, { "code": null, "e": 1295, "s": 1273, "text": "$ du -sk * | sort -nr" }, { "code": null, "e": 1390, "s": 1295, "text": "Dust gives you an instant overview of directories and its disk space and commands are simpler." }, { "code": null, "e": 1402, "s": 1390, "text": "For example" }, { "code": null, "e": 1487, "s": 1402, "text": "$ dust$ dust <dir>$ dust <dir> <another_dir> <and_more>$ dust -p <dir> (full-path)" }, { "code": null, "e": 1520, "s": 1487, "text": "You can find all the usage here." }, { "code": null, "e": 1656, "s": 1520, "text": "In the above image, you can see that the app directory occupies 57MB(29%) and the target directory occupies 139 MB (71%) of disk space." }, { "code": null, "e": 1689, "s": 1656, "text": "You can install dust with Cargo." }, { "code": null, "e": 1726, "s": 1689, "text": "$ cargo install du-dust$ dust --help" }, { "code": null, "e": 1765, "s": 1726, "text": "You can find other installations here." }, { "code": null, "e": 1820, "s": 1765, "text": "dutreeis another du alternative to analyze disk usage." }, { "code": null, "e": 1855, "s": 1820, "text": "You can install dutree with Cargo." }, { "code": null, "e": 1878, "s": 1855, "text": "$ cargo install dutree" }, { "code": null, "e": 1915, "s": 1878, "text": "You can find usage by dutree --help." }, { "code": null, "e": 2046, "s": 1915, "text": "dutree has also simple command options. For example, you can display directories using the -d option to different directory depth." }, { "code": null, "e": 2124, "s": 2046, "text": "$ dutree -d // the default is 1$ dutree -d2 // show directories up to depth 2" }, { "code": null, "e": 2271, "s": 2124, "text": "In Linux, the time command shows you how long a given command takes to run. It is useful for testing the performance of your scripts and commands." }, { "code": null, "e": 2411, "s": 2271, "text": "Let’s say you have two scripts or commands doing the same job. You can use the time command to compare the time required for these scripts." }, { "code": null, "e": 2490, "s": 2411, "text": "hyperfine is a Rust-powered, time alternative, command-line benchmarking tool." }, { "code": null, "e": 2516, "s": 2490, "text": "Installing it with Cargo:" }, { "code": null, "e": 2542, "s": 2516, "text": "$ cargo install hyperfine" }, { "code": null, "e": 2657, "s": 2542, "text": "If you run hyperfine with --warmup N, the hyperfine will perform the warmup N times before the actual measurement." }, { "code": null, "e": 2781, "s": 2657, "text": "// warmup run$ hyperfine --warmup 3 'dutree -d' 'dutree -d2' 'dust'// actual run$ hyperfine 'dutree -d' 'dutree -d2' 'dust'" }, { "code": null, "e": 2878, "s": 2781, "text": "A fuzzy finder helps you to search and open files quickly. It is an interactive version of grep." }, { "code": null, "e": 3003, "s": 2878, "text": "skim is a fuzzy finder in Rust. (fzf is a fuzzy finder written in the Go language, and is an excellent alternative as well.)" }, { "code": null, "e": 3035, "s": 3003, "text": "You can install it using Cargo." }, { "code": null, "e": 3056, "s": 3035, "text": "$ cargo install skim" }, { "code": null, "e": 3102, "s": 3056, "text": "Please see this page for other installations." }, { "code": null, "e": 3128, "s": 3102, "text": "You can search for files." }, { "code": null, "e": 3144, "s": 3128, "text": "$ sk$ file-name" }, { "code": null, "e": 3183, "s": 3144, "text": "Or using grep to find a line in files." }, { "code": null, "e": 3246, "s": 3183, "text": "sk --ansi -i -c 'grep -rI --color=always --line-number \"{}\" .'" }, { "code": null, "e": 3307, "s": 3246, "text": "In Linux, you can use sed to perform basic text replacement." }, { "code": null, "e": 3339, "s": 3307, "text": "You can install sd using Cargo." }, { "code": null, "e": 3356, "s": 3339, "text": "cargo install sd" }, { "code": null, "e": 3380, "s": 3356, "text": "sd uses simpler syntax." }, { "code": null, "e": 3390, "s": 3380, "text": "Using sd:" }, { "code": null, "e": 3408, "s": 3390, "text": "$ sd before after" }, { "code": null, "e": 3427, "s": 3408, "text": "Whereas using sed:" }, { "code": null, "e": 3450, "s": 3427, "text": "$ sed s/before/after/g" }, { "code": null, "e": 3490, "s": 3450, "text": "Replacing newlines with commas with sd:" }, { "code": null, "e": 3504, "s": 3490, "text": "$ sd '\\n' ','" }, { "code": null, "e": 3518, "s": 3504, "text": "And with sed:" }, { "code": null, "e": 3545, "s": 3518, "text": "$ sed ':a;N;$!ba;s/\\n/,/g'" }, { "code": null, "e": 3568, "s": 3545, "text": "sd is faster than sed." }, { "code": null, "e": 3664, "s": 3568, "text": "htop in Linux is an interactive process viewer. ytop and bottom are graphical process monitors." }, { "code": null, "e": 3697, "s": 3664, "text": "You can install them with Cargo:" }, { "code": null, "e": 3740, "s": 3697, "text": "$ cargo install ytop$ cargo install bottom" }, { "code": null, "e": 3770, "s": 3740, "text": "You can run bottom using btm." }, { "code": null, "e": 3950, "s": 3770, "text": "When you use another computer, server, or system, you will be using Linux commands. It is a good idea to keep using Linux commands even if you are using Rust-powered alternatives." }, { "code": null, "e": 3978, "s": 3950, "text": "I suggest creating aliases." }, { "code": null, "e": 4014, "s": 3978, "text": "In my .zshrc I have the followings:" }, { "code": null, "e": 4044, "s": 4014, "text": "If you are a Powershell user:" }, { "code": null, "e": 4195, "s": 4044, "text": "I hope you start using these Rust-powered utility tools. You will find they are very fast and modern looking. If you know of more, please let me know!" } ]
Arithmetic Expression Evaluation - GeeksforGeeks
03 May, 2021 The stack organization is very effective in evaluating arithmetic expressions. Expressions are usually represented in what is known as Infix notation, in which each operator is written between two operands (i.e., A + B). With this notation, we must distinguish between ( A + B )*C and A + ( B * C ) by using either parentheses or some operator-precedence convention. Thus, the order of operators and operands in an arithmetic expression does not uniquely determine the order in which the operations are to be performed. 1. Polish notation (prefix notation) – It refers to the notation in which the operator is placed before its two operands. Here no parentheses are required, i.e., +AB 2. Reverse Polish notation(postfix notation) – It refers to the analogous notation in which the operator is placed after its two operands. Again, no parentheses is required in Reverse Polish notation, i.e., AB+ Stack-organized computers are better suited for post-fix notation than the traditional infix notation. Thus, the infix notation must be converted to the postfix notation. The conversion from infix notation to postfix notation must take into consideration the operational hierarchy. There are 3 levels of precedence for 5 binary operators as given below: Highest: Exponentiation (^) Next highest: Multiplication (*) and division (/) Lowest: Addition (+) and Subtraction (-) For example – Infix notation: (A-B)*[C/(D+E)+F] Post-fix notation: AB- CDE +/F +* Here, we first perform the arithmetic inside the parentheses (A-B) and (D+E). The division of C/(D+E) must be done prior to the addition with F. After that multiply the two terms inside the parentheses and bracket. Now we need to calculate the value of these arithmetic operations by using a stack. The procedure for getting the result is: Convert the expression in Reverse Polish notation( post-fix notation). Push the operands into the stack in the order they appear. When any operator encounters then pop two topmost operands for executing the operation. After execution push the result obtained into the stack. After the complete execution of expression, the final result remains on the top of the stack. Convert the expression in Reverse Polish notation( post-fix notation). Push the operands into the stack in the order they appear. When any operator encounters then pop two topmost operands for executing the operation. After execution push the result obtained into the stack. After the complete execution of expression, the final result remains on the top of the stack. For example – Infix notation: (2+4) * (4+6) Post-fix notation: 2 4 + 4 6 + * Result: 60 The stack operations for this expression evaluation is shown below: sanskarsharma100 bidiptoroy Data Structures-Stack expression-evaluation Inorder Traversal Parentheses-Problems PostOrder Traversal Preorder Traversal Stack Stack Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Sort a stack using a temporary stack Real-time application of Data Structures Reverse individual words Iterative Tower of Hanoi Reduce the string by removing K consecutive identical characters ZigZag Tree Traversal Iterative Postorder Traversal | Set 1 (Using Two Stacks) Construct Binary Tree from String with bracket representation Postfix to Infix Reversing a Queue
[ { "code": null, "e": 24686, "s": 24658, "text": "\n03 May, 2021" }, { "code": null, "e": 25207, "s": 24686, "text": "The stack organization is very effective in evaluating arithmetic expressions. Expressions are usually represented in what is known as Infix notation, in which each operator is written between two operands (i.e., A + B). With this notation, we must distinguish between ( A + B )*C and A + ( B * C ) by using either parentheses or some operator-precedence convention. Thus, the order of operators and operands in an arithmetic expression does not uniquely determine the order in which the operations are to be performed. " }, { "code": null, "e": 25373, "s": 25209, "text": "1. Polish notation (prefix notation) – It refers to the notation in which the operator is placed before its two operands. Here no parentheses are required, i.e., " }, { "code": null, "e": 25378, "s": 25373, "text": "+AB " }, { "code": null, "e": 25589, "s": 25380, "text": "2. Reverse Polish notation(postfix notation) – It refers to the analogous notation in which the operator is placed after its two operands. Again, no parentheses is required in Reverse Polish notation, i.e., " }, { "code": null, "e": 25594, "s": 25589, "text": "AB+ " }, { "code": null, "e": 25877, "s": 25594, "text": "Stack-organized computers are better suited for post-fix notation than the traditional infix notation. Thus, the infix notation must be converted to the postfix notation. The conversion from infix notation to postfix notation must take into consideration the operational hierarchy. " }, { "code": null, "e": 25951, "s": 25877, "text": "There are 3 levels of precedence for 5 binary operators as given below: " }, { "code": null, "e": 26071, "s": 25951, "text": "Highest: Exponentiation (^)\nNext highest: Multiplication (*) and division (/)\nLowest: Addition (+) and Subtraction (-) " }, { "code": null, "e": 26087, "s": 26071, "text": "For example – " }, { "code": null, "e": 26156, "s": 26087, "text": "Infix notation: (A-B)*[C/(D+E)+F]\nPost-fix notation: AB- CDE +/F +* " }, { "code": null, "e": 26372, "s": 26156, "text": "Here, we first perform the arithmetic inside the parentheses (A-B) and (D+E). The division of C/(D+E) must be done prior to the addition with F. After that multiply the two terms inside the parentheses and bracket. " }, { "code": null, "e": 26457, "s": 26372, "text": "Now we need to calculate the value of these arithmetic operations by using a stack. " }, { "code": null, "e": 26500, "s": 26457, "text": "The procedure for getting the result is: " }, { "code": null, "e": 26875, "s": 26500, "text": "Convert the expression in Reverse Polish notation( post-fix notation). Push the operands into the stack in the order they appear. When any operator encounters then pop two topmost operands for executing the operation. After execution push the result obtained into the stack. After the complete execution of expression, the final result remains on the top of the stack. " }, { "code": null, "e": 26948, "s": 26875, "text": "Convert the expression in Reverse Polish notation( post-fix notation). " }, { "code": null, "e": 27009, "s": 26948, "text": "Push the operands into the stack in the order they appear. " }, { "code": null, "e": 27099, "s": 27009, "text": "When any operator encounters then pop two topmost operands for executing the operation. " }, { "code": null, "e": 27158, "s": 27099, "text": "After execution push the result obtained into the stack. " }, { "code": null, "e": 27254, "s": 27158, "text": "After the complete execution of expression, the final result remains on the top of the stack. " }, { "code": null, "e": 27270, "s": 27254, "text": "For example – " }, { "code": null, "e": 27345, "s": 27270, "text": "Infix notation: (2+4) * (4+6)\nPost-fix notation: 2 4 + 4 6 + *\nResult: 60 " }, { "code": null, "e": 27414, "s": 27345, "text": "The stack operations for this expression evaluation is shown below: " }, { "code": null, "e": 27435, "s": 27418, "text": "sanskarsharma100" }, { "code": null, "e": 27446, "s": 27435, "text": "bidiptoroy" }, { "code": null, "e": 27468, "s": 27446, "text": "Data Structures-Stack" }, { "code": null, "e": 27490, "s": 27468, "text": "expression-evaluation" }, { "code": null, "e": 27508, "s": 27490, "text": "Inorder Traversal" }, { "code": null, "e": 27529, "s": 27508, "text": "Parentheses-Problems" }, { "code": null, "e": 27549, "s": 27529, "text": "PostOrder Traversal" }, { "code": null, "e": 27568, "s": 27549, "text": "Preorder Traversal" }, { "code": null, "e": 27574, "s": 27568, "text": "Stack" }, { "code": null, "e": 27580, "s": 27574, "text": "Stack" }, { "code": null, "e": 27678, "s": 27580, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27687, "s": 27678, "text": "Comments" }, { "code": null, "e": 27700, "s": 27687, "text": "Old Comments" }, { "code": null, "e": 27737, "s": 27700, "text": "Sort a stack using a temporary stack" }, { "code": null, "e": 27778, "s": 27737, "text": "Real-time application of Data Structures" }, { "code": null, "e": 27803, "s": 27778, "text": "Reverse individual words" }, { "code": null, "e": 27828, "s": 27803, "text": "Iterative Tower of Hanoi" }, { "code": null, "e": 27893, "s": 27828, "text": "Reduce the string by removing K consecutive identical characters" }, { "code": null, "e": 27915, "s": 27893, "text": "ZigZag Tree Traversal" }, { "code": null, "e": 27972, "s": 27915, "text": "Iterative Postorder Traversal | Set 1 (Using Two Stacks)" }, { "code": null, "e": 28034, "s": 27972, "text": "Construct Binary Tree from String with bracket representation" }, { "code": null, "e": 28051, "s": 28034, "text": "Postfix to Infix" } ]
CSS | border-left-style Property - GeeksforGeeks
22 Aug, 2021 The CSS border-left-style property is used to set the style of the left border of an element. Default Value none Syntax: border-left-style: none| hidden| dotted| dashed| solid| double | groove| ridge| inset| outset| initial| inherit; Properties Value: Return Value: It returns the style of left border of an element. Example-1: Showing Dotted Left Border. html <!DOCTYPE html><html> <head> <style> h1 { border-left-style: dotted; } div { border-style: solid; border-left-style: dotted; } </style></head> <body> <h1>Geeks for Geeks</h1> <div> <h3>Dotted Left Border</h3></div> </body> </html> Output: Example-2: Showing Double Left Border html <!DOCTYPE html><html> <head> <style> h1 { border-left-style: double; } div { border-style: solid; border-left-style: double; } </style></head> <body> <h1>Geeks for Geeks</h1> <div> <h3>Double Left Border</h3></div> </body> </html> Output: Example-3: Showing Solid Left Border html <!DOCTYPE html><html> <head> <style> h1 { border-left-style: solid; } div { border-style: solid; border-left-style: solid; } </style></head> <body> <h1>Geeks for Geeks</h1> <div> <h3>Solid Left Border</h3></div> </body> </html> Output: Supported Browsers: The browsers supported by CSS Border Left Style Property are listed below: Google Chrome Firefox Internet Explorer Opera Safari ManasChhabra2 CSS-Properties 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 How to style a checkbox using CSS? Search Bar using HTML, CSS and JavaScript Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26731, "s": 26703, "text": "\n22 Aug, 2021" }, { "code": null, "e": 26825, "s": 26731, "text": "The CSS border-left-style property is used to set the style of the left border of an element." }, { "code": null, "e": 26839, "s": 26825, "text": "Default Value" }, { "code": null, "e": 26844, "s": 26839, "text": "none" }, { "code": null, "e": 26854, "s": 26844, "text": "Syntax: " }, { "code": null, "e": 26967, "s": 26854, "text": "border-left-style: none| hidden| dotted| dashed| solid| double |\ngroove| ridge| inset| outset| initial| inherit;" }, { "code": null, "e": 26986, "s": 26967, "text": "Properties Value: " }, { "code": null, "e": 27054, "s": 26988, "text": "Return Value: It returns the style of left border of an element. " }, { "code": null, "e": 27095, "s": 27054, "text": "Example-1: Showing Dotted Left Border. " }, { "code": null, "e": 27100, "s": 27095, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <style> h1 { border-left-style: dotted; } div { border-style: solid; border-left-style: dotted; } </style></head> <body> <h1>Geeks for Geeks</h1> <div> <h3>Dotted Left Border</h3></div> </body> </html>", "e": 27429, "s": 27100, "text": null }, { "code": null, "e": 27439, "s": 27429, "text": "Output: " }, { "code": null, "e": 27479, "s": 27439, "text": "Example-2: Showing Double Left Border " }, { "code": null, "e": 27484, "s": 27479, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <style> h1 { border-left-style: double; } div { border-style: solid; border-left-style: double; } </style></head> <body> <h1>Geeks for Geeks</h1> <div> <h3>Double Left Border</h3></div> </body> </html>", "e": 27813, "s": 27484, "text": null }, { "code": null, "e": 27823, "s": 27813, "text": "Output: " }, { "code": null, "e": 27862, "s": 27823, "text": "Example-3: Showing Solid Left Border " }, { "code": null, "e": 27867, "s": 27862, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <style> h1 { border-left-style: solid; } div { border-style: solid; border-left-style: solid; } </style></head> <body> <h1>Geeks for Geeks</h1> <div> <h3>Solid Left Border</h3></div> </body> </html>", "e": 28193, "s": 27867, "text": null }, { "code": null, "e": 28203, "s": 28193, "text": "Output: " }, { "code": null, "e": 28300, "s": 28203, "text": "Supported Browsers: The browsers supported by CSS Border Left Style Property are listed below: " }, { "code": null, "e": 28314, "s": 28300, "text": "Google Chrome" }, { "code": null, "e": 28322, "s": 28314, "text": "Firefox" }, { "code": null, "e": 28340, "s": 28322, "text": "Internet Explorer" }, { "code": null, "e": 28346, "s": 28340, "text": "Opera" }, { "code": null, "e": 28353, "s": 28346, "text": "Safari" }, { "code": null, "e": 28369, "s": 28355, "text": "ManasChhabra2" }, { "code": null, "e": 28384, "s": 28369, "text": "CSS-Properties" }, { "code": null, "e": 28391, "s": 28384, "text": "Picked" }, { "code": null, "e": 28395, "s": 28391, "text": "CSS" }, { "code": null, "e": 28412, "s": 28395, "text": "Web Technologies" }, { "code": null, "e": 28510, "s": 28412, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28549, "s": 28510, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 28586, "s": 28549, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28615, "s": 28586, "text": "Form validation using jQuery" }, { "code": null, "e": 28650, "s": 28615, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 28692, "s": 28650, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 28732, "s": 28692, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28765, "s": 28732, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28810, "s": 28765, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28853, "s": 28810, "text": "How to fetch data from an API in ReactJS ?" } ]
GeeksforGeeks | A computer science portal for geeks
Events at GeeksforGeeks Courses at GeeksforGeeks Write an Article Java Tutorial Python Tutorial Data Structures Tutorial Coding Practice Events at GeeksforGeeks Courses at GeeksforGeeks Write an Article Java Tutorial Python Tutorial Data Structures Tutorial Coding Practice Get Hired With GeeksforGeeks and Win Exciting Rewards!October 30, 2021 October 30, 2021 Master the Coding Interview – Contest Series Based On Real InterviewsOctober 5, 2021 October 5, 2021 Recently Asked Interview Questions in Product Based CompaniesMay 11, 2021 May 11, 2021 Bridge the Gap Between Engineering and Your Dream Job – Complete Interview PreparationMay 1, 2021 May 1, 2021 100 Days of Code – A Complete Guide For Beginners and ExperiencedMay 1, 2021 May 1, 2021 Guest Blogs Must Do Coding Questions Company-wise Practice for cracking any coding interview Placements Complete Interview Preparation With Doubt Assistance GATE Computer Science Notes Machine Learning Django Tutorial Computer Science Projects Amazon SDE Test Series Company Interview Corner The C++ Standard Template Library (STL) Software Design Patterns SQL Tutorial Advanced Data Structures
[ { "code": null, "e": 21877, "s": 21851, "text": "\nEvents at GeeksforGeeks\n" }, { "code": null, "e": 21904, "s": 21877, "text": "\nCourses at GeeksforGeeks\n" }, { "code": null, "e": 21923, "s": 21904, "text": "\nWrite an Article\n" }, { "code": null, "e": 21939, "s": 21923, "text": "\nJava Tutorial\n" }, { "code": null, "e": 21957, "s": 21939, "text": "\nPython Tutorial\n" }, { "code": null, "e": 21984, "s": 21957, "text": "\nData Structures Tutorial\n" }, { "code": null, "e": 22002, "s": 21984, "text": "\nCoding Practice\n" }, { "code": null, "e": 22028, "s": 22002, "text": "\nEvents at GeeksforGeeks\n" }, { "code": null, "e": 22055, "s": 22028, "text": "\nCourses at GeeksforGeeks\n" }, { "code": null, "e": 22074, "s": 22055, "text": "\nWrite an Article\n" }, { "code": null, "e": 22090, "s": 22074, "text": "\nJava Tutorial\n" }, { "code": null, "e": 22108, "s": 22090, "text": "\nPython Tutorial\n" }, { "code": null, "e": 22135, "s": 22108, "text": "\nData Structures Tutorial\n" }, { "code": null, "e": 22153, "s": 22135, "text": "\nCoding Practice\n" }, { "code": null, "e": 22224, "s": 22153, "text": "Get Hired With GeeksforGeeks and Win Exciting Rewards!October 30, 2021" }, { "code": null, "e": 22241, "s": 22224, "text": "October 30, 2021" }, { "code": null, "e": 22326, "s": 22241, "text": "Master the Coding Interview – Contest Series Based On Real InterviewsOctober 5, 2021" }, { "code": null, "e": 22342, "s": 22326, "text": "October 5, 2021" }, { "code": null, "e": 22416, "s": 22342, "text": "Recently Asked Interview Questions in Product Based CompaniesMay 11, 2021" }, { "code": null, "e": 22429, "s": 22416, "text": "May 11, 2021" }, { "code": null, "e": 22527, "s": 22429, "text": "Bridge the Gap Between Engineering and Your Dream Job – Complete Interview PreparationMay 1, 2021" }, { "code": null, "e": 22539, "s": 22527, "text": "May 1, 2021" }, { "code": null, "e": 22616, "s": 22539, "text": "100 Days of Code – A Complete Guide For Beginners and ExperiencedMay 1, 2021" }, { "code": null, "e": 22628, "s": 22616, "text": "May 1, 2021" }, { "code": null, "e": 22640, "s": 22628, "text": "Guest Blogs" }, { "code": null, "e": 22678, "s": 22640, "text": "Must Do Coding Questions\nCompany-wise" }, { "code": null, "e": 22721, "s": 22678, "text": "Practice for cracking any coding\ninterview" }, { "code": null, "e": 22732, "s": 22721, "text": "Placements" }, { "code": null, "e": 22785, "s": 22732, "text": "Complete Interview Preparation With\nDoubt Assistance" }, { "code": null, "e": 22813, "s": 22785, "text": "GATE Computer Science Notes" }, { "code": null, "e": 22830, "s": 22813, "text": "Machine Learning" }, { "code": null, "e": 22846, "s": 22830, "text": "Django Tutorial" }, { "code": null, "e": 22872, "s": 22846, "text": "Computer Science Projects" }, { "code": null, "e": 22895, "s": 22872, "text": "Amazon SDE Test Series" }, { "code": null, "e": 22920, "s": 22895, "text": "Company Interview Corner" }, { "code": null, "e": 22960, "s": 22920, "text": "The C++ Standard Template Library\n(STL)" }, { "code": null, "e": 22985, "s": 22960, "text": "Software Design Patterns" }, { "code": null, "e": 22998, "s": 22985, "text": "SQL Tutorial" } ]
Maximum Sum Path in Two Arrays - GeeksforGeeks
14 Jan, 2022 Given two sorted arrays, such that the arrays may have some common elements. Find the sum of the maximum sum path to reach from the beginning of any array to end of any of the two arrays. We can switch from one array to another array only at common elements. Note: The common elements do not have to be at the same indexes. Expected Time Complexity: O(m+n), where m is the number of elements in ar1[] and n is the number of elements in ar2[]. Examples: Input: ar1[] = {2, 3, 7, 10, 12} ar2[] = {1, 5, 7, 8} Output: 35 Explanation: 35 is sum of 1 + 5 + 7 + 10 + 12. We start from the first element of arr2 which is 1, then we move to 5, then 7. From 7, we switch to ar1 (as 7 is common) and traverse 10 and 12. Input: ar1[] = {10, 12} ar2 = {5, 7, 9} Output: 22 Explanation: 22 is the sum of 10 and 12. Since there is no common element, we need to take all elements from the array with more sum. Input: ar1[] = {2, 3, 7, 10, 12, 15, 30, 34} ar2[] = {1, 5, 7, 8, 10, 15, 16, 19} Output: 122 Explanation: 122 is sum of 1, 5, 7, 8, 10, 12, 15, 30, 34 Efficient Approach: The idea is to do something similar to merge process of merge sort. This involves calculating the sum of elements between all common points of both arrays. Whenever there is a common point, compare the two sums and add the maximum of two to the result. Algorithm: Create some variables, result, sum1, sum2. Initialize result as 0. Also initialize two variables sum1 and sum2 as 0. Here sum1 and sum2 are used to store sum of element in ar1[] and ar2[] respectively. These sums are between two common points.Now run a loop to traverse elements of both arrays. While traversing compare current elements of array 1 and array 2 in the following order.If current element of array 1 is smaller than current element of array 2, then update sum1, else if current element of array 2 is smaller, then update sum2.If the current element of array 1 and array 2are same, then take the maximum of sum1 and sum2 and add it to the result. Also add the common element to the result.This step can be compared to the merging of two sorted arrays, If the smallest element of the two current array indices is processed then it is guaranteed that if there is any common element it will be processed together. So the sum of elements between two common elements can be processed. Create some variables, result, sum1, sum2. Initialize result as 0. Also initialize two variables sum1 and sum2 as 0. Here sum1 and sum2 are used to store sum of element in ar1[] and ar2[] respectively. These sums are between two common points. Now run a loop to traverse elements of both arrays. While traversing compare current elements of array 1 and array 2 in the following order.If current element of array 1 is smaller than current element of array 2, then update sum1, else if current element of array 2 is smaller, then update sum2.If the current element of array 1 and array 2are same, then take the maximum of sum1 and sum2 and add it to the result. Also add the common element to the result.This step can be compared to the merging of two sorted arrays, If the smallest element of the two current array indices is processed then it is guaranteed that if there is any common element it will be processed together. So the sum of elements between two common elements can be processed. If current element of array 1 is smaller than current element of array 2, then update sum1, else if current element of array 2 is smaller, then update sum2.If the current element of array 1 and array 2are same, then take the maximum of sum1 and sum2 and add it to the result. Also add the common element to the result.This step can be compared to the merging of two sorted arrays, If the smallest element of the two current array indices is processed then it is guaranteed that if there is any common element it will be processed together. So the sum of elements between two common elements can be processed. If current element of array 1 is smaller than current element of array 2, then update sum1, else if current element of array 2 is smaller, then update sum2. If the current element of array 1 and array 2are same, then take the maximum of sum1 and sum2 and add it to the result. Also add the common element to the result. This step can be compared to the merging of two sorted arrays, If the smallest element of the two current array indices is processed then it is guaranteed that if there is any common element it will be processed together. So the sum of elements between two common elements can be processed. Below is the implementation of the above code: C++ Java Python3 C# PHP Javascript // C++ program to find maximum sum path#include <iostream>using namespace std; // Utility function to find maximum of two integersint max(int x, int y) { return (x > y) ? x : y; } // This function returns the sum of elements on maximum path// from beginning to endint maxPathSum(int ar1[], int ar2[], int m, int n){ // initialize indexes for ar1[] and ar2[] int i = 0, j = 0; // Initialize result and current sum through ar1[] and // ar2[]. int result = 0, sum1 = 0, sum2 = 0; // Below 3 loops are similar to merge in merge sort while (i < m && j < n) { // Add elements of ar1[] to sum1 if (ar1[i] < ar2[j]) sum1 += ar1[i++]; // Add elements of ar2[] to sum2 else if (ar1[i] > ar2[j]) sum2 += ar2[j++]; else // we reached a common point { // Take the maximum of two sums and add to // result //Also add the common element of array, once result += max(sum1, sum2) + ar1[i]; // Update sum1 and sum2 for elements after this // intersection point sum1 = 0; sum2 = 0; //update i and j to move to next element of each array i++; j++; } } // Add remaining elements of ar1[] while (i < m) sum1 += ar1[i++]; // Add remaining elements of ar2[] while (j < n) sum2 += ar2[j++]; // Add maximum of two sums of remaining elements result += max(sum1, sum2); return result;} // Driver codeint main(){ int ar1[] = { 2, 3, 7, 10, 12, 15, 30, 34 }; int ar2[] = { 1, 5, 7, 8, 10, 15, 16, 19 }; int m = sizeof(ar1) / sizeof(ar1[0]); int n = sizeof(ar2) / sizeof(ar2[0]); // Function call cout << "Maximum sum path is " << maxPathSum(ar1, ar2, m, n); return 0;} // JAVA program to find maximum sum pathclass MaximumSumPath{ // Utility function to find maximum of two integers int max(int x, int y) { return (x > y) ? x : y; } // This function returns the sum of elements on maximum // path from beginning to end int maxPathSum(int ar1[], int ar2[], int m, int n) { // initialize indexes for ar1[] and ar2[] int i = 0, j = 0; // Initialize result and current sum through ar1[] // and ar2[]. int result = 0, sum1 = 0, sum2 = 0; // Below 3 loops are similar to merge in merge sort while (i < m && j < n) { // Add elements of ar1[] to sum1 if (ar1[i] < ar2[j]) sum1 += ar1[i++]; // Add elements of ar2[] to sum2 else if (ar1[i] > ar2[j]) sum2 += ar2[j++]; // we reached a common point else { // Take the maximum of two sums and add to // result //Also add the common element of array, once result += max(sum1, sum2) + ar1[i]; // Update sum1 and sum2 for elements after this // intersection point sum1 = 0; sum2 = 0; //update i and j to move to next element of each array i++; j++; } } // Add remaining elements of ar1[] while (i < m) sum1 += ar1[i++]; // Add remaining elements of ar2[] while (j < n) sum2 += ar2[j++]; // Add maximum of two sums of remaining elements result += max(sum1, sum2); return result; } // Driver code public static void main(String[] args) { MaximumSumPath sumpath = new MaximumSumPath(); int ar1[] = { 2, 3, 7, 10, 12, 15, 30, 34 }; int ar2[] = { 1, 5, 7, 8, 10, 15, 16, 19 }; int m = ar1.length; int n = ar2.length; // Function call System.out.println( "Maximum sum path is :" + sumpath.maxPathSum(ar1, ar2, m, n)); }} // This code has been contributed by Mayank Jaiswal # Python program to find maximum sum path # This function returns the sum of elements on maximum path from# beginning to end def maxPathSum(ar1, ar2, m, n): # initialize indexes for ar1[] and ar2[] i, j = 0, 0 # Initialize result and current sum through ar1[] and ar2[] result, sum1, sum2 = 0, 0, 0 # Below 3 loops are similar to merge in merge sort while (i < m and j < n): # Add elements of ar1[] to sum1 if ar1[i] < ar2[j]: sum1 += ar1[i] i += 1 # Add elements of ar2[] to sum2 elif ar1[i] > ar2[j]: sum2 += ar2[j] j += 1 else: # we reached a common point # Take the maximum of two sums and add to result result += max(sum1, sum2) +ar1[i] #update sum1 and sum2 to be considered fresh for next elements sum1 = 0 sum2 = 0 #update i and j to move to next element in each array i +=1 j +=1 # Add remaining elements of ar1[] while i < m: sum1 += ar1[i] i += 1 # Add remaining elements of b[] while j < n: sum2 += ar2[j] j += 1 # Add maximum of two sums of remaining elements result += max(sum1, sum2) return result # Driver codear1 = [2, 3, 7, 10, 12, 15, 30, 34]ar2 = [1, 5, 7, 8, 10, 15, 16, 19]m = len(ar1)n = len(ar2) # Function callprint ("Maximum sum path is", maxPathSum(ar1, ar2, m, n)) # This code is contributed by __Devesh Agrawal__ // C# program for Maximum Sum Path in// Two Arraysusing System; class GFG { // Utility function to find maximum // of two integers static int max(int x, int y) { return (x > y) ? x : y; } // This function returns the sum of // elements on maximum path from // beginning to end static int maxPathSum(int[] ar1, int[] ar2, int m, int n) { // initialize indexes for ar1[] // and ar2[] int i = 0, j = 0; // Initialize result and current // sum through ar1[] and ar2[]. int result = 0, sum1 = 0, sum2 = 0; // Below 3 loops are similar to // merge in merge sort while (i < m && j < n) { // Add elements of ar1[] to sum1 if (ar1[i] < ar2[j]) sum1 += ar1[i++]; // Add elements of ar2[] to sum2 else if (ar1[i] > ar2[j]) sum2 += ar2[j++]; // we reached a common point else { // Take the maximum of two sums and add to // result // Also add the common element of array, // once result += max(sum1, sum2) + ar1[i]; // Update sum1 and sum2 for elements after // this intersection point sum1 = 0; sum2 = 0; // update i and j to move to next element of // each array i++; j++; } } // Add remaining elements of ar1[] while (i < m) sum1 += ar1[i++]; // Add remaining elements of ar2[] while (j < n) sum2 += ar2[j++]; // Add maximum of two sums of // remaining elements result += max(sum1, sum2); return result; } // Driver code public static void Main() { int[] ar1 = { 2, 3, 7, 10, 12, 15, 30, 34 }; int[] ar2 = { 1, 5, 7, 8, 10, 15, 16, 19 }; int m = ar1.Length; int n = ar2.Length; // Function call Console.Write("Maximum sum path is :" + maxPathSum(ar1, ar2, m, n)); }} // This code is contributed by nitin mittal. <?php// PHP Program to find Maximum Sum// Path in Two Arrays // This function returns the sum of// elements on maximum path// from beginning to endfunction maxPathSum($ar1, $ar2, $m, $n){ // initialize indexes for // ar1[] and ar2[] $i = 0; $j = 0; // Initialize result and // current sum through ar1[] // and ar2[]. $result = 0; $sum1 = 0; $sum2 = 0; // Below 3 loops are similar // to merge in merge sort while ($i < $m and $j < $n) { // Add elements of // ar1[] to sum1 if ($ar1[$i] < $ar2[$j]) $sum1 += $ar1[$i++]; // Add elements of // ar2[] to sum2 else if ($ar1[$i] > $ar2[$j]) $sum2 += $ar2[$j++]; // we reached a // common point else { // Take the maximum of two sums and add to // result //Also add the common element of array, once $result += max($sum1, $sum2) + $ar1[$i]; // Update sum1 and sum2 for elements after this // intersection point $sum1 = 0; $sum2 = 0; //update i and j to move to next element of each array $i++; $j++; } } // Add remaining elements of ar1[] while ($i < $m) $sum1 += $ar1[$i++]; // Add remaining elements of ar2[] while ($j < $n) $sum2 += $ar2[$j++]; // Add maximum of two sums // of remaining elements $result += max($sum1, $sum2); return $result;} // Driver Code $ar1 = array(2, 3, 7, 10, 12, 15, 30, 34); $ar2 = array(1, 5, 7, 8, 10, 15, 16, 19); $m = count($ar1); $n = count($ar2); // Function call echo "Maximum sum path is " , maxPathSum($ar1, $ar2, $m, $n); // This code is contributed by anuj_67.?> <script> // Javascript program to find maximum sum path // Utility function to find maximum of two integersfunction max(x, y){ return (x > y) ? x : y;} // This function returns the sum of elements// on maximum path from beginning to endfunction maxPathSum(ar1, ar2, m, n){ // Initialize indexes for ar1[] and ar2[] let i = 0, j = 0; // Initialize result and current sum // through ar1[] and ar2[]. let result = 0, sum1 = 0, sum2 = 0; // Below3 loops are similar to // merge in merge sort while (i < m && j < n) { // Add elements of ar1[] to sum1 if (ar1[i] < ar2[j]) sum1 += ar1[i++]; // Add elements of ar2[] to sum2 else if (ar1[i] > ar2[j]) sum2 += ar2[j++]; // We reached a common point else { // Take the maximum of two sums and add to // result //Also add the common element of array, once result += Math.max(sum1, sum2) + ar1[i]; // Update sum1 and sum2 for elements after this // intersection point sum1 = 0; sum2 = 0; //update i and j to move to next element of each array i++; j++; } } // Add remaining elements of ar1[] while (i < m) sum1 += ar1[i++]; // Add remaining elements of ar2[] while (j < n) sum2 += ar2[j++]; // Add maximum of two sums of // remaining elements result += Math.max(sum1, sum2); return result;} // Driver codelet ar1 = [ 2, 3, 7, 10, 12, 15, 30, 34 ];let ar2 = [ 1, 5, 7, 8, 10, 15, 16, 19 ];let m = ar1.length;let n = ar2.length; // Function calldocument.write("Maximum sum path is " + maxPathSum(ar1, ar2, m, n)); // This code is contributed by Mayank Tyagi </script> Maximum sum path is 122 Complexity Analysis: Space Complexity: O(1). Any extra space is not required, so the space complexity is constant. Time complexity: O(m+n). In every iteration of while loops, an element from either of the two arrays is processed. There are total m + n elements. Therefore, the time complexity is O(m+n). This article is contributed by Piyush Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal vt_m andrew1234 mohith23102000 nithinsgowda vipinrai399 mayanktyagi1709 divyanshuraj kapoorsagar226 amartyaghoshgfg Amazon Arrays Amazon Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Introduction to Arrays Linear Search Maximum and minimum of an array using minimum number of comparisons Multidimensional Arrays in Java Linked List vs Array Queue | Set 1 (Introduction and Array Implementation) Python | Using 2D arrays/lists the right way Subset Sum Problem | DP-25
[ { "code": null, "e": 24793, "s": 24765, "text": "\n14 Jan, 2022" }, { "code": null, "e": 25117, "s": 24793, "text": "Given two sorted arrays, such that the arrays may have some common elements. Find the sum of the maximum sum path to reach from the beginning of any array to end of any of the two arrays. We can switch from one array to another array only at common elements. Note: The common elements do not have to be at the same indexes." }, { "code": null, "e": 25236, "s": 25117, "text": "Expected Time Complexity: O(m+n), where m is the number of elements in ar1[] and n is the number of elements in ar2[]." }, { "code": null, "e": 25247, "s": 25236, "text": "Examples: " }, { "code": null, "e": 25870, "s": 25247, "text": "Input: ar1[] = {2, 3, 7, 10, 12}\n ar2[] = {1, 5, 7, 8}\nOutput: 35\n\nExplanation: 35 is sum of 1 + 5 + 7 + 10 + 12.\nWe start from the first element of arr2 which is 1, then we\nmove to 5, then 7. From 7, we switch to ar1 (as 7 is common)\nand traverse 10 and 12.\n\nInput: ar1[] = {10, 12}\n ar2 = {5, 7, 9}\nOutput: 22\n\nExplanation: 22 is the sum of 10 and 12.\nSince there is no common element, we need to take all \nelements from the array with more sum.\n\nInput: ar1[] = {2, 3, 7, 10, 12, 15, 30, 34}\n ar2[] = {1, 5, 7, 8, 10, 15, 16, 19}\nOutput: 122\n\nExplanation: 122 is sum of 1, 5, 7, 8, 10, 12, 15, 30, 34" }, { "code": null, "e": 26143, "s": 25870, "text": "Efficient Approach: The idea is to do something similar to merge process of merge sort. This involves calculating the sum of elements between all common points of both arrays. Whenever there is a common point, compare the two sums and add the maximum of two to the result." }, { "code": null, "e": 26155, "s": 26143, "text": "Algorithm: " }, { "code": null, "e": 27147, "s": 26155, "text": "Create some variables, result, sum1, sum2. Initialize result as 0. Also initialize two variables sum1 and sum2 as 0. Here sum1 and sum2 are used to store sum of element in ar1[] and ar2[] respectively. These sums are between two common points.Now run a loop to traverse elements of both arrays. While traversing compare current elements of array 1 and array 2 in the following order.If current element of array 1 is smaller than current element of array 2, then update sum1, else if current element of array 2 is smaller, then update sum2.If the current element of array 1 and array 2are same, then take the maximum of sum1 and sum2 and add it to the result. Also add the common element to the result.This step can be compared to the merging of two sorted arrays, If the smallest element of the two current array indices is processed then it is guaranteed that if there is any common element it will be processed together. So the sum of elements between two common elements can be processed." }, { "code": null, "e": 27391, "s": 27147, "text": "Create some variables, result, sum1, sum2. Initialize result as 0. Also initialize two variables sum1 and sum2 as 0. Here sum1 and sum2 are used to store sum of element in ar1[] and ar2[] respectively. These sums are between two common points." }, { "code": null, "e": 28140, "s": 27391, "text": "Now run a loop to traverse elements of both arrays. While traversing compare current elements of array 1 and array 2 in the following order.If current element of array 1 is smaller than current element of array 2, then update sum1, else if current element of array 2 is smaller, then update sum2.If the current element of array 1 and array 2are same, then take the maximum of sum1 and sum2 and add it to the result. Also add the common element to the result.This step can be compared to the merging of two sorted arrays, If the smallest element of the two current array indices is processed then it is guaranteed that if there is any common element it will be processed together. So the sum of elements between two common elements can be processed." }, { "code": null, "e": 28749, "s": 28140, "text": "If current element of array 1 is smaller than current element of array 2, then update sum1, else if current element of array 2 is smaller, then update sum2.If the current element of array 1 and array 2are same, then take the maximum of sum1 and sum2 and add it to the result. Also add the common element to the result.This step can be compared to the merging of two sorted arrays, If the smallest element of the two current array indices is processed then it is guaranteed that if there is any common element it will be processed together. So the sum of elements between two common elements can be processed." }, { "code": null, "e": 28906, "s": 28749, "text": "If current element of array 1 is smaller than current element of array 2, then update sum1, else if current element of array 2 is smaller, then update sum2." }, { "code": null, "e": 29069, "s": 28906, "text": "If the current element of array 1 and array 2are same, then take the maximum of sum1 and sum2 and add it to the result. Also add the common element to the result." }, { "code": null, "e": 29360, "s": 29069, "text": "This step can be compared to the merging of two sorted arrays, If the smallest element of the two current array indices is processed then it is guaranteed that if there is any common element it will be processed together. So the sum of elements between two common elements can be processed." }, { "code": null, "e": 29408, "s": 29360, "text": "Below is the implementation of the above code: " }, { "code": null, "e": 29412, "s": 29408, "text": "C++" }, { "code": null, "e": 29417, "s": 29412, "text": "Java" }, { "code": null, "e": 29425, "s": 29417, "text": "Python3" }, { "code": null, "e": 29428, "s": 29425, "text": "C#" }, { "code": null, "e": 29432, "s": 29428, "text": "PHP" }, { "code": null, "e": 29443, "s": 29432, "text": "Javascript" }, { "code": "// C++ program to find maximum sum path#include <iostream>using namespace std; // Utility function to find maximum of two integersint max(int x, int y) { return (x > y) ? x : y; } // This function returns the sum of elements on maximum path// from beginning to endint maxPathSum(int ar1[], int ar2[], int m, int n){ // initialize indexes for ar1[] and ar2[] int i = 0, j = 0; // Initialize result and current sum through ar1[] and // ar2[]. int result = 0, sum1 = 0, sum2 = 0; // Below 3 loops are similar to merge in merge sort while (i < m && j < n) { // Add elements of ar1[] to sum1 if (ar1[i] < ar2[j]) sum1 += ar1[i++]; // Add elements of ar2[] to sum2 else if (ar1[i] > ar2[j]) sum2 += ar2[j++]; else // we reached a common point { // Take the maximum of two sums and add to // result //Also add the common element of array, once result += max(sum1, sum2) + ar1[i]; // Update sum1 and sum2 for elements after this // intersection point sum1 = 0; sum2 = 0; //update i and j to move to next element of each array i++; j++; } } // Add remaining elements of ar1[] while (i < m) sum1 += ar1[i++]; // Add remaining elements of ar2[] while (j < n) sum2 += ar2[j++]; // Add maximum of two sums of remaining elements result += max(sum1, sum2); return result;} // Driver codeint main(){ int ar1[] = { 2, 3, 7, 10, 12, 15, 30, 34 }; int ar2[] = { 1, 5, 7, 8, 10, 15, 16, 19 }; int m = sizeof(ar1) / sizeof(ar1[0]); int n = sizeof(ar2) / sizeof(ar2[0]); // Function call cout << \"Maximum sum path is \" << maxPathSum(ar1, ar2, m, n); return 0;}", "e": 31299, "s": 29443, "text": null }, { "code": "// JAVA program to find maximum sum pathclass MaximumSumPath{ // Utility function to find maximum of two integers int max(int x, int y) { return (x > y) ? x : y; } // This function returns the sum of elements on maximum // path from beginning to end int maxPathSum(int ar1[], int ar2[], int m, int n) { // initialize indexes for ar1[] and ar2[] int i = 0, j = 0; // Initialize result and current sum through ar1[] // and ar2[]. int result = 0, sum1 = 0, sum2 = 0; // Below 3 loops are similar to merge in merge sort while (i < m && j < n) { // Add elements of ar1[] to sum1 if (ar1[i] < ar2[j]) sum1 += ar1[i++]; // Add elements of ar2[] to sum2 else if (ar1[i] > ar2[j]) sum2 += ar2[j++]; // we reached a common point else { // Take the maximum of two sums and add to // result //Also add the common element of array, once result += max(sum1, sum2) + ar1[i]; // Update sum1 and sum2 for elements after this // intersection point sum1 = 0; sum2 = 0; //update i and j to move to next element of each array i++; j++; } } // Add remaining elements of ar1[] while (i < m) sum1 += ar1[i++]; // Add remaining elements of ar2[] while (j < n) sum2 += ar2[j++]; // Add maximum of two sums of remaining elements result += max(sum1, sum2); return result; } // Driver code public static void main(String[] args) { MaximumSumPath sumpath = new MaximumSumPath(); int ar1[] = { 2, 3, 7, 10, 12, 15, 30, 34 }; int ar2[] = { 1, 5, 7, 8, 10, 15, 16, 19 }; int m = ar1.length; int n = ar2.length; // Function call System.out.println( \"Maximum sum path is :\" + sumpath.maxPathSum(ar1, ar2, m, n)); }} // This code has been contributed by Mayank Jaiswal", "e": 33474, "s": 31299, "text": null }, { "code": "# Python program to find maximum sum path # This function returns the sum of elements on maximum path from# beginning to end def maxPathSum(ar1, ar2, m, n): # initialize indexes for ar1[] and ar2[] i, j = 0, 0 # Initialize result and current sum through ar1[] and ar2[] result, sum1, sum2 = 0, 0, 0 # Below 3 loops are similar to merge in merge sort while (i < m and j < n): # Add elements of ar1[] to sum1 if ar1[i] < ar2[j]: sum1 += ar1[i] i += 1 # Add elements of ar2[] to sum2 elif ar1[i] > ar2[j]: sum2 += ar2[j] j += 1 else: # we reached a common point # Take the maximum of two sums and add to result result += max(sum1, sum2) +ar1[i] #update sum1 and sum2 to be considered fresh for next elements sum1 = 0 sum2 = 0 #update i and j to move to next element in each array i +=1 j +=1 # Add remaining elements of ar1[] while i < m: sum1 += ar1[i] i += 1 # Add remaining elements of b[] while j < n: sum2 += ar2[j] j += 1 # Add maximum of two sums of remaining elements result += max(sum1, sum2) return result # Driver codear1 = [2, 3, 7, 10, 12, 15, 30, 34]ar2 = [1, 5, 7, 8, 10, 15, 16, 19]m = len(ar1)n = len(ar2) # Function callprint (\"Maximum sum path is\", maxPathSum(ar1, ar2, m, n)) # This code is contributed by __Devesh Agrawal__", "e": 34976, "s": 33474, "text": null }, { "code": "// C# program for Maximum Sum Path in// Two Arraysusing System; class GFG { // Utility function to find maximum // of two integers static int max(int x, int y) { return (x > y) ? x : y; } // This function returns the sum of // elements on maximum path from // beginning to end static int maxPathSum(int[] ar1, int[] ar2, int m, int n) { // initialize indexes for ar1[] // and ar2[] int i = 0, j = 0; // Initialize result and current // sum through ar1[] and ar2[]. int result = 0, sum1 = 0, sum2 = 0; // Below 3 loops are similar to // merge in merge sort while (i < m && j < n) { // Add elements of ar1[] to sum1 if (ar1[i] < ar2[j]) sum1 += ar1[i++]; // Add elements of ar2[] to sum2 else if (ar1[i] > ar2[j]) sum2 += ar2[j++]; // we reached a common point else { // Take the maximum of two sums and add to // result // Also add the common element of array, // once result += max(sum1, sum2) + ar1[i]; // Update sum1 and sum2 for elements after // this intersection point sum1 = 0; sum2 = 0; // update i and j to move to next element of // each array i++; j++; } } // Add remaining elements of ar1[] while (i < m) sum1 += ar1[i++]; // Add remaining elements of ar2[] while (j < n) sum2 += ar2[j++]; // Add maximum of two sums of // remaining elements result += max(sum1, sum2); return result; } // Driver code public static void Main() { int[] ar1 = { 2, 3, 7, 10, 12, 15, 30, 34 }; int[] ar2 = { 1, 5, 7, 8, 10, 15, 16, 19 }; int m = ar1.Length; int n = ar2.Length; // Function call Console.Write(\"Maximum sum path is :\" + maxPathSum(ar1, ar2, m, n)); }} // This code is contributed by nitin mittal.", "e": 37172, "s": 34976, "text": null }, { "code": "<?php// PHP Program to find Maximum Sum// Path in Two Arrays // This function returns the sum of// elements on maximum path// from beginning to endfunction maxPathSum($ar1, $ar2, $m, $n){ // initialize indexes for // ar1[] and ar2[] $i = 0; $j = 0; // Initialize result and // current sum through ar1[] // and ar2[]. $result = 0; $sum1 = 0; $sum2 = 0; // Below 3 loops are similar // to merge in merge sort while ($i < $m and $j < $n) { // Add elements of // ar1[] to sum1 if ($ar1[$i] < $ar2[$j]) $sum1 += $ar1[$i++]; // Add elements of // ar2[] to sum2 else if ($ar1[$i] > $ar2[$j]) $sum2 += $ar2[$j++]; // we reached a // common point else { // Take the maximum of two sums and add to // result //Also add the common element of array, once $result += max($sum1, $sum2) + $ar1[$i]; // Update sum1 and sum2 for elements after this // intersection point $sum1 = 0; $sum2 = 0; //update i and j to move to next element of each array $i++; $j++; } } // Add remaining elements of ar1[] while ($i < $m) $sum1 += $ar1[$i++]; // Add remaining elements of ar2[] while ($j < $n) $sum2 += $ar2[$j++]; // Add maximum of two sums // of remaining elements $result += max($sum1, $sum2); return $result;} // Driver Code $ar1 = array(2, 3, 7, 10, 12, 15, 30, 34); $ar2 = array(1, 5, 7, 8, 10, 15, 16, 19); $m = count($ar1); $n = count($ar2); // Function call echo \"Maximum sum path is \" , maxPathSum($ar1, $ar2, $m, $n); // This code is contributed by anuj_67.?>", "e": 39023, "s": 37172, "text": null }, { "code": "<script> // Javascript program to find maximum sum path // Utility function to find maximum of two integersfunction max(x, y){ return (x > y) ? x : y;} // This function returns the sum of elements// on maximum path from beginning to endfunction maxPathSum(ar1, ar2, m, n){ // Initialize indexes for ar1[] and ar2[] let i = 0, j = 0; // Initialize result and current sum // through ar1[] and ar2[]. let result = 0, sum1 = 0, sum2 = 0; // Below3 loops are similar to // merge in merge sort while (i < m && j < n) { // Add elements of ar1[] to sum1 if (ar1[i] < ar2[j]) sum1 += ar1[i++]; // Add elements of ar2[] to sum2 else if (ar1[i] > ar2[j]) sum2 += ar2[j++]; // We reached a common point else { // Take the maximum of two sums and add to // result //Also add the common element of array, once result += Math.max(sum1, sum2) + ar1[i]; // Update sum1 and sum2 for elements after this // intersection point sum1 = 0; sum2 = 0; //update i and j to move to next element of each array i++; j++; } } // Add remaining elements of ar1[] while (i < m) sum1 += ar1[i++]; // Add remaining elements of ar2[] while (j < n) sum2 += ar2[j++]; // Add maximum of two sums of // remaining elements result += Math.max(sum1, sum2); return result;} // Driver codelet ar1 = [ 2, 3, 7, 10, 12, 15, 30, 34 ];let ar2 = [ 1, 5, 7, 8, 10, 15, 16, 19 ];let m = ar1.length;let n = ar2.length; // Function calldocument.write(\"Maximum sum path is \" + maxPathSum(ar1, ar2, m, n)); // This code is contributed by Mayank Tyagi </script>", "e": 40874, "s": 39023, "text": null }, { "code": null, "e": 40898, "s": 40874, "text": "Maximum sum path is 122" }, { "code": null, "e": 40921, "s": 40898, "text": "Complexity Analysis: " }, { "code": null, "e": 41015, "s": 40921, "text": "Space Complexity: O(1). Any extra space is not required, so the space complexity is constant." }, { "code": null, "e": 41204, "s": 41015, "text": "Time complexity: O(m+n). In every iteration of while loops, an element from either of the two arrays is processed. There are total m + n elements. Therefore, the time complexity is O(m+n)." }, { "code": null, "e": 41375, "s": 41204, "text": "This article is contributed by Piyush Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 41388, "s": 41375, "text": "nitin mittal" }, { "code": null, "e": 41393, "s": 41388, "text": "vt_m" }, { "code": null, "e": 41404, "s": 41393, "text": "andrew1234" }, { "code": null, "e": 41419, "s": 41404, "text": "mohith23102000" }, { "code": null, "e": 41432, "s": 41419, "text": "nithinsgowda" }, { "code": null, "e": 41444, "s": 41432, "text": "vipinrai399" }, { "code": null, "e": 41460, "s": 41444, "text": "mayanktyagi1709" }, { "code": null, "e": 41473, "s": 41460, "text": "divyanshuraj" }, { "code": null, "e": 41488, "s": 41473, "text": "kapoorsagar226" }, { "code": null, "e": 41504, "s": 41488, "text": "amartyaghoshgfg" }, { "code": null, "e": 41511, "s": 41504, "text": "Amazon" }, { "code": null, "e": 41518, "s": 41511, "text": "Arrays" }, { "code": null, "e": 41525, "s": 41518, "text": "Amazon" }, { "code": null, "e": 41532, "s": 41525, "text": "Arrays" }, { "code": null, "e": 41630, "s": 41532, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41639, "s": 41630, "text": "Comments" }, { "code": null, "e": 41652, "s": 41639, "text": "Old Comments" }, { "code": null, "e": 41700, "s": 41652, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 41744, "s": 41700, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 41767, "s": 41744, "text": "Introduction to Arrays" }, { "code": null, "e": 41781, "s": 41767, "text": "Linear Search" }, { "code": null, "e": 41849, "s": 41781, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 41881, "s": 41849, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 41902, "s": 41881, "text": "Linked List vs Array" }, { "code": null, "e": 41956, "s": 41902, "text": "Queue | Set 1 (Introduction and Array Implementation)" }, { "code": null, "e": 42001, "s": 41956, "text": "Python | Using 2D arrays/lists the right way" } ]
Material Design Lite - Footers
An MDL footer component comes in two primary forms: mega-footer and mini-footer. mega-footer contains more complex content than mini-footer. A mega-footer can represent multiple sections of content which are separated by horizontal rules, whereas a mini-footer presents a single section of content. The footers typically contain both informational and clickable content, such as links. MDL provides various CSS classes to apply various predefined visual and behavioral enhancements to the mega-footer and mini-footer. The following table lists down the available classes and their effects. mdl-mega-footer Identifies container as an MDL mega-footer component. Required for footer element. mdl-mega-footer__top-section Identifies container as a footer top section. Required for top section "outer" div element. mdl-mega-footer__left-section Identifies container as a left section. Required for left section "inner" div element. mdl-mega-footer__social-btn Identifies a decorative square within mega-footer. Required for button element (if used). mdl-mega-footer__right-section Identifies container as a right section. Required for right section "inner" div element. mdl-mega-footer__middle-section Identifies container as a footer middle section. Required for middle section "outer" div element. mdl-mega-footer__drop-down-section Identifies container as a drop-down (vertical) content area. Required for drop-down "inner" div elements. mdl-mega-footer__heading Identifies a heading as a mega-footer heading. Required for h1 element inside drop-down section. mdl-mega-footer__link-list Identifies an unordered list as a drop-down (vertical) list. Required for ul element inside drop-down section. mdl-mega-footer__bottom-section Identifies container as a footer bottom section. Required for bottom section "outer" div element. mdl-logo Identifies a container as a styled section heading. Required for "inner" div element in mega-footer bottom-section or mini-footer left-section. mdl-mini-footer Identifies container as an MDL mini-footer component. Required for footer element. mdl-mini-footer__left-section Identifies container as a left section. Required for left section "inner" div element. mdl-mini-footer__link-list Identifies an unordered list as an inline (horizontal) list. Required for ul element sibling to "mdl-logo" div element. mdl-mini-footer__right-section Identifies container as a right section. Required for right section "inner" div element. mdl-mini-footer__social-btn Identifies a decorative square within mini-footer. Required for button element (if used). Now, let us see a few examples to understand the use of MDL footer classes to style footers. Let us discuss the use of the mdl-mega-footer class to layout contents in a footer. The following MDL classes will be used in this example. mdl-layout − Identifies a div as an MDL component. mdl-layout − Identifies a div as an MDL component. mdl-js-layout − Adds basic MDL behavior to outer div. mdl-js-layout − Adds basic MDL behavior to outer div. mdl-layout--fixed-header − Makes the header always visible, even in small screens. mdl-layout--fixed-header − Makes the header always visible, even in small screens. mdl-layout__header-row − Identifies container as MDL header row. mdl-layout__header-row − Identifies container as MDL header row. mdl-layout-title − Identifies layout title text. mdl-layout-title − Identifies layout title text. mdl-layout__content − Identifies div as MDL layout content. mdl-layout__content − Identifies div as MDL layout content. mdl-mega-footer − Identifies container as an MDL mega-footer component. mdl-mega-footer − Identifies container as an MDL mega-footer component. mdl-mega-footer__top-section − Identifies container as a footer top section. mdl-mega-footer__top-section − Identifies container as a footer top section. mdl-mega-footer__left-section − Identifies container as a left section. mdl-mega-footer__left-section − Identifies container as a left section. mdl-mega-footer__social-btn − Identifies a decorative square within mini-footer. mdl-mega-footer__social-btn − Identifies a decorative square within mini-footer. mdl-mega-footer__right-section − Identifies container as a right section. mdl-mega-footer__right-section − Identifies container as a right section. mdl-mega-footer__middle-section − Identifies container as a footer middle section. mdl-mega-footer__middle-section − Identifies container as a footer middle section. mdl-mega-footer__drop-down-section − Identifies container as a drop-down (vertical) content area. mdl-mega-footer__drop-down-section − Identifies container as a drop-down (vertical) content area. mdl-mega-footer__heading − Identifies a heading as a mega-footer heading. mdl-mega-footer__heading − Identifies a heading as a mega-footer heading. mdl-mega-footer__link-list − Identifies an unordered list as an inline (horizontal) list. mdl-mega-footer__link-list − Identifies an unordered list as an inline (horizontal) list. mdl-mega-footer__bottom-section − Identifies container as a footer bottom section. mdl-mega-footer__bottom-section − Identifies container as a footer bottom section. mdl-logo − Identifies a container as a styled section heading. mdl-logo − Identifies a container as a styled section heading. <html> <head> <link rel = "stylesheet" href = "https://storage.googleapis.com/code.getmdl.io/1.0.6/material.indigo-pink.min.css"> <script src = "https://storage.googleapis.com/code.getmdl.io/1.0.6/material.min.js"> </script> <link rel = "stylesheet" href = "https://fonts.googleapis.com/icon?family=Material+Icons"> </head> <body> <div class = "mdl-layout mdl-js-layout mdl-layout--fixed-header"> <header class = "mdl-layout__header"> <div class = "mdl-layout__header-row"> <span class = "mdl-layout-title">Material Design Tabs</span> </div> </header> <main class = "mdl-layout__content"> <footer class = "mdl-mega-footer"> <div class = "mdl-mega-footer__top-section"> <div class = "mdl-mega-footer__left-section"> <button class = "mdl-mega-footer__social-btn">1</button> <button class = "mdl-mega-footer__social-btn">2</button> <button class = "mdl-mega-footer__social-btn">3</button> </div> <div class = "mdl-mega-footer__right-section"> <a href = "">Link 1</a> <a href = "">Link 2</a> <a href = "">Link 3</a> </div> </div> <div class = "mdl-mega-footer__middle-section"> <div class = "mdl-mega-footer__drop-down-section"> <h1 class = "mdl-mega-footer__heading">Heading </h1> <ul class = "mdl-mega-footer__link-list"> <li><a href = "">Link A</a></li> <li><a href = "">Link B</a></li> </ul> </div> <div class = "mdl-mega-footer__drop-down-section"> <h1 class = "mdl-mega-footer__heading">Heading </h1> <ul class = "mdl-mega-footer__link-list"> <li><a href = "">Link C</a></li> <li><a href = "">Link D</a></li> </ul> </div> </div> <div class = "mdl-mega-footer__bottom-section"> <div class = "mdl-logo"> Bottom Section </div> <ul class = "mdl-mega-footer__link-list"> <li><a href = "">Link A</a></li> <li><a href = "">Link B</a></li> </ul> </div> </footer> </main> </div> </body> </html> Verify the result.
[ { "code": null, "e": 2272, "s": 1886, "text": "An MDL footer component comes in two primary forms: mega-footer and mini-footer. mega-footer contains more complex content than mini-footer. A mega-footer can represent multiple sections of content which are separated by horizontal rules, whereas a mini-footer presents a single section of content. The footers typically contain both informational and clickable content, such as links." }, { "code": null, "e": 2476, "s": 2272, "text": "MDL provides various CSS classes to apply various predefined visual and behavioral enhancements to the mega-footer and mini-footer. The following table lists down the available classes and their effects." }, { "code": null, "e": 2492, "s": 2476, "text": "mdl-mega-footer" }, { "code": null, "e": 2575, "s": 2492, "text": "Identifies container as an MDL mega-footer component. Required for footer element." }, { "code": null, "e": 2604, "s": 2575, "text": "mdl-mega-footer__top-section" }, { "code": null, "e": 2696, "s": 2604, "text": "Identifies container as a footer top section. Required for top section \"outer\" div element." }, { "code": null, "e": 2726, "s": 2696, "text": "mdl-mega-footer__left-section" }, { "code": null, "e": 2813, "s": 2726, "text": "Identifies container as a left section. Required for left section \"inner\" div element." }, { "code": null, "e": 2841, "s": 2813, "text": "mdl-mega-footer__social-btn" }, { "code": null, "e": 2931, "s": 2841, "text": "Identifies a decorative square within mega-footer. Required for button element (if used)." }, { "code": null, "e": 2962, "s": 2931, "text": "mdl-mega-footer__right-section" }, { "code": null, "e": 3051, "s": 2962, "text": "Identifies container as a right section. Required for right section \"inner\" div element." }, { "code": null, "e": 3083, "s": 3051, "text": "mdl-mega-footer__middle-section" }, { "code": null, "e": 3181, "s": 3083, "text": "Identifies container as a footer middle section. Required for middle section \"outer\" div element." }, { "code": null, "e": 3216, "s": 3181, "text": "mdl-mega-footer__drop-down-section" }, { "code": null, "e": 3322, "s": 3216, "text": "Identifies container as a drop-down (vertical) content area. Required for drop-down \"inner\" div elements." }, { "code": null, "e": 3347, "s": 3322, "text": "mdl-mega-footer__heading" }, { "code": null, "e": 3444, "s": 3347, "text": "Identifies a heading as a mega-footer heading. Required for h1 element inside drop-down section." }, { "code": null, "e": 3471, "s": 3444, "text": "mdl-mega-footer__link-list" }, { "code": null, "e": 3582, "s": 3471, "text": "Identifies an unordered list as a drop-down (vertical) list. Required for ul element inside drop-down section." }, { "code": null, "e": 3614, "s": 3582, "text": "mdl-mega-footer__bottom-section" }, { "code": null, "e": 3712, "s": 3614, "text": "Identifies container as a footer bottom section. Required for bottom section \"outer\" div element." }, { "code": null, "e": 3721, "s": 3712, "text": "mdl-logo" }, { "code": null, "e": 3865, "s": 3721, "text": "Identifies a container as a styled section heading. Required for \"inner\" div element in mega-footer bottom-section or mini-footer left-section." }, { "code": null, "e": 3881, "s": 3865, "text": "mdl-mini-footer" }, { "code": null, "e": 3964, "s": 3881, "text": "Identifies container as an MDL mini-footer component. Required for footer element." }, { "code": null, "e": 3994, "s": 3964, "text": "mdl-mini-footer__left-section" }, { "code": null, "e": 4081, "s": 3994, "text": "Identifies container as a left section. Required for left section \"inner\" div element." }, { "code": null, "e": 4108, "s": 4081, "text": "mdl-mini-footer__link-list" }, { "code": null, "e": 4228, "s": 4108, "text": "Identifies an unordered list as an inline (horizontal) list. Required for ul element sibling to \"mdl-logo\" div element." }, { "code": null, "e": 4259, "s": 4228, "text": "mdl-mini-footer__right-section" }, { "code": null, "e": 4348, "s": 4259, "text": "Identifies container as a right section. Required for right section \"inner\" div element." }, { "code": null, "e": 4376, "s": 4348, "text": "mdl-mini-footer__social-btn" }, { "code": null, "e": 4466, "s": 4376, "text": "Identifies a decorative square within mini-footer. Required for button element (if used)." }, { "code": null, "e": 4559, "s": 4466, "text": "Now, let us see a few examples to understand the use of MDL footer classes to style footers." }, { "code": null, "e": 4699, "s": 4559, "text": "Let us discuss the use of the mdl-mega-footer class to layout contents in a footer. The following MDL classes will be used in this example." }, { "code": null, "e": 4750, "s": 4699, "text": "mdl-layout − Identifies a div as an MDL component." }, { "code": null, "e": 4801, "s": 4750, "text": "mdl-layout − Identifies a div as an MDL component." }, { "code": null, "e": 4855, "s": 4801, "text": "mdl-js-layout − Adds basic MDL behavior to outer div." }, { "code": null, "e": 4909, "s": 4855, "text": "mdl-js-layout − Adds basic MDL behavior to outer div." }, { "code": null, "e": 4992, "s": 4909, "text": "mdl-layout--fixed-header − Makes the header always visible, even in small screens." }, { "code": null, "e": 5075, "s": 4992, "text": "mdl-layout--fixed-header − Makes the header always visible, even in small screens." }, { "code": null, "e": 5140, "s": 5075, "text": "mdl-layout__header-row − Identifies container as MDL header row." }, { "code": null, "e": 5205, "s": 5140, "text": "mdl-layout__header-row − Identifies container as MDL header row." }, { "code": null, "e": 5254, "s": 5205, "text": "mdl-layout-title − Identifies layout title text." }, { "code": null, "e": 5303, "s": 5254, "text": "mdl-layout-title − Identifies layout title text." }, { "code": null, "e": 5363, "s": 5303, "text": "mdl-layout__content − Identifies div as MDL layout content." }, { "code": null, "e": 5423, "s": 5363, "text": "mdl-layout__content − Identifies div as MDL layout content." }, { "code": null, "e": 5495, "s": 5423, "text": "mdl-mega-footer − Identifies container as an MDL mega-footer component." }, { "code": null, "e": 5567, "s": 5495, "text": "mdl-mega-footer − Identifies container as an MDL mega-footer component." }, { "code": null, "e": 5644, "s": 5567, "text": "mdl-mega-footer__top-section − Identifies container as a footer top section." }, { "code": null, "e": 5721, "s": 5644, "text": "mdl-mega-footer__top-section − Identifies container as a footer top section." }, { "code": null, "e": 5793, "s": 5721, "text": "mdl-mega-footer__left-section − Identifies container as a left section." }, { "code": null, "e": 5865, "s": 5793, "text": "mdl-mega-footer__left-section − Identifies container as a left section." }, { "code": null, "e": 5946, "s": 5865, "text": "mdl-mega-footer__social-btn − Identifies a decorative square within mini-footer." }, { "code": null, "e": 6027, "s": 5946, "text": "mdl-mega-footer__social-btn − Identifies a decorative square within mini-footer." }, { "code": null, "e": 6101, "s": 6027, "text": "mdl-mega-footer__right-section − Identifies container as a right section." }, { "code": null, "e": 6175, "s": 6101, "text": "mdl-mega-footer__right-section − Identifies container as a right section." }, { "code": null, "e": 6258, "s": 6175, "text": "mdl-mega-footer__middle-section − Identifies container as a footer middle section." }, { "code": null, "e": 6341, "s": 6258, "text": "mdl-mega-footer__middle-section − Identifies container as a footer middle section." }, { "code": null, "e": 6439, "s": 6341, "text": "mdl-mega-footer__drop-down-section − Identifies container as a drop-down (vertical) content area." }, { "code": null, "e": 6537, "s": 6439, "text": "mdl-mega-footer__drop-down-section − Identifies container as a drop-down (vertical) content area." }, { "code": null, "e": 6611, "s": 6537, "text": "mdl-mega-footer__heading − Identifies a heading as a mega-footer heading." }, { "code": null, "e": 6685, "s": 6611, "text": "mdl-mega-footer__heading − Identifies a heading as a mega-footer heading." }, { "code": null, "e": 6775, "s": 6685, "text": "mdl-mega-footer__link-list − Identifies an unordered list as an inline (horizontal) list." }, { "code": null, "e": 6865, "s": 6775, "text": "mdl-mega-footer__link-list − Identifies an unordered list as an inline (horizontal) list." }, { "code": null, "e": 6948, "s": 6865, "text": "mdl-mega-footer__bottom-section − Identifies container as a footer bottom section." }, { "code": null, "e": 7031, "s": 6948, "text": "mdl-mega-footer__bottom-section − Identifies container as a footer bottom section." }, { "code": null, "e": 7094, "s": 7031, "text": "mdl-logo − Identifies a container as a styled section heading." }, { "code": null, "e": 7157, "s": 7094, "text": "mdl-logo − Identifies a container as a styled section heading." }, { "code": null, "e": 9969, "s": 7157, "text": "<html>\n <head>\n <link rel = \"stylesheet\" \n href = \"https://storage.googleapis.com/code.getmdl.io/1.0.6/material.indigo-pink.min.css\">\n <script src = \"https://storage.googleapis.com/code.getmdl.io/1.0.6/material.min.js\">\n </script>\n <link rel = \"stylesheet\" \n href = \"https://fonts.googleapis.com/icon?family=Material+Icons\">\n </head>\n \n <body>\n <div class = \"mdl-layout mdl-js-layout mdl-layout--fixed-header\">\n <header class = \"mdl-layout__header\">\n <div class = \"mdl-layout__header-row\"> \n <span class = \"mdl-layout-title\">Material Design Tabs</span> \n </div> \n </header> \n \n <main class = \"mdl-layout__content\"> \n <footer class = \"mdl-mega-footer\">\n <div class = \"mdl-mega-footer__top-section\">\n <div class = \"mdl-mega-footer__left-section\">\n <button class = \"mdl-mega-footer__social-btn\">1</button>\n <button class = \"mdl-mega-footer__social-btn\">2</button>\n <button class = \"mdl-mega-footer__social-btn\">3</button>\n </div>\n \n <div class = \"mdl-mega-footer__right-section\">\n <a href = \"\">Link 1</a>\n <a href = \"\">Link 2</a>\n <a href = \"\">Link 3</a>\n </div>\n </div>\n \n <div class = \"mdl-mega-footer__middle-section\">\n <div class = \"mdl-mega-footer__drop-down-section\">\n <h1 class = \"mdl-mega-footer__heading\">Heading </h1>\n <ul class = \"mdl-mega-footer__link-list\">\n <li><a href = \"\">Link A</a></li>\n <li><a href = \"\">Link B</a></li> \n </ul>\n </div> \n \n <div class = \"mdl-mega-footer__drop-down-section\">\n <h1 class = \"mdl-mega-footer__heading\">Heading </h1>\n <ul class = \"mdl-mega-footer__link-list\">\n <li><a href = \"\">Link C</a></li>\n <li><a href = \"\">Link D</a></li> \n </ul>\n </div> \t\n </div>\n \n <div class = \"mdl-mega-footer__bottom-section\">\n <div class = \"mdl-logo\">\n Bottom Section\n </div>\n <ul class = \"mdl-mega-footer__link-list\">\n <li><a href = \"\">Link A</a></li>\n <li><a href = \"\">Link B</a></li>\n </ul>\n </div>\n \n </footer>\n </main>\n </div>\n </body>\n</html>" } ]
Pass long parameter to an overloaded method in Java
Method overloading in a class contains multiple methods with the same name but the parameter list of the methods should not be the same. One of these methods can have a long parameter in their parameter list. A program that demonstrates this is given as follows − Live Demo class PrintValues { public void print(int val) { System.out.println("The int value is: " + val); } public void print(long val) { System.out.println("The long value is: " + val); } } public class Demo { public static void main(String[] args) { PrintValues obj = new PrintValues(); obj.print(15); obj.print(8L); } } The int value is: 15 The long value is: 8 Now let us understand the above program. The PrintValues class is created with two methods print() in the implementation of method overloading. One of these takes a parameter of type int and the other takes a parameter of type long. A code snippet which demonstrates this is as follows: class PrintValues { public void print(int val) { System.out.println("The int value is: " + val); } public void print(long val) { System.out.println("The long value is: " + val); } } In the main() method, object obj of class PrintValues is created and the print() method is called two times with parameters 15 and 8L respectively where the former is an int value and the latter a long value. A code snippet which demonstrates this is as follows: public class Demo { public static void main(String[] args) { PrintValues obj = new PrintValues(); obj.print(15); obj.print(8L); } }
[ { "code": null, "e": 1271, "s": 1062, "text": "Method overloading in a class contains multiple methods with the same name but the parameter list of the methods should not be the same. One of these methods can have a long parameter in their parameter list." }, { "code": null, "e": 1326, "s": 1271, "text": "A program that demonstrates this is given as follows −" }, { "code": null, "e": 1337, "s": 1326, "text": " Live Demo" }, { "code": null, "e": 1699, "s": 1337, "text": "class PrintValues {\n public void print(int val) {\n System.out.println(\"The int value is: \" + val);\n }\n public void print(long val) {\n System.out.println(\"The long value is: \" + val);\n }\n}\npublic class Demo {\n public static void main(String[] args) {\n PrintValues obj = new PrintValues();\n obj.print(15);\n obj.print(8L);\n }\n}" }, { "code": null, "e": 1741, "s": 1699, "text": "The int value is: 15\nThe long value is: 8" }, { "code": null, "e": 1782, "s": 1741, "text": "Now let us understand the above program." }, { "code": null, "e": 2028, "s": 1782, "text": "The PrintValues class is created with two methods print() in the implementation of method overloading. One of these takes a parameter of type int and the other takes a parameter of type long. A code snippet which demonstrates this is as follows:" }, { "code": null, "e": 2234, "s": 2028, "text": "class PrintValues {\n public void print(int val) {\n System.out.println(\"The int value is: \" + val);\n }\n public void print(long val) {\n System.out.println(\"The long value is: \" + val);\n }\n}" }, { "code": null, "e": 2497, "s": 2234, "text": "In the main() method, object obj of class PrintValues is created and the print() method is called two times with parameters 15 and 8L respectively where the former is an int value and the latter a long value. A code snippet which demonstrates this is as follows:" }, { "code": null, "e": 2653, "s": 2497, "text": "public class Demo {\n public static void main(String[] args) {\n PrintValues obj = new PrintValues();\n obj.print(15);\n obj.print(8L);\n }\n}" } ]
How to increment all the rows of a particular column by 1 in a single MySQL query (ID column +1)?
To increment all the rows of a particular ID column by 1, you need to use UPDATE command and update the table. The syntax of the query is as follows. We have also used ORDER BY here UPDATE yourTableName SET yourIdColumnName=yourIdColumnName+1 ORDER BY yourIdColumnName DESC; To understand the above syntax, let us create a table. The query to create a table is as follows mysql> create table IdColumnadd1Demo - > ( - > Id int NOT NULL AUTO_INCREMENT PRIMARY KEY - > ); Query OK, 0 rows affected (0.58 sec) Insert some records in the table using insert command. The query is as follows mysql> insert into IdColumnadd1Demo values(); Query OK, 1 row affected (0.12 sec) mysql> insert into IdColumnadd1Demo values(); Query OK, 1 row affected (0.18 sec) mysql> insert into IdColumnadd1Demo values(); Query OK, 1 row affected (0.17 sec) mysql> insert into IdColumnadd1Demo values(); Query OK, 1 row affected (0.08 sec) mysql> insert into IdColumnadd1Demo values(); Query OK, 1 row affected (0.10 sec) mysql> insert into IdColumnadd1Demo values(); Query OK, 1 row affected (0.13 sec) mysql> insert into IdColumnadd1Demo values(); Query OK, 1 row affected (0.25 sec) mysql> insert into IdColumnadd1Demo values(); Query OK, 1 row affected (0.40 sec) Display all records from the table using select statement. The query is as follows mysql> select *from IdColumnadd1Demo; The following is the output +----+ | Id | +----+ | 1 | | 2 | | 3 | | 4 | | 5 | | 6 | | 7 | | 8 | +----+ 8 rows in set (0.00 sec) Here is the query to adjust the MySQL ID column+1 mysql> update IdColumnadd1Demo set Id=Id+1 Order By Id DESC; Query OK, 8 rows affected (0.18 sec) Rows matched: 8 Changed: 8 Warnings: 0 Check the table records once again. The query is as follows mysql> select *from IdColumnadd1Demo; The following is the output +----+ | Id | +----+ | 2 | | 3 | | 4 | | 5 | | 6 | | 7 | | 8 | | 9 | +----+ 8 rows in set (0.00 sec)
[ { "code": null, "e": 1244, "s": 1062, "text": "To increment all the rows of a particular ID column by 1, you need to use UPDATE command and update the table. The syntax of the query is as follows. We have also used ORDER BY here" }, { "code": null, "e": 1337, "s": 1244, "text": "UPDATE yourTableName SET yourIdColumnName=yourIdColumnName+1 ORDER BY yourIdColumnName DESC;" }, { "code": null, "e": 1434, "s": 1337, "text": "To understand the above syntax, let us create a table. The query to create a table is as follows" }, { "code": null, "e": 1577, "s": 1434, "text": "mysql> create table IdColumnadd1Demo\n - > (\n - > Id int NOT NULL AUTO_INCREMENT PRIMARY KEY\n - > );\nQuery OK, 0 rows affected (0.58 sec)" }, { "code": null, "e": 1632, "s": 1577, "text": "Insert some records in the table using insert command." }, { "code": null, "e": 1656, "s": 1632, "text": "The query is as follows" }, { "code": null, "e": 2312, "s": 1656, "text": "mysql> insert into IdColumnadd1Demo values();\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into IdColumnadd1Demo values();\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into IdColumnadd1Demo values();\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into IdColumnadd1Demo values();\nQuery OK, 1 row affected (0.08 sec)\nmysql> insert into IdColumnadd1Demo values();\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into IdColumnadd1Demo values();\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into IdColumnadd1Demo values();\nQuery OK, 1 row affected (0.25 sec)\nmysql> insert into IdColumnadd1Demo values();\nQuery OK, 1 row affected (0.40 sec)" }, { "code": null, "e": 2371, "s": 2312, "text": "Display all records from the table using select statement." }, { "code": null, "e": 2395, "s": 2371, "text": "The query is as follows" }, { "code": null, "e": 2433, "s": 2395, "text": "mysql> select *from IdColumnadd1Demo;" }, { "code": null, "e": 2461, "s": 2433, "text": "The following is the output" }, { "code": null, "e": 2570, "s": 2461, "text": "+----+\n| Id |\n+----+\n| 1 |\n| 2 |\n| 3 |\n| 4 |\n| 5 |\n| 6 |\n| 7 |\n| 8 |\n+----+\n8 rows in set (0.00 sec)" }, { "code": null, "e": 2620, "s": 2570, "text": "Here is the query to adjust the MySQL ID column+1" }, { "code": null, "e": 2757, "s": 2620, "text": "mysql> update IdColumnadd1Demo set Id=Id+1 Order By Id DESC;\nQuery OK, 8 rows affected (0.18 sec)\nRows matched: 8 Changed: 8 Warnings: 0" }, { "code": null, "e": 2793, "s": 2757, "text": "Check the table records once again." }, { "code": null, "e": 2817, "s": 2793, "text": "The query is as follows" }, { "code": null, "e": 2855, "s": 2817, "text": "mysql> select *from IdColumnadd1Demo;" }, { "code": null, "e": 2883, "s": 2855, "text": "The following is the output" }, { "code": null, "e": 2992, "s": 2883, "text": "+----+\n| Id |\n+----+\n| 2 |\n| 3 |\n| 4 |\n| 5 |\n| 6 |\n| 7 |\n| 8 |\n| 9 |\n+----+\n8 rows in set (0.00 sec)" } ]
How to Build a Real-time SCADA System Using Python and Arduino | by M Khorasani | Towards Data Science
Those of us who have worked with SCADA (supervisory control and data acquisition) systems the likes of OSIsoft and Oracle know how invaluable the data they provide can be. Especially for many in the business of data and natural sciences, SCADA is a rich source of real-world data on demand. Yet such systems do not come cheap and the average individual would not be able to acquire their services readily. Luckily there is a way to create your own SCADA pipeline with simple and inexpensive equipment that is easily accessible. In this tutorial, I will show you how to set up an ambient temperature signal that will record and visualize data with a real-time dashboard on your computer. To begin with, we will use an Arduino Uno board to read temperature values from the MLX9061 4infrared thermometer. Once you have connected the infrared thermometer as shown above, proceed with uploading the following program to the Arduino. If you have not already done so, first download and install the Adafruit_MLX90614 library using the Arduino IDE’s library manager in Tools > Manage Libraries. To verify that the Arduino and thermometer are working as expected, open the serial monitor (Tools > Serial monitor) to ensure that a temperature recording is being printed every second as shown below. Alternatively, you can also open the Arduino’s serial plotter (Tools > Serial plotter) to see a real-time plot of the ambient temperature as shown below. Now that the Arduino and infrared thermometer are working and printing values to the serial port, we need to acquire the readings in Python to produce our SCADA dashboard. To interface our Python script with the Arduino through a serial USB connection, we will need to download and install Pyserial. Go ahead and fire up Anaconda or any other Python IDE of your choice and type the following command: pip install pyserial To produce a graphical user interface where we can interact with our dashboard we will use Streamlit. This highly versatile web framework allows you to quickly develop and deploy applications to a web server or alternatively run them locally on your browser. And to display a gauge of the current temperature reading as well as a chart of all previous temperature records, we will use Plotly. This is a Python binding for JavaScript’s highly interactive data visualization framework that allows you to render dazzling visuals at your fingertips. Proceed by saving the following source code in your local directory: The above code will initiate a connection to the Arduino and then will continuously read values from the serial port for the number of iterations specified. It will continuously render and update the gauge and chart. Finally, upon completion of the loop, the port will be closed and a CSV file with all the recordings will be saved in your local directory. To run the above script type the following commands in Anaconda prompt: cd C:/Users/.../local_directorystreamlit run temperature_dashboard.py And there you have it your own real-time SCADA dashboard running on your local browser. Now that you have created a SCADA system with real-time data visualization, you can further enhance the system by using an Arduino Uno WIFI that will enable you to extend the range of your signals. For further information please refer to Arduino Uno WIFI’s configuration guide. In addition, you can connect a whole variety of different third-party sensors and even actuators to the same Arduino for enhanced supervision and control. If you want to learn more about data visualization and Python, then feel free to check out the following (affiliate linked) courses:
[ { "code": null, "e": 858, "s": 171, "text": "Those of us who have worked with SCADA (supervisory control and data acquisition) systems the likes of OSIsoft and Oracle know how invaluable the data they provide can be. Especially for many in the business of data and natural sciences, SCADA is a rich source of real-world data on demand. Yet such systems do not come cheap and the average individual would not be able to acquire their services readily. Luckily there is a way to create your own SCADA pipeline with simple and inexpensive equipment that is easily accessible. In this tutorial, I will show you how to set up an ambient temperature signal that will record and visualize data with a real-time dashboard on your computer." }, { "code": null, "e": 973, "s": 858, "text": "To begin with, we will use an Arduino Uno board to read temperature values from the MLX9061 4infrared thermometer." }, { "code": null, "e": 1099, "s": 973, "text": "Once you have connected the infrared thermometer as shown above, proceed with uploading the following program to the Arduino." }, { "code": null, "e": 1258, "s": 1099, "text": "If you have not already done so, first download and install the Adafruit_MLX90614 library using the Arduino IDE’s library manager in Tools > Manage Libraries." }, { "code": null, "e": 1460, "s": 1258, "text": "To verify that the Arduino and thermometer are working as expected, open the serial monitor (Tools > Serial monitor) to ensure that a temperature recording is being printed every second as shown below." }, { "code": null, "e": 1614, "s": 1460, "text": "Alternatively, you can also open the Arduino’s serial plotter (Tools > Serial plotter) to see a real-time plot of the ambient temperature as shown below." }, { "code": null, "e": 2015, "s": 1614, "text": "Now that the Arduino and infrared thermometer are working and printing values to the serial port, we need to acquire the readings in Python to produce our SCADA dashboard. To interface our Python script with the Arduino through a serial USB connection, we will need to download and install Pyserial. Go ahead and fire up Anaconda or any other Python IDE of your choice and type the following command:" }, { "code": null, "e": 2036, "s": 2015, "text": "pip install pyserial" }, { "code": null, "e": 2582, "s": 2036, "text": "To produce a graphical user interface where we can interact with our dashboard we will use Streamlit. This highly versatile web framework allows you to quickly develop and deploy applications to a web server or alternatively run them locally on your browser. And to display a gauge of the current temperature reading as well as a chart of all previous temperature records, we will use Plotly. This is a Python binding for JavaScript’s highly interactive data visualization framework that allows you to render dazzling visuals at your fingertips." }, { "code": null, "e": 2651, "s": 2582, "text": "Proceed by saving the following source code in your local directory:" }, { "code": null, "e": 3008, "s": 2651, "text": "The above code will initiate a connection to the Arduino and then will continuously read values from the serial port for the number of iterations specified. It will continuously render and update the gauge and chart. Finally, upon completion of the loop, the port will be closed and a CSV file with all the recordings will be saved in your local directory." }, { "code": null, "e": 3080, "s": 3008, "text": "To run the above script type the following commands in Anaconda prompt:" }, { "code": null, "e": 3150, "s": 3080, "text": "cd C:/Users/.../local_directorystreamlit run temperature_dashboard.py" }, { "code": null, "e": 3238, "s": 3150, "text": "And there you have it your own real-time SCADA dashboard running on your local browser." }, { "code": null, "e": 3671, "s": 3238, "text": "Now that you have created a SCADA system with real-time data visualization, you can further enhance the system by using an Arduino Uno WIFI that will enable you to extend the range of your signals. For further information please refer to Arduino Uno WIFI’s configuration guide. In addition, you can connect a whole variety of different third-party sensors and even actuators to the same Arduino for enhanced supervision and control." } ]
JavaScript - Image Map
You can use JavaScript to create client-side image map. Client-side image maps are enabled by the usemap attribute for the <img /> tag and defined by special <map> and <area> extension tags. The image that is going to form the map is inserted into the page using the <img /> element as normal, except that it carries an extra attribute called usemap. The value of the usemap attribute is the value of the name attribute on the <map> element, which you are about to meet, preceded by a pound or hash sign. The <map> element actually creates the map for the image and usually follows directly after the <img /> element. It acts as a container for the <area /> elements that actually define the clickable hotspots. The <map> element carries only one attribute, the name attribute, which is the name that identifies the map. This is how the <img /> element knows which <map> element to use. The <area> element specifies the shape and the coordinates that define the boundaries of each clickable hotspot. The following code combines imagemaps and JavaScript to produce a message in a text box when the mouse is moved over different parts of an image. <html> <head> <title>Using JavaScript Image Map</title> <script type = "text/javascript"> <!-- function showTutorial(name) { document.myform.stage.value = name } //--> </script> </head> <body> <form name = "myform"> <input type = "text" name = "stage" size = "20" /> </form> <!-- Create Mappings --> <img src = "/images/usemap.gif" alt = "HTML Map" border = "0" usemap = "#tutorials"/> <map name = "tutorials"> <area shape="poly" coords = "74,0,113,29,98,72,52,72,38,27" href = "/perl/index.htm" alt = "Perl Tutorial" target = "_self" onMouseOver = "showTutorial('perl')" onMouseOut = "showTutorial('')"/> <area shape = "rect" coords = "22,83,126,125" href = "/html/index.htm" alt = "HTML Tutorial" target = "_self" onMouseOver = "showTutorial('html')" onMouseOut = "showTutorial('')"/> <area shape = "circle" coords = "73,168,32" href = "/php/index.htm" alt = "PHP Tutorial" target = "_self" onMouseOver = "showTutorial('php')" onMouseOut = "showTutorial('')"/> </map> </body> </html> You can feel the map concept by placing the mouse cursor on the image object. 25 Lectures 2.5 hours Anadi Sharma 74 Lectures 10 hours Lets Kode It 72 Lectures 4.5 hours Frahaan Hussain 70 Lectures 4.5 hours Frahaan Hussain 46 Lectures 6 hours Eduonix Learning Solutions 88 Lectures 14 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2657, "s": 2466, "text": "You can use JavaScript to create client-side image map. Client-side image maps are enabled by the usemap attribute for the <img /> tag and defined by special <map> and <area> extension tags." }, { "code": null, "e": 2971, "s": 2657, "text": "The image that is going to form the map is inserted into the page using the <img /> element as normal, except that it carries an extra attribute called usemap. The value of the usemap attribute is the value of the name attribute on the <map> element, which you are about to meet, preceded by a pound or hash sign." }, { "code": null, "e": 3353, "s": 2971, "text": "The <map> element actually creates the map for the image and usually follows directly after the <img /> element. It acts as a container for the <area /> elements that actually define the clickable hotspots. The <map> element carries only one attribute, the name attribute, which is the name that identifies the map. This is how the <img /> element knows which <map> element to use." }, { "code": null, "e": 3466, "s": 3353, "text": "The <area> element specifies the shape and the coordinates that define the boundaries of each clickable hotspot." }, { "code": null, "e": 3612, "s": 3466, "text": "The following code combines imagemaps and JavaScript to produce a message in a text box when the mouse is moved over different parts of an image." }, { "code": null, "e": 4996, "s": 3612, "text": "<html> \n <head>\n <title>Using JavaScript Image Map</title>\n \n <script type = \"text/javascript\">\n <!--\n function showTutorial(name) {\n document.myform.stage.value = name\n }\n //-->\n </script>\n </head>\n \n <body>\n <form name = \"myform\">\n <input type = \"text\" name = \"stage\" size = \"20\" />\n </form>\n \n <!-- Create Mappings -->\n <img src = \"/images/usemap.gif\" alt = \"HTML Map\" border = \"0\" usemap = \"#tutorials\"/>\n \n <map name = \"tutorials\">\n <area shape=\"poly\" \n coords = \"74,0,113,29,98,72,52,72,38,27\"\n href = \"/perl/index.htm\" alt = \"Perl Tutorial\"\n target = \"_self\" \n onMouseOver = \"showTutorial('perl')\" \n onMouseOut = \"showTutorial('')\"/>\n \n <area shape = \"rect\" \n coords = \"22,83,126,125\"\n href = \"/html/index.htm\" alt = \"HTML Tutorial\" \n target = \"_self\" \n onMouseOver = \"showTutorial('html')\" \n onMouseOut = \"showTutorial('')\"/>\n \n <area shape = \"circle\" \n coords = \"73,168,32\"\n href = \"/php/index.htm\" alt = \"PHP Tutorial\"\n target = \"_self\" \n onMouseOver = \"showTutorial('php')\" \n onMouseOut = \"showTutorial('')\"/>\n </map>\n </body>\n</html>" }, { "code": null, "e": 5074, "s": 4996, "text": "You can feel the map concept by placing the mouse cursor on the image object." }, { "code": null, "e": 5109, "s": 5074, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5123, "s": 5109, "text": " Anadi Sharma" }, { "code": null, "e": 5157, "s": 5123, "text": "\n 74 Lectures \n 10 hours \n" }, { "code": null, "e": 5171, "s": 5157, "text": " Lets Kode It" }, { "code": null, "e": 5206, "s": 5171, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5223, "s": 5206, "text": " Frahaan Hussain" }, { "code": null, "e": 5258, "s": 5223, "text": "\n 70 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5275, "s": 5258, "text": " Frahaan Hussain" }, { "code": null, "e": 5308, "s": 5275, "text": "\n 46 Lectures \n 6 hours \n" }, { "code": null, "e": 5336, "s": 5308, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5370, "s": 5336, "text": "\n 88 Lectures \n 14 hours \n" }, { "code": null, "e": 5398, "s": 5370, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5405, "s": 5398, "text": " Print" }, { "code": null, "e": 5416, "s": 5405, "text": " Add Notes" } ]
Change string based on a condition - JavaScript
We are required to write a JavaScript function that takes in a string. The task of our function is to change the string according to the following condition − If the first letter in the string is a capital letter then we should change the full string to capital letters. Otherwise, we should change the full string to small letters. Following is the code − const str1 = "This is a normal string"; const str2 = "thisIsACamelCasedString"; const changeStringCase = str => { let newStr = ''; const isUpperCase = str[0].charCodeAt(0) >= 65 && str[0].charCodeAt(0) <= 90; if(isUpperCase){ newStr = str.toUpperCase(); }else{ newStr = str.toLowerCase(); }; return newStr; }; console.log(changeStringCase(str1)); console.log(changeStringCase(str2)); Following is the output in the console − THIS IS A NORMAL STRING thisisacamelcasedstring
[ { "code": null, "e": 1221, "s": 1062, "text": "We are required to write a JavaScript function that takes in a string. The task of our function is to change the string according to the following condition −" }, { "code": null, "e": 1333, "s": 1221, "text": "If the first letter in the string is a capital letter then we should change the full string to capital letters." }, { "code": null, "e": 1395, "s": 1333, "text": "Otherwise, we should change the full string to small letters." }, { "code": null, "e": 1419, "s": 1395, "text": "Following is the code −" }, { "code": null, "e": 1833, "s": 1419, "text": "const str1 = \"This is a normal string\";\nconst str2 = \"thisIsACamelCasedString\";\nconst changeStringCase = str => {\n let newStr = '';\n const isUpperCase = str[0].charCodeAt(0) >= 65 && str[0].charCodeAt(0) <= 90;\n if(isUpperCase){\n newStr = str.toUpperCase();\n }else{\n newStr = str.toLowerCase();\n };\n return newStr;\n};\nconsole.log(changeStringCase(str1));\nconsole.log(changeStringCase(str2));" }, { "code": null, "e": 1874, "s": 1833, "text": "Following is the output in the console −" }, { "code": null, "e": 1922, "s": 1874, "text": "THIS IS A NORMAL STRING\nthisisacamelcasedstring" } ]
A nested loop puzzle - GeeksforGeeks
13 Jan, 2022 Which of the following two code segments is faster? Assume that compiler makes no optimizations. C++ C Python3 /* FIRST */for(i = 0; i < 10; i++) for(j = 0; j < 100; j++) //do something // This code is contributed by Shubham Singh /* FIRST */for(i=0;i<10;i++) for(j=0;j<100;j++) //do something # FIRSTfor i in range(10): for j in range(100): #do something # This code is contributed by shivani C++ C Python3 /* SECOND */for(i=0;i<100;i++) for(j=0;j<10;j++) //do something //This code is contributed by Shubham Singh /* SECOND */for(i=0;i<100;i++) for(j=0;j<10;j++) //do something # SECONDfor i in range(100): for j in range(10): # Do something # This code is contributed by shivani Both code segments provide same functionality, and the code inside the two for loops would be executed same number of times in both code segments. If we take a closer look then we can see that the SECOND does more operations than the FIRST. It executes all three parts (assignment, comparison and increment) of the for loop more times than the corresponding parts of FIRST: The SECOND executes assignment operations ( j = 0 or i = 0) 101 times while FIRST executes only 11 times.The SECOND does 101 + 1100 comparisons (i < 100 or j < 10) while the FIRST does 11 + 1010 comparisons (i < 10 or j < 100).The SECOND executes 1100 increment operations (i++ or j++) while the FIRST executes 1010 increment operation. The SECOND executes assignment operations ( j = 0 or i = 0) 101 times while FIRST executes only 11 times. The SECOND does 101 + 1100 comparisons (i < 100 or j < 10) while the FIRST does 11 + 1010 comparisons (i < 10 or j < 100). The SECOND executes 1100 increment operations (i++ or j++) while the FIRST executes 1010 increment operation. Below code counts the number of increment operations executed in FIRST and SECOND, and prints the counts. C++ Java Python3 C# Javascript // C++ program to count number of increment// operations in FIRST and SECOND#include<iostream> using namespace std; int main(){ int c1 = 0, c2 = 0; /* FIRST */ for(int i=0;i<10;i++,c1++) for(int j=0;j<100;j++, c1++); /* SECOND */ for(int i=0; i<100; i++, c2++) for(int j=0; j<10; j++, c2++); cout << " Count in FIRST = " <<c1 << endl; cout << " Count in SECOND = " <<c2 << endl; getchar(); return 0;} // Java program to count number of increment// operations in FIRST and SECOND import java.io.*; class GFG { public static void main (String[] args) { int c1 = 0, c2 = 0; for(int i=0; i<10;i++, c1++){ for(int j=0;j<100;j++, c1++){} } for(int i=0;i<100;i++, c2++){ for(int j=0;j<10;j++, c2++){} } System.out.println( "Count in First = "+c1); System.out.println( "Count in SECOND = "+c2); }} # Python program to count number of increment# operations in FIRST and SECONDc1 = 0c2 = 0 # FIRSTfor i in range (10): for j in range (100): c1 += 1 c1 += 1 # SECONDfor i in range (100): for j in range (10): c2 += 1 c2 += 1 print("Count in FIRST = " ,c1)print("Count in SECOND = " ,c2) # This code is contributed by shivanisinghss2110 // C# program to count number of increment// operations in FIRST and SECONDusing System; class GFG{ public static void Main (String[] args){ int c1 = 0, c2 = 0; for(int i = 0; i < 10; i++, c1++) { for(int j = 0; j < 100;j++, c1++){} } for(int i = 0; i < 100; i++, c2++) { for(int j = 0; j < 10; j++, c2++){} } Console.WriteLine("Count in First = " + c1); Console.WriteLine("Count in SECOND = " + c2);}} // This code is contributed by shivanisinghss2110 <script> // JavaScript program to count number of increment// operations in FIRST and SECOND let c1 = 0, c2 = 0; for(let i=0; i<10;i++, c1++){ for(let j=0;j<100;j++, c1++){} } for(let i=0;i<100;i++, c2++){ for(let j=0;j<10;j++, c2++){} } document.write( "Count in First = "+c1 +"<br>"); document.write( "Count in SECOND = "+c2); // this code is contributed by shivanisinghss2110 </script> Count in FIRST = 1010 Count in SECOND = 1100 Below code counts the number of comparison operations executed by FIRST and SECOND C++ Java Python3 C# Javascript //program to count the number of comparison//operations executed by FIRST and SECOND */#include<iostream> using namespace std; int main(){ int c1 = 0, c2 = 0; /* FIRST */ for(int i=0; ++c1&&i<10; i++) for(int j=0; ++c1&&j<100;j++); /* SECOND */ for(int i=0; ++c2&&i<100; i++) for(int j=0; ++c2&&j<10; j++); cout << " Count for FIRST " <<c1 << endl; cout << " Count for SECOND " <<c2 << endl; getchar(); return 0;} /*package whatever //do not write package name here */ import java.io.*; class GFG { public static void main (String[] args) { int c1 = 0, c2 = 0; for(int i=0; i<++c1 && i<10;i++) { for(int j=0;j<++c1 &&j<100;j++) { } } for(int i=0;i<++c2 && i<100;i++) { for(int j=0;j<++c2 &&j<10;j++) { } } System.out.println( "Count in FIRST = "+c1); System.out.println( "Count in SECOND = "+c2); }} #program to count the number of comparison#operations executed by FIRST and SECOND */ # FIRSTc1 = 1c2 = 1i = 0while (i < c1 and i < 10): j = -1 c1 += 1 while (j < c1 and j < 100): c1 += 1 j += 1 i += 1 # SECONDi = 0while (i < c2 and i < 100): j = -1 c2 += 1 while (j < c2 and j < 10): c2 += 1 j += 1 i += 1 print(" Count fot FIRST " , c1)print(" Count fot SECOND " , c2) # This code is contributed by shivanisinghss2110 /*package whatever //do not write package name here */ using System; class GFG { public static void Main (String[] args) { int c1 = 0, c2 = 0; for(int i = 0; i < ++c1 && i < 10; i++) { for(int j = 0; j < ++c1 && j < 100; j++) { } } for(int i = 0; i < ++c2 && i < 100; i++) { for(int j = 0; j < ++c2 && j < 10; j++) { } } Console.WriteLine( "Count in FIRST = "+c1); Console.WriteLine( "Count in SECOND = "+c2); }} // This code is contributed by shivanisinghss2110 <script> /*package whatever //do not write package name here *///program to count the number of comparison//operations executed by FIRST and SECOND */ let c1 = 0, c2 = 0; for(let i=0; i<++c1 && i<10;i++) { for(let j=0;j<++c1 &&j<100;j++) { } } for(let i=0;i<++c2 && i<100;i++) { for(let j=0;j<++c2 &&j<10;j++) { } } document.write( "Count in FIRST = "+c1 +"<br>"); document.write( "Count in SECOND = "+c2); // this code is contributed by shivanisinghss2110 </script> Count for FIRST 1021 Count for SECOND 1201 Thanks to Dheeraj for suggesting the solution.Please write comments if you find any of the answers/codes incorrect, or you want to share more information about the topics discussed above. nidhi_biet shubhamsharma8337 vaibhavupadhyay shivanisinghss2110 gulshankumarar231 shubhamsingh84100 C-Loops & Control Statements C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Multidimensional Arrays in C / C++ rand() and srand() in C/C++ Left Shift and Right Shift Operators in C/C++ Command line arguments in C/C++ fork() in C Different methods to reverse a string in C/C++ TCP Server-Client implementation in C Substring in C++ Enumeration (or enum) in C Structures in C
[ { "code": null, "e": 24408, "s": 24380, "text": "\n13 Jan, 2022" }, { "code": null, "e": 24507, "s": 24408, "text": "Which of the following two code segments is faster? Assume that compiler makes no optimizations. " }, { "code": null, "e": 24511, "s": 24507, "text": "C++" }, { "code": null, "e": 24513, "s": 24511, "text": "C" }, { "code": null, "e": 24521, "s": 24513, "text": "Python3" }, { "code": "/* FIRST */for(i = 0; i < 10; i++) for(j = 0; j < 100; j++) //do something // This code is contributed by Shubham Singh", "e": 24645, "s": 24521, "text": null }, { "code": "/* FIRST */for(i=0;i<10;i++) for(j=0;j<100;j++) //do something", "e": 24712, "s": 24645, "text": null }, { "code": "# FIRSTfor i in range(10): for j in range(100): #do something # This code is contributed by shivani", "e": 24822, "s": 24712, "text": null }, { "code": null, "e": 24826, "s": 24822, "text": "C++" }, { "code": null, "e": 24828, "s": 24826, "text": "C" }, { "code": null, "e": 24836, "s": 24828, "text": "Python3" }, { "code": "/* SECOND */for(i=0;i<100;i++) for(j=0;j<10;j++) //do something //This code is contributed by Shubham Singh", "e": 24948, "s": 24836, "text": null }, { "code": "/* SECOND */for(i=0;i<100;i++) for(j=0;j<10;j++) //do something", "e": 25016, "s": 24948, "text": null }, { "code": "# SECONDfor i in range(100): for j in range(10): # Do something # This code is contributed by shivani", "e": 25133, "s": 25016, "text": null }, { "code": null, "e": 25508, "s": 25133, "text": "Both code segments provide same functionality, and the code inside the two for loops would be executed same number of times in both code segments. If we take a closer look then we can see that the SECOND does more operations than the FIRST. It executes all three parts (assignment, comparison and increment) of the for loop more times than the corresponding parts of FIRST: " }, { "code": null, "e": 25845, "s": 25508, "text": "The SECOND executes assignment operations ( j = 0 or i = 0) 101 times while FIRST executes only 11 times.The SECOND does 101 + 1100 comparisons (i < 100 or j < 10) while the FIRST does 11 + 1010 comparisons (i < 10 or j < 100).The SECOND executes 1100 increment operations (i++ or j++) while the FIRST executes 1010 increment operation." }, { "code": null, "e": 25951, "s": 25845, "text": "The SECOND executes assignment operations ( j = 0 or i = 0) 101 times while FIRST executes only 11 times." }, { "code": null, "e": 26074, "s": 25951, "text": "The SECOND does 101 + 1100 comparisons (i < 100 or j < 10) while the FIRST does 11 + 1010 comparisons (i < 10 or j < 100)." }, { "code": null, "e": 26184, "s": 26074, "text": "The SECOND executes 1100 increment operations (i++ or j++) while the FIRST executes 1010 increment operation." }, { "code": null, "e": 26290, "s": 26184, "text": "Below code counts the number of increment operations executed in FIRST and SECOND, and prints the counts." }, { "code": null, "e": 26294, "s": 26290, "text": "C++" }, { "code": null, "e": 26299, "s": 26294, "text": "Java" }, { "code": null, "e": 26307, "s": 26299, "text": "Python3" }, { "code": null, "e": 26310, "s": 26307, "text": "C#" }, { "code": null, "e": 26321, "s": 26310, "text": "Javascript" }, { "code": "// C++ program to count number of increment// operations in FIRST and SECOND#include<iostream> using namespace std; int main(){ int c1 = 0, c2 = 0; /* FIRST */ for(int i=0;i<10;i++,c1++) for(int j=0;j<100;j++, c1++); /* SECOND */ for(int i=0; i<100; i++, c2++) for(int j=0; j<10; j++, c2++); cout << \" Count in FIRST = \" <<c1 << endl; cout << \" Count in SECOND = \" <<c2 << endl; getchar(); return 0;}", "e": 26765, "s": 26321, "text": null }, { "code": "// Java program to count number of increment// operations in FIRST and SECOND import java.io.*; class GFG { public static void main (String[] args) { int c1 = 0, c2 = 0; for(int i=0; i<10;i++, c1++){ for(int j=0;j<100;j++, c1++){} } for(int i=0;i<100;i++, c2++){ for(int j=0;j<10;j++, c2++){} } System.out.println( \"Count in First = \"+c1); System.out.println( \"Count in SECOND = \"+c2); }}", "e": 27269, "s": 26765, "text": null }, { "code": "# Python program to count number of increment# operations in FIRST and SECONDc1 = 0c2 = 0 # FIRSTfor i in range (10): for j in range (100): c1 += 1 c1 += 1 # SECONDfor i in range (100): for j in range (10): c2 += 1 c2 += 1 print(\"Count in FIRST = \" ,c1)print(\"Count in SECOND = \" ,c2) # This code is contributed by shivanisinghss2110", "e": 27632, "s": 27269, "text": null }, { "code": "// C# program to count number of increment// operations in FIRST and SECONDusing System; class GFG{ public static void Main (String[] args){ int c1 = 0, c2 = 0; for(int i = 0; i < 10; i++, c1++) { for(int j = 0; j < 100;j++, c1++){} } for(int i = 0; i < 100; i++, c2++) { for(int j = 0; j < 10; j++, c2++){} } Console.WriteLine(\"Count in First = \" + c1); Console.WriteLine(\"Count in SECOND = \" + c2);}} // This code is contributed by shivanisinghss2110", "e": 28155, "s": 27632, "text": null }, { "code": "<script> // JavaScript program to count number of increment// operations in FIRST and SECOND let c1 = 0, c2 = 0; for(let i=0; i<10;i++, c1++){ for(let j=0;j<100;j++, c1++){} } for(let i=0;i<100;i++, c2++){ for(let j=0;j<10;j++, c2++){} } document.write( \"Count in First = \"+c1 +\"<br>\"); document.write( \"Count in SECOND = \"+c2); // this code is contributed by shivanisinghss2110 </script>", "e": 28655, "s": 28155, "text": null }, { "code": null, "e": 28703, "s": 28655, "text": " Count in FIRST = 1010\n Count in SECOND = 1100" }, { "code": null, "e": 28786, "s": 28703, "text": "Below code counts the number of comparison operations executed by FIRST and SECOND" }, { "code": null, "e": 28790, "s": 28786, "text": "C++" }, { "code": null, "e": 28795, "s": 28790, "text": "Java" }, { "code": null, "e": 28803, "s": 28795, "text": "Python3" }, { "code": null, "e": 28806, "s": 28803, "text": "C#" }, { "code": null, "e": 28817, "s": 28806, "text": "Javascript" }, { "code": "//program to count the number of comparison//operations executed by FIRST and SECOND */#include<iostream> using namespace std; int main(){ int c1 = 0, c2 = 0; /* FIRST */ for(int i=0; ++c1&&i<10; i++) for(int j=0; ++c1&&j<100;j++); /* SECOND */ for(int i=0; ++c2&&i<100; i++) for(int j=0; ++c2&&j<10; j++); cout << \" Count for FIRST \" <<c1 << endl; cout << \" Count for SECOND \" <<c2 << endl; getchar(); return 0;}", "e": 29281, "s": 28817, "text": null }, { "code": "/*package whatever //do not write package name here */ import java.io.*; class GFG { public static void main (String[] args) { int c1 = 0, c2 = 0; for(int i=0; i<++c1 && i<10;i++) { for(int j=0;j<++c1 &&j<100;j++) { } } for(int i=0;i<++c2 && i<100;i++) { for(int j=0;j<++c2 &&j<10;j++) { } } System.out.println( \"Count in FIRST = \"+c1); System.out.println( \"Count in SECOND = \"+c2); }}", "e": 29821, "s": 29281, "text": null }, { "code": "#program to count the number of comparison#operations executed by FIRST and SECOND */ # FIRSTc1 = 1c2 = 1i = 0while (i < c1 and i < 10): j = -1 c1 += 1 while (j < c1 and j < 100): c1 += 1 j += 1 i += 1 # SECONDi = 0while (i < c2 and i < 100): j = -1 c2 += 1 while (j < c2 and j < 10): c2 += 1 j += 1 i += 1 print(\" Count fot FIRST \" , c1)print(\" Count fot SECOND \" , c2) # This code is contributed by shivanisinghss2110 ", "e": 30304, "s": 29821, "text": null }, { "code": "/*package whatever //do not write package name here */ using System; class GFG { public static void Main (String[] args) { int c1 = 0, c2 = 0; for(int i = 0; i < ++c1 && i < 10; i++) { for(int j = 0; j < ++c1 && j < 100; j++) { } } for(int i = 0; i < ++c2 && i < 100; i++) { for(int j = 0; j < ++c2 && j < 10; j++) { } } Console.WriteLine( \"Count in FIRST = \"+c1); Console.WriteLine( \"Count in SECOND = \"+c2); }} // This code is contributed by shivanisinghss2110", "e": 30941, "s": 30304, "text": null }, { "code": "<script> /*package whatever //do not write package name here *///program to count the number of comparison//operations executed by FIRST and SECOND */ let c1 = 0, c2 = 0; for(let i=0; i<++c1 && i<10;i++) { for(let j=0;j<++c1 &&j<100;j++) { } } for(let i=0;i<++c2 && i<100;i++) { for(let j=0;j<++c2 &&j<10;j++) { } } document.write( \"Count in FIRST = \"+c1 +\"<br>\"); document.write( \"Count in SECOND = \"+c2); // this code is contributed by shivanisinghss2110 </script>", "e": 31558, "s": 30941, "text": null }, { "code": null, "e": 31605, "s": 31558, "text": " Count for FIRST 1021\n Count for SECOND 1201" }, { "code": null, "e": 31794, "s": 31605, "text": "Thanks to Dheeraj for suggesting the solution.Please write comments if you find any of the answers/codes incorrect, or you want to share more information about the topics discussed above. " }, { "code": null, "e": 31805, "s": 31794, "text": "nidhi_biet" }, { "code": null, "e": 31823, "s": 31805, "text": "shubhamsharma8337" }, { "code": null, "e": 31839, "s": 31823, "text": "vaibhavupadhyay" }, { "code": null, "e": 31858, "s": 31839, "text": "shivanisinghss2110" }, { "code": null, "e": 31876, "s": 31858, "text": "gulshankumarar231" }, { "code": null, "e": 31894, "s": 31876, "text": "shubhamsingh84100" }, { "code": null, "e": 31923, "s": 31894, "text": "C-Loops & Control Statements" }, { "code": null, "e": 31934, "s": 31923, "text": "C Language" }, { "code": null, "e": 32032, "s": 31934, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32041, "s": 32032, "text": "Comments" }, { "code": null, "e": 32054, "s": 32041, "text": "Old Comments" }, { "code": null, "e": 32089, "s": 32054, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 32117, "s": 32089, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 32163, "s": 32117, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 32195, "s": 32163, "text": "Command line arguments in C/C++" }, { "code": null, "e": 32207, "s": 32195, "text": "fork() in C" }, { "code": null, "e": 32254, "s": 32207, "text": "Different methods to reverse a string in C/C++" }, { "code": null, "e": 32292, "s": 32254, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 32309, "s": 32292, "text": "Substring in C++" }, { "code": null, "e": 32336, "s": 32309, "text": "Enumeration (or enum) in C" } ]
Evine - Interactive Web Crawler in Kali Linux - GeeksforGeeks
14 Sep, 2021 Web Crawling is the technique of finding the hidden files and directories from the target server which can consist of some sensitive data about the architecture of the target domain. Manual crawling can be difficult if the scope of the target is vast. So we should approach Automated Crawling. There are various automated crawlers available on the internet. Evine is the tool or crawler developed in the Go programming language, which comes with GUI and CLI versions. Evine may be useful for a wide range of purposes such as metadata and data extraction, data mining, reconnaissance, and testing. Evine tool is available on GitHub, it’s open-source and free-to-use. Note: Make Sure You have Golang Installed on your System, as this is a Golang-based tool. Click to check the Installation process – Golang Installation Steps on Linux Step 1: Use the following command to install the tool in your Kali Linux operating system. git clone https://github.com/saeeddhqan/evine.git Step 2: Now use the following command to move into the directory of the tool. You have to move in the directory in order to run the tool. cd evine Step 3: You are in the directory of the Evine. Now you have to install the Evine using the following command. sudo go build Step 4: All the dependencies have been installed in your Kali Linux operating system. Now use the following command to run the tool and check the help section. ./evine -h Example 1: Crawling In this example, we will give the URL and click on the tab button and go to the options section, and true all the options that we want to crawl. We have changed the values from false to true. We will not see results before entering “all” on the key section but after entering “all” keywords we can see that result. Example 2: Save Output In this example, we will save our output or results by pressing “Ctrl+S” as input through the keyboard on the response section, give the file name and exit it by “Ctrl+q“. We have given the file name as results.txt. We are displaying the saved results which are saved in the results.txt file. Example 3: Filters In this example, we will be getting the exact results by filtrating out our relevant results. We have entered PHP which will return the URLs consisting of PHP. We have got all the URLs consisting of PHP. Example 4: Custom Header In this example, We will be adding our own custom header to the request. Kali-Linux Linux-Tools Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. nohup Command in Linux with Examples scp command in Linux with Examples Thread functions in C/C++ mv command in Linux with examples chown command in Linux with Examples SED command in Linux | Set 2 Docker - COPY Instruction Array Basics in Shell Scripting | Set 1 Basic Operators in Shell Scripting nslookup command in Linux with Examples
[ { "code": null, "e": 24406, "s": 24378, "text": "\n14 Sep, 2021" }, { "code": null, "e": 25072, "s": 24406, "text": "Web Crawling is the technique of finding the hidden files and directories from the target server which can consist of some sensitive data about the architecture of the target domain. Manual crawling can be difficult if the scope of the target is vast. So we should approach Automated Crawling. There are various automated crawlers available on the internet. Evine is the tool or crawler developed in the Go programming language, which comes with GUI and CLI versions. Evine may be useful for a wide range of purposes such as metadata and data extraction, data mining, reconnaissance, and testing. Evine tool is available on GitHub, it’s open-source and free-to-use." }, { "code": null, "e": 25239, "s": 25072, "text": "Note: Make Sure You have Golang Installed on your System, as this is a Golang-based tool. Click to check the Installation process – Golang Installation Steps on Linux" }, { "code": null, "e": 25330, "s": 25239, "text": "Step 1: Use the following command to install the tool in your Kali Linux operating system." }, { "code": null, "e": 25380, "s": 25330, "text": "git clone https://github.com/saeeddhqan/evine.git" }, { "code": null, "e": 25518, "s": 25380, "text": "Step 2: Now use the following command to move into the directory of the tool. You have to move in the directory in order to run the tool." }, { "code": null, "e": 25527, "s": 25518, "text": "cd evine" }, { "code": null, "e": 25637, "s": 25527, "text": "Step 3: You are in the directory of the Evine. Now you have to install the Evine using the following command." }, { "code": null, "e": 25651, "s": 25637, "text": "sudo go build" }, { "code": null, "e": 25811, "s": 25651, "text": "Step 4: All the dependencies have been installed in your Kali Linux operating system. Now use the following command to run the tool and check the help section." }, { "code": null, "e": 25822, "s": 25811, "text": "./evine -h" }, { "code": null, "e": 25842, "s": 25822, "text": "Example 1: Crawling" }, { "code": null, "e": 25987, "s": 25842, "text": "In this example, we will give the URL and click on the tab button and go to the options section, and true all the options that we want to crawl." }, { "code": null, "e": 26034, "s": 25987, "text": "We have changed the values from false to true." }, { "code": null, "e": 26157, "s": 26034, "text": "We will not see results before entering “all” on the key section but after entering “all” keywords we can see that result." }, { "code": null, "e": 26180, "s": 26157, "text": "Example 2: Save Output" }, { "code": null, "e": 26352, "s": 26180, "text": "In this example, we will save our output or results by pressing “Ctrl+S” as input through the keyboard on the response section, give the file name and exit it by “Ctrl+q“." }, { "code": null, "e": 26396, "s": 26352, "text": "We have given the file name as results.txt." }, { "code": null, "e": 26473, "s": 26396, "text": "We are displaying the saved results which are saved in the results.txt file." }, { "code": null, "e": 26492, "s": 26473, "text": "Example 3: Filters" }, { "code": null, "e": 26652, "s": 26492, "text": "In this example, we will be getting the exact results by filtrating out our relevant results. We have entered PHP which will return the URLs consisting of PHP." }, { "code": null, "e": 26696, "s": 26652, "text": "We have got all the URLs consisting of PHP." }, { "code": null, "e": 26721, "s": 26696, "text": "Example 4: Custom Header" }, { "code": null, "e": 26794, "s": 26721, "text": "In this example, We will be adding our own custom header to the request." }, { "code": null, "e": 26805, "s": 26794, "text": "Kali-Linux" }, { "code": null, "e": 26817, "s": 26805, "text": "Linux-Tools" }, { "code": null, "e": 26828, "s": 26817, "text": "Linux-Unix" }, { "code": null, "e": 26926, "s": 26828, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26963, "s": 26926, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 26998, "s": 26963, "text": "scp command in Linux with Examples" }, { "code": null, "e": 27024, "s": 26998, "text": "Thread functions in C/C++" }, { "code": null, "e": 27058, "s": 27024, "text": "mv command in Linux with examples" }, { "code": null, "e": 27095, "s": 27058, "text": "chown command in Linux with Examples" }, { "code": null, "e": 27124, "s": 27095, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 27150, "s": 27124, "text": "Docker - COPY Instruction" }, { "code": null, "e": 27190, "s": 27150, "text": "Array Basics in Shell Scripting | Set 1" }, { "code": null, "e": 27225, "s": 27190, "text": "Basic Operators in Shell Scripting" } ]
C++ | References | Question 1 - GeeksforGeeks
28 Jun, 2021 What is the return value of f(p, p) if the value of p is initialized to 5 before the call? Note that the first parameter is passed by reference, whereas the second parameter is passed by value. int f(int &x, int c) { c = c - 1; if (c == 0) return 1; x = x + 1; return f(x, c) * x; } (A) 3024(B) 6561(C) 55440(D) 161051Answer: (B)Explanation: Since c is passed by value and x is passed by reference, all functions will have same copy of x, but different copies of c. f(5, 5) = f(x, 4)*x = f(x, 3)*x*x = f(x, 2)*x*x*x = f(x, 1)*x*x*x*x = 1*x*x*x*x = x^4 Since x is incremented in every function call, it becomes 9 after f(x, 2) call. So the value of expression x^4 becomes 9^4 which is 6561. #include <stdio.h> int f(int &x, int c){ c = c - 1; if (c == 0) return 1; x = x + 1; return f(x, c) * x;}int main(){ int p = 5; printf("%d", f(p, p));} Quiz of this Question C++-References References C Language C++ Quiz Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments TCP Server-Client implementation in C Exception Handling in C++ Multithreading in C 'this' pointer in C++ UDP Server-Client implementation in C C++ | Exception Handling | Question 3 C++ | new and delete | Question 4 C++ | Inheritance | Question 7 C++ | Virtual Functions | Question 12 C++ | Inheritance | Question 1
[ { "code": null, "e": 24234, "s": 24206, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24428, "s": 24234, "text": "What is the return value of f(p, p) if the value of p is initialized to 5 before the call? Note that the first parameter is passed by reference, whereas the second parameter is passed by value." }, { "code": null, "e": 24531, "s": 24428, "text": "int f(int &x, int c) {\n c = c - 1;\n if (c == 0) return 1;\n x = x + 1;\n return f(x, c) * x;\n} " }, { "code": null, "e": 24714, "s": 24531, "text": "(A) 3024(B) 6561(C) 55440(D) 161051Answer: (B)Explanation: Since c is passed by value and x is passed by reference, all functions will have same copy of x, but different copies of c." }, { "code": null, "e": 24800, "s": 24714, "text": "f(5, 5) = f(x, 4)*x = f(x, 3)*x*x = f(x, 2)*x*x*x = f(x, 1)*x*x*x*x = 1*x*x*x*x = x^4" }, { "code": null, "e": 24938, "s": 24800, "text": "Since x is incremented in every function call, it becomes 9 after f(x, 2) call. So the value of expression x^4 becomes 9^4 which is 6561." }, { "code": "#include <stdio.h> int f(int &x, int c){ c = c - 1; if (c == 0) return 1; x = x + 1; return f(x, c) * x;}int main(){ int p = 5; printf(\"%d\", f(p, p));}", "e": 25110, "s": 24938, "text": null }, { "code": null, "e": 25132, "s": 25110, "text": "Quiz of this Question" }, { "code": null, "e": 25147, "s": 25132, "text": "C++-References" }, { "code": null, "e": 25158, "s": 25147, "text": "References" }, { "code": null, "e": 25169, "s": 25158, "text": "C Language" }, { "code": null, "e": 25178, "s": 25169, "text": "C++ Quiz" }, { "code": null, "e": 25276, "s": 25178, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25285, "s": 25276, "text": "Comments" }, { "code": null, "e": 25298, "s": 25285, "text": "Old Comments" }, { "code": null, "e": 25336, "s": 25298, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 25362, "s": 25336, "text": "Exception Handling in C++" }, { "code": null, "e": 25382, "s": 25362, "text": "Multithreading in C" }, { "code": null, "e": 25404, "s": 25382, "text": "'this' pointer in C++" }, { "code": null, "e": 25442, "s": 25404, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 25480, "s": 25442, "text": "C++ | Exception Handling | Question 3" }, { "code": null, "e": 25514, "s": 25480, "text": "C++ | new and delete | Question 4" }, { "code": null, "e": 25545, "s": 25514, "text": "C++ | Inheritance | Question 7" }, { "code": null, "e": 25583, "s": 25545, "text": "C++ | Virtual Functions | Question 12" } ]
4 Easy Steps for Implementing CatBoost | Towards Data Science
IntroductionInstallation and ImportsDefine DatasetApply ModelPredictSummaryReferences Introduction Installation and Imports Define Dataset Apply Model Predict Summary References CatBoost [2] has beaten many other popular machine learning algorithms on benchmark datasets where logloss was the error metric. It beat mainly LightGBM and XGBoost, which have recently been the standard before in not only data science competitions, but also in professional settings as well. Now is the time to learn this powerful library, and below is how you can implement it in four easy steps. This tutorial will be using popular data science tools like Python and Jupyter Notebook. First, we will start off with the three simple installation commands, then move on to all the necessary imports that you would need for your first, basic CatBoost regression model — which, as you will see, might be your first and last, because that is how impressively great CatBoost is without much tuning or additional code. Here are the main installation commands: !pip install catboost!pip install ipywidgets!jupyter nbextension enable — py widgetsnbextension Here are the main import commands: from catboost import CatBoostRegressorfrom sklearn.model_selection import train_test_splitimport numpy as npimport pandas as pd As you can see, there are only just a few lines of code that you need for installing and importing. We will import other common useful libraries like numpy, pandas, and sklearn as well. Next, we will discuss the dataset process. There are several ways to import a dataset, but the most common one that I do or see is importing a CSV file with pandas. You will establish your x attributes and your y variable, the variable you are trying to predict. You can isolate your dataset in the common way of a 75:25, for your train and test split. The random state is so that you can reproduce the same split in the future, or when collaborating with others. Here are the main dataset defining commands: dataframe = pd.read_csv('file_path_to_your_dataset.csv')X = dataframe[['X_feature_1', 'X_feature_2', etc.,]]y = dataframe['target_variable']X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.75, random_state=42) When applying the CatBoost model, it works similarly to other sklearn approaches. However, the most important part is to designate your categorical variables, so that you can get the most out of your CatBoost model. Also, CatBoost has some awesome plots that visualize the error metric improvements over iterations, so if you want to visually see how the train and test set compare over time, setting the plot to True is a great approach. I have also included a common loss function and evaluation metric of RMSE for a regression model. The default n_estimators is 100, which is a great place to start, if you see that the model is still improving on the last round, then you can up the number of iterations. Here are the main model commands: CAT_FEATURES = [] #list of your categorical features# set up the modelcatboost_model = CatBoostRegressor(n_estimators=100, loss_function = 'RMSE', eval_metric = 'RMSE', cat_features = CAT_FEATURES)# fit modelcatboost_model.fit(X_train, y_trian, eval_set = (X_test, y_test), use_best_model = True, plot = True) Perhaps the easiest and most rewarding step is to see your predictions. Some other useful ways that you can use the predict method is to merge your original dataframe with your predictions with an inner join with both indexes set to true, so that you can see the features that led to those predictions. This command also follows the typical sklearn approach that most data scientists are used to. Here is the main predict command: # get your predictionspreds = catboost_model.predict(X_test) I hope you enjoyed this short tutorial on CatBoost. It really is a powerful machine learning algorithm and library that anyone can implement. It is designed so that parameter tuning is usually not necessary, and the default parameters are the best. Additionally, there are other key visualizations that you can play around with, which are made from the popular SHAP library. The purpose of this article was to introduce you to CatBoost, and all you need moving forward is this code and your dataset to start making your first model predictions. Here are all of the steps once more, summarized: * Installation and Imports* Define Dataset* Apply Model* Predict I hope you found my article both interesting and useful! Please feel free to comment down below if you have used CatBoost before. Has it helped you in your Data Science career now? Do you agree or disagree, and why? Please feel free to check out my profile and other articles, as well as reach out to me on LinkedIn. I have no affiliations with these mentioned companies. Thank you for reading! [1] Photo by Manja Vitolic on Unsplash, (2018) [2] Yandex, CatBoost, (2021) [3] Photo by Christopher Gower on Unsplash, (2017) [4] Photo by krakenimages on Unsplash, (2020)
[ { "code": null, "e": 133, "s": 47, "text": "IntroductionInstallation and ImportsDefine DatasetApply ModelPredictSummaryReferences" }, { "code": null, "e": 146, "s": 133, "text": "Introduction" }, { "code": null, "e": 171, "s": 146, "text": "Installation and Imports" }, { "code": null, "e": 186, "s": 171, "text": "Define Dataset" }, { "code": null, "e": 198, "s": 186, "text": "Apply Model" }, { "code": null, "e": 206, "s": 198, "text": "Predict" }, { "code": null, "e": 214, "s": 206, "text": "Summary" }, { "code": null, "e": 225, "s": 214, "text": "References" }, { "code": null, "e": 624, "s": 225, "text": "CatBoost [2] has beaten many other popular machine learning algorithms on benchmark datasets where logloss was the error metric. It beat mainly LightGBM and XGBoost, which have recently been the standard before in not only data science competitions, but also in professional settings as well. Now is the time to learn this powerful library, and below is how you can implement it in four easy steps." }, { "code": null, "e": 1040, "s": 624, "text": "This tutorial will be using popular data science tools like Python and Jupyter Notebook. First, we will start off with the three simple installation commands, then move on to all the necessary imports that you would need for your first, basic CatBoost regression model — which, as you will see, might be your first and last, because that is how impressively great CatBoost is without much tuning or additional code." }, { "code": null, "e": 1081, "s": 1040, "text": "Here are the main installation commands:" }, { "code": null, "e": 1178, "s": 1081, "text": "!pip install catboost!pip install ipywidgets!jupyter nbextension enable — py widgetsnbextension" }, { "code": null, "e": 1213, "s": 1178, "text": "Here are the main import commands:" }, { "code": null, "e": 1341, "s": 1213, "text": "from catboost import CatBoostRegressorfrom sklearn.model_selection import train_test_splitimport numpy as npimport pandas as pd" }, { "code": null, "e": 1570, "s": 1341, "text": "As you can see, there are only just a few lines of code that you need for installing and importing. We will import other common useful libraries like numpy, pandas, and sklearn as well. Next, we will discuss the dataset process." }, { "code": null, "e": 1991, "s": 1570, "text": "There are several ways to import a dataset, but the most common one that I do or see is importing a CSV file with pandas. You will establish your x attributes and your y variable, the variable you are trying to predict. You can isolate your dataset in the common way of a 75:25, for your train and test split. The random state is so that you can reproduce the same split in the future, or when collaborating with others." }, { "code": null, "e": 2036, "s": 1991, "text": "Here are the main dataset defining commands:" }, { "code": null, "e": 2268, "s": 2036, "text": "dataframe = pd.read_csv('file_path_to_your_dataset.csv')X = dataframe[['X_feature_1', 'X_feature_2', etc.,]]y = dataframe['target_variable']X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.75, random_state=42)" }, { "code": null, "e": 2977, "s": 2268, "text": "When applying the CatBoost model, it works similarly to other sklearn approaches. However, the most important part is to designate your categorical variables, so that you can get the most out of your CatBoost model. Also, CatBoost has some awesome plots that visualize the error metric improvements over iterations, so if you want to visually see how the train and test set compare over time, setting the plot to True is a great approach. I have also included a common loss function and evaluation metric of RMSE for a regression model. The default n_estimators is 100, which is a great place to start, if you see that the model is still improving on the last round, then you can up the number of iterations." }, { "code": null, "e": 3011, "s": 2977, "text": "Here are the main model commands:" }, { "code": null, "e": 3478, "s": 3011, "text": "CAT_FEATURES = [] #list of your categorical features# set up the modelcatboost_model = CatBoostRegressor(n_estimators=100, loss_function = 'RMSE', eval_metric = 'RMSE', cat_features = CAT_FEATURES)# fit modelcatboost_model.fit(X_train, y_trian, eval_set = (X_test, y_test), use_best_model = True, plot = True)" }, { "code": null, "e": 3875, "s": 3478, "text": "Perhaps the easiest and most rewarding step is to see your predictions. Some other useful ways that you can use the predict method is to merge your original dataframe with your predictions with an inner join with both indexes set to true, so that you can see the features that led to those predictions. This command also follows the typical sklearn approach that most data scientists are used to." }, { "code": null, "e": 3909, "s": 3875, "text": "Here is the main predict command:" }, { "code": null, "e": 3970, "s": 3909, "text": "# get your predictionspreds = catboost_model.predict(X_test)" }, { "code": null, "e": 4515, "s": 3970, "text": "I hope you enjoyed this short tutorial on CatBoost. It really is a powerful machine learning algorithm and library that anyone can implement. It is designed so that parameter tuning is usually not necessary, and the default parameters are the best. Additionally, there are other key visualizations that you can play around with, which are made from the popular SHAP library. The purpose of this article was to introduce you to CatBoost, and all you need moving forward is this code and your dataset to start making your first model predictions." }, { "code": null, "e": 4564, "s": 4515, "text": "Here are all of the steps once more, summarized:" }, { "code": null, "e": 4629, "s": 4564, "text": "* Installation and Imports* Define Dataset* Apply Model* Predict" }, { "code": null, "e": 4845, "s": 4629, "text": "I hope you found my article both interesting and useful! Please feel free to comment down below if you have used CatBoost before. Has it helped you in your Data Science career now? Do you agree or disagree, and why?" }, { "code": null, "e": 5001, "s": 4845, "text": "Please feel free to check out my profile and other articles, as well as reach out to me on LinkedIn. I have no affiliations with these mentioned companies." }, { "code": null, "e": 5024, "s": 5001, "text": "Thank you for reading!" }, { "code": null, "e": 5071, "s": 5024, "text": "[1] Photo by Manja Vitolic on Unsplash, (2018)" }, { "code": null, "e": 5100, "s": 5071, "text": "[2] Yandex, CatBoost, (2021)" }, { "code": null, "e": 5151, "s": 5100, "text": "[3] Photo by Christopher Gower on Unsplash, (2017)" } ]
Neo4j Delete Node - GeeksforGeeks
23 Aug, 2019 In Neo4j to delete a node or relations between nodes you have to use DELETE clause. To delete any node you need DELETE clause with the MATCH statement, the MATCH statement data will find the specific node and whichever node is matched with the statement that node will be vanished. Similar to the CREATE and RETURN statement just it will replace the CREATE with MATCH and RETURN with the DELETE. Below examples will illustrate the approach. Example: The basic way to delete a node is to find the node and delete the match node, but before you can check the node is that the node you want to delete by using RETURN statement after that you can fire below query. This query will delete the node where label is “GeeksforGeeks” Tag is “A Computer Science Portal” and the type is “Edutech”. To delete node:$ MATCH (a:GeksforGeeks { Tag : "A Computer Science Portal", Type : "Edutech" }) DELETE aOutput:Deleting multiple nodes:To delete multiple nodes use the DELETE statement and separate the nodes by “, ” coma or you can use multiple time MATCH statement Like the below query. $ MATCH (a:GeksforGeeks { Tag : "A Computer Science Portal", Type : "Edutech" }) DELETE a Output: Deleting multiple nodes:To delete multiple nodes use the DELETE statement and separate the nodes by “, ” coma or you can use multiple time MATCH statement Like the below query. Multiple nodes deleted:$ DELETE (a:GeeksforGeeks { Tag: "A Computer Science Portal"}), (b:W3School { Tag: "We are the Learner"}) MATCH a, bor$ MATCH (a:GeeksforGeeks { Tag: "A Computer Science Portal"}) MATCH (b:W3School { Tag: "We are the Learner"}) DELETE a, b Output:Delete all nodes: To delete all the nodes at once is to much short query to fire the below query will delete all the nodes at once. $ DELETE (a:GeeksforGeeks { Tag: "A Computer Science Portal"}), (b:W3School { Tag: "We are the Learner"}) MATCH a, b or $ MATCH (a:GeeksforGeeks { Tag: "A Computer Science Portal"}) MATCH (b:W3School { Tag: "We are the Learner"}) DELETE a, b Output: Delete all nodes: To delete all the nodes at once is to much short query to fire the below query will delete all the nodes at once. Delete all nodes:$ MATCH (n) DELETE nOutput:Note: To delete any node or nodes that containing relationship with other nodes will display an error message.My Personal Notes arrow_drop_upSave $ MATCH (n) DELETE n Output: Note: To delete any node or nodes that containing relationship with other nodes will display an error message. DBMS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SQL Trigger | Student Database CTE in SQL Introduction of ER Model SQL | Views Introduction of DBMS (Database Management System) | Set 1 SQL Interview Questions Third Normal Form (3NF) SQL | GROUP BY Second Normal Form (2NF) Difference between DELETE, DROP and TRUNCATE
[ { "code": null, "e": 24276, "s": 24248, "text": "\n23 Aug, 2019" }, { "code": null, "e": 24717, "s": 24276, "text": "In Neo4j to delete a node or relations between nodes you have to use DELETE clause. To delete any node you need DELETE clause with the MATCH statement, the MATCH statement data will find the specific node and whichever node is matched with the statement that node will be vanished. Similar to the CREATE and RETURN statement just it will replace the CREATE with MATCH and RETURN with the DELETE. Below examples will illustrate the approach." }, { "code": null, "e": 25062, "s": 24717, "text": "Example: The basic way to delete a node is to find the node and delete the match node, but before you can check the node is that the node you want to delete by using RETURN statement after that you can fire below query. This query will delete the node where label is “GeeksforGeeks” Tag is “A Computer Science Portal” and the type is “Edutech”." }, { "code": null, "e": 25351, "s": 25062, "text": "To delete node:$ MATCH (a:GeksforGeeks { Tag : \"A Computer Science Portal\", Type : \"Edutech\" }) \nDELETE aOutput:Deleting multiple nodes:To delete multiple nodes use the DELETE statement and separate the nodes by “, ” coma or you can use multiple time MATCH statement Like the below query." }, { "code": null, "e": 25442, "s": 25351, "text": "$ MATCH (a:GeksforGeeks { Tag : \"A Computer Science Portal\", Type : \"Edutech\" }) \nDELETE a" }, { "code": null, "e": 25450, "s": 25442, "text": "Output:" }, { "code": null, "e": 25627, "s": 25450, "text": "Deleting multiple nodes:To delete multiple nodes use the DELETE statement and separate the nodes by “, ” coma or you can use multiple time MATCH statement Like the below query." }, { "code": null, "e": 26033, "s": 25627, "text": "Multiple nodes deleted:$ DELETE (a:GeeksforGeeks { Tag: \"A Computer Science Portal\"}), \n(b:W3School { Tag: \"We are the Learner\"}) \nMATCH a, bor$ MATCH (a:GeeksforGeeks { Tag: \"A Computer Science Portal\"}) \nMATCH (b:W3School { Tag: \"We are the Learner\"}) \nDELETE a, b\nOutput:Delete all nodes: To delete all the nodes at once is to much short query to fire the below query will delete all the nodes at once." }, { "code": null, "e": 26152, "s": 26033, "text": "$ DELETE (a:GeeksforGeeks { Tag: \"A Computer Science Portal\"}), \n(b:W3School { Tag: \"We are the Learner\"}) \nMATCH a, b" }, { "code": null, "e": 26155, "s": 26152, "text": "or" }, { "code": null, "e": 26280, "s": 26155, "text": "$ MATCH (a:GeeksforGeeks { Tag: \"A Computer Science Portal\"}) \nMATCH (b:W3School { Tag: \"We are the Learner\"}) \nDELETE a, b\n" }, { "code": null, "e": 26288, "s": 26280, "text": "Output:" }, { "code": null, "e": 26420, "s": 26288, "text": "Delete all nodes: To delete all the nodes at once is to much short query to fire the below query will delete all the nodes at once." }, { "code": null, "e": 26610, "s": 26420, "text": "Delete all nodes:$ MATCH (n) DELETE nOutput:Note: To delete any node or nodes that containing relationship with other nodes will display an error message.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 26631, "s": 26610, "text": "$ MATCH (n) DELETE n" }, { "code": null, "e": 26639, "s": 26631, "text": "Output:" }, { "code": null, "e": 26750, "s": 26639, "text": "Note: To delete any node or nodes that containing relationship with other nodes will display an error message." }, { "code": null, "e": 26755, "s": 26750, "text": "DBMS" }, { "code": null, "e": 26760, "s": 26755, "text": "DBMS" }, { "code": null, "e": 26858, "s": 26760, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26889, "s": 26858, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 26900, "s": 26889, "text": "CTE in SQL" }, { "code": null, "e": 26925, "s": 26900, "text": "Introduction of ER Model" }, { "code": null, "e": 26937, "s": 26925, "text": "SQL | Views" }, { "code": null, "e": 26995, "s": 26937, "text": "Introduction of DBMS (Database Management System) | Set 1" }, { "code": null, "e": 27019, "s": 26995, "text": "SQL Interview Questions" }, { "code": null, "e": 27043, "s": 27019, "text": "Third Normal Form (3NF)" }, { "code": null, "e": 27058, "s": 27043, "text": "SQL | GROUP BY" }, { "code": null, "e": 27083, "s": 27058, "text": "Second Normal Form (2NF)" } ]
5 Highly Practical NumPy Operations | by Soner Yıldırım | Towards Data Science
NumPy is the most widely-used scientific computing library for Python. It serves as a basis for many other libraries such as Pandas. NumPy makes it very simple and fast to operate on large arrays of numbers. Since we are likely to have lots of data, having a super efficient tools like NumPy is of great importance. In this article, we will go over 5 operations that are essential in the analysis of large arrays. These operations provide some statistics and characteristics of arrays. The name is quite descriptive. It counts the number of non-zero elements in an array. There are many ways to do this operation but the count_nonzero function might be the most simple one. Let’s create an array of 10000 integers between 0 and 10. We can then use our straightforward function to count the non-zero elements. import numpy as nparr = np.random.randint(5, size=10000)np.count_nonzero(arr)8033 We know that there are 8033 non-zero numbers in this array. What if we need the indices of them? The answer is the next operation. The argwhere function returns the indices of the non-zero elements in an array. nonzero = np.argwhere(arr)len(nonzero)8033 We can confirm the result by checking some of the values in the array. arr[:8]array([4, 2, 1, 4, 3, 0, 3, 2])nonzero[:8]array([[0], [1], [2], [3], [4], [6], [7], [8]]) As you can see, the index 5 is skipped because the value at that index is zero. These functions are used to find the index of the minimum or maximum value in an array. Let’s create a smaller array this time and apply argmin and argmax functions. arr2 = np.array([4,3,1,6,1,2,6])np.argmin(arr2)2np.argmax(arr2)3 The minimum value is 1 so the argmin returns the index of the first occurrence of 1. Similarly, argmax returns the of the first occurrence of the maximum value. However, these minimum and maximum values occur more than once in the array. If we need to find the indices of all occurrences of these values, we can use the where function of NumPy. The where function can be used to find the indices of values that fit the specified condition. In case of minimum and maximum values, we can set the condition as being equal to these values. np.where(arr2 == arr2.min())(array([2, 4]),)np.where(arr2 == arr2.max())(array([3, 6]),) The returned arrays contain the indices of all the occurrences of the minimum and maximum values. The where function can also modify the array according to a condition. Let’s do an example. arr2 = np.array([4,3,1,6,1,2,6])np.where(arr2 > 3, 1, 0)array([1, 0, 0, 1, 0, 0, 1]) The values that are greater than 3 are replaced with 1 and all other values are replaced with 0. Thus, the second parameter indicates what to do with the numbers that fit the condition. The third parameter deals with the values that do not fit the specified condition. Both these functions can be used to get a sorted version of an array. Argsort returns the indices of the sorted array. Sort returns the values of the sorted array. arr2 = np.array([4,3,1,6,1,2,6])np.sort(arr2)array([1, 1, 2, 3, 4, 6, 6])np.argsort(arr2)array([2, 4, 5, 1, 0, 3, 6]) What the sort function returns is the values sorted in ascending order. As you can compare, the argsort returns the indices of these sorted values in the original array. We have covered only a part of the NumPy operations on arrays. However, these are the operations that you are likely to use in a typical data analysis and manipulation process. NumPy proved to be a very flexible and efficient scientific computing library. It serves as a base for many Python libraries such as Pandas. Thus, it is a fundamental tool to learn for aspiring data scientists. Thank you for reading. Please let me know if you have any feedback.
[ { "code": null, "e": 305, "s": 172, "text": "NumPy is the most widely-used scientific computing library for Python. It serves as a basis for many other libraries such as Pandas." }, { "code": null, "e": 488, "s": 305, "text": "NumPy makes it very simple and fast to operate on large arrays of numbers. Since we are likely to have lots of data, having a super efficient tools like NumPy is of great importance." }, { "code": null, "e": 658, "s": 488, "text": "In this article, we will go over 5 operations that are essential in the analysis of large arrays. These operations provide some statistics and characteristics of arrays." }, { "code": null, "e": 846, "s": 658, "text": "The name is quite descriptive. It counts the number of non-zero elements in an array. There are many ways to do this operation but the count_nonzero function might be the most simple one." }, { "code": null, "e": 981, "s": 846, "text": "Let’s create an array of 10000 integers between 0 and 10. We can then use our straightforward function to count the non-zero elements." }, { "code": null, "e": 1063, "s": 981, "text": "import numpy as nparr = np.random.randint(5, size=10000)np.count_nonzero(arr)8033" }, { "code": null, "e": 1194, "s": 1063, "text": "We know that there are 8033 non-zero numbers in this array. What if we need the indices of them? The answer is the next operation." }, { "code": null, "e": 1274, "s": 1194, "text": "The argwhere function returns the indices of the non-zero elements in an array." }, { "code": null, "e": 1317, "s": 1274, "text": "nonzero = np.argwhere(arr)len(nonzero)8033" }, { "code": null, "e": 1388, "s": 1317, "text": "We can confirm the result by checking some of the values in the array." }, { "code": null, "e": 1527, "s": 1388, "text": "arr[:8]array([4, 2, 1, 4, 3, 0, 3, 2])nonzero[:8]array([[0], [1], [2], [3], [4], [6], [7], [8]])" }, { "code": null, "e": 1607, "s": 1527, "text": "As you can see, the index 5 is skipped because the value at that index is zero." }, { "code": null, "e": 1695, "s": 1607, "text": "These functions are used to find the index of the minimum or maximum value in an array." }, { "code": null, "e": 1773, "s": 1695, "text": "Let’s create a smaller array this time and apply argmin and argmax functions." }, { "code": null, "e": 1838, "s": 1773, "text": "arr2 = np.array([4,3,1,6,1,2,6])np.argmin(arr2)2np.argmax(arr2)3" }, { "code": null, "e": 1999, "s": 1838, "text": "The minimum value is 1 so the argmin returns the index of the first occurrence of 1. Similarly, argmax returns the of the first occurrence of the maximum value." }, { "code": null, "e": 2183, "s": 1999, "text": "However, these minimum and maximum values occur more than once in the array. If we need to find the indices of all occurrences of these values, we can use the where function of NumPy." }, { "code": null, "e": 2278, "s": 2183, "text": "The where function can be used to find the indices of values that fit the specified condition." }, { "code": null, "e": 2374, "s": 2278, "text": "In case of minimum and maximum values, we can set the condition as being equal to these values." }, { "code": null, "e": 2463, "s": 2374, "text": "np.where(arr2 == arr2.min())(array([2, 4]),)np.where(arr2 == arr2.max())(array([3, 6]),)" }, { "code": null, "e": 2561, "s": 2463, "text": "The returned arrays contain the indices of all the occurrences of the minimum and maximum values." }, { "code": null, "e": 2653, "s": 2561, "text": "The where function can also modify the array according to a condition. Let’s do an example." }, { "code": null, "e": 2738, "s": 2653, "text": "arr2 = np.array([4,3,1,6,1,2,6])np.where(arr2 > 3, 1, 0)array([1, 0, 0, 1, 0, 0, 1])" }, { "code": null, "e": 3007, "s": 2738, "text": "The values that are greater than 3 are replaced with 1 and all other values are replaced with 0. Thus, the second parameter indicates what to do with the numbers that fit the condition. The third parameter deals with the values that do not fit the specified condition." }, { "code": null, "e": 3077, "s": 3007, "text": "Both these functions can be used to get a sorted version of an array." }, { "code": null, "e": 3126, "s": 3077, "text": "Argsort returns the indices of the sorted array." }, { "code": null, "e": 3171, "s": 3126, "text": "Sort returns the values of the sorted array." }, { "code": null, "e": 3289, "s": 3171, "text": "arr2 = np.array([4,3,1,6,1,2,6])np.sort(arr2)array([1, 1, 2, 3, 4, 6, 6])np.argsort(arr2)array([2, 4, 5, 1, 0, 3, 6])" }, { "code": null, "e": 3459, "s": 3289, "text": "What the sort function returns is the values sorted in ascending order. As you can compare, the argsort returns the indices of these sorted values in the original array." }, { "code": null, "e": 3636, "s": 3459, "text": "We have covered only a part of the NumPy operations on arrays. However, these are the operations that you are likely to use in a typical data analysis and manipulation process." }, { "code": null, "e": 3847, "s": 3636, "text": "NumPy proved to be a very flexible and efficient scientific computing library. It serves as a base for many Python libraries such as Pandas. Thus, it is a fundamental tool to learn for aspiring data scientists." } ]
Count of triplets in an Array (i, j, k) such that i < j < k and a[k] < a[i] < a[j] - GeeksforGeeks
13 Apr, 2021 Given an array arr[] of N integers, the task is to count number of triplets (i, j, k) in the array such that a[k] < a[i] < a[j] and i < j < k.Examples: Input: arr[] = {2, 5, 1, 3, 0} Output: 4 Explanation: Below are the triplets (i, j, k) such that i < j < k and a[k] < a[i] < a[j]: 1. (0, 1, 2) and arr[2] < arr[0] 1 < 2 < 5.2. (0, 1, 4) and arr[4] < arr[0] 0 < 2 < 5.3. (0, 3, 4) and arr[4] < arr[0] 0 < 2 < 3.4. (2, 3, 4) and arr[4] < arr[2] 0 < 1 < 3.Input: arr[] = {2, 5, 1, 2, 0, 3, 10, 1, 5, 0 } Output: 25 Naive Approach: The idea is to iterate 3 loops and check for each triplet (i, j, k) satisfy the given conditions or not. If yes then increment for that triplet and print the final count after checking all the triplets. 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 count triplets with the// given conditionsint CountTriplets(int arr[], int n){ int cnt = 0; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) for (int k = j + 1; k < n; k++) // If it satisfy the // given conditions if (arr[k] < arr[i] && arr[i] < arr[j]) { cnt += 1; } // Return the final count return cnt;} // Driver Codeint main(){ // Given array arr[] int arr[] = { 2, 5, 1, 3, 0 }; int n = sizeof(arr) / sizeof(arr[0]); // Function Call cout << CountTriplets(arr, n) << endl; return 0;} // Java program for the above approachclass GFG{ // Function to count triplets// with the given conditionsstatic int CountTriplets(int arr[], int n){ int cnt = 0; for(int i = 0; i < n; i++) for(int j = i + 1; j < n; j++) for(int k = j + 1; k < n; k++) // If it satisfy the // given conditions if (arr[k] < arr[i] && arr[i] < arr[j]) { cnt += 1; } // Return the final count return cnt;} // Driver Codepublic static void main(String[] args){ // Given array arr[] int arr[] = new int[]{ 2, 5, 1, 3, 0 }; int n = arr.length; System.out.print(CountTriplets(arr, n));}} // This code is contributed by Pratima Pandey # Python3 program for the above approach # Function to count triplets with the# given conditionsdef CountTriplets(arr, n): cnt = 0; for i in range(0, n): for j in range(i + 1, n): for k in range(j + 1, n): # If it satisfy the # given conditions if (arr[k] < arr[i] and arr[i] < arr[j]): cnt += 1; # Return the final count return cnt; # Driver Code # Given array arr[]arr = [ 2, 5, 1, 3, 0 ]; n = len(arr); # Function Callprint(CountTriplets(arr, n)) # This code is contributed by Code_Mech // C# program for the above approachusing System;class GFG{ // Function to count triplets// with the given conditionsstatic int CountTriplets(int []arr, int n){ int cnt = 0; for(int i = 0; i < n; i++) for(int j = i + 1; j < n; j++) for(int k = j + 1; k < n; k++) // If it satisfy the // given conditions if (arr[k] < arr[i] && arr[i] < arr[j]) { cnt += 1; } // Return the final count return cnt;} // Driver Codepublic static void Main(string[] args){ // Given array arr[] int []arr = new int[]{ 2, 5, 1, 3, 0 }; int n = arr.Length; Console.Write(CountTriplets(arr, n));}} // This code is contributed by Ritik Bansal <script> // Javascript program for the above approach // Function to count triplets with the // given conditions function CountTriplets(arr, n) { let cnt = 0; for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) for (let k = j + 1; k < n; k++) // If it satisfy the // given conditions if (arr[k] < arr[i] && arr[i] < arr[j]) { cnt += 1; } // Return the final count return cnt; } // Given array arr[] let arr = [ 2, 5, 1, 3, 0 ]; let n = arr.length; // Function Call document.write(CountTriplets(arr, n)); </script> 4 Time Complexity: O(N3) Auxiliary Space: O(1) Efficient Approach: We can reduce the complexity from N^3 to N^2, using the below steps: Run two loops to find pairs (i, j) such that i < j and arr[j] > arr[i] and keep the count of these pairs as cnt.While in the above loop if there exists any element such arr[j] < arr[i] then increment the count of triplets by cnt as the current element is the Kth element such that a[k] < a[i] < a[j] for triplet i < j < k. Run two loops to find pairs (i, j) such that i < j and arr[j] > arr[i] and keep the count of these pairs as cnt. While in the above loop if there exists any element such arr[j] < arr[i] then increment the count of triplets by cnt as the current element is the Kth element such that a[k] < a[i] < a[j] for triplet i < j < k. 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 count tripletsint CountTriplets(int a[], int n){ // To store count of total triplets int ans = 0; for (int i = 0; i < n; i++) { // Initialize count to zero int cnt = 0; for (int j = i + 1; j < n; j++) { // If a[j] > a[i] then, // increment cnt if (a[j] > a[i]) cnt++; // If a[j] < a[i], then // it mean we have found a[k] // such that a[k] < a[i] < a[j] else ans += cnt; } } // Return the final count return ans;} // Driver codeint main(){ int arr[] = { 2, 5, 1, 3, 0 }; int n = sizeof(arr) / sizeof(arr[0]); cout << CountTriplets(arr, n) << endl; return 0;} // Java program for the above approachclass GFG{ // Function to count tripletsstatic int CountTriplets(int a[], int n){ // To store count of total triplets int ans = 0; for (int i = 0; i < n; i++) { // Initialize count to zero int cnt = 0; for (int j = i + 1; j < n; j++) { // If a[j] > a[i] then, // increment cnt if (a[j] > a[i]) cnt++; // If a[j] < a[i], then // it mean we have found a[k] // such that a[k] < a[i] < a[j] else ans += cnt; } } // Return the final count return ans;} // Driver codepublic static void main(String[] args){ int arr[] = { 2, 5, 1, 3, 0 }; int n = arr.length; System.out.print(CountTriplets(arr, n));}} // This code is contributed by shivanisinghss2110 # Python3 program for# the above approach # Function to count tripletsdef CountTriplets(a, n): # To store count # of total triplets ans = 0 for i in range (n): # Initialize count to zero cnt = 0 for j in range (i + 1 , n): # If a[j] > a[i] then, # increment cnt if (a[j] > a[i]): cnt += 1 # If a[j] < a[i], then # it mean we have found a[k] # such that a[k] < a[i] < a[j] else: ans += cnt # Return the final count return ans # Driver codeif __name__ == "__main__": arr = [2, 5, 1, 3, 0] n = len(arr) print (CountTriplets(arr, n)) # This code is contributed by Chitranayal // C# program for the above approachusing System;class GFG{ // Function to count tripletsstatic int CountTriplets(int []a, int n){ // To store count of total triplets int ans = 0; for (int i = 0; i < n; i++) { // Initialize count to zero int cnt = 0; for (int j = i + 1; j < n; j++) { // If a[j] > a[i] then, // increment cnt if (a[j] > a[i]) cnt++; // If a[j] < a[i], then // it mean we have found a[k] // such that a[k] < a[i] < a[j] else ans += cnt; } } // Return the final count return ans;} // Driver codepublic static void Main(){ int []arr = { 2, 5, 1, 3, 0 }; int n = arr.Length; Console.Write(CountTriplets(arr, n));}} // This code is contributed by Code_Mech <script> // Javascript program for the above approach // Function to count tripletsfunction CountTriplets(a, n){ // To store count of total triplets let ans = 0; for(let i = 0; i < n; i++) { // Initialize count to zero let cnt = 0; for(let j = i + 1; j < n; j++) { // If a[j] > a[i] then, // increment cnt if (a[j] > a[i]) cnt++; // If a[j] < a[i], then // it mean we have found a[k] // such that a[k] < a[i] < a[j] else ans += cnt; } } // Return the final count return ans;} // Driver codelet arr = [ 2, 5, 1, 3, 0 ];let n = arr.length; document.write(CountTriplets(arr, n)); // This code is contributed by rameshtravel07 </script> 4 Time Complexity: O(N2) Auxiliary Space: O(1) dewantipandeydp bansal_rtk_ shivanisinghss2110 Code_Mech ukasp divyesh072019 rameshtravel07 Arrays Competitive Programming Data Structures Data Structures Arrays 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 Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Introduction to Arrays Competitive Programming - A Complete Guide Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Top 10 Algorithms and Data Structures for Competitive Programming Bits manipulation (Important tactics)
[ { "code": null, "e": 25174, "s": 25146, "text": "\n13 Apr, 2021" }, { "code": null, "e": 25327, "s": 25174, "text": "Given an array arr[] of N integers, the task is to count number of triplets (i, j, k) in the array such that a[k] < a[i] < a[j] and i < j < k.Examples: " }, { "code": null, "e": 25691, "s": 25327, "text": "Input: arr[] = {2, 5, 1, 3, 0} Output: 4 Explanation: Below are the triplets (i, j, k) such that i < j < k and a[k] < a[i] < a[j]: 1. (0, 1, 2) and arr[2] < arr[0] 1 < 2 < 5.2. (0, 1, 4) and arr[4] < arr[0] 0 < 2 < 5.3. (0, 3, 4) and arr[4] < arr[0] 0 < 2 < 3.4. (2, 3, 4) and arr[4] < arr[2] 0 < 1 < 3.Input: arr[] = {2, 5, 1, 2, 0, 3, 10, 1, 5, 0 } Output: 25 " }, { "code": null, "e": 25910, "s": 25691, "text": "Naive Approach: The idea is to iterate 3 loops and check for each triplet (i, j, k) satisfy the given conditions or not. If yes then increment for that triplet and print the final count after checking all the triplets." }, { "code": null, "e": 25962, "s": 25910, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25966, "s": 25962, "text": "C++" }, { "code": null, "e": 25971, "s": 25966, "text": "Java" }, { "code": null, "e": 25979, "s": 25971, "text": "Python3" }, { "code": null, "e": 25982, "s": 25979, "text": "C#" }, { "code": null, "e": 25993, "s": 25982, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to count triplets with the// given conditionsint CountTriplets(int arr[], int n){ int cnt = 0; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) for (int k = j + 1; k < n; k++) // If it satisfy the // given conditions if (arr[k] < arr[i] && arr[i] < arr[j]) { cnt += 1; } // Return the final count return cnt;} // Driver Codeint main(){ // Given array arr[] int arr[] = { 2, 5, 1, 3, 0 }; int n = sizeof(arr) / sizeof(arr[0]); // Function Call cout << CountTriplets(arr, n) << endl; return 0;}", "e": 26751, "s": 25993, "text": null }, { "code": "// Java program for the above approachclass GFG{ // Function to count triplets// with the given conditionsstatic int CountTriplets(int arr[], int n){ int cnt = 0; for(int i = 0; i < n; i++) for(int j = i + 1; j < n; j++) for(int k = j + 1; k < n; k++) // If it satisfy the // given conditions if (arr[k] < arr[i] && arr[i] < arr[j]) { cnt += 1; } // Return the final count return cnt;} // Driver Codepublic static void main(String[] args){ // Given array arr[] int arr[] = new int[]{ 2, 5, 1, 3, 0 }; int n = arr.length; System.out.print(CountTriplets(arr, n));}} // This code is contributed by Pratima Pandey", "e": 27532, "s": 26751, "text": null }, { "code": "# Python3 program for the above approach # Function to count triplets with the# given conditionsdef CountTriplets(arr, n): cnt = 0; for i in range(0, n): for j in range(i + 1, n): for k in range(j + 1, n): # If it satisfy the # given conditions if (arr[k] < arr[i] and arr[i] < arr[j]): cnt += 1; # Return the final count return cnt; # Driver Code # Given array arr[]arr = [ 2, 5, 1, 3, 0 ]; n = len(arr); # Function Callprint(CountTriplets(arr, n)) # This code is contributed by Code_Mech", "e": 28136, "s": 27532, "text": null }, { "code": "// C# program for the above approachusing System;class GFG{ // Function to count triplets// with the given conditionsstatic int CountTriplets(int []arr, int n){ int cnt = 0; for(int i = 0; i < n; i++) for(int j = i + 1; j < n; j++) for(int k = j + 1; k < n; k++) // If it satisfy the // given conditions if (arr[k] < arr[i] && arr[i] < arr[j]) { cnt += 1; } // Return the final count return cnt;} // Driver Codepublic static void Main(string[] args){ // Given array arr[] int []arr = new int[]{ 2, 5, 1, 3, 0 }; int n = arr.Length; Console.Write(CountTriplets(arr, n));}} // This code is contributed by Ritik Bansal", "e": 28922, "s": 28136, "text": null }, { "code": "<script> // Javascript program for the above approach // Function to count triplets with the // given conditions function CountTriplets(arr, n) { let cnt = 0; for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) for (let k = j + 1; k < n; k++) // If it satisfy the // given conditions if (arr[k] < arr[i] && arr[i] < arr[j]) { cnt += 1; } // Return the final count return cnt; } // Given array arr[] let arr = [ 2, 5, 1, 3, 0 ]; let n = arr.length; // Function Call document.write(CountTriplets(arr, n)); </script>", "e": 29676, "s": 28922, "text": null }, { "code": null, "e": 29678, "s": 29676, "text": "4" }, { "code": null, "e": 29725, "s": 29680, "text": "Time Complexity: O(N3) Auxiliary Space: O(1)" }, { "code": null, "e": 29816, "s": 29725, "text": "Efficient Approach: We can reduce the complexity from N^3 to N^2, using the below steps: " }, { "code": null, "e": 30139, "s": 29816, "text": "Run two loops to find pairs (i, j) such that i < j and arr[j] > arr[i] and keep the count of these pairs as cnt.While in the above loop if there exists any element such arr[j] < arr[i] then increment the count of triplets by cnt as the current element is the Kth element such that a[k] < a[i] < a[j] for triplet i < j < k." }, { "code": null, "e": 30252, "s": 30139, "text": "Run two loops to find pairs (i, j) such that i < j and arr[j] > arr[i] and keep the count of these pairs as cnt." }, { "code": null, "e": 30463, "s": 30252, "text": "While in the above loop if there exists any element such arr[j] < arr[i] then increment the count of triplets by cnt as the current element is the Kth element such that a[k] < a[i] < a[j] for triplet i < j < k." }, { "code": null, "e": 30515, "s": 30463, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 30519, "s": 30515, "text": "C++" }, { "code": null, "e": 30524, "s": 30519, "text": "Java" }, { "code": null, "e": 30532, "s": 30524, "text": "Python3" }, { "code": null, "e": 30535, "s": 30532, "text": "C#" }, { "code": null, "e": 30546, "s": 30535, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to count tripletsint CountTriplets(int a[], int n){ // To store count of total triplets int ans = 0; for (int i = 0; i < n; i++) { // Initialize count to zero int cnt = 0; for (int j = i + 1; j < n; j++) { // If a[j] > a[i] then, // increment cnt if (a[j] > a[i]) cnt++; // If a[j] < a[i], then // it mean we have found a[k] // such that a[k] < a[i] < a[j] else ans += cnt; } } // Return the final count return ans;} // Driver codeint main(){ int arr[] = { 2, 5, 1, 3, 0 }; int n = sizeof(arr) / sizeof(arr[0]); cout << CountTriplets(arr, n) << endl; return 0;}", "e": 31378, "s": 30546, "text": null }, { "code": "// Java program for the above approachclass GFG{ // Function to count tripletsstatic int CountTriplets(int a[], int n){ // To store count of total triplets int ans = 0; for (int i = 0; i < n; i++) { // Initialize count to zero int cnt = 0; for (int j = i + 1; j < n; j++) { // If a[j] > a[i] then, // increment cnt if (a[j] > a[i]) cnt++; // If a[j] < a[i], then // it mean we have found a[k] // such that a[k] < a[i] < a[j] else ans += cnt; } } // Return the final count return ans;} // Driver codepublic static void main(String[] args){ int arr[] = { 2, 5, 1, 3, 0 }; int n = arr.length; System.out.print(CountTriplets(arr, n));}} // This code is contributed by shivanisinghss2110", "e": 32242, "s": 31378, "text": null }, { "code": "# Python3 program for# the above approach # Function to count tripletsdef CountTriplets(a, n): # To store count # of total triplets ans = 0 for i in range (n): # Initialize count to zero cnt = 0 for j in range (i + 1 , n): # If a[j] > a[i] then, # increment cnt if (a[j] > a[i]): cnt += 1 # If a[j] < a[i], then # it mean we have found a[k] # such that a[k] < a[i] < a[j] else: ans += cnt # Return the final count return ans # Driver codeif __name__ == \"__main__\": arr = [2, 5, 1, 3, 0] n = len(arr) print (CountTriplets(arr, n)) # This code is contributed by Chitranayal", "e": 32983, "s": 32242, "text": null }, { "code": "// C# program for the above approachusing System;class GFG{ // Function to count tripletsstatic int CountTriplets(int []a, int n){ // To store count of total triplets int ans = 0; for (int i = 0; i < n; i++) { // Initialize count to zero int cnt = 0; for (int j = i + 1; j < n; j++) { // If a[j] > a[i] then, // increment cnt if (a[j] > a[i]) cnt++; // If a[j] < a[i], then // it mean we have found a[k] // such that a[k] < a[i] < a[j] else ans += cnt; } } // Return the final count return ans;} // Driver codepublic static void Main(){ int []arr = { 2, 5, 1, 3, 0 }; int n = arr.Length; Console.Write(CountTriplets(arr, n));}} // This code is contributed by Code_Mech", "e": 33833, "s": 32983, "text": null }, { "code": "<script> // Javascript program for the above approach // Function to count tripletsfunction CountTriplets(a, n){ // To store count of total triplets let ans = 0; for(let i = 0; i < n; i++) { // Initialize count to zero let cnt = 0; for(let j = i + 1; j < n; j++) { // If a[j] > a[i] then, // increment cnt if (a[j] > a[i]) cnt++; // If a[j] < a[i], then // it mean we have found a[k] // such that a[k] < a[i] < a[j] else ans += cnt; } } // Return the final count return ans;} // Driver codelet arr = [ 2, 5, 1, 3, 0 ];let n = arr.length; document.write(CountTriplets(arr, n)); // This code is contributed by rameshtravel07 </script>", "e": 34661, "s": 33833, "text": null }, { "code": null, "e": 34663, "s": 34661, "text": "4" }, { "code": null, "e": 34710, "s": 34665, "text": "Time Complexity: O(N2) Auxiliary Space: O(1)" }, { "code": null, "e": 34726, "s": 34710, "text": "dewantipandeydp" }, { "code": null, "e": 34738, "s": 34726, "text": "bansal_rtk_" }, { "code": null, "e": 34757, "s": 34738, "text": "shivanisinghss2110" }, { "code": null, "e": 34767, "s": 34757, "text": "Code_Mech" }, { "code": null, "e": 34773, "s": 34767, "text": "ukasp" }, { "code": null, "e": 34787, "s": 34773, "text": "divyesh072019" }, { "code": null, "e": 34802, "s": 34787, "text": "rameshtravel07" }, { "code": null, "e": 34809, "s": 34802, "text": "Arrays" }, { "code": null, "e": 34833, "s": 34809, "text": "Competitive Programming" }, { "code": null, "e": 34849, "s": 34833, "text": "Data Structures" }, { "code": null, "e": 34865, "s": 34849, "text": "Data Structures" }, { "code": null, "e": 34872, "s": 34865, "text": "Arrays" }, { "code": null, "e": 34970, "s": 34872, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35038, "s": 34970, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 35086, "s": 35038, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 35130, "s": 35086, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 35162, "s": 35130, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 35185, "s": 35162, "text": "Introduction to Arrays" }, { "code": null, "e": 35228, "s": 35185, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 35271, "s": 35228, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 35312, "s": 35271, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 35378, "s": 35312, "text": "Top 10 Algorithms and Data Structures for Competitive Programming" } ]
Filter sub documents by sub document in MongoDB?
For this, use aggregate() along with $unwind. Let us create a collection with documents − > db.demo583.insert([ ... { ... "details1" : [ ... { ... "details2" : [ ... { ... "isMarried" : true, ... "Name" : "Chris" ... }, ... { ... "isMarried" : true, ... "Name" : "Bob" ... } ... ] ... }, ... { ... "details2" : [ ... { ... "isMarried" : false, ... "Name" : "Chris" ... }, ... { ... "isMarried" : true, ... "Name" : "Mike" ... } ... ] ... } ... ] ... } ... ]); BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 1, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] }) Display all documents from a collection with the help of find() method − > db.demo583.find(); This will produce the following output − { "_id" : ObjectId("5e91d3c4fd2d90c177b5bcc1"), "details1" : [ { "details2" : [ { "isMarried" : true, "Name" : "Chris" }, { "isMarried" : true, "Name" : "Bob" } ] }, { "details2" : [ { "isMarried" : false, "Name" : "Chris" }, { "isMarried" : true, "Name" : "Mike" } ] } ] } Following is the query to filter sub documents by sub-document − > var q= [ ... { ... "$match": { ... "details1.details2.isMarried": true, ... "details1.details2.Name": "Chris" ... } ... }, ... { ... "$unwind": "$details1" ... }, ... { ... "$unwind": "$details1.details2" ... }, ... { ... "$match": { ... "details1.details2.isMarried": true, ... "details1.details2.Name": "Chris" ... } ... } ... ]; > db.demo583.aggregate(q).pretty(); This will produce the following output − { "_id" : ObjectId("5e91d3c4fd2d90c177b5bcc1"), "details1" : { "details2" : { "isMarried" : true, "Name" : "Chris" } } }
[ { "code": null, "e": 1152, "s": 1062, "text": "For this, use aggregate() along with $unwind. Let us create a collection with documents −" }, { "code": null, "e": 2082, "s": 1152, "text": "> db.demo583.insert([\n... {\n... \"details1\" : [\n... {\n... \"details2\" : [\n... {\n... \"isMarried\" : true,\n... \"Name\" : \"Chris\"\n... },\n... {\n... \"isMarried\" : true,\n... \"Name\" : \"Bob\"\n... }\n... ]\n... },\n... {\n... \"details2\" : [\n... {\n... \"isMarried\" : false,\n... \"Name\" : \"Chris\"\n... },\n... {\n... \"isMarried\" : true,\n... \"Name\" : \"Mike\"\n... }\n... ]\n... }\n... ]\n... }\n... ]);\nBulkWriteResult({\n \"writeErrors\" : [ ],\n \"writeConcernErrors\" : [ ],\n \"nInserted\" : 1,\n \"nUpserted\" : 0,\n \"nMatched\" : 0,\n \"nModified\" : 0,\n \"nRemoved\" : 0,\n \"upserted\" : [ ]\n})" }, { "code": null, "e": 2155, "s": 2082, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 2176, "s": 2155, "text": "> db.demo583.find();" }, { "code": null, "e": 2217, "s": 2176, "text": "This will produce the following output −" }, { "code": null, "e": 2527, "s": 2217, "text": "{ \"_id\" : ObjectId(\"5e91d3c4fd2d90c177b5bcc1\"), \"details1\" : [\n { \"details2\" : [\n { \"isMarried\" : true, \"Name\" : \"Chris\" },\n { \"isMarried\" : true, \"Name\" : \"Bob\" }\n ] },\n { \"details2\" : [\n { \"isMarried\" : false, \"Name\" : \"Chris\" },\n { \"isMarried\" : true, \"Name\" : \"Mike\" }\n ] }\n] }" }, { "code": null, "e": 2592, "s": 2527, "text": "Following is the query to filter sub documents by sub-document −" }, { "code": null, "e": 3058, "s": 2592, "text": "> var q= [\n... {\n... \"$match\": {\n... \"details1.details2.isMarried\": true,\n... \"details1.details2.Name\": \"Chris\"\n... }\n... },\n... {\n... \"$unwind\": \"$details1\"\n... },\n... {\n... \"$unwind\": \"$details1.details2\"\n... },\n... {\n... \"$match\": {\n... \"details1.details2.isMarried\": true,\n... \"details1.details2.Name\": \"Chris\"\n... }\n... }\n... ];\n> db.demo583.aggregate(q).pretty();" }, { "code": null, "e": 3099, "s": 3058, "text": "This will produce the following output −" }, { "code": null, "e": 3259, "s": 3099, "text": "{\n \"_id\" : ObjectId(\"5e91d3c4fd2d90c177b5bcc1\"),\n \"details1\" : {\n \"details2\" : {\n \"isMarried\" : true,\n \"Name\" : \"Chris\"\n }\n }\n}" } ]
C++ program to find sum of digits of a number until sum becomes single digit
In this article, we will be discussing a program to find the sum of digits of a number until the sum itself becomes a single digit and cannot be done summation of further. For example, take the case of a number 14520. Adding the digits of this number we get 1 + 4 + 5 + 2 + 0 = 12. Since this is not a single digit number, we would further add the digits of the number received. Adding them we get, 1 + 2 = 3. Now, 3 is the final answer because it is a single digit number itself and its digits cannot be added further. To solve this, we would use the approach that the sum of digits of a number divisible by 9 is equal to 9 only. For the numbers that are not divisible by 9, we can divide them by 9 so as to get the remaining digit which would be the final sum of the given number. Live Demo #include<bits/stdc++.h> using namespace std; //function to check the divisibility by 9 int sum_digits(int n) { if (n == 0) return 0; else if (n%9 == 0) return 9; else return (n%9); } int main() { int x = 14520; cout<<sum_digits(x)<<endl; return 0; } 3
[ { "code": null, "e": 1234, "s": 1062, "text": "In this article, we will be discussing a program to find the sum of digits of a number until the sum itself becomes a single digit and cannot be done summation of further." }, { "code": null, "e": 1472, "s": 1234, "text": "For example, take the case of a number 14520. Adding the digits of this number we get 1 + 4 + 5 + 2 + 0 = 12. Since this is not a single digit number, we would further add the digits of the number received. Adding them we get, 1 + 2 = 3." }, { "code": null, "e": 1582, "s": 1472, "text": "Now, 3 is the final answer because it is a single digit number itself and its digits cannot be added further." }, { "code": null, "e": 1845, "s": 1582, "text": "To solve this, we would use the approach that the sum of digits of a number divisible by 9 is equal to 9 only. For the numbers that are not divisible by 9, we can divide them by 9 so as to get the remaining digit which would be the final sum of the given number." }, { "code": null, "e": 1856, "s": 1845, "text": " Live Demo" }, { "code": null, "e": 2142, "s": 1856, "text": "#include<bits/stdc++.h>\nusing namespace std;\n//function to check the divisibility by 9\nint sum_digits(int n) {\n if (n == 0)\n return 0;\n else if (n%9 == 0)\n return 9;\n else\n return (n%9);\n}\nint main() {\n int x = 14520;\n cout<<sum_digits(x)<<endl;\n return 0;\n}" }, { "code": null, "e": 2144, "s": 2142, "text": "3" } ]
Bring your Telegram Chatbot to the next level | by Beppe Catanese | Towards Data Science
Telegram is a popular platform to develop chatbots: excellent documentation, vibrant community, various libraries and tons of examples. If you are getting started there are plenty of tutorials around, especially on Medium. And Stackoverflow is also a great resource for answering questions and understanding issues (your author is often spotted there to try helping fellow developers out 🤓). This article instead focusses on more advanced aspects related to the implementation of a Telegram bot using Python Telegram Bot: Pull vs Webhook Grab the chat ID Display “Typing...” and suggest answers Deep linking Send media and files Telegram Bot can work with a Pull or with a Push mechanism (see further Webhooks). The pull mechanism is where the bot (your code) is checking regularly for new available messages on the server. Everyone agrees this is not an ideal approach (unnecessary waste of resources, messages are discarded after 24 hours), but it is convenient when developing locally. (no tunneling software like ngrok is required). def main(): updater = Updater('myTelegramToken') dp = updater.dispatcher # define command handler dp.add_handler(CommandHandler("help", help_command_handler)) # define message handler dp.add_handler(MessageHandler(Filters.text, main_handler)) updater.start_polling() Once the bot is ready for deployment it is time to enable the Webhook: doing so Telegram will push the updates to the registered webhook endpoint and your service gets busy only when there are new incoming messages. updater.start_webhook(listen="0.0.0.0", port=3978, url_path='myTelegramToken')updater.bot.setWebhook('https://example.com/svc/myTelegramToken') Note: webhook works nicely with a serverless architecture or with ‘on-demand’ nodes. I have deployed Telegram webhooks on Heroku Free Tier which goes to sleep after 30 min inactivity, but if a new message is pushed the Heroky Dyno starts up and the message is consumed within few seconds. Note 2: depending on where the bot is deployed the port number needs to be configured. On Heroku, for example, the port is typically defined by the PORT environment variable and should never be hardcoded. How to register a webhook You can do this calling a the setWebhook URL: use your private token and pass the URL (must be HTTPS) of the webhook. https://api.telegram.org/bot{myTelegramToken}/setWebhook?url=https://example.com/svc Switch between Pull and Push mode I find it extremely convenient to switch programmatically between polling and webhook using an environment variable: the default is polling to work locally but, when deploying on the live system, it can be overridden (to webhook) . # read MODE env variable, fall back to 'polling' when undefinedmode = os.environ.get("MODE", "polling")if DefaultConfig.MODE == 'webhook': # enable webhook updater.start_webhook(listen="0.0.0.0", port=3978, url_path='myTelegramToken') updater.bot.setWebhook('https://example.com/svc/myTelegramToken')else: # enable polling updater.start_polling() Replying to an incoming message is pretty simple. update.message.reply_text("Hi there!") however sometimes we want to be able to initiate the message without the user asking anything (for example a notification after few days to re-engage our users). Retrieve (and save) the chat_id which is found in the JSON payload of the message sent by the user (yes, you need at least one message) {'update_id': 527095032, 'message': { 'message_id': 412, 'date': 1615991013, 'chat': { 'id': 931365322, 'type': 'private', 'username': 'gcatanese', .... When parsing the payload Python do not forget that different messages have slightly different JSON. def get_chat_id(update, context): chat_id = -1 if update.message is not None: # text message chat_id = update.message.chat.id elif update.callback_query is not None: # callback message chat_id = update.callback_query.message.chat.id elif update.poll is not None: # answer in Poll chat_id = context.bot_data[update.poll.id] return chat_id Guide the conversation providing the user with predefined options to choose from. This can be achieved using the InlineKeyboardMarkup , a keyboard that appears along the message (like a question). Here is the Python snippet to create the options: options = []options.append(InlineKeyboardButton(text='Text', callback_data='1'))options.append(InlineKeyboardButton(text='File', callback_data='2'))options.append(InlineKeyboardButton(text='GoogleDoc', callback_data='3'))options.append(InlineKeyboardButton(text='Gallery', callback_data='4'))reply_markup = InlineKeyboardMarkup([options])context.bot.send_message(chat_id=get_chat_id(update, context), text='What would you like to receive?', reply_markup=reply_markup) It is important to understand that the response will be processed by a CallbackQueryHandler and the incoming JSON payload is different from the plain text message. # input from text messagetext = update.message.text# selection from callbackchoice = update.callback_query.data Note: one a selection is made the Options disappear from the chat. Note2: define callback_data using a constant value which will be used to decide what to do. Unlike the text on the button this value should not change as it is not visible to the user. choice = update.callback_query.dataif choice == '1': # Choice 1: Text update.callback_query.message.edit_text('You have chosen Text') Display the Typing indicator is a common feature in chatbots: users are informed a message is about to arrive, even if there is a little delay. context.bot.send_chat_action(chat_id=get_chat_id(update, context), action=telegram.ChatAction.TYPING, timeout=1)time.sleep(1) Note: while display the Typing indicator I normally introduce a short delay to create the feeling of a real conversation. Deeplinking is a mechanism which allows to open a conversation with a given bot. This is useful to share the link to the bot on web sites, emails or Social Media. When defining the deep link it is possible to add an additional parameter: https://t.me/username_bot?start=signup The link opens the Telegram application prompting to start the conversation with the bot. The additional parameter is passed to the CommandHandler processing the /start command. def start_command_handler(update, context): param_value = context.args[0] update.message.reply_text('Value is ' + param_value) The chatbot can send files (i.e. PDFs, Office) in different ways. Use send_document with the full URL to the file: url='https://github.com/gc/TelegramBotDemo/raw/main/test.pdf'context.bot.send_document(chat_id=get_chat_id(update, context), document=url) Note: this approach requires a URL which points directly to the file. Another approach is to first download locally the file then send it with the same method send_document . # fetch from Google Driveurl = 'https://drive.google.com/file/d/0BZ3dWQ2ZXVOdE1V/view'r = requests.get(url, allow_redirects=True)# save local copyopen('file.ppt', 'wb').write(r.content)# send file to usercontext.bot.send_document(chat_id=get_chat_id(update, context), document=open('file.ppt', 'rb'), filename="Presentation.pptx") Note: this approach is usually necessary when the URL does not point directly to a file, but it is an endpoint streaming out the content on demand. A cool feature is sending a group of media like photos, videos and audios. list = []# define list of fileslist.append(InputMediaPhoto(media='https://../mintie.jpg', caption='Mint'))list.append(InputMediaPhoto(media='https://../pinkie.png', caption='Pink'))list.append(InputMediaPhoto(media='https://../orangie.png', caption='Orange'))context.bot.send_media_group(chat_id=get_chat_id(update, context), media=list) Note: the bot can send up to 10 media files at the same time. Note2: each message counts within the Telegram Rate limits (30 messages per second) therefore you can send up to 3 messages with 10 media each (in total 30) but, in this case, you cannot add anything else in the same transaction (not even a simple text message). I hope the article helps to understand some more advanced scenarios and to discover features that can make your Telegram chatbot a little bit more special. My advise is to always consider first what the users are looking for (why would they chat? ) and then design it in a way that makes their conversation frictionless and enjoyable: striking a good balance determines the success of your chatbot. Check out the Github repo where you can grab the code snippets shown above. Find me on Twitter for questions and suggestions.
[ { "code": null, "e": 308, "s": 172, "text": "Telegram is a popular platform to develop chatbots: excellent documentation, vibrant community, various libraries and tons of examples." }, { "code": null, "e": 564, "s": 308, "text": "If you are getting started there are plenty of tutorials around, especially on Medium. And Stackoverflow is also a great resource for answering questions and understanding issues (your author is often spotted there to try helping fellow developers out 🤓)." }, { "code": null, "e": 694, "s": 564, "text": "This article instead focusses on more advanced aspects related to the implementation of a Telegram bot using Python Telegram Bot:" }, { "code": null, "e": 710, "s": 694, "text": "Pull vs Webhook" }, { "code": null, "e": 727, "s": 710, "text": "Grab the chat ID" }, { "code": null, "e": 767, "s": 727, "text": "Display “Typing...” and suggest answers" }, { "code": null, "e": 780, "s": 767, "text": "Deep linking" }, { "code": null, "e": 801, "s": 780, "text": "Send media and files" }, { "code": null, "e": 996, "s": 801, "text": "Telegram Bot can work with a Pull or with a Push mechanism (see further Webhooks). The pull mechanism is where the bot (your code) is checking regularly for new available messages on the server." }, { "code": null, "e": 1209, "s": 996, "text": "Everyone agrees this is not an ideal approach (unnecessary waste of resources, messages are discarded after 24 hours), but it is convenient when developing locally. (no tunneling software like ngrok is required)." }, { "code": null, "e": 1497, "s": 1209, "text": "def main(): updater = Updater('myTelegramToken') dp = updater.dispatcher # define command handler dp.add_handler(CommandHandler(\"help\", help_command_handler)) # define message handler dp.add_handler(MessageHandler(Filters.text, main_handler)) updater.start_polling()" }, { "code": null, "e": 1713, "s": 1497, "text": "Once the bot is ready for deployment it is time to enable the Webhook: doing so Telegram will push the updates to the registered webhook endpoint and your service gets busy only when there are new incoming messages." }, { "code": null, "e": 1899, "s": 1713, "text": "updater.start_webhook(listen=\"0.0.0.0\", port=3978, url_path='myTelegramToken')updater.bot.setWebhook('https://example.com/svc/myTelegramToken')" }, { "code": null, "e": 2188, "s": 1899, "text": "Note: webhook works nicely with a serverless architecture or with ‘on-demand’ nodes. I have deployed Telegram webhooks on Heroku Free Tier which goes to sleep after 30 min inactivity, but if a new message is pushed the Heroky Dyno starts up and the message is consumed within few seconds." }, { "code": null, "e": 2393, "s": 2188, "text": "Note 2: depending on where the bot is deployed the port number needs to be configured. On Heroku, for example, the port is typically defined by the PORT environment variable and should never be hardcoded." }, { "code": null, "e": 2419, "s": 2393, "text": "How to register a webhook" }, { "code": null, "e": 2537, "s": 2419, "text": "You can do this calling a the setWebhook URL: use your private token and pass the URL (must be HTTPS) of the webhook." }, { "code": null, "e": 2622, "s": 2537, "text": "https://api.telegram.org/bot{myTelegramToken}/setWebhook?url=https://example.com/svc" }, { "code": null, "e": 2656, "s": 2622, "text": "Switch between Pull and Push mode" }, { "code": null, "e": 2888, "s": 2656, "text": "I find it extremely convenient to switch programmatically between polling and webhook using an environment variable: the default is polling to work locally but, when deploying on the live system, it can be overridden (to webhook) ." }, { "code": null, "e": 3286, "s": 2888, "text": "# read MODE env variable, fall back to 'polling' when undefinedmode = os.environ.get(\"MODE\", \"polling\")if DefaultConfig.MODE == 'webhook': # enable webhook updater.start_webhook(listen=\"0.0.0.0\", port=3978, url_path='myTelegramToken') updater.bot.setWebhook('https://example.com/svc/myTelegramToken')else: # enable polling updater.start_polling()" }, { "code": null, "e": 3336, "s": 3286, "text": "Replying to an incoming message is pretty simple." }, { "code": null, "e": 3375, "s": 3336, "text": "update.message.reply_text(\"Hi there!\")" }, { "code": null, "e": 3537, "s": 3375, "text": "however sometimes we want to be able to initiate the message without the user asking anything (for example a notification after few days to re-engage our users)." }, { "code": null, "e": 3673, "s": 3537, "text": "Retrieve (and save) the chat_id which is found in the JSON payload of the message sent by the user (yes, you need at least one message)" }, { "code": null, "e": 3872, "s": 3673, "text": "{'update_id': 527095032, 'message': { 'message_id': 412, 'date': 1615991013, 'chat': { 'id': 931365322, 'type': 'private', 'username': 'gcatanese', ...." }, { "code": null, "e": 3972, "s": 3872, "text": "When parsing the payload Python do not forget that different messages have slightly different JSON." }, { "code": null, "e": 4367, "s": 3972, "text": "def get_chat_id(update, context): chat_id = -1 if update.message is not None: # text message chat_id = update.message.chat.id elif update.callback_query is not None: # callback message chat_id = update.callback_query.message.chat.id elif update.poll is not None: # answer in Poll chat_id = context.bot_data[update.poll.id] return chat_id" }, { "code": null, "e": 4564, "s": 4367, "text": "Guide the conversation providing the user with predefined options to choose from. This can be achieved using the InlineKeyboardMarkup , a keyboard that appears along the message (like a question)." }, { "code": null, "e": 4614, "s": 4564, "text": "Here is the Python snippet to create the options:" }, { "code": null, "e": 5082, "s": 4614, "text": "options = []options.append(InlineKeyboardButton(text='Text', callback_data='1'))options.append(InlineKeyboardButton(text='File', callback_data='2'))options.append(InlineKeyboardButton(text='GoogleDoc', callback_data='3'))options.append(InlineKeyboardButton(text='Gallery', callback_data='4'))reply_markup = InlineKeyboardMarkup([options])context.bot.send_message(chat_id=get_chat_id(update, context), text='What would you like to receive?', reply_markup=reply_markup)" }, { "code": null, "e": 5246, "s": 5082, "text": "It is important to understand that the response will be processed by a CallbackQueryHandler and the incoming JSON payload is different from the plain text message." }, { "code": null, "e": 5358, "s": 5246, "text": "# input from text messagetext = update.message.text# selection from callbackchoice = update.callback_query.data" }, { "code": null, "e": 5425, "s": 5358, "text": "Note: one a selection is made the Options disappear from the chat." }, { "code": null, "e": 5610, "s": 5425, "text": "Note2: define callback_data using a constant value which will be used to decide what to do. Unlike the text on the button this value should not change as it is not visible to the user." }, { "code": null, "e": 5746, "s": 5610, "text": "choice = update.callback_query.dataif choice == '1': # Choice 1: Text update.callback_query.message.edit_text('You have chosen Text')" }, { "code": null, "e": 5890, "s": 5746, "text": "Display the Typing indicator is a common feature in chatbots: users are informed a message is about to arrive, even if there is a little delay." }, { "code": null, "e": 6016, "s": 5890, "text": "context.bot.send_chat_action(chat_id=get_chat_id(update, context), action=telegram.ChatAction.TYPING, timeout=1)time.sleep(1)" }, { "code": null, "e": 6138, "s": 6016, "text": "Note: while display the Typing indicator I normally introduce a short delay to create the feeling of a real conversation." }, { "code": null, "e": 6301, "s": 6138, "text": "Deeplinking is a mechanism which allows to open a conversation with a given bot. This is useful to share the link to the bot on web sites, emails or Social Media." }, { "code": null, "e": 6376, "s": 6301, "text": "When defining the deep link it is possible to add an additional parameter:" }, { "code": null, "e": 6415, "s": 6376, "text": "https://t.me/username_bot?start=signup" }, { "code": null, "e": 6593, "s": 6415, "text": "The link opens the Telegram application prompting to start the conversation with the bot. The additional parameter is passed to the CommandHandler processing the /start command." }, { "code": null, "e": 6726, "s": 6593, "text": "def start_command_handler(update, context): param_value = context.args[0] update.message.reply_text('Value is ' + param_value)" }, { "code": null, "e": 6792, "s": 6726, "text": "The chatbot can send files (i.e. PDFs, Office) in different ways." }, { "code": null, "e": 6841, "s": 6792, "text": "Use send_document with the full URL to the file:" }, { "code": null, "e": 6980, "s": 6841, "text": "url='https://github.com/gc/TelegramBotDemo/raw/main/test.pdf'context.bot.send_document(chat_id=get_chat_id(update, context), document=url)" }, { "code": null, "e": 7050, "s": 6980, "text": "Note: this approach requires a URL which points directly to the file." }, { "code": null, "e": 7155, "s": 7050, "text": "Another approach is to first download locally the file then send it with the same method send_document ." }, { "code": null, "e": 7486, "s": 7155, "text": "# fetch from Google Driveurl = 'https://drive.google.com/file/d/0BZ3dWQ2ZXVOdE1V/view'r = requests.get(url, allow_redirects=True)# save local copyopen('file.ppt', 'wb').write(r.content)# send file to usercontext.bot.send_document(chat_id=get_chat_id(update, context), document=open('file.ppt', 'rb'), filename=\"Presentation.pptx\")" }, { "code": null, "e": 7634, "s": 7486, "text": "Note: this approach is usually necessary when the URL does not point directly to a file, but it is an endpoint streaming out the content on demand." }, { "code": null, "e": 7709, "s": 7634, "text": "A cool feature is sending a group of media like photos, videos and audios." }, { "code": null, "e": 8047, "s": 7709, "text": "list = []# define list of fileslist.append(InputMediaPhoto(media='https://../mintie.jpg', caption='Mint'))list.append(InputMediaPhoto(media='https://../pinkie.png', caption='Pink'))list.append(InputMediaPhoto(media='https://../orangie.png', caption='Orange'))context.bot.send_media_group(chat_id=get_chat_id(update, context), media=list)" }, { "code": null, "e": 8109, "s": 8047, "text": "Note: the bot can send up to 10 media files at the same time." }, { "code": null, "e": 8372, "s": 8109, "text": "Note2: each message counts within the Telegram Rate limits (30 messages per second) therefore you can send up to 3 messages with 10 media each (in total 30) but, in this case, you cannot add anything else in the same transaction (not even a simple text message)." }, { "code": null, "e": 8771, "s": 8372, "text": "I hope the article helps to understand some more advanced scenarios and to discover features that can make your Telegram chatbot a little bit more special. My advise is to always consider first what the users are looking for (why would they chat? ) and then design it in a way that makes their conversation frictionless and enjoyable: striking a good balance determines the success of your chatbot." }, { "code": null, "e": 8847, "s": 8771, "text": "Check out the Github repo where you can grab the code snippets shown above." } ]
Java Examples - Retrieve Contents from many Tables
How to join contents of more than one table & display? Following example uses inner join sql command to combine data from two tables. To display the contents of the table getString() method of resultset is used. import java.sql.*; public class jdbcConn { public static void main(String[] args) throws Exception { Class.forName("org.apache.derby.jdbc.ClientDriver"); Connection con = DriverManager.getConnection ( "jdbc:derby://localhost:1527/testDb","username", "password"); Statement stmt = con.createStatement(); String query ="SELECT fname,lname,isbn from author inner join books on author.AUTHORID = books.AUTHORID"; ResultSet rs = stmt.executeQuery(query); System.out.println("Fname Lname ISBN"); while (rs.next()) { String fname = rs.getString("fname"); String lname = rs.getString("lname"); int isbn = rs.getInt("isbn"); System.out.println(fname + " " + lname+" "+isbn); } System.out.println(); System.out.println(); } } The above code sample will produce the following result. The result may vary. Fname Lname ISBN john grisham 123 jeffry archer 113 jeffry archer 112 jeffry archer 122 Print Add Notes Bookmark this page
[ { "code": null, "e": 2123, "s": 2068, "text": "How to join contents of more than one table & display?" }, { "code": null, "e": 2280, "s": 2123, "text": "Following example uses inner join sql command to combine data from two tables. To display the contents of the table getString() method of resultset is used." }, { "code": null, "e": 3128, "s": 2280, "text": "import java.sql.*;\n\npublic class jdbcConn {\n public static void main(String[] args) throws Exception {\n Class.forName(\"org.apache.derby.jdbc.ClientDriver\");\n Connection con = DriverManager.getConnection (\n \"jdbc:derby://localhost:1527/testDb\",\"username\", \"password\");\n \n Statement stmt = con.createStatement();\n String query =\"SELECT fname,lname,isbn from author inner join books on author.AUTHORID = books.AUTHORID\";\n ResultSet rs = stmt.executeQuery(query);\n System.out.println(\"Fname Lname ISBN\");\n \n while (rs.next()) {\n String fname = rs.getString(\"fname\");\n String lname = rs.getString(\"lname\");\n int isbn = rs.getInt(\"isbn\");\n System.out.println(fname + \" \" + lname+\" \"+isbn);\n }\n System.out.println();\n System.out.println();\n }\n}" }, { "code": null, "e": 3206, "s": 3128, "text": "The above code sample will produce the following result. The result may vary." }, { "code": null, "e": 3310, "s": 3206, "text": "Fname Lname ISBN\njohn grisham 123\njeffry archer 113\njeffry archer 112\njeffry archer 122\n" }, { "code": null, "e": 3317, "s": 3310, "text": " Print" }, { "code": null, "e": 3328, "s": 3317, "text": " Add Notes" } ]
Python program to get all unique combinations of two Lists
16 Jun, 2021 The combination is a mathematical technique which calculates the number of possible arrangements in a collection of items or list. In combination order of selection doesn’t matter. The unique combination of two lists in Python can be formed by pairing each element of the first list with the elements of the second list. Example: List_1 = ["a","b"] List_2 = [1,2] Unique_combination = [[('a',1),('b',2)],[('a',2),('b',1)]] Method 1 : Using permutation() of itertools package and zip() function. Approach : Import itertools package and initialize list_1 and list_2. Create an empty list of ‘unique_combinations’ to store the resulting combinations so obtained. Call itertools.permutations( ) which will return permutations of list_1 with length of list_2. Generally, the length of the shorter list is taken and if both lists are equal, use either. For loop is used and zip() function is called to pair each permutation and shorter list element into the combination. Then each combination is converted into a list and append to the combination list. Below is the implementation. Python3 # python program to demonstrate# unique combination of two lists# using zip() and permutation of itertools # import itertools packageimport itertoolsfrom itertools import permutations # initialize listslist_1 = ["a", "b", "c","d"]list_2 = [1,4,9] # create empty list to store the# combinationsunique_combinations = [] # Getting all permutations of list_1# with length of list_2permut = itertools.permutations(list_1, len(list_2)) # zip() is called to pair each permutation# and shorter list element into combinationfor comb in permut: zipped = zip(comb, list_2) unique_combinations.append(list(zipped)) # printing unique_combination listprint(unique_combinations) Output : [[(‘a’, 1), (‘b’, 4), (‘c’, 9)], [(‘a’, 1), (‘b’, 4), (‘d’, 9)], [(‘a’, 1), (‘c’, 4), (‘b’, 9)], [(‘a’, 1), (‘c’, 4), (‘d’, 9)], [(‘a’, 1), (‘d’, 4), (‘b’, 9)], [(‘a’, 1), (‘d’, 4), (‘c’, 9)], [(‘b’, 1), (‘a’, 4), (‘c’, 9)], [(‘b’, 1), (‘a’, 4), (‘d’, 9)], [(‘b’, 1), (‘c’, 4), (‘a’, 9)], [(‘b’, 1), (‘c’, 4), (‘d’, 9)], [(‘b’, 1), (‘d’, 4), (‘a’, 9)], [(‘b’, 1), (‘d’, 4), (‘c’, 9)], [(‘c’, 1), (‘a’, 4), (‘b’, 9)], [(‘c’, 1), (‘a’, 4), (‘d’, 9)], [(‘c’, 1), (‘b’, 4), (‘a’, 9)], [(‘c’, 1), (‘b’, 4), (‘d’, 9)], [(‘c’, 1), (‘d’, 4), (‘a’, 9)], [(‘c’, 1), (‘d’, 4), (‘b’, 9)], [(‘d’, 1), (‘a’, 4), (‘b’, 9)], [(‘d’, 1), (‘a’, 4), (‘c’, 9)], [(‘d’, 1), (‘b’, 4), (‘a’, 9)], [(‘d’, 1), (‘b’, 4), (‘c’, 9)], [(‘d’, 1), (‘c’, 4), (‘a’, 9)], [(‘d’, 1), (‘c’, 4), (‘b’, 9)]] Method 2 : Using product() of itertools package and zip() function. Approach : Import itertools package and initialize list_1 and list_2. Create an empty list of ‘unique_combinations’ to store the resulting combinations so obtained. product() is called to find all possible combinations of elements. And zip() is used to pair up all these combinations, converting each element into a list and append them to the desired combination list. Below is the implementation. Python3 # python program to demonstrate# unique combination of two lists# using zip() and product() of itertools # import itertools packageimport itertoolsfrom itertools import product # initialize listslist_1 = ["b","c","d"]list_2 = [1,4,9] # create empty list to store the combinationsunique_combinations = [] # Extract Combination Mapping in two lists# using zip() + product()unique_combinations = list(list(zip(list_1, element)) for element in product(list_2, repeat = len(list_1))) # printing unique_combination listprint(unique_combinations) Output : [[(‘b’, 1), (‘c’, 1), (‘d’, 1)], [(‘b’, 1), (‘c’, 1), (‘d’, 4)], [(‘b’, 1), (‘c’, 1), (‘d’, 9)], [(‘b’, 1), (‘c’, 4), (‘d’, 1)], [(‘b’, 1), (‘c’, 4), (‘d’, 4)], [(‘b’, 1), (‘c’, 4), (‘d’, 9)], [(‘b’, 1), (‘c’, 9), (‘d’, 1)], [(‘b’, 1), (‘c’, 9), (‘d’, 4)], [(‘b’, 1), (‘c’, 9), (‘d’, 9)], [(‘b’, 4), (‘c’, 1), (‘d’, 1)], [(‘b’, 4), (‘c’, 1), (‘d’, 4)], [(‘b’, 4), (‘c’, 1), (‘d’, 9)], [(‘b’, 4), (‘c’, 4), (‘d’, 1)], [(‘b’, 4), (‘c’, 4), (‘d’, 4)], [(‘b’, 4), (‘c’, 4), (‘d’, 9)], [(‘b’, 4), (‘c’, 9), (‘d’, 1)], [(‘b’, 4), (‘c’, 9), (‘d’, 4)], [(‘b’, 4), (‘c’, 9), (‘d’, 9)], [(‘b’, 9), (‘c’, 1), (‘d’, 1)], [(‘b’, 9), (‘c’, 1), (‘d’, 4)], [(‘b’, 9), (‘c’, 1), (‘d’, 9)], [(‘b’, 9), (‘c’, 4), (‘d’, 1)], [(‘b’, 9), (‘c’, 4), (‘d’, 4)], [(‘b’, 9), (‘c’, 4), (‘d’, 9)], [(‘b’, 9), (‘c’, 9), (‘d’, 1)], [(‘b’, 9), (‘c’, 9), (‘d’, 4)], [(‘b’, 9), (‘c’, 9), (‘d’, 9)]] sweetyty Python list-programs Python-itertools 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": "\n16 Jun, 2021" }, { "code": null, "e": 350, "s": 28, "text": "The combination is a mathematical technique which calculates the number of possible arrangements in a collection of items or list. In combination order of selection doesn’t matter. The unique combination of two lists in Python can be formed by pairing each element of the first list with the elements of the second list. " }, { "code": null, "e": 359, "s": 350, "text": "Example:" }, { "code": null, "e": 453, "s": 359, "text": "List_1 = [\"a\",\"b\"]\nList_2 = [1,2]\nUnique_combination = [[('a',1),('b',2)],[('a',2),('b',1)]] " }, { "code": null, "e": 525, "s": 453, "text": "Method 1 : Using permutation() of itertools package and zip() function." }, { "code": null, "e": 536, "s": 525, "text": "Approach :" }, { "code": null, "e": 595, "s": 536, "text": "Import itertools package and initialize list_1 and list_2." }, { "code": null, "e": 690, "s": 595, "text": "Create an empty list of ‘unique_combinations’ to store the resulting combinations so obtained." }, { "code": null, "e": 877, "s": 690, "text": "Call itertools.permutations( ) which will return permutations of list_1 with length of list_2. Generally, the length of the shorter list is taken and if both lists are equal, use either." }, { "code": null, "e": 995, "s": 877, "text": "For loop is used and zip() function is called to pair each permutation and shorter list element into the combination." }, { "code": null, "e": 1078, "s": 995, "text": "Then each combination is converted into a list and append to the combination list." }, { "code": null, "e": 1107, "s": 1078, "text": "Below is the implementation." }, { "code": null, "e": 1115, "s": 1107, "text": "Python3" }, { "code": "# python program to demonstrate# unique combination of two lists# using zip() and permutation of itertools # import itertools packageimport itertoolsfrom itertools import permutations # initialize listslist_1 = [\"a\", \"b\", \"c\",\"d\"]list_2 = [1,4,9] # create empty list to store the# combinationsunique_combinations = [] # Getting all permutations of list_1# with length of list_2permut = itertools.permutations(list_1, len(list_2)) # zip() is called to pair each permutation# and shorter list element into combinationfor comb in permut: zipped = zip(comb, list_2) unique_combinations.append(list(zipped)) # printing unique_combination listprint(unique_combinations)", "e": 1785, "s": 1115, "text": null }, { "code": null, "e": 1794, "s": 1785, "text": "Output :" }, { "code": null, "e": 2565, "s": 1794, "text": "[[(‘a’, 1), (‘b’, 4), (‘c’, 9)], [(‘a’, 1), (‘b’, 4), (‘d’, 9)], [(‘a’, 1), (‘c’, 4), (‘b’, 9)], [(‘a’, 1), (‘c’, 4), (‘d’, 9)], [(‘a’, 1), (‘d’, 4), (‘b’, 9)], [(‘a’, 1), (‘d’, 4), (‘c’, 9)], [(‘b’, 1), (‘a’, 4), (‘c’, 9)], [(‘b’, 1), (‘a’, 4), (‘d’, 9)], [(‘b’, 1), (‘c’, 4), (‘a’, 9)], [(‘b’, 1), (‘c’, 4), (‘d’, 9)], [(‘b’, 1), (‘d’, 4), (‘a’, 9)], [(‘b’, 1), (‘d’, 4), (‘c’, 9)], [(‘c’, 1), (‘a’, 4), (‘b’, 9)], [(‘c’, 1), (‘a’, 4), (‘d’, 9)], [(‘c’, 1), (‘b’, 4), (‘a’, 9)], [(‘c’, 1), (‘b’, 4), (‘d’, 9)], [(‘c’, 1), (‘d’, 4), (‘a’, 9)], [(‘c’, 1), (‘d’, 4), (‘b’, 9)], [(‘d’, 1), (‘a’, 4), (‘b’, 9)], [(‘d’, 1), (‘a’, 4), (‘c’, 9)], [(‘d’, 1), (‘b’, 4), (‘a’, 9)], [(‘d’, 1), (‘b’, 4), (‘c’, 9)], [(‘d’, 1), (‘c’, 4), (‘a’, 9)], [(‘d’, 1), (‘c’, 4), (‘b’, 9)]] " }, { "code": null, "e": 2633, "s": 2565, "text": "Method 2 : Using product() of itertools package and zip() function." }, { "code": null, "e": 2644, "s": 2633, "text": "Approach :" }, { "code": null, "e": 2703, "s": 2644, "text": "Import itertools package and initialize list_1 and list_2." }, { "code": null, "e": 2798, "s": 2703, "text": "Create an empty list of ‘unique_combinations’ to store the resulting combinations so obtained." }, { "code": null, "e": 2865, "s": 2798, "text": "product() is called to find all possible combinations of elements." }, { "code": null, "e": 3003, "s": 2865, "text": "And zip() is used to pair up all these combinations, converting each element into a list and append them to the desired combination list." }, { "code": null, "e": 3032, "s": 3003, "text": "Below is the implementation." }, { "code": null, "e": 3040, "s": 3032, "text": "Python3" }, { "code": "# python program to demonstrate# unique combination of two lists# using zip() and product() of itertools # import itertools packageimport itertoolsfrom itertools import product # initialize listslist_1 = [\"b\",\"c\",\"d\"]list_2 = [1,4,9] # create empty list to store the combinationsunique_combinations = [] # Extract Combination Mapping in two lists# using zip() + product()unique_combinations = list(list(zip(list_1, element)) for element in product(list_2, repeat = len(list_1))) # printing unique_combination listprint(unique_combinations)", "e": 3606, "s": 3040, "text": null }, { "code": null, "e": 3615, "s": 3606, "text": "Output :" }, { "code": null, "e": 4482, "s": 3615, "text": "[[(‘b’, 1), (‘c’, 1), (‘d’, 1)], [(‘b’, 1), (‘c’, 1), (‘d’, 4)], [(‘b’, 1), (‘c’, 1), (‘d’, 9)], [(‘b’, 1), (‘c’, 4), (‘d’, 1)], [(‘b’, 1), (‘c’, 4), (‘d’, 4)], [(‘b’, 1), (‘c’, 4), (‘d’, 9)], [(‘b’, 1), (‘c’, 9), (‘d’, 1)], [(‘b’, 1), (‘c’, 9), (‘d’, 4)], [(‘b’, 1), (‘c’, 9), (‘d’, 9)], [(‘b’, 4), (‘c’, 1), (‘d’, 1)], [(‘b’, 4), (‘c’, 1), (‘d’, 4)], [(‘b’, 4), (‘c’, 1), (‘d’, 9)], [(‘b’, 4), (‘c’, 4), (‘d’, 1)], [(‘b’, 4), (‘c’, 4), (‘d’, 4)], [(‘b’, 4), (‘c’, 4), (‘d’, 9)], [(‘b’, 4), (‘c’, 9), (‘d’, 1)], [(‘b’, 4), (‘c’, 9), (‘d’, 4)], [(‘b’, 4), (‘c’, 9), (‘d’, 9)], [(‘b’, 9), (‘c’, 1), (‘d’, 1)], [(‘b’, 9), (‘c’, 1), (‘d’, 4)], [(‘b’, 9), (‘c’, 1), (‘d’, 9)], [(‘b’, 9), (‘c’, 4), (‘d’, 1)], [(‘b’, 9), (‘c’, 4), (‘d’, 4)], [(‘b’, 9), (‘c’, 4), (‘d’, 9)], [(‘b’, 9), (‘c’, 9), (‘d’, 1)], [(‘b’, 9), (‘c’, 9), (‘d’, 4)], [(‘b’, 9), (‘c’, 9), (‘d’, 9)]] " }, { "code": null, "e": 4491, "s": 4482, "text": "sweetyty" }, { "code": null, "e": 4512, "s": 4491, "text": "Python list-programs" }, { "code": null, "e": 4529, "s": 4512, "text": "Python-itertools" }, { "code": null, "e": 4536, "s": 4529, "text": "Python" }, { "code": null, "e": 4552, "s": 4536, "text": "Python Programs" } ]
How to get the entire HTML document as a string in JavaScript ?
13 Apr, 2021 Given an HTML document, the task is to get the entire document as a string using JavaScript. Here few methods are discussed: getElementsByTagName() Method This method returns a set of all elements in the document with the defined tag name, as a NodeList object. This object represents a collection of nodes, Which are accessed by index numbers. The index starts at 0. Syntax: document.getElementsByTagName(tagname) Parameters: tagname: This parameter is required. It specifies the tagname of the elements to get. tagname: This parameter is required. It specifies the tagname of the elements to get. HTML DOM innerHTML Property This property set/return the HTML content (inner HTML) of an element. Syntax: Return the innerHTML property: Return the innerHTML property: HTMLElementObject.innerHTML Set the innerHTML property: HTMLElementObject.innerHTML = text text: It specifies the HTML content of an element. Example 1: This example gets the whole document as string using document.documentElement.innerHTML. html <!DOCTYPE html> <html> <head> <title> JavaScript | Get the entire document HTML as a string. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksforGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <button onclick="GFG_Fun(); "> click here </button> <script> var up = document.getElementById('GFG_UP'); up.innerHTML = 'Click on the button to convert whole document to string'; function GFG_Fun() { var string = document.documentElement.innerHTML; alert(string); } </script></body> </html> Output: Before clicking the button: After clicking the button: Example 2: This example gets the whole document by first selecting the elements with tagname ‘HTML’ and selecting the first element by indexing using document.getElementsByTagName(‘html’)[0].innerHTML. html <!DOCTYPE html> <html> <head> <title> JavaScript | Get the entire document HTML as a string. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksforGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <button onclick="GFG_Fun(); "> click here </button> <script> var up = document.getElementById('GFG_UP'); up.innerHTML = 'Click on the button to convert whole document to string'; function GFG_Fun() { var string = document.getElementsByTagName('html')[0].innerHTML; alert(string); } </script></body> </html> Output: Before clicking the button: After clicking the button: Supported Browsers: Google Chrome Mozilla Firefox Internet Explorer Safari Opera arorakashish0911 HTML-DOM JavaScript-Misc javascript-string JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Apr, 2021" }, { "code": null, "e": 155, "s": 28, "text": "Given an HTML document, the task is to get the entire document as a string using JavaScript. Here few methods are discussed: " }, { "code": null, "e": 408, "s": 155, "text": "getElementsByTagName() Method This method returns a set of all elements in the document with the defined tag name, as a NodeList object. This object represents a collection of nodes, Which are accessed by index numbers. The index starts at 0. Syntax: " }, { "code": null, "e": 447, "s": 408, "text": "document.getElementsByTagName(tagname)" }, { "code": null, "e": 547, "s": 447, "text": "Parameters: tagname: This parameter is required. It specifies the tagname of the elements to get. " }, { "code": null, "e": 635, "s": 547, "text": "tagname: This parameter is required. It specifies the tagname of the elements to get. " }, { "code": null, "e": 774, "s": 635, "text": "HTML DOM innerHTML Property This property set/return the HTML content (inner HTML) of an element. Syntax: Return the innerHTML property: " }, { "code": null, "e": 807, "s": 774, "text": "Return the innerHTML property: " }, { "code": null, "e": 835, "s": 807, "text": "HTMLElementObject.innerHTML" }, { "code": null, "e": 865, "s": 835, "text": "Set the innerHTML property: " }, { "code": null, "e": 900, "s": 865, "text": "HTMLElementObject.innerHTML = text" }, { "code": null, "e": 953, "s": 900, "text": "text: It specifies the HTML content of an element. " }, { "code": null, "e": 1055, "s": 953, "text": "Example 1: This example gets the whole document as string using document.documentElement.innerHTML. " }, { "code": null, "e": 1060, "s": 1055, "text": "html" }, { "code": "<!DOCTYPE html> <html> <head> <title> JavaScript | Get the entire document HTML as a string. </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <button onclick=\"GFG_Fun(); \"> click here </button> <script> var up = document.getElementById('GFG_UP'); up.innerHTML = 'Click on the button to convert whole document to string'; function GFG_Fun() { var string = document.documentElement.innerHTML; alert(string); } </script></body> </html>", "e": 1728, "s": 1060, "text": null }, { "code": null, "e": 1738, "s": 1728, "text": "Output: " }, { "code": null, "e": 1768, "s": 1738, "text": "Before clicking the button: " }, { "code": null, "e": 1797, "s": 1768, "text": "After clicking the button: " }, { "code": null, "e": 2000, "s": 1797, "text": "Example 2: This example gets the whole document by first selecting the elements with tagname ‘HTML’ and selecting the first element by indexing using document.getElementsByTagName(‘html’)[0].innerHTML. " }, { "code": null, "e": 2005, "s": 2000, "text": "html" }, { "code": "<!DOCTYPE html> <html> <head> <title> JavaScript | Get the entire document HTML as a string. </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <button onclick=\"GFG_Fun(); \"> click here </button> <script> var up = document.getElementById('GFG_UP'); up.innerHTML = 'Click on the button to convert whole document to string'; function GFG_Fun() { var string = document.getElementsByTagName('html')[0].innerHTML; alert(string); } </script></body> </html>", "e": 2689, "s": 2005, "text": null }, { "code": null, "e": 2699, "s": 2689, "text": "Output: " }, { "code": null, "e": 2729, "s": 2699, "text": "Before clicking the button: " }, { "code": null, "e": 2758, "s": 2729, "text": "After clicking the button: " }, { "code": null, "e": 2780, "s": 2760, "text": "Supported Browsers:" }, { "code": null, "e": 2794, "s": 2780, "text": "Google Chrome" }, { "code": null, "e": 2810, "s": 2794, "text": "Mozilla Firefox" }, { "code": null, "e": 2828, "s": 2810, "text": "Internet Explorer" }, { "code": null, "e": 2835, "s": 2828, "text": "Safari" }, { "code": null, "e": 2841, "s": 2835, "text": "Opera" }, { "code": null, "e": 2860, "s": 2843, "text": "arorakashish0911" }, { "code": null, "e": 2869, "s": 2860, "text": "HTML-DOM" }, { "code": null, "e": 2885, "s": 2869, "text": "JavaScript-Misc" }, { "code": null, "e": 2903, "s": 2885, "text": "javascript-string" }, { "code": null, "e": 2914, "s": 2903, "text": "JavaScript" }, { "code": null, "e": 2931, "s": 2914, "text": "Web Technologies" }, { "code": null, "e": 2958, "s": 2931, "text": "Web technologies Questions" } ]
How to check if an instance of 15 puzzle is solvable?
30 Nov, 2021 Given a 4×4 board with 15 tiles (every tile has one number from 1 to 15) and one empty space. The objective is to place the numbers on tiles in order using the empty space. We can slide four adjacent (left, right, above and below) tiles into the empty space. For example, Here X marks the spot to where the elements can be shifted and the final configuration always remains the same the puzzle is solvable. In general, for a given grid of width N, we can find out check if a N*N – 1 puzzle is solvable or not by following below simple rules : If N is odd, then puzzle instance is solvable if number of inversions is even in the input state.If N is even, puzzle instance is solvable if the blank is on an even row counting from the bottom (second-last, fourth-last, etc.) and number of inversions is odd.the blank is on an odd row counting from the bottom (last, third-last, fifth-last, etc.) and number of inversions is even.For all other cases, the puzzle instance is not solvable. If N is odd, then puzzle instance is solvable if number of inversions is even in the input state. If N is even, puzzle instance is solvable if the blank is on an even row counting from the bottom (second-last, fourth-last, etc.) and number of inversions is odd.the blank is on an odd row counting from the bottom (last, third-last, fifth-last, etc.) and number of inversions is even. the blank is on an even row counting from the bottom (second-last, fourth-last, etc.) and number of inversions is odd. the blank is on an odd row counting from the bottom (last, third-last, fifth-last, etc.) and number of inversions is even. For all other cases, the puzzle instance is not solvable. What is an inversion here? If we assume the tiles written out in a single row (1D Array) instead of being spread in N-rows (2D Array), a pair of tiles (a, b) form an inversion if a appears before b but a > b. For above example, consider the tiles written out in a row, like this: 2 1 3 4 5 6 7 8 9 10 11 12 13 14 15 X The above grid forms only 1 inversion i.e. (2, 1).Illustration: Below is a simple C++ program to check whether a given instance of 15 puzzle is solvable or not. The program is generic and can be extended to any grid width. C++ PHP Python3 // C++ program to check if a given instance of N*N-1// puzzle is solvable or not#include <iostream>#define N 4using namespace std; // A utility function to count inversions in given// array 'arr[]'. Note that this function can be// optimized to work in O(n Log n) time. The idea// here is to keep code small and simple.int getInvCount(int arr[]){ int inv_count = 0; for (int i = 0; i < N * N - 1; i++) { for (int j = i + 1; j < N * N; j++) { // count pairs(arr[i], arr[j]) such that // i < j but arr[i] > arr[j] if (arr[j] && arr[i] && arr[i] > arr[j]) inv_count++; } } return inv_count;} // find Position of blank from bottomint findXPosition(int puzzle[N][N]){ // start from bottom-right corner of matrix for (int i = N - 1; i >= 0; i--) for (int j = N - 1; j >= 0; j--) if (puzzle[i][j] == 0) return N - i;} // This function returns true if given// instance of N*N - 1 puzzle is solvablebool isSolvable(int puzzle[N][N]){ // Count inversions in given puzzle int invCount = getInvCount((int*)puzzle); // If grid is odd, return true if inversion // count is even. if (N & 1) return !(invCount & 1); else // grid is even { int pos = findXPosition(puzzle); if (pos & 1) return !(invCount & 1); else return invCount & 1; }} /* Driver program to test above functions */int main(){ int puzzle[N][N] = { {12, 1, 10, 2}, {7, 11, 4, 14}, {5, 0, 9, 15}, // Value 0 is used for empty space {8, 13, 6, 3}, }; /* int puzzle[N][N] = {{1, 8, 2}, {0, 4, 3}, {7, 6, 5}}; int puzzle[N][N] = { {13, 2, 10, 3}, {1, 12, 8, 4}, {5, 0, 9, 6}, {15, 14, 11, 7}, }; int puzzle[N][N] = { {6, 13, 7, 10}, {8, 9, 11, 0}, {15, 2, 12, 5}, {14, 3, 1, 4}, }; int puzzle[N][N] = { {3, 9, 1, 15}, {14, 11, 4, 6}, {13, 0, 10, 12}, {2, 7, 8, 5}, }; */ isSolvable(puzzle)? cout << "Solvable": cout << "Not Solvable"; return 0;} <?php//PHP program to check if a given instance of N*N-1// puzzle is solvable or not $N= 4; // A utility function to count inversions in given// array 'arr[]'. Note that this function can be// optimized to work in O(n Log n) time. The idea// here is to keep code small and simple. function getInvCount( $arr){ global $N; $inv_count = 0; for ($i = 0; $i < $N * $N - 1; $i++) { for ($j = $i + 1; $j < $N * $N; $j++) { // count pairs(arr[i], arr[j]) such that // i < j but arr[i] > arr[j] $inv_count++; } } return $inv_count;} // find Position of blank from bottomfunction findXPosition($puzzle){ global $N; // start from bottom-right corner of matrix for ($i = $N - 1; $i >= 0; $i--) for ($j = $N - 1; $j >= 0; $j--) if ($puzzle[$i][$j] == 0) return $N - $i;} // This function returns true if given// instance of N*N - 1 puzzle is solvablefunction isSolvable( $puzzle){ global $N; // Count inversions in given puzzle $invCount = getInvCount($puzzle); // If grid is odd, return true if inversion // count is even. if ($N & 1) return !($invCount & 1); else // grid is even { $pos = findXPosition($puzzle); if ($pos & 1) return !($invCount & 1); else return $invCount & 1; }} /* Driver program to test above functions */ $puzzle = array( array(12, 1, 10, 2), array(7, 11, 4, 14), array(5, 0, 9, 15), // Value 0 is used for empty space array(8, 13, 6, 3), ); if(isSolvable($puzzle)==0) echo "Solvable"; else echo "Not Solvable"; #This code is contributed by aj_36?> # Python3 program to check if a given instance of N*N-1# puzzle is solvable or not # A utility function to count inversions in given# array . Note that this function can be# optimized to work in O(n Log n) time. The idea# here is to keep code small and simple.N=4def getInvCount(arr): arr1=[] for y in arr: for x in y: arr1.append(x) arr=arr1 inv_count = 0 for i in range(N * N - 1): for j in range(i + 1,N * N): # count pairs(arr[i], arr[j]) such that # i < j and arr[i] > arr[j] if (arr[j] and arr[i] and arr[i] > arr[j]): inv_count+=1 return inv_count # find Position of blank from bottomdef findXPosition(puzzle): # start from bottom-right corner of matrix for i in range(N - 1,-1,-1): for j in range(N - 1,-1,-1): if (puzzle[i][j] == 0): return N - i # This function returns true if given# instance of N*N - 1 puzzle is solvabledef isSolvable(puzzle): # Count inversions in given puzzle invCount = getInvCount(puzzle) # If grid is odd, return true if inversion # count is even. if (N & 1): return ~(invCount & 1) else: # grid is even pos = findXPosition(puzzle) if (pos & 1): return ~(invCount & 1) else: return invCount & 1 # Driver program to test above functionsif __name__ == '__main__': puzzle =[ [12, 1, 10, 2,], [7, 11, 4, 14,], [5, 0, 9, 15,], # Value 0 is used for empty space [8, 13, 6, 3,],] print("Solvable") if isSolvable(puzzle) else print("Not Solvable") Solvable Time Complexity : O(n2) Space Complexity: O(n) How does this works?Fact 1: For a grid of odd width, all legal moves preserve the polarity (even or odd) of the number of inversions.Proof of Fact 1 Moving a tile along the row (left or right) doesn’t change the number of inversions, and therefore doesn’t change its polarity. Moving a tile along the column (up or down) can change the number of inversions. The tile moves past an even number of other tiles (N – 1). So move either increases/decreases inversion count by 2, or keeps the inversion count same. Fact 2: For a grid of even width, the following is invariant: (#inversions even) == (blank on odd row from bottom). Example: Consider the move above. The number of inversions on the left is 49, and the blank is on an even row from the bottom. So the value of the invariant is “false == false”, which is true. The number of inversions on the right is 48, because the 11 has lost two inversions, but the 14 has gained one. The blank is on an odd row from the bottom. So the value of the invariant is “true==true”, which is still true.Proof of Fact 2 Moving a tile along the row (left or right) doesn’t change the number of inversions and doesn’t change the row of the blank. Moving a tile along the column (up or down) does change the number of inversions. The tile moves past an odd number of other tiles (N – 1). So the number of inversions changes by odd number of times. The row of the blank also changes, from odd to even, or from even to odd. So both halves of the invariant changes. So its value is preserved. Combining Fact 1 + Fact 2 = Fact 3: If the width is odd, then every solvable state has an even number of inversions. If the width is even, then every solvable state has an even number of inversions if the blank is on an odd numbered row counting from the bottom;an odd number of inversions if the blank is on an even numbered row counting from the bottom; an even number of inversions if the blank is on an odd numbered row counting from the bottom; an odd number of inversions if the blank is on an even numbered row counting from the bottom; Proof of fact 3: The initial (solved) state has those properties. Those properties are preserved by every legal move. Any solvable state can be reached from the initial state by some sequence of legal moves. Related Article: How to check if an instance of 8 puzzle is solvable?Source : https://www.cs.bham.ac.uk/~mdr/teaching/modules04/java2/TilesSolvability.htmlThis article is contributed by Aditya Goel. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above jit_t akshitajp amartyaghoshgfg Algorithms Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Nov, 2021" }, { "code": null, "e": 325, "s": 52, "text": "Given a 4×4 board with 15 tiles (every tile has one number from 1 to 15) and one empty space. The objective is to place the numbers on tiles in order using the empty space. We can slide four adjacent (left, right, above and below) tiles into the empty space. For example, " }, { "code": null, "e": 598, "s": 325, "text": "Here X marks the spot to where the elements can be shifted and the final configuration always remains the same the puzzle is solvable. In general, for a given grid of width N, we can find out check if a N*N – 1 puzzle is solvable or not by following below simple rules : " }, { "code": null, "e": 1038, "s": 598, "text": "If N is odd, then puzzle instance is solvable if number of inversions is even in the input state.If N is even, puzzle instance is solvable if the blank is on an even row counting from the bottom (second-last, fourth-last, etc.) and number of inversions is odd.the blank is on an odd row counting from the bottom (last, third-last, fifth-last, etc.) and number of inversions is even.For all other cases, the puzzle instance is not solvable." }, { "code": null, "e": 1136, "s": 1038, "text": "If N is odd, then puzzle instance is solvable if number of inversions is even in the input state." }, { "code": null, "e": 1422, "s": 1136, "text": "If N is even, puzzle instance is solvable if the blank is on an even row counting from the bottom (second-last, fourth-last, etc.) and number of inversions is odd.the blank is on an odd row counting from the bottom (last, third-last, fifth-last, etc.) and number of inversions is even." }, { "code": null, "e": 1541, "s": 1422, "text": "the blank is on an even row counting from the bottom (second-last, fourth-last, etc.) and number of inversions is odd." }, { "code": null, "e": 1664, "s": 1541, "text": "the blank is on an odd row counting from the bottom (last, third-last, fifth-last, etc.) and number of inversions is even." }, { "code": null, "e": 1722, "s": 1664, "text": "For all other cases, the puzzle instance is not solvable." }, { "code": null, "e": 2106, "s": 1722, "text": "What is an inversion here? If we assume the tiles written out in a single row (1D Array) instead of being spread in N-rows (2D Array), a pair of tiles (a, b) form an inversion if a appears before b but a > b. For above example, consider the tiles written out in a row, like this: 2 1 3 4 5 6 7 8 9 10 11 12 13 14 15 X The above grid forms only 1 inversion i.e. (2, 1).Illustration: " }, { "code": null, "e": 2272, "s": 2112, "text": "Below is a simple C++ program to check whether a given instance of 15 puzzle is solvable or not. The program is generic and can be extended to any grid width. " }, { "code": null, "e": 2276, "s": 2272, "text": "C++" }, { "code": null, "e": 2280, "s": 2276, "text": "PHP" }, { "code": null, "e": 2288, "s": 2280, "text": "Python3" }, { "code": "// C++ program to check if a given instance of N*N-1// puzzle is solvable or not#include <iostream>#define N 4using namespace std; // A utility function to count inversions in given// array 'arr[]'. Note that this function can be// optimized to work in O(n Log n) time. The idea// here is to keep code small and simple.int getInvCount(int arr[]){ int inv_count = 0; for (int i = 0; i < N * N - 1; i++) { for (int j = i + 1; j < N * N; j++) { // count pairs(arr[i], arr[j]) such that // i < j but arr[i] > arr[j] if (arr[j] && arr[i] && arr[i] > arr[j]) inv_count++; } } return inv_count;} // find Position of blank from bottomint findXPosition(int puzzle[N][N]){ // start from bottom-right corner of matrix for (int i = N - 1; i >= 0; i--) for (int j = N - 1; j >= 0; j--) if (puzzle[i][j] == 0) return N - i;} // This function returns true if given// instance of N*N - 1 puzzle is solvablebool isSolvable(int puzzle[N][N]){ // Count inversions in given puzzle int invCount = getInvCount((int*)puzzle); // If grid is odd, return true if inversion // count is even. if (N & 1) return !(invCount & 1); else // grid is even { int pos = findXPosition(puzzle); if (pos & 1) return !(invCount & 1); else return invCount & 1; }} /* Driver program to test above functions */int main(){ int puzzle[N][N] = { {12, 1, 10, 2}, {7, 11, 4, 14}, {5, 0, 9, 15}, // Value 0 is used for empty space {8, 13, 6, 3}, }; /* int puzzle[N][N] = {{1, 8, 2}, {0, 4, 3}, {7, 6, 5}}; int puzzle[N][N] = { {13, 2, 10, 3}, {1, 12, 8, 4}, {5, 0, 9, 6}, {15, 14, 11, 7}, }; int puzzle[N][N] = { {6, 13, 7, 10}, {8, 9, 11, 0}, {15, 2, 12, 5}, {14, 3, 1, 4}, }; int puzzle[N][N] = { {3, 9, 1, 15}, {14, 11, 4, 6}, {13, 0, 10, 12}, {2, 7, 8, 5}, }; */ isSolvable(puzzle)? cout << \"Solvable\": cout << \"Not Solvable\"; return 0;}", "e": 4686, "s": 2288, "text": null }, { "code": "<?php//PHP program to check if a given instance of N*N-1// puzzle is solvable or not $N= 4; // A utility function to count inversions in given// array 'arr[]'. Note that this function can be// optimized to work in O(n Log n) time. The idea// here is to keep code small and simple. function getInvCount( $arr){ global $N; $inv_count = 0; for ($i = 0; $i < $N * $N - 1; $i++) { for ($j = $i + 1; $j < $N * $N; $j++) { // count pairs(arr[i], arr[j]) such that // i < j but arr[i] > arr[j] $inv_count++; } } return $inv_count;} // find Position of blank from bottomfunction findXPosition($puzzle){ global $N; // start from bottom-right corner of matrix for ($i = $N - 1; $i >= 0; $i--) for ($j = $N - 1; $j >= 0; $j--) if ($puzzle[$i][$j] == 0) return $N - $i;} // This function returns true if given// instance of N*N - 1 puzzle is solvablefunction isSolvable( $puzzle){ global $N; // Count inversions in given puzzle $invCount = getInvCount($puzzle); // If grid is odd, return true if inversion // count is even. if ($N & 1) return !($invCount & 1); else // grid is even { $pos = findXPosition($puzzle); if ($pos & 1) return !($invCount & 1); else return $invCount & 1; }} /* Driver program to test above functions */ $puzzle = array( array(12, 1, 10, 2), array(7, 11, 4, 14), array(5, 0, 9, 15), // Value 0 is used for empty space array(8, 13, 6, 3), ); if(isSolvable($puzzle)==0) echo \"Solvable\"; else echo \"Not Solvable\"; #This code is contributed by aj_36?>", "e": 6436, "s": 4686, "text": null }, { "code": "# Python3 program to check if a given instance of N*N-1# puzzle is solvable or not # A utility function to count inversions in given# array . Note that this function can be# optimized to work in O(n Log n) time. The idea# here is to keep code small and simple.N=4def getInvCount(arr): arr1=[] for y in arr: for x in y: arr1.append(x) arr=arr1 inv_count = 0 for i in range(N * N - 1): for j in range(i + 1,N * N): # count pairs(arr[i], arr[j]) such that # i < j and arr[i] > arr[j] if (arr[j] and arr[i] and arr[i] > arr[j]): inv_count+=1 return inv_count # find Position of blank from bottomdef findXPosition(puzzle): # start from bottom-right corner of matrix for i in range(N - 1,-1,-1): for j in range(N - 1,-1,-1): if (puzzle[i][j] == 0): return N - i # This function returns true if given# instance of N*N - 1 puzzle is solvabledef isSolvable(puzzle): # Count inversions in given puzzle invCount = getInvCount(puzzle) # If grid is odd, return true if inversion # count is even. if (N & 1): return ~(invCount & 1) else: # grid is even pos = findXPosition(puzzle) if (pos & 1): return ~(invCount & 1) else: return invCount & 1 # Driver program to test above functionsif __name__ == '__main__': puzzle =[ [12, 1, 10, 2,], [7, 11, 4, 14,], [5, 0, 9, 15,], # Value 0 is used for empty space [8, 13, 6, 3,],] print(\"Solvable\") if isSolvable(puzzle) else print(\"Not Solvable\")", "e": 8074, "s": 6436, "text": null }, { "code": null, "e": 8083, "s": 8074, "text": "Solvable" }, { "code": null, "e": 8107, "s": 8083, "text": "Time Complexity : O(n2)" }, { "code": null, "e": 8130, "s": 8107, "text": "Space Complexity: O(n)" }, { "code": null, "e": 8281, "s": 8130, "text": "How does this works?Fact 1: For a grid of odd width, all legal moves preserve the polarity (even or odd) of the number of inversions.Proof of Fact 1 " }, { "code": null, "e": 8409, "s": 8281, "text": "Moving a tile along the row (left or right) doesn’t change the number of inversions, and therefore doesn’t change its polarity." }, { "code": null, "e": 8641, "s": 8409, "text": "Moving a tile along the column (up or down) can change the number of inversions. The tile moves past an even number of other tiles (N – 1). So move either increases/decreases inversion count by 2, or keeps the inversion count same." }, { "code": null, "e": 8759, "s": 8641, "text": "Fact 2: For a grid of even width, the following is invariant: (#inversions even) == (blank on odd row from bottom). " }, { "code": null, "e": 9193, "s": 8759, "text": "Example: Consider the move above. The number of inversions on the left is 49, and the blank is on an even row from the bottom. So the value of the invariant is “false == false”, which is true. The number of inversions on the right is 48, because the 11 has lost two inversions, but the 14 has gained one. The blank is on an odd row from the bottom. So the value of the invariant is “true==true”, which is still true.Proof of Fact 2 " }, { "code": null, "e": 9318, "s": 9193, "text": "Moving a tile along the row (left or right) doesn’t change the number of inversions and doesn’t change the row of the blank." }, { "code": null, "e": 9660, "s": 9318, "text": "Moving a tile along the column (up or down) does change the number of inversions. The tile moves past an odd number of other tiles (N – 1). So the number of inversions changes by odd number of times. The row of the blank also changes, from odd to even, or from even to odd. So both halves of the invariant changes. So its value is preserved." }, { "code": null, "e": 9699, "s": 9660, "text": "Combining Fact 1 + Fact 2 = Fact 3: " }, { "code": null, "e": 10019, "s": 9699, "text": "If the width is odd, then every solvable state has an even number of inversions. If the width is even, then every solvable state has an even number of inversions if the blank is on an odd numbered row counting from the bottom;an odd number of inversions if the blank is on an even numbered row counting from the bottom;" }, { "code": null, "e": 10113, "s": 10019, "text": "an even number of inversions if the blank is on an odd numbered row counting from the bottom;" }, { "code": null, "e": 10207, "s": 10113, "text": "an odd number of inversions if the blank is on an even numbered row counting from the bottom;" }, { "code": null, "e": 10226, "s": 10207, "text": "Proof of fact 3: " }, { "code": null, "e": 10275, "s": 10226, "text": "The initial (solved) state has those properties." }, { "code": null, "e": 10327, "s": 10275, "text": "Those properties are preserved by every legal move." }, { "code": null, "e": 10417, "s": 10327, "text": "Any solvable state can be reached from the initial state by some sequence of legal moves." }, { "code": null, "e": 10741, "s": 10417, "text": "Related Article: How to check if an instance of 8 puzzle is solvable?Source : https://www.cs.bham.ac.uk/~mdr/teaching/modules04/java2/TilesSolvability.htmlThis article is contributed by Aditya Goel. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 10747, "s": 10741, "text": "jit_t" }, { "code": null, "e": 10757, "s": 10747, "text": "akshitajp" }, { "code": null, "e": 10773, "s": 10757, "text": "amartyaghoshgfg" }, { "code": null, "e": 10784, "s": 10773, "text": "Algorithms" }, { "code": null, "e": 10795, "s": 10784, "text": "Algorithms" } ]
Look-and-Say Sequence
28 Jun, 2022 Find the n’th term in Look-and-say (Or Count and Say) Sequence. The look-and-say sequence is the sequence of the below integers: 1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211, ... How is the above sequence generated? n’th term is generated by reading (n-1)’th term. The first term is "1" Second term is "11", generated by reading first term as "One 1" (There is one 1 in previous term) Third term is "21", generated by reading second term as "Two 1" Fourth term is "1211", generated by reading third term as "One 2 One 1" and so on How to find n’th term? Example: Input: n = 3 Output: 21 Input: n = 5 Output: 111221 The idea is simple, we generate all terms from 1 to n. First, two terms are initialized as “1” and “11”, and all other terms are generated using previous terms. To generate a term using the previous term, we scan the previous term. While scanning a term, we simply keep track of the count of all consecutive characters. For a sequence of the same characters, we append the count followed by the character to generate the next term. Below is an implementation of the above idea. C++ Java C# Python3 PHP Javascript // C++ program to find n'th term in look and say// sequence#include <bits/stdc++.h>using namespace std; // Returns n'th term in look-and-say sequencestring countnndSay(int n){ // Base cases if (n == 1) return "1"; if (n == 2) return "11"; // Find n'th term by generating all terms from 3 to // n-1. Every term is generated using previous term string str = "11"; // Initialize previous term for (int i = 3; i<=n; i++) { // In below for loop, previous character // is processed in current iteration. That // is why a dummy character is added to make // sure that loop runs one extra iteration. str += '$'; int len = str.length(); int cnt = 1; // Initialize count of matching chars string tmp = ""; // Initialize i'th term in series // Process previous term to find the next term for (int j = 1; j < len; j++) { // If current character doesn't match if (str[j] != str[j-1]) { // Append count of str[j-1] to temp tmp += cnt + '0'; // Append str[j-1] tmp += str[j-1]; // Reset count cnt = 1; } // If matches, then increment count of matching // characters else cnt++; } // Update str str = tmp; } return str;} // Driver programint main(){ int N = 3; cout << countnndSay(N) << endl; return 0;} // Java program to find n'th// term in look and say sequence class GFG{ // Returns n'th term in // look-and-say sequence static String countnndSay(int n) { // Base cases if (n == 1) return "1"; if (n == 2) return "11"; // Find n'th term by generating // all terms from 3 to n-1. // Every term is generated // using previous term // Initialize previous term String str = "11"; for (int i = 3; i <= n; i++) { // In below for loop, previous // character is processed in // current iteration. That is // why a dummy character is // added to make sure that loop // runs one extra iteration. str += '$'; int len = str.length(); int cnt = 1; // Initialize count // of matching chars String tmp = ""; // Initialize i'th // term in series char []arr = str.toCharArray(); // Process previous term // to find the next term for (int j = 1; j < len; j++) { // If current character // doesn't match if (arr[j] != arr[j - 1]) { // Append count of // str[j-1] to temp tmp += cnt + 0; // Append str[j-1] tmp += arr[j - 1]; // Reset count cnt = 1; } // If matches, then increment // count of matching characters else cnt++; } // Update str str = tmp; } return str; } // Driver Code public static void main(String[] args) { int N = 3; System.out.println(countnndSay(N)); }} // This code is contributed// by ChitraNayal // C# program to find n'th// term in look and say sequenceusing System; class GFG{ // Returns n'th term in // look-and-say sequence static string countnndSay(int n) { // Base cases if (n == 1) return "1"; if (n == 2) return "11"; // Find n'th term by generating // all terms from 3 to n-1. // Every term is generated using // previous term // Initialize previous term string str = "11"; for (int i = 3; i <= n; i++) { // In below for loop, previous // character is processed in // current iteration. That is // why a dummy character is // added to make sure that loop // runs one extra iteration. str += '$'; int len = str.Length; int cnt = 1; // Initialize count of // matching chars string tmp = ""; // Initialize i'th // term in series char []arr = str.ToCharArray(); // Process previous term // to find the next term for (int j = 1; j < len; j++) { // If current character // doesn't match if (arr[j] != arr[j - 1]) { // Append count of // str[j-1] to temp tmp += cnt + 0; // Append str[j-1] tmp += arr[j - 1]; // Reset count cnt = 1; } // If matches, then increment // count of matching characters else cnt++; } // Update str str = tmp; } return str; } // Driver Code public static void Main() { int N = 3; Console.Write(countnndSay(N)); }} // This code is contributed// by ChitraNayal # Python 3 program to find# n'th term in look and# say sequence # Returns n'th term in# look-and-say sequencedef countnndSay(n): # Base cases if (n == 1): return "1" if (n == 2): return "11" # Find n'th term by generating # all terms from 3 to n-1. # Every term is generated using # previous term # Initialize previous term s = "11" for i in range(3, n + 1): # In below for loop, # previous character is # processed in current # iteration. That is why # a dummy character is # added to make sure that # loop runs one extra iteration. s += '$' l = len(s) cnt = 1 # Initialize count # of matching chars tmp = "" # Initialize i'th # term in series # Process previous term to # find the next term for j in range(1 , l): # If current character # doesn't match if (s[j] != s[j - 1]): # Append count of # str[j-1] to temp tmp += str(cnt + 0) # Append str[j-1] tmp += s[j - 1] # Reset count cnt = 1 # If matches, then increment # count of matching characters else: cnt += 1 # Update str s = tmp return s; # Driver CodeN = 3print(countnndSay(N)) # This code is contributed# by ChitraNayal <?php// PHP program to find// n'th term in look// and say sequence // Returns n'th term in// look-and-say sequencefunction countnndSay($n){ // Base cases if ($n == 1) return "1"; if ($n == 2) return "11"; // Find n'th term by generating // all terms from 3 to n-1. // Every term is generated // using previous term // Initialize previous term $str = "11"; for ($i = 3; $i <= $n; $i++) { // In below for loop, // previous character is // processed in current // iteration. That is why // a dummy character is // added to make sure that // loop runs one extra iteration. $str = $str.'$'; $len = strlen($str); $cnt = 1; // Initialize count of // matching chars $tmp = ""; // Initialize i'th // term in series // Process previous term // to find the next term for ($j = 1; $j < $len; $j++) { // If current character // doesn't match if ($str[$j] != $str[$j - 1]) { // Append count of // str[j-1] to temp $tmp = $tmp.$cnt + 0; // Append str[j-1] $tmp = $tmp. $str[$j - 1]; // Reset count $cnt = 1; } // If matches, then increment // count of matching characters else $cnt++; } // Update str $str = $tmp; } return $str;} // Driver Code$N = 3;echo countnndSay($N);return 0; // This code is contributed// by ChitraNayal?> <script> // Javascript program to find n'th// term in look and say sequence // Returns n'th term in// look-and-say sequencefunction countnndSay(n){ // Base cases if (n == 1) return "1"; if (n == 2) return "11"; // Find n'th term by generating // all terms from 3 to n-1. // Every term is generated // using previous term // Initialize previous term let str = "11"; for(let i = 3; i <= n; i++) { // In below for loop, previous // character is processed in // current iteration. That is // why a dummy character is // added to make sure that loop // runs one extra iteration. str += '$'; let len = str.length; // Initialize count // of matching chars let cnt = 1; // Initialize i'th // term in series let tmp = ""; let arr = str.split(""); // Process previous term // to find the next term for(let j = 1; j < len; j++) { // If current character // doesn't match if (arr[j] != arr[j - 1]) { // Append count of // str[j-1] to temp tmp += cnt + 0; // Append str[j-1] tmp += arr[j - 1]; // Reset count cnt = 1; } // If matches, then increment // count of matching characters else cnt++; } // Update str str = tmp; } return str;} // Driver Codelet N = 3; document.write(countnndSay(N)); // This code is contributed by avanitrachhadiya2155 </script> 21 Another Approach(Using STL): There is one more idea where we can use unordered_map from c++ stl to track the count of digits. Basic idea is to use a generator function that will generate a string from the previous string. In the count and say function we will iterate over integers from 1 to n-1 and keep updating our result. C++ Java Javascript #include <bits/stdc++.h>using namespace std; // generator function returns int string from prev int// string e.g. -> it will return '1211' for '21' ( One 2's// and One 1)string generator(string str){ string ans = ""; unordered_map<char, int> tempCount; // It is used to count integer sequence for (int i = 0; i < str.length() + 1; i++) { // when current char is different from prev one we // clear the map and update the ans if (tempCount.find(str[i]) == tempCount.end() && i > 0) { auto prev = tempCount.find(str[i - 1]); ans += to_string(prev->second) + prev->first; tempCount.clear(); } // when current char is same as prev one we increase // it's count value tempCount[str[i]]++; } return ans;} string countnndSay(int n){ string res = "1"; // res variable keep tracks of string // from 1 to n-1 // For loop iterates for n-1 time and generate strings // in sequence "1" -> "11" -> "21" -> "1211" for (int i = 1; i < n; i++) { res = generator(res); } return res;} int main(){ int N = 3; cout << countnndSay(N) << endl; return 0;} import java.io.*;import java.util.*; class GFG { // generator function returns int string from prev int // string e.g. -> it will return '1211' for '21' ( One 2's // and One 1) static String generator(String str) { String ans = ""; HashMap<Character, Integer>tempCount = new HashMap<>(); // It is used to count integer sequence for (int i = 0; i < str.length() + 1; i++) { // when current char is different from prev one we // clear the map and update the ans if (i == str.length() || tempCount.containsKey(str.charAt(i)) == false && i > 0) { ans += String.valueOf(tempCount.get(str.charAt(i-1))) + str.charAt(i-1); tempCount.clear(); } // when current char is same as prev one we increase // it's count value if(i == str.length()){ tempCount.put(null, 1); } else{ if(tempCount.containsKey(str.charAt(i))){ tempCount.put(str.charAt(i), tempCount.get(str.charAt(i))+1); } else{ if(i != str.length())tempCount.put(str.charAt(i), 1); } } } return ans; } static String countnndSay(int n) { String res = "1"; // res variable keep tracks of string // from 1 to n-1 // For loop iterates for n-1 time and generate strings // in sequence "1" -> "11" -> "21" -> "1211" for (int i = 1; i < n; i++) { res = generator(res); } return res; } // Driver Code public static void main(String args[]) { int N = 3; System.out.println(countnndSay(N)); }} // This code is contributed by shinjanpatra <script>// generator function returns int string from prev int// string e.g. -> it will return '1211' for '21' ( One 2's// and One 1)function generator(str){ let ans = ""; let tempCount = new Map(); // It is used to count integer sequence for ( i = 0; i < str.length + 1; i++) { // when current char is different from prev one we // clear the map and update the ans if (tempCount.has(str[i]) == false && i > 0) { let prev = tempCount.get(str[i - 1]); ans += prev.toString() + str[i - 1]; tempCount.clear(); } // when current char is same as prev one we increase // it's count value if(tempCount.has(str[i]) == false) tempCount.set(str[i],1); else tempCount.set(str[i],tempCount.get(str[i])+1); } return ans;} function countnndSay(n){ let res = "1"; // res variable keep tracks of string // from 1 to n-1 // For loop iterates for n-1 time and generate strings // in sequence "1" -> "11" -> "21" -> "1211" for (let i = 1; i < n; i++) { res = generator(res); } return res;} // driver codelet N = 5;document.write(countnndSay(N),"</br>"); // This code is contributed by shinjanpatra </script> 21 Thanks to Utkarsh and Neeraj for suggesting the above solution. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above ukasp avanitrachhadiya2155 neerajpatil22 shinjanpatra rkbhola5 mukulsomukesh hardikkoriintern Amazon Facebook pattern-printing series Zoho Misc Strings Zoho Amazon Facebook Misc Strings pattern-printing Misc series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Jun, 2022" }, { "code": null, "e": 243, "s": 54, "text": "Find the n’th term in Look-and-say (Or Count and Say) Sequence. The look-and-say sequence is the sequence of the below integers: 1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211, ... " }, { "code": null, "e": 329, "s": 243, "text": "How is the above sequence generated? n’th term is generated by reading (n-1)’th term." }, { "code": null, "e": 601, "s": 329, "text": "The first term is \"1\"\n\nSecond term is \"11\", generated by reading first term as \"One 1\" \n(There is one 1 in previous term)\n\nThird term is \"21\", generated by reading second term as \"Two 1\"\n\nFourth term is \"1211\", generated by reading third term as \"One 2 One 1\" \n\nand so on" }, { "code": null, "e": 625, "s": 601, "text": "How to find n’th term? " }, { "code": null, "e": 635, "s": 625, "text": "Example: " }, { "code": null, "e": 688, "s": 635, "text": "Input: n = 3\nOutput: 21\n\nInput: n = 5\nOutput: 111221" }, { "code": null, "e": 1120, "s": 688, "text": "The idea is simple, we generate all terms from 1 to n. First, two terms are initialized as “1” and “11”, and all other terms are generated using previous terms. To generate a term using the previous term, we scan the previous term. While scanning a term, we simply keep track of the count of all consecutive characters. For a sequence of the same characters, we append the count followed by the character to generate the next term." }, { "code": null, "e": 1168, "s": 1120, "text": "Below is an implementation of the above idea. " }, { "code": null, "e": 1172, "s": 1168, "text": "C++" }, { "code": null, "e": 1177, "s": 1172, "text": "Java" }, { "code": null, "e": 1180, "s": 1177, "text": "C#" }, { "code": null, "e": 1188, "s": 1180, "text": "Python3" }, { "code": null, "e": 1192, "s": 1188, "text": "PHP" }, { "code": null, "e": 1203, "s": 1192, "text": "Javascript" }, { "code": "// C++ program to find n'th term in look and say// sequence#include <bits/stdc++.h>using namespace std; // Returns n'th term in look-and-say sequencestring countnndSay(int n){ // Base cases if (n == 1) return \"1\"; if (n == 2) return \"11\"; // Find n'th term by generating all terms from 3 to // n-1. Every term is generated using previous term string str = \"11\"; // Initialize previous term for (int i = 3; i<=n; i++) { // In below for loop, previous character // is processed in current iteration. That // is why a dummy character is added to make // sure that loop runs one extra iteration. str += '$'; int len = str.length(); int cnt = 1; // Initialize count of matching chars string tmp = \"\"; // Initialize i'th term in series // Process previous term to find the next term for (int j = 1; j < len; j++) { // If current character doesn't match if (str[j] != str[j-1]) { // Append count of str[j-1] to temp tmp += cnt + '0'; // Append str[j-1] tmp += str[j-1]; // Reset count cnt = 1; } // If matches, then increment count of matching // characters else cnt++; } // Update str str = tmp; } return str;} // Driver programint main(){ int N = 3; cout << countnndSay(N) << endl; return 0;}", "e": 2716, "s": 1203, "text": null }, { "code": "// Java program to find n'th// term in look and say sequence class GFG{ // Returns n'th term in // look-and-say sequence static String countnndSay(int n) { // Base cases if (n == 1) return \"1\"; if (n == 2) return \"11\"; // Find n'th term by generating // all terms from 3 to n-1. // Every term is generated // using previous term // Initialize previous term String str = \"11\"; for (int i = 3; i <= n; i++) { // In below for loop, previous // character is processed in // current iteration. That is // why a dummy character is // added to make sure that loop // runs one extra iteration. str += '$'; int len = str.length(); int cnt = 1; // Initialize count // of matching chars String tmp = \"\"; // Initialize i'th // term in series char []arr = str.toCharArray(); // Process previous term // to find the next term for (int j = 1; j < len; j++) { // If current character // doesn't match if (arr[j] != arr[j - 1]) { // Append count of // str[j-1] to temp tmp += cnt + 0; // Append str[j-1] tmp += arr[j - 1]; // Reset count cnt = 1; } // If matches, then increment // count of matching characters else cnt++; } // Update str str = tmp; } return str; } // Driver Code public static void main(String[] args) { int N = 3; System.out.println(countnndSay(N)); }} // This code is contributed// by ChitraNayal", "e": 4494, "s": 2716, "text": null }, { "code": "// C# program to find n'th// term in look and say sequenceusing System; class GFG{ // Returns n'th term in // look-and-say sequence static string countnndSay(int n) { // Base cases if (n == 1) return \"1\"; if (n == 2) return \"11\"; // Find n'th term by generating // all terms from 3 to n-1. // Every term is generated using // previous term // Initialize previous term string str = \"11\"; for (int i = 3; i <= n; i++) { // In below for loop, previous // character is processed in // current iteration. That is // why a dummy character is // added to make sure that loop // runs one extra iteration. str += '$'; int len = str.Length; int cnt = 1; // Initialize count of // matching chars string tmp = \"\"; // Initialize i'th // term in series char []arr = str.ToCharArray(); // Process previous term // to find the next term for (int j = 1; j < len; j++) { // If current character // doesn't match if (arr[j] != arr[j - 1]) { // Append count of // str[j-1] to temp tmp += cnt + 0; // Append str[j-1] tmp += arr[j - 1]; // Reset count cnt = 1; } // If matches, then increment // count of matching characters else cnt++; } // Update str str = tmp; } return str; } // Driver Code public static void Main() { int N = 3; Console.Write(countnndSay(N)); }} // This code is contributed// by ChitraNayal", "e": 6264, "s": 4494, "text": null }, { "code": "# Python 3 program to find# n'th term in look and# say sequence # Returns n'th term in# look-and-say sequencedef countnndSay(n): # Base cases if (n == 1): return \"1\" if (n == 2): return \"11\" # Find n'th term by generating # all terms from 3 to n-1. # Every term is generated using # previous term # Initialize previous term s = \"11\" for i in range(3, n + 1): # In below for loop, # previous character is # processed in current # iteration. That is why # a dummy character is # added to make sure that # loop runs one extra iteration. s += '$' l = len(s) cnt = 1 # Initialize count # of matching chars tmp = \"\" # Initialize i'th # term in series # Process previous term to # find the next term for j in range(1 , l): # If current character # doesn't match if (s[j] != s[j - 1]): # Append count of # str[j-1] to temp tmp += str(cnt + 0) # Append str[j-1] tmp += s[j - 1] # Reset count cnt = 1 # If matches, then increment # count of matching characters else: cnt += 1 # Update str s = tmp return s; # Driver CodeN = 3print(countnndSay(N)) # This code is contributed# by ChitraNayal", "e": 7788, "s": 6264, "text": null }, { "code": "<?php// PHP program to find// n'th term in look// and say sequence // Returns n'th term in// look-and-say sequencefunction countnndSay($n){ // Base cases if ($n == 1) return \"1\"; if ($n == 2) return \"11\"; // Find n'th term by generating // all terms from 3 to n-1. // Every term is generated // using previous term // Initialize previous term $str = \"11\"; for ($i = 3; $i <= $n; $i++) { // In below for loop, // previous character is // processed in current // iteration. That is why // a dummy character is // added to make sure that // loop runs one extra iteration. $str = $str.'$'; $len = strlen($str); $cnt = 1; // Initialize count of // matching chars $tmp = \"\"; // Initialize i'th // term in series // Process previous term // to find the next term for ($j = 1; $j < $len; $j++) { // If current character // doesn't match if ($str[$j] != $str[$j - 1]) { // Append count of // str[j-1] to temp $tmp = $tmp.$cnt + 0; // Append str[j-1] $tmp = $tmp. $str[$j - 1]; // Reset count $cnt = 1; } // If matches, then increment // count of matching characters else $cnt++; } // Update str $str = $tmp; } return $str;} // Driver Code$N = 3;echo countnndSay($N);return 0; // This code is contributed// by ChitraNayal?>", "e": 9438, "s": 7788, "text": null }, { "code": "<script> // Javascript program to find n'th// term in look and say sequence // Returns n'th term in// look-and-say sequencefunction countnndSay(n){ // Base cases if (n == 1) return \"1\"; if (n == 2) return \"11\"; // Find n'th term by generating // all terms from 3 to n-1. // Every term is generated // using previous term // Initialize previous term let str = \"11\"; for(let i = 3; i <= n; i++) { // In below for loop, previous // character is processed in // current iteration. That is // why a dummy character is // added to make sure that loop // runs one extra iteration. str += '$'; let len = str.length; // Initialize count // of matching chars let cnt = 1; // Initialize i'th // term in series let tmp = \"\"; let arr = str.split(\"\"); // Process previous term // to find the next term for(let j = 1; j < len; j++) { // If current character // doesn't match if (arr[j] != arr[j - 1]) { // Append count of // str[j-1] to temp tmp += cnt + 0; // Append str[j-1] tmp += arr[j - 1]; // Reset count cnt = 1; } // If matches, then increment // count of matching characters else cnt++; } // Update str str = tmp; } return str;} // Driver Codelet N = 3; document.write(countnndSay(N)); // This code is contributed by avanitrachhadiya2155 </script>", "e": 11192, "s": 9438, "text": null }, { "code": null, "e": 11195, "s": 11192, "text": "21" }, { "code": null, "e": 11521, "s": 11195, "text": "Another Approach(Using STL): There is one more idea where we can use unordered_map from c++ stl to track the count of digits. Basic idea is to use a generator function that will generate a string from the previous string. In the count and say function we will iterate over integers from 1 to n-1 and keep updating our result." }, { "code": null, "e": 11525, "s": 11521, "text": "C++" }, { "code": null, "e": 11530, "s": 11525, "text": "Java" }, { "code": null, "e": 11541, "s": 11530, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; // generator function returns int string from prev int// string e.g. -> it will return '1211' for '21' ( One 2's// and One 1)string generator(string str){ string ans = \"\"; unordered_map<char, int> tempCount; // It is used to count integer sequence for (int i = 0; i < str.length() + 1; i++) { // when current char is different from prev one we // clear the map and update the ans if (tempCount.find(str[i]) == tempCount.end() && i > 0) { auto prev = tempCount.find(str[i - 1]); ans += to_string(prev->second) + prev->first; tempCount.clear(); } // when current char is same as prev one we increase // it's count value tempCount[str[i]]++; } return ans;} string countnndSay(int n){ string res = \"1\"; // res variable keep tracks of string // from 1 to n-1 // For loop iterates for n-1 time and generate strings // in sequence \"1\" -> \"11\" -> \"21\" -> \"1211\" for (int i = 1; i < n; i++) { res = generator(res); } return res;} int main(){ int N = 3; cout << countnndSay(N) << endl; return 0;}", "e": 12749, "s": 11541, "text": null }, { "code": "import java.io.*;import java.util.*; class GFG { // generator function returns int string from prev int // string e.g. -> it will return '1211' for '21' ( One 2's // and One 1) static String generator(String str) { String ans = \"\"; HashMap<Character, Integer>tempCount = new HashMap<>(); // It is used to count integer sequence for (int i = 0; i < str.length() + 1; i++) { // when current char is different from prev one we // clear the map and update the ans if (i == str.length() || tempCount.containsKey(str.charAt(i)) == false && i > 0) { ans += String.valueOf(tempCount.get(str.charAt(i-1))) + str.charAt(i-1); tempCount.clear(); } // when current char is same as prev one we increase // it's count value if(i == str.length()){ tempCount.put(null, 1); } else{ if(tempCount.containsKey(str.charAt(i))){ tempCount.put(str.charAt(i), tempCount.get(str.charAt(i))+1); } else{ if(i != str.length())tempCount.put(str.charAt(i), 1); } } } return ans; } static String countnndSay(int n) { String res = \"1\"; // res variable keep tracks of string // from 1 to n-1 // For loop iterates for n-1 time and generate strings // in sequence \"1\" -> \"11\" -> \"21\" -> \"1211\" for (int i = 1; i < n; i++) { res = generator(res); } return res; } // Driver Code public static void main(String args[]) { int N = 3; System.out.println(countnndSay(N)); }} // This code is contributed by shinjanpatra", "e": 14311, "s": 12749, "text": null }, { "code": "<script>// generator function returns int string from prev int// string e.g. -> it will return '1211' for '21' ( One 2's// and One 1)function generator(str){ let ans = \"\"; let tempCount = new Map(); // It is used to count integer sequence for ( i = 0; i < str.length + 1; i++) { // when current char is different from prev one we // clear the map and update the ans if (tempCount.has(str[i]) == false && i > 0) { let prev = tempCount.get(str[i - 1]); ans += prev.toString() + str[i - 1]; tempCount.clear(); } // when current char is same as prev one we increase // it's count value if(tempCount.has(str[i]) == false) tempCount.set(str[i],1); else tempCount.set(str[i],tempCount.get(str[i])+1); } return ans;} function countnndSay(n){ let res = \"1\"; // res variable keep tracks of string // from 1 to n-1 // For loop iterates for n-1 time and generate strings // in sequence \"1\" -> \"11\" -> \"21\" -> \"1211\" for (let i = 1; i < n; i++) { res = generator(res); } return res;} // driver codelet N = 5;document.write(countnndSay(N),\"</br>\"); // This code is contributed by shinjanpatra </script>", "e": 15590, "s": 14311, "text": null }, { "code": null, "e": 15593, "s": 15590, "text": "21" }, { "code": null, "e": 15657, "s": 15593, "text": "Thanks to Utkarsh and Neeraj for suggesting the above solution." }, { "code": null, "e": 15784, "s": 15657, "text": "Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above" }, { "code": null, "e": 15790, "s": 15784, "text": "ukasp" }, { "code": null, "e": 15811, "s": 15790, "text": "avanitrachhadiya2155" }, { "code": null, "e": 15825, "s": 15811, "text": "neerajpatil22" }, { "code": null, "e": 15838, "s": 15825, "text": "shinjanpatra" }, { "code": null, "e": 15847, "s": 15838, "text": "rkbhola5" }, { "code": null, "e": 15861, "s": 15847, "text": "mukulsomukesh" }, { "code": null, "e": 15878, "s": 15861, "text": "hardikkoriintern" }, { "code": null, "e": 15885, "s": 15878, "text": "Amazon" }, { "code": null, "e": 15894, "s": 15885, "text": "Facebook" }, { "code": null, "e": 15911, "s": 15894, "text": "pattern-printing" }, { "code": null, "e": 15918, "s": 15911, "text": "series" }, { "code": null, "e": 15923, "s": 15918, "text": "Zoho" }, { "code": null, "e": 15928, "s": 15923, "text": "Misc" }, { "code": null, "e": 15936, "s": 15928, "text": "Strings" }, { "code": null, "e": 15941, "s": 15936, "text": "Zoho" }, { "code": null, "e": 15948, "s": 15941, "text": "Amazon" }, { "code": null, "e": 15957, "s": 15948, "text": "Facebook" }, { "code": null, "e": 15962, "s": 15957, "text": "Misc" }, { "code": null, "e": 15970, "s": 15962, "text": "Strings" }, { "code": null, "e": 15987, "s": 15970, "text": "pattern-printing" }, { "code": null, "e": 15992, "s": 15987, "text": "Misc" }, { "code": null, "e": 15999, "s": 15992, "text": "series" } ]
Number of ways in which N can be represented as the sum of two positive integers
19 Mar, 2022 Given a number N, the task is to find the number of unique ways in which N can be represented as a sum of two positive integers.Examples: Input: N = 7 Output: 3 (1 + 6), (2 + 5) and (3 + 4).Input: N = 200 Output: 100 Approach: The number of ways in which the number can be expressed as the sum of two positive integers are 1 + (N – 1), 2 + (N – 2), ..., (N – 1) + 1 and (N – 2) + 2. There are N – 1 terms in the series and they appear in identical pairs i.e. (X + Y, Y + X). So the required count will be N / 2.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the number of// distinct ways to represent n// as the sum of two integersint ways(int n){ return n / 2;} // Driver codeint main(){ int n = 2; cout << ways(n); return 0;} // Java implementation of the approach class GFG{ // Function to return the number of // distinct ways to represent n // as the sum of two integers static int ways(int n) { return n / 2; } // Driver code public static void main(String args[]) { int n = 2; System.out.println(ways(n)); }} // This code is contributed by AnkitRai01 # Python3 implementation of the approach # Function to return the number of# distinct ways to represent n# as the sum of two integersdef ways(n): return n // 2 # Driver coden = 2 print(ways(n)) # This code is contributed by Mohit Kumar // C# implementation of the approachusing System; class GFG{ // Function to return the number of// distinct ways to represent n// as the sum of two integersstatic int ways(int n){ return n / 2;} // Driver codepublic static void Main(){ int n = 2; Console.WriteLine(ways(n));}} // This code is contributed by Nidhi_Biet <script> // Javascript implementation of the approach // Function to return the number of// distinct ways to represent n// as the sum of two integersfunction ways(n){ return parseInt(n / 2);} // Driver codevar n = 2;document.write(ways(n)); // This code is contributed by noob2000.</script> 1 Time Complexity: O(1) Auxiliary Space: O(1) mohit kumar 29 nidhi_biet ankthon noob2000 subham348 Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Mar, 2022" }, { "code": null, "e": 168, "s": 28, "text": "Given a number N, the task is to find the number of unique ways in which N can be represented as a sum of two positive integers.Examples: " }, { "code": null, "e": 249, "s": 168, "text": "Input: N = 7 Output: 3 (1 + 6), (2 + 5) and (3 + 4).Input: N = 200 Output: 100 " }, { "code": null, "e": 598, "s": 251, "text": "Approach: The number of ways in which the number can be expressed as the sum of two positive integers are 1 + (N – 1), 2 + (N – 2), ..., (N – 1) + 1 and (N – 2) + 2. There are N – 1 terms in the series and they appear in identical pairs i.e. (X + Y, Y + X). So the required count will be N / 2.Below is the implementation of the above approach: " }, { "code": null, "e": 602, "s": 598, "text": "C++" }, { "code": null, "e": 607, "s": 602, "text": "Java" }, { "code": null, "e": 615, "s": 607, "text": "Python3" }, { "code": null, "e": 618, "s": 615, "text": "C#" }, { "code": null, "e": 629, "s": 618, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the number of// distinct ways to represent n// as the sum of two integersint ways(int n){ return n / 2;} // Driver codeint main(){ int n = 2; cout << ways(n); return 0;}", "e": 917, "s": 629, "text": null }, { "code": "// Java implementation of the approach class GFG{ // Function to return the number of // distinct ways to represent n // as the sum of two integers static int ways(int n) { return n / 2; } // Driver code public static void main(String args[]) { int n = 2; System.out.println(ways(n)); }} // This code is contributed by AnkitRai01", "e": 1313, "s": 917, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the number of# distinct ways to represent n# as the sum of two integersdef ways(n): return n // 2 # Driver coden = 2 print(ways(n)) # This code is contributed by Mohit Kumar", "e": 1552, "s": 1313, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to return the number of// distinct ways to represent n// as the sum of two integersstatic int ways(int n){ return n / 2;} // Driver codepublic static void Main(){ int n = 2; Console.WriteLine(ways(n));}} // This code is contributed by Nidhi_Biet", "e": 1885, "s": 1552, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to return the number of// distinct ways to represent n// as the sum of two integersfunction ways(n){ return parseInt(n / 2);} // Driver codevar n = 2;document.write(ways(n)); // This code is contributed by noob2000.</script>", "e": 2180, "s": 1885, "text": null }, { "code": null, "e": 2182, "s": 2180, "text": "1" }, { "code": null, "e": 2206, "s": 2184, "text": "Time Complexity: O(1)" }, { "code": null, "e": 2228, "s": 2206, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 2243, "s": 2228, "text": "mohit kumar 29" }, { "code": null, "e": 2254, "s": 2243, "text": "nidhi_biet" }, { "code": null, "e": 2262, "s": 2254, "text": "ankthon" }, { "code": null, "e": 2271, "s": 2262, "text": "noob2000" }, { "code": null, "e": 2281, "s": 2271, "text": "subham348" }, { "code": null, "e": 2294, "s": 2281, "text": "Mathematical" }, { "code": null, "e": 2307, "s": 2294, "text": "Mathematical" } ]
How to Insert Image in SQLite using Python?
16 May, 2021 In this article, we will discuss how to insert images in SQLite using sqlite3 module in Python. 1. Set the connection to the SQLite database using Python code. sqliteConnection = sqlite3.connect('SQLite_Retrieving_data.db') cursor = sqliteConnection.cursor() 2. We need to define an INSERT query for inserting the BLOB data into the table. sqlite_insert_blob_query = """ INSERT INTO Student (name, img) VALUES (?, ?)""" 3. Converting human-readable file into binary data by calling this convertToBinaryData() function, and storing it empPhoto variable, empPhoto = convertToBinaryData(photo) 4. Once the file converted into binary format, now let’s convert data into tuple format, data_tuple = (name, empPhoto) 5. Use cursor.execute() to execute a SELECT query in Python. cursor = sqliteConnection.cursor() cursor.execute(sqlite_insert_blob_query, data_tuple) 6. Use sqliteConnection.commit() for saving the changes we made. sqliteConnection.commit() 7. Create a function that converts Human Readable data into the binary format for storing it into database. def convertToBinaryData(filename): # Convert binary format to images or files data with open(filename, 'rb') as file: blobData = file.read() return blobData 8. Close the cursor connection and MySQL database. if sqliteConnection: sqliteConnection.close() print("the sqlite connection is closed") Below is the implementation. Python3 import sqlite3 # Function for Convert Binary Data # to Human Readable Formatdef convertToBinaryData(filename): # Convert binary format to images # or files data with open(filename, 'rb') as file: blobData = file.read() return blobData def insertBLOB(name, photo): try: # Using connect method for establishing # a connection sqliteConnection = sqlite3.connect('SQLite_Retrieving_data.db') cursor = sqliteConnection.cursor() print("Connected to SQLite") # insert query sqlite_insert_blob_query = """ INSERT INTO Student (name, img) VALUES (?, ?)""" # Converting human readable file into # binary data empPhoto = convertToBinaryData(photo) # Convert data into tuple format data_tuple = (name, empPhoto) # using cursor object executing our query cursor.execute(sqlite_insert_blob_query, data_tuple) sqliteConnection.commit() print("Image and file inserted successfully as a BLOB into a table") cursor.close() except sqlite3.Error as error: print("Failed to insert blob data into sqlite table", error) finally: if sqliteConnection: sqliteConnection.close() print("the sqlite connection is closed") insertBLOB("Smith", "D:\Internship Tasks\GFG\images\One.png")insertBLOB("David", "D:\Internship Tasks\GFG\images\person.png") Output: Output for above Python Program Let’s check output in the database using SELECT query with proper format commands, Output inside database Picked Python-SQLite Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 May, 2021" }, { "code": null, "e": 124, "s": 28, "text": "In this article, we will discuss how to insert images in SQLite using sqlite3 module in Python." }, { "code": null, "e": 188, "s": 124, "text": "1. Set the connection to the SQLite database using Python code." }, { "code": null, "e": 287, "s": 188, "text": "sqliteConnection = sqlite3.connect('SQLite_Retrieving_data.db')\ncursor = sqliteConnection.cursor()" }, { "code": null, "e": 370, "s": 287, "text": "2. We need to define an INSERT query for inserting the BLOB data into the table. " }, { "code": null, "e": 483, "s": 370, "text": "sqlite_insert_blob_query = \"\"\" INSERT INTO Student\n (name, img) VALUES (?, ?)\"\"\"" }, { "code": null, "e": 616, "s": 483, "text": "3. Converting human-readable file into binary data by calling this convertToBinaryData() function, and storing it empPhoto variable," }, { "code": null, "e": 654, "s": 616, "text": "empPhoto = convertToBinaryData(photo)" }, { "code": null, "e": 743, "s": 654, "text": "4. Once the file converted into binary format, now let’s convert data into tuple format," }, { "code": null, "e": 773, "s": 743, "text": "data_tuple = (name, empPhoto)" }, { "code": null, "e": 836, "s": 773, "text": "5. Use cursor.execute() to execute a SELECT query in Python. " }, { "code": null, "e": 924, "s": 836, "text": "cursor = sqliteConnection.cursor()\ncursor.execute(sqlite_insert_blob_query, data_tuple)" }, { "code": null, "e": 991, "s": 924, "text": "6. Use sqliteConnection.commit() for saving the changes we made. " }, { "code": null, "e": 1017, "s": 991, "text": "sqliteConnection.commit()" }, { "code": null, "e": 1127, "s": 1017, "text": "7. Create a function that converts Human Readable data into the binary format for storing it into database. " }, { "code": null, "e": 1297, "s": 1127, "text": "def convertToBinaryData(filename):\n\n # Convert binary format to images or files data\n with open(filename, 'rb') as file:\n blobData = file.read()\n return blobData" }, { "code": null, "e": 1348, "s": 1297, "text": "8. Close the cursor connection and MySQL database." }, { "code": null, "e": 1443, "s": 1348, "text": "if sqliteConnection:\n sqliteConnection.close()\n print(\"the sqlite connection is closed\")" }, { "code": null, "e": 1472, "s": 1443, "text": "Below is the implementation." }, { "code": null, "e": 1480, "s": 1472, "text": "Python3" }, { "code": "import sqlite3 # Function for Convert Binary Data # to Human Readable Formatdef convertToBinaryData(filename): # Convert binary format to images # or files data with open(filename, 'rb') as file: blobData = file.read() return blobData def insertBLOB(name, photo): try: # Using connect method for establishing # a connection sqliteConnection = sqlite3.connect('SQLite_Retrieving_data.db') cursor = sqliteConnection.cursor() print(\"Connected to SQLite\") # insert query sqlite_insert_blob_query = \"\"\" INSERT INTO Student (name, img) VALUES (?, ?)\"\"\" # Converting human readable file into # binary data empPhoto = convertToBinaryData(photo) # Convert data into tuple format data_tuple = (name, empPhoto) # using cursor object executing our query cursor.execute(sqlite_insert_blob_query, data_tuple) sqliteConnection.commit() print(\"Image and file inserted successfully as a BLOB into a table\") cursor.close() except sqlite3.Error as error: print(\"Failed to insert blob data into sqlite table\", error) finally: if sqliteConnection: sqliteConnection.close() print(\"the sqlite connection is closed\") insertBLOB(\"Smith\", \"D:\\Internship Tasks\\GFG\\images\\One.png\")insertBLOB(\"David\", \"D:\\Internship Tasks\\GFG\\images\\person.png\")", "e": 2988, "s": 1480, "text": null }, { "code": null, "e": 2996, "s": 2988, "text": "Output:" }, { "code": null, "e": 3028, "s": 2996, "text": "Output for above Python Program" }, { "code": null, "e": 3111, "s": 3028, "text": "Let’s check output in the database using SELECT query with proper format commands," }, { "code": null, "e": 3134, "s": 3111, "text": "Output inside database" }, { "code": null, "e": 3141, "s": 3134, "text": "Picked" }, { "code": null, "e": 3155, "s": 3141, "text": "Python-SQLite" }, { "code": null, "e": 3162, "s": 3155, "text": "Python" } ]
Flip all K-bits of a given number
04 May, 2021 Given two integers N and K, the task is to represent N in K bits and print the number obtained after flipping all the bits. Examples: Input:N = 1, K = 32Output: 4294967294Explanation:1 in K(= 32) bit representation is (00000000000000000000000000000001)2.Flipping all the bits modifies N to (11111111111111111111111111111110)2 = (4294967294)10. Input: N = 0, K = 32Output: 4294967295 Approach: Follow the steps below to solve the problem: Find the value of (1 << (K – 1)) – 1, say X. Finally, print the value of (X – N). 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 flip all K-bits// of an unsigned number Nvoid flippingBits(unsigned long N, unsigned long K){ // Stores (2 ^ K) - 1 unsigned long X = (1 << (K - 1)) - 1; // Update N N = X - N; // Print the answer cout << N;} // Driver Codeint main(){ unsigned long N = 1, K = 8; flippingBits(N, K); return 0;} // Java program for the above approachimport java.util.*; class GFG{ // Function to flip all K-bits// of an unsigned number Nstatic void flippingBits(long N, long K){ // Stores (2 ^ K) - 1 long X = (1 << (K - 1)) - 1; // Update N N = X - N; // Print the answer System.out.print(N);} // Driver Codepublic static void main(String[] args){ long N = 1, K = 8; flippingBits(N, K);}} // This code is contributed by shikhasingrajput # Python3 Program for the above approach # Function to flip all K-bits# of an unsigned number Ndef flippingBits(N, K): # Stores (2 ^ K) - 1 X = (1 << (K - 1)) - 1 # Update N N = X - N # Print the answer print(N) # Driver Codeif __name__ == '__main__': N, K = 1, 8 flippingBits(N, K) # This code is contribute by mohit kumar 29 // C# program for the above approachusing System; class GFG{ // Function to flip all K-bits// of an unsigned number Nstatic void flippingBits(int N, int K){ // Stores (2 ^ K) - 1 int X = (1 << (K - 1)) - 1; // Update N N = X - N; // Print the answer Console.Write(N);} // Driver Codepublic static void Main(string[] args){ int N = 1, K = 8; flippingBits(N, K);}} // This code is contributed by chitranayal <script> // Javascript program of the above approach // Function to flip all K-bits// of an unsigned number Nfunction flippingBits(N, K){ // Stores (2 ^ K) - 1 let X = (1 << (K - 1)) - 1; // Update N N = X - N; // Print the answer document.write(N);} // Driver Code let N = 1, K = 8; flippingBits(N, K); </script> 126 Time Complexity: O(1)Auxiliary Space: O(1) mohit kumar 29 ukasp shikhasingrajput target_2 Technical Scripter 2020 Bit Magic Mathematical Technical Scripter Mathematical Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n04 May, 2021" }, { "code": null, "e": 178, "s": 54, "text": "Given two integers N and K, the task is to represent N in K bits and print the number obtained after flipping all the bits." }, { "code": null, "e": 188, "s": 178, "text": "Examples:" }, { "code": null, "e": 398, "s": 188, "text": "Input:N = 1, K = 32Output: 4294967294Explanation:1 in K(= 32) bit representation is (00000000000000000000000000000001)2.Flipping all the bits modifies N to (11111111111111111111111111111110)2 = (4294967294)10." }, { "code": null, "e": 437, "s": 398, "text": "Input: N = 0, K = 32Output: 4294967295" }, { "code": null, "e": 492, "s": 437, "text": "Approach: Follow the steps below to solve the problem:" }, { "code": null, "e": 537, "s": 492, "text": "Find the value of (1 << (K – 1)) – 1, say X." }, { "code": null, "e": 574, "s": 537, "text": "Finally, print the value of (X – N)." }, { "code": null, "e": 625, "s": 574, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 629, "s": 625, "text": "C++" }, { "code": null, "e": 634, "s": 629, "text": "Java" }, { "code": null, "e": 642, "s": 634, "text": "Python3" }, { "code": null, "e": 645, "s": 642, "text": "C#" }, { "code": null, "e": 656, "s": 645, "text": "Javascript" }, { "code": "// C++ Program for the above approach #include <bits/stdc++.h>using namespace std; // Function to flip all K-bits// of an unsigned number Nvoid flippingBits(unsigned long N, unsigned long K){ // Stores (2 ^ K) - 1 unsigned long X = (1 << (K - 1)) - 1; // Update N N = X - N; // Print the answer cout << N;} // Driver Codeint main(){ unsigned long N = 1, K = 8; flippingBits(N, K); return 0;}", "e": 1096, "s": 656, "text": null }, { "code": "// Java program for the above approachimport java.util.*; class GFG{ // Function to flip all K-bits// of an unsigned number Nstatic void flippingBits(long N, long K){ // Stores (2 ^ K) - 1 long X = (1 << (K - 1)) - 1; // Update N N = X - N; // Print the answer System.out.print(N);} // Driver Codepublic static void main(String[] args){ long N = 1, K = 8; flippingBits(N, K);}} // This code is contributed by shikhasingrajput", "e": 1590, "s": 1096, "text": null }, { "code": "# Python3 Program for the above approach # Function to flip all K-bits# of an unsigned number Ndef flippingBits(N, K): # Stores (2 ^ K) - 1 X = (1 << (K - 1)) - 1 # Update N N = X - N # Print the answer print(N) # Driver Codeif __name__ == '__main__': N, K = 1, 8 flippingBits(N, K) # This code is contribute by mohit kumar 29", "e": 1948, "s": 1590, "text": null }, { "code": "// C# program for the above approachusing System; class GFG{ // Function to flip all K-bits// of an unsigned number Nstatic void flippingBits(int N, int K){ // Stores (2 ^ K) - 1 int X = (1 << (K - 1)) - 1; // Update N N = X - N; // Print the answer Console.Write(N);} // Driver Codepublic static void Main(string[] args){ int N = 1, K = 8; flippingBits(N, K);}} // This code is contributed by chitranayal", "e": 2390, "s": 1948, "text": null }, { "code": "<script> // Javascript program of the above approach // Function to flip all K-bits// of an unsigned number Nfunction flippingBits(N, K){ // Stores (2 ^ K) - 1 let X = (1 << (K - 1)) - 1; // Update N N = X - N; // Print the answer document.write(N);} // Driver Code let N = 1, K = 8; flippingBits(N, K); </script>", "e": 2760, "s": 2390, "text": null }, { "code": null, "e": 2764, "s": 2760, "text": "126" }, { "code": null, "e": 2809, "s": 2766, "text": "Time Complexity: O(1)Auxiliary Space: O(1)" }, { "code": null, "e": 2824, "s": 2809, "text": "mohit kumar 29" }, { "code": null, "e": 2830, "s": 2824, "text": "ukasp" }, { "code": null, "e": 2847, "s": 2830, "text": "shikhasingrajput" }, { "code": null, "e": 2856, "s": 2847, "text": "target_2" }, { "code": null, "e": 2880, "s": 2856, "text": "Technical Scripter 2020" }, { "code": null, "e": 2890, "s": 2880, "text": "Bit Magic" }, { "code": null, "e": 2903, "s": 2890, "text": "Mathematical" }, { "code": null, "e": 2922, "s": 2903, "text": "Technical Scripter" }, { "code": null, "e": 2935, "s": 2922, "text": "Mathematical" }, { "code": null, "e": 2945, "s": 2935, "text": "Bit Magic" } ]
PyQt5 – Multi line label
06 May, 2020 In this article we will see how we can create a multi-line label, when we create a label and set text to it and if the text length is greater then the length of the label extra text did not show, multi-line label make that extra text go into the other line. Below is the representation of how normal and multi-line label looks like In order to do this we will use setWordWrap method. Syntax : label.setWordWrap(True) Argument : It takes bool as argument Return : None Below is the implementation # importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating label label1 = QLabel("Normal label With out multi line", self) # setting geometry to the label label1.setGeometry(200, 150, 100, 50) # adding border to the label label1.setStyleSheet("border : 2px solid black;") # creating label label2 = QLabel("Multi label i.e With multi line", self) # setting geometry to the label label2.setGeometry(200, 250, 100, 50) # adding border to the label label2.setStyleSheet("border : 2px solid black;") # making it multi line label2.setWordWrap(True) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() window.show() # start the appsys.exit(App.exec()) Output : Python PyQt5-Label Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python How to Install PIP on Windows ? Python String | replace() *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Iterate over a list in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n06 May, 2020" }, { "code": null, "e": 360, "s": 28, "text": "In this article we will see how we can create a multi-line label, when we create a label and set text to it and if the text length is greater then the length of the label extra text did not show, multi-line label make that extra text go into the other line. Below is the representation of how normal and multi-line label looks like" }, { "code": null, "e": 414, "s": 362, "text": "In order to do this we will use setWordWrap method." }, { "code": null, "e": 447, "s": 414, "text": "Syntax : label.setWordWrap(True)" }, { "code": null, "e": 484, "s": 447, "text": "Argument : It takes bool as argument" }, { "code": null, "e": 498, "s": 484, "text": "Return : None" }, { "code": null, "e": 526, "s": 498, "text": "Below is the implementation" }, { "code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating label label1 = QLabel(\"Normal label With out multi line\", self) # setting geometry to the label label1.setGeometry(200, 150, 100, 50) # adding border to the label label1.setStyleSheet(\"border : 2px solid black;\") # creating label label2 = QLabel(\"Multi label i.e With multi line\", self) # setting geometry to the label label2.setGeometry(200, 250, 100, 50) # adding border to the label label2.setStyleSheet(\"border : 2px solid black;\") # making it multi line label2.setWordWrap(True) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() window.show() # start the appsys.exit(App.exec())", "e": 1811, "s": 526, "text": null }, { "code": null, "e": 1820, "s": 1811, "text": "Output :" }, { "code": null, "e": 1839, "s": 1820, "text": "Python PyQt5-Label" }, { "code": null, "e": 1850, "s": 1839, "text": "Python-gui" }, { "code": null, "e": 1862, "s": 1850, "text": "Python-PyQt" }, { "code": null, "e": 1869, "s": 1862, "text": "Python" }, { "code": null, "e": 1967, "s": 1869, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1985, "s": 1967, "text": "Python Dictionary" }, { "code": null, "e": 2027, "s": 1985, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2049, "s": 2027, "text": "Enumerate() in Python" }, { "code": null, "e": 2084, "s": 2049, "text": "Read a file line by line in Python" }, { "code": null, "e": 2116, "s": 2084, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2142, "s": 2116, "text": "Python String | replace()" }, { "code": null, "e": 2171, "s": 2142, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2198, "s": 2171, "text": "Python Classes and Objects" }, { "code": null, "e": 2219, "s": 2198, "text": "Python OOPs Concepts" } ]
Manipulators in C++ with Examples
12 Jun, 2022 Manipulators are helping functions that can modify the input/output stream. It does not mean that we change the value of a variable, it only modifies the I/O stream using insertion (<<) and extraction (>>) operators. Manipulators are special functions that can be included in the I/O statement to alter the format parameters of a stream. Manipulators are operators that are used to format the data display. To access manipulators, the file iomanip.h should be included in the program. For example, if we want to print the hexadecimal value of 100 then we can print it as: cout<<setbase(16)<<100 Types of Manipulators There are various types of manipulators: Manipulators without arguments: The most important manipulators defined by the IOStream library are provided below.endl: It is defined in ostream. It is used to enter a new line and after entering a new line it flushes (i.e. it forces all the output written on the screen or in the file) the output stream.ws: It is defined in istream and is used to ignore the whitespaces in the string sequence.ends: It is also defined in ostream and it inserts a null character into the output stream. It typically works with std::ostrstream, when the associated output buffer needs to be null-terminated to be processed as a C string.flush: It is also defined in ostream and it flushes the output stream, i.e. it forces all the output written on the screen or in the file. Without flush, the output would be the same, but may not appear in real-time. Examples: Manipulators without arguments: The most important manipulators defined by the IOStream library are provided below.endl: It is defined in ostream. It is used to enter a new line and after entering a new line it flushes (i.e. it forces all the output written on the screen or in the file) the output stream.ws: It is defined in istream and is used to ignore the whitespaces in the string sequence.ends: It is also defined in ostream and it inserts a null character into the output stream. It typically works with std::ostrstream, when the associated output buffer needs to be null-terminated to be processed as a C string.flush: It is also defined in ostream and it flushes the output stream, i.e. it forces all the output written on the screen or in the file. Without flush, the output would be the same, but may not appear in real-time. Examples: endl: It is defined in ostream. It is used to enter a new line and after entering a new line it flushes (i.e. it forces all the output written on the screen or in the file) the output stream. ws: It is defined in istream and is used to ignore the whitespaces in the string sequence. ends: It is also defined in ostream and it inserts a null character into the output stream. It typically works with std::ostrstream, when the associated output buffer needs to be null-terminated to be processed as a C string. flush: It is also defined in ostream and it flushes the output stream, i.e. it forces all the output written on the screen or in the file. Without flush, the output would be the same, but may not appear in real-time. Examples: CPP #include <iostream>#include <istream>#include <sstream>#include <string> using namespace std; int main(){ istringstream str(" Programmer"); string line; // Ignore all the whitespace in string // str before the first word. getline(str >> std::ws, line); // you can also write str>>ws // After printing the output it will automatically // write a new line in the output stream. cout << line << endl; // without flush, the output will be the same. cout << "only a test" << flush; // Use of ends Manipulator cout << "\na"; // NULL character will be added in the Output cout << "b" << ends; cout << "c" << endl; return 0;} Programmer only a test abc Manipulators with Arguments: Some of the manipulators are used with the argument like setw (20), setfill (‘*’), and many more. These all are defined in the header file. If we want to use these manipulators then we must include this header file in our program. For Example, you can use following manipulators to set minimum width and fill the empty space with any character you want: std::cout << std::setw (6) << std::setfill (’*’);Some important manipulators in <iomanip> are:setw (val): It is used to set the field width in output operations.setfill (c): It is used to fill the character ‘c’ on output stream.setprecision (val): It sets val as the new value for the precision of floating-point values.setbase(val): It is used to set the numeric base value for numeric values.setiosflags(flag): It is used to set the format flags specified by parameter mask.resetiosflags(m): It is used to reset the format flags specified by parameter mask.Some important manipulators in <ios> are:showpos: It forces to show a positive sign on positive numbers.noshowpos: It forces not to write a positive sign on positive numbers.showbase: It indicates the numeric base of numeric values.uppercase: It forces uppercase letters for numeric values.nouppercase: It forces lowercase letters for numeric values.fixed: It uses decimal notation for floating-point values.scientific: It uses scientific floating-point notation.hex: Read and write hexadecimal values for integers and it works same as the setbase(16).dec: Read and write decimal values for integers i.e. setbase(10).oct: Read and write octal values for integers i.e. setbase(10).left: It adjusts output to the left.right: It adjusts output to the right. Manipulators with Arguments: Some of the manipulators are used with the argument like setw (20), setfill (‘*’), and many more. These all are defined in the header file. If we want to use these manipulators then we must include this header file in our program. For Example, you can use following manipulators to set minimum width and fill the empty space with any character you want: std::cout << std::setw (6) << std::setfill (’*’);Some important manipulators in <iomanip> are:setw (val): It is used to set the field width in output operations.setfill (c): It is used to fill the character ‘c’ on output stream.setprecision (val): It sets val as the new value for the precision of floating-point values.setbase(val): It is used to set the numeric base value for numeric values.setiosflags(flag): It is used to set the format flags specified by parameter mask.resetiosflags(m): It is used to reset the format flags specified by parameter mask.Some important manipulators in <ios> are:showpos: It forces to show a positive sign on positive numbers.noshowpos: It forces not to write a positive sign on positive numbers.showbase: It indicates the numeric base of numeric values.uppercase: It forces uppercase letters for numeric values.nouppercase: It forces lowercase letters for numeric values.fixed: It uses decimal notation for floating-point values.scientific: It uses scientific floating-point notation.hex: Read and write hexadecimal values for integers and it works same as the setbase(16).dec: Read and write decimal values for integers i.e. setbase(10).oct: Read and write octal values for integers i.e. setbase(10).left: It adjusts output to the left.right: It adjusts output to the right. Some important manipulators in <iomanip> are:setw (val): It is used to set the field width in output operations.setfill (c): It is used to fill the character ‘c’ on output stream.setprecision (val): It sets val as the new value for the precision of floating-point values.setbase(val): It is used to set the numeric base value for numeric values.setiosflags(flag): It is used to set the format flags specified by parameter mask.resetiosflags(m): It is used to reset the format flags specified by parameter mask. setw (val): It is used to set the field width in output operations.setfill (c): It is used to fill the character ‘c’ on output stream.setprecision (val): It sets val as the new value for the precision of floating-point values.setbase(val): It is used to set the numeric base value for numeric values.setiosflags(flag): It is used to set the format flags specified by parameter mask.resetiosflags(m): It is used to reset the format flags specified by parameter mask. setw (val): It is used to set the field width in output operations. setfill (c): It is used to fill the character ‘c’ on output stream. setprecision (val): It sets val as the new value for the precision of floating-point values. setbase(val): It is used to set the numeric base value for numeric values. setiosflags(flag): It is used to set the format flags specified by parameter mask. resetiosflags(m): It is used to reset the format flags specified by parameter mask. Some important manipulators in <ios> are:showpos: It forces to show a positive sign on positive numbers.noshowpos: It forces not to write a positive sign on positive numbers.showbase: It indicates the numeric base of numeric values.uppercase: It forces uppercase letters for numeric values.nouppercase: It forces lowercase letters for numeric values.fixed: It uses decimal notation for floating-point values.scientific: It uses scientific floating-point notation.hex: Read and write hexadecimal values for integers and it works same as the setbase(16).dec: Read and write decimal values for integers i.e. setbase(10).oct: Read and write octal values for integers i.e. setbase(10).left: It adjusts output to the left.right: It adjusts output to the right. showpos: It forces to show a positive sign on positive numbers.noshowpos: It forces not to write a positive sign on positive numbers.showbase: It indicates the numeric base of numeric values.uppercase: It forces uppercase letters for numeric values.nouppercase: It forces lowercase letters for numeric values.fixed: It uses decimal notation for floating-point values.scientific: It uses scientific floating-point notation.hex: Read and write hexadecimal values for integers and it works same as the setbase(16).dec: Read and write decimal values for integers i.e. setbase(10).oct: Read and write octal values for integers i.e. setbase(10).left: It adjusts output to the left.right: It adjusts output to the right. showpos: It forces to show a positive sign on positive numbers. noshowpos: It forces not to write a positive sign on positive numbers. showbase: It indicates the numeric base of numeric values. uppercase: It forces uppercase letters for numeric values. nouppercase: It forces lowercase letters for numeric values. fixed: It uses decimal notation for floating-point values. scientific: It uses scientific floating-point notation. hex: Read and write hexadecimal values for integers and it works same as the setbase(16). dec: Read and write decimal values for integers i.e. setbase(10). oct: Read and write octal values for integers i.e. setbase(10). left: It adjusts output to the left. right: It adjusts output to the right. There are two types of manipulators used generally:1] Parameterized and 2] Non-parameterized Manipulator -> Meaningsetw (int n) -> To set field width to nsetprecision (int p) -> The precision is fixed to psetfill (Char f) -> To set the character to be filledsetiosflags (long l) -> Format flag is set to lresetiosflags (long l) -> Removes the flags indicated by lSetbase(int b) -> To set the base of the number to b setw () is a function in Manipulators in C++: The setw() function is an output manipulator that inserts whitespace between two variables. You must enter an integer value equal to the needed space. Syntax: setw ( int n) As an example, int a=15; int b=20; cout << setw(10) << a << setw(10) << b << endl; setfill() is a function in Manipulators in C++:It replaces setw(whitespaces )’s with a different character. It’s similar to setw() in that it manipulates output, but the only parameter required is a single character. Syntax: setfill(char ch) Example: int a,b; a=15; b=20; cout<< setfill(‘*’) << endl; cout << setw(5) << a << setw(5) << a << endl; setprecision() is a function in Manipulators in C++:It is an output manipulator that controls the number of digits to display after the decimal for a floating point integer. Syntax: setprecision (int p)Example: float A = 1.34255; cout <<fixed<< setprecision(3) << A << endl; setbase() is a function in Manipulators in C++:The setbase() manipulator is used to change the base of a number to a different value. The following base values are supported by the C++ language: • hex (Hexadecimal = 16) • oct (Octal = 8) • dec (Decimal = 10) The manipulators hex, oct, and dec can change the basis of input and output numbers. C++ // Example: #include <iostream> #include <iomanip> using namespace std;main(){ int number = 100; cout << "Hex Value =" << " " << hex << number << endl; cout << "Octal Value=" << " " << oct << number << endl; cout << "Setbase Value=" << " " << setbase(8) << number << endl; cout << "Setbase Value=" << " " << setbase(16) << number << endl; return 0; } Hex Value = 64 Octal Value= 144 Setbase Value= 144 Setbase Value= 64 2] Non-parameterizedExamples are endl, fixed, showpoint and flush.• endl – Gives a new line• ends – Adds null character to close an output string• flush – Flushes the buffer stream• ws – Omits the leading white spaces present before the first field• hex, oct, dec – Displays the number in hexadecimal or octal or in decimal format C++ // Example: ws – Omits the leading white spaces present before the first field #include<iostream>using namespace std; int main() { char name[125]; cout << "Enter your name" << endl; cin >> ws; cin.getline(name,125); cout << name << endl; return 0;} Output Enter your name ram ram References: http://www.cplusplus.com/reference/iomanip/ http://www.cplusplus.com/reference/ios/basic_ios/ http://www.cplusplus.com/reference/ios/ jyotibalodhi aditiyadav20102001 CPP-Basics cpp-manipulators C++ 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++ Priority Queue in C++ Standard Template Library (STL) Inheritance in C++ unordered_map in C++ STL Sorting a vector in C++ The C++ Standard Template Library (STL) C++ Classes and Objects Object Oriented Programming in C++
[ { "code": null, "e": 54, "s": 26, "text": "\n12 Jun, 2022" }, { "code": null, "e": 272, "s": 54, "text": "Manipulators are helping functions that can modify the input/output stream. It does not mean that we change the value of a variable, it only modifies the I/O stream using insertion (<<) and extraction (>>) operators. " }, { "code": null, "e": 394, "s": 272, "text": "Manipulators are special functions that can be included in the I/O statement to alter the format parameters of a stream. " }, { "code": null, "e": 463, "s": 394, "text": "Manipulators are operators that are used to format the data display." }, { "code": null, "e": 542, "s": 463, "text": "To access manipulators, the file iomanip.h should be included in the program. " }, { "code": null, "e": 629, "s": 542, "text": "For example, if we want to print the hexadecimal value of 100 then we can print it as:" }, { "code": null, "e": 652, "s": 629, "text": "cout<<setbase(16)<<100" }, { "code": null, "e": 715, "s": 652, "text": "Types of Manipulators There are various types of manipulators:" }, { "code": null, "e": 1564, "s": 715, "text": "Manipulators without arguments: The most important manipulators defined by the IOStream library are provided below.endl: It is defined in ostream. It is used to enter a new line and after entering a new line it flushes (i.e. it forces all the output written on the screen or in the file) the output stream.ws: It is defined in istream and is used to ignore the whitespaces in the string sequence.ends: It is also defined in ostream and it inserts a null character into the output stream. It typically works with std::ostrstream, when the associated output buffer needs to be null-terminated to be processed as a C string.flush: It is also defined in ostream and it flushes the output stream, i.e. it forces all the output written on the screen or in the file. Without flush, the output would be the same, but may not appear in real-time. Examples: " }, { "code": null, "e": 2413, "s": 1564, "text": "Manipulators without arguments: The most important manipulators defined by the IOStream library are provided below.endl: It is defined in ostream. It is used to enter a new line and after entering a new line it flushes (i.e. it forces all the output written on the screen or in the file) the output stream.ws: It is defined in istream and is used to ignore the whitespaces in the string sequence.ends: It is also defined in ostream and it inserts a null character into the output stream. It typically works with std::ostrstream, when the associated output buffer needs to be null-terminated to be processed as a C string.flush: It is also defined in ostream and it flushes the output stream, i.e. it forces all the output written on the screen or in the file. Without flush, the output would be the same, but may not appear in real-time. Examples: " }, { "code": null, "e": 2605, "s": 2413, "text": "endl: It is defined in ostream. It is used to enter a new line and after entering a new line it flushes (i.e. it forces all the output written on the screen or in the file) the output stream." }, { "code": null, "e": 2696, "s": 2605, "text": "ws: It is defined in istream and is used to ignore the whitespaces in the string sequence." }, { "code": null, "e": 2922, "s": 2696, "text": "ends: It is also defined in ostream and it inserts a null character into the output stream. It typically works with std::ostrstream, when the associated output buffer needs to be null-terminated to be processed as a C string." }, { "code": null, "e": 3150, "s": 2922, "text": "flush: It is also defined in ostream and it flushes the output stream, i.e. it forces all the output written on the screen or in the file. Without flush, the output would be the same, but may not appear in real-time. Examples: " }, { "code": null, "e": 3154, "s": 3150, "text": "CPP" }, { "code": "#include <iostream>#include <istream>#include <sstream>#include <string> using namespace std; int main(){ istringstream str(\" Programmer\"); string line; // Ignore all the whitespace in string // str before the first word. getline(str >> std::ws, line); // you can also write str>>ws // After printing the output it will automatically // write a new line in the output stream. cout << line << endl; // without flush, the output will be the same. cout << \"only a test\" << flush; // Use of ends Manipulator cout << \"\\na\"; // NULL character will be added in the Output cout << \"b\" << ends; cout << \"c\" << endl; return 0;}", "e": 3838, "s": 3154, "text": null }, { "code": null, "e": 3865, "s": 3838, "text": "Programmer\nonly a test\nabc" }, { "code": null, "e": 5562, "s": 3865, "text": "Manipulators with Arguments: Some of the manipulators are used with the argument like setw (20), setfill (‘*’), and many more. These all are defined in the header file. If we want to use these manipulators then we must include this header file in our program. For Example, you can use following manipulators to set minimum width and fill the empty space with any character you want: std::cout << std::setw (6) << std::setfill (’*’);Some important manipulators in <iomanip> are:setw (val): It is used to set the field width in output operations.setfill (c): It is used to fill the character ‘c’ on output stream.setprecision (val): It sets val as the new value for the precision of floating-point values.setbase(val): It is used to set the numeric base value for numeric values.setiosflags(flag): It is used to set the format flags specified by parameter mask.resetiosflags(m): It is used to reset the format flags specified by parameter mask.Some important manipulators in <ios> are:showpos: It forces to show a positive sign on positive numbers.noshowpos: It forces not to write a positive sign on positive numbers.showbase: It indicates the numeric base of numeric values.uppercase: It forces uppercase letters for numeric values.nouppercase: It forces lowercase letters for numeric values.fixed: It uses decimal notation for floating-point values.scientific: It uses scientific floating-point notation.hex: Read and write hexadecimal values for integers and it works same as the setbase(16).dec: Read and write decimal values for integers i.e. setbase(10).oct: Read and write octal values for integers i.e. setbase(10).left: It adjusts output to the left.right: It adjusts output to the right." }, { "code": null, "e": 7259, "s": 5562, "text": "Manipulators with Arguments: Some of the manipulators are used with the argument like setw (20), setfill (‘*’), and many more. These all are defined in the header file. If we want to use these manipulators then we must include this header file in our program. For Example, you can use following manipulators to set minimum width and fill the empty space with any character you want: std::cout << std::setw (6) << std::setfill (’*’);Some important manipulators in <iomanip> are:setw (val): It is used to set the field width in output operations.setfill (c): It is used to fill the character ‘c’ on output stream.setprecision (val): It sets val as the new value for the precision of floating-point values.setbase(val): It is used to set the numeric base value for numeric values.setiosflags(flag): It is used to set the format flags specified by parameter mask.resetiosflags(m): It is used to reset the format flags specified by parameter mask.Some important manipulators in <ios> are:showpos: It forces to show a positive sign on positive numbers.noshowpos: It forces not to write a positive sign on positive numbers.showbase: It indicates the numeric base of numeric values.uppercase: It forces uppercase letters for numeric values.nouppercase: It forces lowercase letters for numeric values.fixed: It uses decimal notation for floating-point values.scientific: It uses scientific floating-point notation.hex: Read and write hexadecimal values for integers and it works same as the setbase(16).dec: Read and write decimal values for integers i.e. setbase(10).oct: Read and write octal values for integers i.e. setbase(10).left: It adjusts output to the left.right: It adjusts output to the right." }, { "code": null, "e": 7770, "s": 7259, "text": "Some important manipulators in <iomanip> are:setw (val): It is used to set the field width in output operations.setfill (c): It is used to fill the character ‘c’ on output stream.setprecision (val): It sets val as the new value for the precision of floating-point values.setbase(val): It is used to set the numeric base value for numeric values.setiosflags(flag): It is used to set the format flags specified by parameter mask.resetiosflags(m): It is used to reset the format flags specified by parameter mask." }, { "code": null, "e": 8236, "s": 7770, "text": "setw (val): It is used to set the field width in output operations.setfill (c): It is used to fill the character ‘c’ on output stream.setprecision (val): It sets val as the new value for the precision of floating-point values.setbase(val): It is used to set the numeric base value for numeric values.setiosflags(flag): It is used to set the format flags specified by parameter mask.resetiosflags(m): It is used to reset the format flags specified by parameter mask." }, { "code": null, "e": 8304, "s": 8236, "text": "setw (val): It is used to set the field width in output operations." }, { "code": null, "e": 8372, "s": 8304, "text": "setfill (c): It is used to fill the character ‘c’ on output stream." }, { "code": null, "e": 8465, "s": 8372, "text": "setprecision (val): It sets val as the new value for the precision of floating-point values." }, { "code": null, "e": 8540, "s": 8465, "text": "setbase(val): It is used to set the numeric base value for numeric values." }, { "code": null, "e": 8623, "s": 8540, "text": "setiosflags(flag): It is used to set the format flags specified by parameter mask." }, { "code": null, "e": 8707, "s": 8623, "text": "resetiosflags(m): It is used to reset the format flags specified by parameter mask." }, { "code": null, "e": 9462, "s": 8707, "text": "Some important manipulators in <ios> are:showpos: It forces to show a positive sign on positive numbers.noshowpos: It forces not to write a positive sign on positive numbers.showbase: It indicates the numeric base of numeric values.uppercase: It forces uppercase letters for numeric values.nouppercase: It forces lowercase letters for numeric values.fixed: It uses decimal notation for floating-point values.scientific: It uses scientific floating-point notation.hex: Read and write hexadecimal values for integers and it works same as the setbase(16).dec: Read and write decimal values for integers i.e. setbase(10).oct: Read and write octal values for integers i.e. setbase(10).left: It adjusts output to the left.right: It adjusts output to the right." }, { "code": null, "e": 10176, "s": 9462, "text": "showpos: It forces to show a positive sign on positive numbers.noshowpos: It forces not to write a positive sign on positive numbers.showbase: It indicates the numeric base of numeric values.uppercase: It forces uppercase letters for numeric values.nouppercase: It forces lowercase letters for numeric values.fixed: It uses decimal notation for floating-point values.scientific: It uses scientific floating-point notation.hex: Read and write hexadecimal values for integers and it works same as the setbase(16).dec: Read and write decimal values for integers i.e. setbase(10).oct: Read and write octal values for integers i.e. setbase(10).left: It adjusts output to the left.right: It adjusts output to the right." }, { "code": null, "e": 10240, "s": 10176, "text": "showpos: It forces to show a positive sign on positive numbers." }, { "code": null, "e": 10311, "s": 10240, "text": "noshowpos: It forces not to write a positive sign on positive numbers." }, { "code": null, "e": 10370, "s": 10311, "text": "showbase: It indicates the numeric base of numeric values." }, { "code": null, "e": 10429, "s": 10370, "text": "uppercase: It forces uppercase letters for numeric values." }, { "code": null, "e": 10490, "s": 10429, "text": "nouppercase: It forces lowercase letters for numeric values." }, { "code": null, "e": 10549, "s": 10490, "text": "fixed: It uses decimal notation for floating-point values." }, { "code": null, "e": 10605, "s": 10549, "text": "scientific: It uses scientific floating-point notation." }, { "code": null, "e": 10695, "s": 10605, "text": "hex: Read and write hexadecimal values for integers and it works same as the setbase(16)." }, { "code": null, "e": 10761, "s": 10695, "text": "dec: Read and write decimal values for integers i.e. setbase(10)." }, { "code": null, "e": 10825, "s": 10761, "text": "oct: Read and write octal values for integers i.e. setbase(10)." }, { "code": null, "e": 10862, "s": 10825, "text": "left: It adjusts output to the left." }, { "code": null, "e": 10901, "s": 10862, "text": "right: It adjusts output to the right." }, { "code": null, "e": 10995, "s": 10901, "text": "There are two types of manipulators used generally:1] Parameterized and 2] Non-parameterized " }, { "code": null, "e": 11447, "s": 10995, "text": "Manipulator -> Meaningsetw (int n) -> To set field width to nsetprecision (int p) -> The precision is fixed to psetfill (Char f) -> To set the character to be filledsetiosflags (long l) -> Format flag is set to lresetiosflags (long l) -> Removes the flags indicated by lSetbase(int b) -> To set the base of the number to b" }, { "code": null, "e": 11493, "s": 11447, "text": "setw () is a function in Manipulators in C++:" }, { "code": null, "e": 11840, "s": 11493, "text": " The setw() function is an output manipulator that inserts whitespace between two variables. You must enter an integer value equal to the needed space. Syntax: setw ( int n) As an example, int a=15; int b=20; cout << setw(10) << a << setw(10) << b << endl; " }, { "code": null, "e": 12159, "s": 11840, "text": "setfill() is a function in Manipulators in C++:It replaces setw(whitespaces )’s with a different character. It’s similar to setw() in that it manipulates output, but the only parameter required is a single character. Syntax: setfill(char ch) Example: int a,b; a=15; b=20; cout<< setfill(‘*’) << endl;" }, { "code": null, "e": 12221, "s": 12159, "text": " cout << setw(5) << a << setw(5) << a << endl;" }, { "code": null, "e": 12436, "s": 12221, "text": "setprecision() is a function in Manipulators in C++:It is an output manipulator that controls the number of digits to display after the decimal for a floating point integer. Syntax: setprecision (int p)Example:" }, { "code": null, "e": 12469, "s": 12436, "text": " float A = 1.34255;" }, { "code": null, "e": 12528, "s": 12469, "text": " cout <<fixed<< setprecision(3) << A << endl;" }, { "code": null, "e": 12791, "s": 12528, "text": "setbase() is a function in Manipulators in C++:The setbase() manipulator is used to change the base of a number to a different value. The following base values are supported by the C++ language: • hex (Hexadecimal = 16) • oct (Octal = 8) • dec (Decimal = 10) " }, { "code": null, "e": 12888, "s": 12791, "text": " The manipulators hex, oct, and dec can change the basis of input and output numbers. " }, { "code": null, "e": 12892, "s": 12888, "text": "C++" }, { "code": "// Example: #include <iostream> #include <iomanip> using namespace std;main(){ int number = 100; cout << \"Hex Value =\" << \" \" << hex << number << endl; cout << \"Octal Value=\" << \" \" << oct << number << endl; cout << \"Setbase Value=\" << \" \" << setbase(8) << number << endl; cout << \"Setbase Value=\" << \" \" << setbase(16) << number << endl; return 0; }", "e": 13246, "s": 12892, "text": null }, { "code": null, "e": 13315, "s": 13246, "text": "Hex Value = 64\nOctal Value= 144\nSetbase Value= 144\nSetbase Value= 64" }, { "code": null, "e": 13647, "s": 13315, "text": "2] Non-parameterizedExamples are endl, fixed, showpoint and flush.• endl – Gives a new line• ends – Adds null character to close an output string• flush – Flushes the buffer stream• ws – Omits the leading white spaces present before the first field• hex, oct, dec – Displays the number in hexadecimal or octal or in decimal format " }, { "code": null, "e": 13651, "s": 13647, "text": "C++" }, { "code": "// Example: ws – Omits the leading white spaces present before the first field #include<iostream>using namespace std; int main() { char name[125]; cout << \"Enter your name\" << endl; cin >> ws; cin.getline(name,125); cout << name << endl; return 0;}", "e": 13940, "s": 13651, "text": null }, { "code": null, "e": 13947, "s": 13940, "text": "Output" }, { "code": null, "e": 13971, "s": 13947, "text": "Enter your name\nram\nram" }, { "code": null, "e": 13983, "s": 13971, "text": "References:" }, { "code": null, "e": 14027, "s": 13983, "text": "http://www.cplusplus.com/reference/iomanip/" }, { "code": null, "e": 14077, "s": 14027, "text": "http://www.cplusplus.com/reference/ios/basic_ios/" }, { "code": null, "e": 14117, "s": 14077, "text": "http://www.cplusplus.com/reference/ios/" }, { "code": null, "e": 14130, "s": 14117, "text": "jyotibalodhi" }, { "code": null, "e": 14149, "s": 14130, "text": "aditiyadav20102001" }, { "code": null, "e": 14160, "s": 14149, "text": "CPP-Basics" }, { "code": null, "e": 14177, "s": 14160, "text": "cpp-manipulators" }, { "code": null, "e": 14181, "s": 14177, "text": "C++" }, { "code": null, "e": 14185, "s": 14181, "text": "CPP" }, { "code": null, "e": 14283, "s": 14185, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 14310, "s": 14283, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 14353, "s": 14310, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 14387, "s": 14353, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 14441, "s": 14387, "text": "Priority Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 14460, "s": 14441, "text": "Inheritance in C++" }, { "code": null, "e": 14485, "s": 14460, "text": "unordered_map in C++ STL" }, { "code": null, "e": 14509, "s": 14485, "text": "Sorting a vector in C++" }, { "code": null, "e": 14549, "s": 14509, "text": "The C++ Standard Template Library (STL)" }, { "code": null, "e": 14573, "s": 14549, "text": "C++ Classes and Objects" } ]
Vectors in Octave GNU
18 Aug, 2020 Vector in Octave is similar to the array in every aspect except the vector size is dynamic, which means its size can be increased however array does not allow such type of increment in its size. Types of Vectors Row Vector Column Vector Row vectors are created by enclosing the set of elements in square brackets, using space or comma to delimit the elements. % using space as the delimiterRowVector1 = [1 2 3 4 5];disp(RowVector1); % using comma as the delimiterRowVector2 = [1, 2, 3, 4, 5];disp(RowVector2); Output : 1 2 3 4 5 1 2 3 4 5 Column vectors are created by enclosing the set of elements in square brackets, using a semicolon to delimit the elements. ColumnVector = [1; 2; 3; 4; 5];disp(ColumnVector); Output : 1 2 3 4 5 Accessing Elements in a Vector in Octave GNU : A vector element is accessed using the index of that element. The indexing starts from 1(not from 0). Language like C++, Java uses index from 0 to size-1, whereas in OCTAVE GNU index starts from 1 and ends at size; Also C++, java uses [] (Square Bracket) to access elements using index but in OCTAVE GNU parenthesis are used to access elements using the index. Vector = [10 20 30 40 50];for i = 1 : 5 printf("Element at Vector(%d) is %d\n", i, Vector(i));endfor Output : Element at Vector(1) is 10 Element at Vector(2) is 20 Element at Vector(3) is 30 Element at Vector(4) is 40 Element at Vector(5) is 50 Octave-GNU Programming Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Data Types Decorators with parameters in Python Difference between Shallow and Deep copy of a class Shallow Copy and Deep Copy in C++ Top 10 Programming Languages to Learn in 2022 Kotlin Array Advantages and Disadvantages of OOP Difference between while and do-while loop in C, C++, Java Top 10 Fastest Programming Languages Which Programming Language Should I Choose as a Beginner?
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Aug, 2020" }, { "code": null, "e": 223, "s": 28, "text": "Vector in Octave is similar to the array in every aspect except the vector size is dynamic, which means its size can be increased however array does not allow such type of increment in its size." }, { "code": null, "e": 240, "s": 223, "text": "Types of Vectors" }, { "code": null, "e": 251, "s": 240, "text": "Row Vector" }, { "code": null, "e": 265, "s": 251, "text": "Column Vector" }, { "code": null, "e": 388, "s": 265, "text": "Row vectors are created by enclosing the set of elements in square brackets, using space or comma to delimit the elements." }, { "code": "% using space as the delimiterRowVector1 = [1 2 3 4 5];disp(RowVector1); % using comma as the delimiterRowVector2 = [1, 2, 3, 4, 5];disp(RowVector2);", "e": 539, "s": 388, "text": null }, { "code": null, "e": 548, "s": 539, "text": "Output :" }, { "code": null, "e": 591, "s": 548, "text": " 1 2 3 4 5\n 1 2 3 4 5\n" }, { "code": null, "e": 714, "s": 591, "text": "Column vectors are created by enclosing the set of elements in square brackets, using a semicolon to delimit the elements." }, { "code": "ColumnVector = [1; 2; 3; 4; 5];disp(ColumnVector);", "e": 765, "s": 714, "text": null }, { "code": null, "e": 774, "s": 765, "text": "Output :" }, { "code": null, "e": 800, "s": 774, "text": " 1\n 2\n 3\n 4\n 5\n" }, { "code": null, "e": 1208, "s": 800, "text": "Accessing Elements in a Vector in Octave GNU : A vector element is accessed using the index of that element. The indexing starts from 1(not from 0). Language like C++, Java uses index from 0 to size-1, whereas in OCTAVE GNU index starts from 1 and ends at size; Also C++, java uses [] (Square Bracket) to access elements using index but in OCTAVE GNU parenthesis are used to access elements using the index." }, { "code": "Vector = [10 20 30 40 50];for i = 1 : 5 printf(\"Element at Vector(%d) is %d\\n\", i, Vector(i));endfor", "e": 1312, "s": 1208, "text": null }, { "code": null, "e": 1321, "s": 1312, "text": "Output :" }, { "code": null, "e": 1457, "s": 1321, "text": "Element at Vector(1) is 10\nElement at Vector(2) is 20\nElement at Vector(3) is 30\nElement at Vector(4) is 40\nElement at Vector(5) is 50\n" }, { "code": null, "e": 1468, "s": 1457, "text": "Octave-GNU" }, { "code": null, "e": 1489, "s": 1468, "text": "Programming Language" }, { "code": null, "e": 1587, "s": 1489, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1603, "s": 1587, "text": "C# | Data Types" }, { "code": null, "e": 1640, "s": 1603, "text": "Decorators with parameters in Python" }, { "code": null, "e": 1692, "s": 1640, "text": "Difference between Shallow and Deep copy of a class" }, { "code": null, "e": 1726, "s": 1692, "text": "Shallow Copy and Deep Copy in C++" }, { "code": null, "e": 1772, "s": 1726, "text": "Top 10 Programming Languages to Learn in 2022" }, { "code": null, "e": 1785, "s": 1772, "text": "Kotlin Array" }, { "code": null, "e": 1821, "s": 1785, "text": "Advantages and Disadvantages of OOP" }, { "code": null, "e": 1880, "s": 1821, "text": "Difference between while and do-while loop in C, C++, Java" }, { "code": null, "e": 1917, "s": 1880, "text": "Top 10 Fastest Programming Languages" } ]
Python | numpy.putmask() method
03 Oct, 2019 With the help of numpy.putmask() method, we can change the elements in an array with the help of condition and given value by using numpy.putmask() method. Syntax : numpy.putmask(array, condition, value)Return : Return the array having new elements according to value. Example #1 :In this example we can see that by using numpy.putmask() method, we are able to get the new array with the help of a given condition and value. # import numpyimport numpy as np # using numpy.putmask() methodarr = np.array([1, 2, 3, 4, 5, 6])np.putmask(arr, arr % 2 == 0, 0) print(arr) Output : array([1, 0, 3, 0, 5, 0]) Example #2 : # import numpyimport numpy as np # using numpy.putmask() methodarr = np.array([[1, 2, 3], [3, 2, 1], [1, 2, 3]]) np.putmask(arr, arr>2, 4) print(arr) Output : [[1 2 4][4 2 1][1 2 4]] 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 Read a file line by line in Python How to Install PIP on Windows ? Python String | replace() *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Oct, 2019" }, { "code": null, "e": 184, "s": 28, "text": "With the help of numpy.putmask() method, we can change the elements in an array with the help of condition and given value by using numpy.putmask() method." }, { "code": null, "e": 297, "s": 184, "text": "Syntax : numpy.putmask(array, condition, value)Return : Return the array having new elements according to value." }, { "code": null, "e": 453, "s": 297, "text": "Example #1 :In this example we can see that by using numpy.putmask() method, we are able to get the new array with the help of a given condition and value." }, { "code": "# import numpyimport numpy as np # using numpy.putmask() methodarr = np.array([1, 2, 3, 4, 5, 6])np.putmask(arr, arr % 2 == 0, 0) print(arr)", "e": 596, "s": 453, "text": null }, { "code": null, "e": 605, "s": 596, "text": "Output :" }, { "code": null, "e": 631, "s": 605, "text": "array([1, 0, 3, 0, 5, 0])" }, { "code": null, "e": 644, "s": 631, "text": "Example #2 :" }, { "code": "# import numpyimport numpy as np # using numpy.putmask() methodarr = np.array([[1, 2, 3], [3, 2, 1], [1, 2, 3]]) np.putmask(arr, arr>2, 4) print(arr)", "e": 827, "s": 644, "text": null }, { "code": null, "e": 836, "s": 827, "text": "Output :" }, { "code": null, "e": 860, "s": 836, "text": "[[1 2 4][4 2 1][1 2 4]]" }, { "code": null, "e": 873, "s": 860, "text": "Python-numpy" }, { "code": null, "e": 880, "s": 873, "text": "Python" }, { "code": null, "e": 978, "s": 880, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 996, "s": 978, "text": "Python Dictionary" }, { "code": null, "e": 1038, "s": 996, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1073, "s": 1038, "text": "Read a file line by line in Python" }, { "code": null, "e": 1105, "s": 1073, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1131, "s": 1105, "text": "Python String | replace()" }, { "code": null, "e": 1160, "s": 1131, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1187, "s": 1160, "text": "Python Classes and Objects" }, { "code": null, "e": 1208, "s": 1187, "text": "Python OOPs Concepts" }, { "code": null, "e": 1231, "s": 1208, "text": "Introduction To PYTHON" } ]
Get the Hour from timestamp in Pandas
24 Jul, 2020 Let’s see how to extract the hour from a timestamp in Pandas, with the help of multiple examples. Example 1 : pandas.timestamp.now() takes timezone as input and returns current timestamp object of that timezone. # importing the moduleimport pandas as pd # input current timestampdate = pd.Timestamp.now()print("currentTimestamp: ", date) # extract the Hours from the timestampframe = date.hourprint("Hour: ", frame) Output: Example 2 : pandas.timestamp() is used for DateTimeIndex of a specific timezone. It takes year, month, day, time and timezone as input and returns DateTimeIndex of that timezone. # importing the moduleimport pandas as pd # input the timestampdate = pd.Timestamp(year = 2020, month = 7, day = 21, hour = 6, minute = 30, second = 44, tz = 'Asia / Kolkata') print("Timestamp: ", date) # extract the Hours from the timestampprint("Hour: ", date.hour) Output : Example 3 : Take input as range of timestamps using pandas.dt_range() and use pandas.series() to convert into an array of timestamps. # importing the moduleimport pandas as pd # take input Dates in a rangedates = pd.Series(pd.date_range('2019-8-5 10:23:05', periods = 6, freq ='H')) # convert in a dict containerframe = pd.DataFrame(dict(givenDate = dates)) # extract Hours from Timestampframe['hourOfTimestamp'] = frame['givenDate'].dt.hourprint(frame) Output : Solution 4 : Use object.hour attribute to return the hour of the datetime within data of the given Series object. # importing the moduleimport pandas as pd # take inputsdates = pd.Series(['2015-01-11 09:20', '2019-4-8 11:31', '2018-12-22 10:10', '2011-4-2 04:25', '2017-1-6 03:51']) # give a Name to the seriesseriesName = ['T1', 'T2', 'T3', 'T4', 'T5'] # give index to each timestampdates.index = seriesName dates = pd.to_datetime(dates) # extract Hours from Timestamp rs = dates.dt.hour print(rs) Output : Solution 5 : Read timestamp data from a csv file and get Hours from each timestamp. # importing the moduleimport pandas as pd # read the date from xyz.csv fileframe = pd.read_csv(r'xyz.csv')print("Values in xyz.csv: ")print(frame.head()) frame['dateTime'] = frame['dateTime'].astype('datetime64[ns]') # extract Hours from Timestamp print("Hours: ")print(frame.dateTime.dt.hour.head()) Output : Picked Python Pandas-exercise Python Pandas-Timestamp Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Jul, 2020" }, { "code": null, "e": 126, "s": 28, "text": "Let’s see how to extract the hour from a timestamp in Pandas, with the help of multiple examples." }, { "code": null, "e": 240, "s": 126, "text": "Example 1 : pandas.timestamp.now() takes timezone as input and returns current timestamp object of that timezone." }, { "code": "# importing the moduleimport pandas as pd # input current timestampdate = pd.Timestamp.now()print(\"currentTimestamp: \", date) # extract the Hours from the timestampframe = date.hourprint(\"Hour: \", frame)", "e": 446, "s": 240, "text": null }, { "code": null, "e": 454, "s": 446, "text": "Output:" }, { "code": null, "e": 633, "s": 454, "text": "Example 2 : pandas.timestamp() is used for DateTimeIndex of a specific timezone. It takes year, month, day, time and timezone as input and returns DateTimeIndex of that timezone." }, { "code": "# importing the moduleimport pandas as pd # input the timestampdate = pd.Timestamp(year = 2020, month = 7, day = 21, hour = 6, minute = 30, second = 44, tz = 'Asia / Kolkata') print(\"Timestamp: \", date) # extract the Hours from the timestampprint(\"Hour: \", date.hour)", "e": 947, "s": 633, "text": null }, { "code": null, "e": 956, "s": 947, "text": "Output :" }, { "code": null, "e": 1090, "s": 956, "text": "Example 3 : Take input as range of timestamps using pandas.dt_range() and use pandas.series() to convert into an array of timestamps." }, { "code": "# importing the moduleimport pandas as pd # take input Dates in a rangedates = pd.Series(pd.date_range('2019-8-5 10:23:05', periods = 6, freq ='H')) # convert in a dict containerframe = pd.DataFrame(dict(givenDate = dates)) # extract Hours from Timestampframe['hourOfTimestamp'] = frame['givenDate'].dt.hourprint(frame)", "e": 1414, "s": 1090, "text": null }, { "code": null, "e": 1423, "s": 1414, "text": "Output :" }, { "code": null, "e": 1537, "s": 1423, "text": "Solution 4 : Use object.hour attribute to return the hour of the datetime within data of the given Series object." }, { "code": "# importing the moduleimport pandas as pd # take inputsdates = pd.Series(['2015-01-11 09:20', '2019-4-8 11:31', '2018-12-22 10:10', '2011-4-2 04:25', '2017-1-6 03:51']) # give a Name to the seriesseriesName = ['T1', 'T2', 'T3', 'T4', 'T5'] # give index to each timestampdates.index = seriesName dates = pd.to_datetime(dates) # extract Hours from Timestamp rs = dates.dt.hour print(rs)", "e": 1952, "s": 1537, "text": null }, { "code": null, "e": 1961, "s": 1952, "text": "Output :" }, { "code": null, "e": 2045, "s": 1961, "text": "Solution 5 : Read timestamp data from a csv file and get Hours from each timestamp." }, { "code": "# importing the moduleimport pandas as pd # read the date from xyz.csv fileframe = pd.read_csv(r'xyz.csv')print(\"Values in xyz.csv: \")print(frame.head()) frame['dateTime'] = frame['dateTime'].astype('datetime64[ns]') # extract Hours from Timestamp print(\"Hours: \")print(frame.dateTime.dt.hour.head())", "e": 2350, "s": 2045, "text": null }, { "code": null, "e": 2359, "s": 2350, "text": "Output :" }, { "code": null, "e": 2366, "s": 2359, "text": "Picked" }, { "code": null, "e": 2389, "s": 2366, "text": "Python Pandas-exercise" }, { "code": null, "e": 2413, "s": 2389, "text": "Python Pandas-Timestamp" }, { "code": null, "e": 2427, "s": 2413, "text": "Python-pandas" }, { "code": null, "e": 2434, "s": 2427, "text": "Python" } ]
Big Data Engineering — Best Practices | by Kaya Kupferschmidt | Towards Data Science
This is part 1 of a series on data engineering in a big data environment. It will reflect my personal journey of lessons learnt and culminate in the open source tool Flowman I created to take the burden of reimplementing all the boiler plate code over and over again in a couple of projects. Part 1: Big Data Engineering — Best Practices Part 2: Big Data Engineering — Apache Spark Part 3: Big Data Engineering — Declarative Data Flows Part 4: Big Data Engineering — Flowman up and running This series is about building data pipelines with Apache Spark for batch processing. But some aspects are also valid for other frameworks or for stream processing. Eventually I will introduce Flowman, an Apache Spark based application that simplifies the implementation of data pipelines for batch processing. An every growing number of companies and projects build their data processing pipelines using Apache Spark as the central data processing framework. And there are very good reasons to do that (more on those in another part of this series). Apache Spark as being a framework per se does not provide much guidance to follow best practices when designing data pipelines nor does it take care of many details which are not directly part of the data transformation itself but which are important from a broader point of view like schema management and the ability to reprocess data in case of failures or logical errors. Before discussing various aspects to keep in mind while developing data processing pipelines (with whatever technology — although I prefer Apache Spark), let us first have a look what a typical data pipelines actually does. I would say that most data pipelines essentially contain three steps: Extraction. Read data from some source system (be it a shared filesystem like HDFS or in an object store like S3 or some database like MySQL or MongoDB)Transformation. Apply some transformations like data extraction, filtering, joining or even aggregation.Loading. Store the results back again into some target system. Again this can be a shared filesystem, object store or some database. Extraction. Read data from some source system (be it a shared filesystem like HDFS or in an object store like S3 or some database like MySQL or MongoDB) Transformation. Apply some transformations like data extraction, filtering, joining or even aggregation. Loading. Store the results back again into some target system. Again this can be a shared filesystem, object store or some database. Apache Spark well supports all these steps and you can implement a simple data pipeline with a couple of lines of code. Once you have it in production, some questions might arise over time leading to non-functional requirements and best practices. These are not directly implemented by Apache Spark, you have to take care of these yourself. This series is about supporting you with building rock solid data pipelines which also take care of many of those non-functional requirements which are nevertheless really important in production. This first part of the series is about best practices. This refers to specific ways of doing things in order to enable stable operations. The techniques to implement many of them is not revolutionary, but they are not discussed about very often (at least this is my impression). The first requirement is to provide some form of logging. This is not very exciting, and many developers already provide that. But often the question is how verbose the logging should be: Should every detail be logged to the console or only problems? This question is hard to answer, but I prefer to log all important decisions my application makes and to log all important variables and state information that has some influence on the application. You might want to ask yourself: What kind of information would be helpful for most incidents where your application does not work as expected? Typical examples of what I am logging: What are the custom settings for the current run? For example what date range is being processed? What customer is being processed? What data is read? Where is the data stored? How many files? This information helps to validate that the application tries to read from the correct place. Where does the application tries to write its results to? Again this information helps to validate that all settings for the target system are correct. You should also log some sort of a success message at the end — this is invaluable for setting up automated alerts when this message is missing for some longer time. As mentioned in the last item, alerting is also something that you should think of. Most of the time it is desirable to store all logs in a central logging aggregator like Graylog where you can easily search for specific issues and setup alerts. Related to logging there is also the topic metrics. With this term I do not want to refer only to the internal technical metrics of Apache Spark, but also to some metrics with more business relevance. For example it might be interesting to provide metrics about the number of records read and written — both metrics are not directly available in Apache Spark, at least not per data source and data sink. A very important feature that you should plan in from the very beginning are so called reruns. In many batch processing applications, input data is provided in time slices (daily or hourly) and you only want to process the new data. But what happens if something goes wrong? For example what should be done if the input data is incomplete or corrupted? Or if your application contains some logic error and produces wrong results? The very simple answer to this situation is reruns. This term refers to the capability of your application to reprocess old data in case of any issue. But this capability doesn’t come automatically, you have to carefully think about your data management strategy how to organize both your input and our output data to support reruns. There are a couple of aspects required for reruns, which are discussed separately in the next topics. In order to support reruns, you have to think about the data organization. In case of any error, you ideally can simply remove the output of a specific batch run and replace it with the results of a new batch run. This is very easily possible, if you use some simple partitioning mechanism. With partitioning I refer to use subfolders (for file based outputs) or Hive partitions (when you are using Hive) to organize your data which logically belongs to the same output (like a single Hive table). The basic idea is that every batch run should write into a separate partition. For example if you application processes new data coming in every hour, simply create partitions using the data and hour as its identifier. In a file based workflow, the partition is a directory which might look as follows for some imaginary data warehouse containing customer and transaction data /warehouse/shop_db/customer_transactions/hour=2020-09-12T08:00/ Inside the directory, all files are stored from the specific job run for 2020–09–12 08:00 . In case of any error in that batch run, you can simply remove the whole directory and restart the job. If you are using Hive (and I strongly recommend to do so if you are using Spark on top of some shared file system or object store), partitions are a core feature of Hive. Unfortunately Spark doesn’t support writing into a specific partition very well (but that limitation can be worked around). Schema management is a very important topic. This term refers to all project and development tasks about the data input and output format. When you read in the data of some source system, you expect a specific format of the data. This includes both the technical file format (like CSV, JSON or Parquet) and the set of columns and data types used to store the data. I highly recommend two things: Make the expectations about the input schema explicit. This means do not simply let your application infer the correct types.Prepare for change. Too often I was told “that the input schema will never change” — and that assumption always turned out to be wrong. Make the expectations about the input schema explicit. This means do not simply let your application infer the correct types. Prepare for change. Too often I was told “that the input schema will never change” — and that assumption always turned out to be wrong. The first advise improves the robustness of your application since silent schema changes are detected earlier, because the application should report an error if the input data does not match your expected schema any more (some relaxations are allowed and even advisable, more on that below). Many companies even have some lightweight organizational process for negotiating schemas — rightfully in my opinion, since a schema of a data export that is picked up by another application is a technical contract. And both parties (the delivering and the consuming side) should be aware of that by explicitly using the schema for writing and reading. The second advise is the more difficult one, especially combined with a rerun capability. Changing data processing to reflect a new version of the input schema can break the ability to reprocess old data, since it is probably stored using an older version of the schema. This means that you need to think about how your data pipeline can possibly work with different schema versions. A simple solution could be to use an older version of your data pipeline to process older data — but too often this is not a good option, because the older version of the application is missing some important features which should also be applied to older data. So my advise for reruns with different schema versions is to create some sort of super schema that is compatible with all versions of the input data — at least as an internal intermediate representation in your application before any business logic is applied. I also advise to try to negotiate with the source system to only allow compatible changes for new schema versions. Unfortunately the term compatible highly depends on the technology being used, for example Spring has other restrictions for changing types in JSON as Spark. Finally as an even broader concept, some sort of “data ownership” should be available in every project. This term actually refers to two possibly different aspects, where responsibilities should be clear in case of any question or incident that needs some care taking: Phyisical Data Ownership. All data eventually is stored on some system — be it in the cloud or in the on-premise data center or even on the server below my desk (not recommended). There needs to be a team which is responsible for operating this system (yes, even cloud needs some operations), including backups, updates etc. This role is typically owned by the IT operations department.Business Data Ownership. In addition to the physical ownership, each data source also requires a business owner. That person or team is responsible for the kind of data stored, for the data schema and for the interfaces with other systems. This role has to be owned by the team who defines the data that is stored. I always recommend a simple rule: The team who writes the data also owns the data. That also implies that no other team is allowed to write into ones data — except for some interface area for data exchange. Phyisical Data Ownership. All data eventually is stored on some system — be it in the cloud or in the on-premise data center or even on the server below my desk (not recommended). There needs to be a team which is responsible for operating this system (yes, even cloud needs some operations), including backups, updates etc. This role is typically owned by the IT operations department. Business Data Ownership. In addition to the physical ownership, each data source also requires a business owner. That person or team is responsible for the kind of data stored, for the data schema and for the interfaces with other systems. This role has to be owned by the team who defines the data that is stored. I always recommend a simple rule: The team who writes the data also owns the data. That also implies that no other team is allowed to write into ones data — except for some interface area for data exchange. This was part 1 of a series about building robust data pipelines with Apache Spark. You might feel a little bit betrayed, because it didn’t contain any actual code. Nevertheless I think it is important to discuss some concepts first. The next part will focus more on Apache Spark.
[ { "code": null, "e": 339, "s": 47, "text": "This is part 1 of a series on data engineering in a big data environment. It will reflect my personal journey of lessons learnt and culminate in the open source tool Flowman I created to take the burden of reimplementing all the boiler plate code over and over again in a couple of projects." }, { "code": null, "e": 385, "s": 339, "text": "Part 1: Big Data Engineering — Best Practices" }, { "code": null, "e": 429, "s": 385, "text": "Part 2: Big Data Engineering — Apache Spark" }, { "code": null, "e": 483, "s": 429, "text": "Part 3: Big Data Engineering — Declarative Data Flows" }, { "code": null, "e": 537, "s": 483, "text": "Part 4: Big Data Engineering — Flowman up and running" }, { "code": null, "e": 847, "s": 537, "text": "This series is about building data pipelines with Apache Spark for batch processing. But some aspects are also valid for other frameworks or for stream processing. Eventually I will introduce Flowman, an Apache Spark based application that simplifies the implementation of data pipelines for batch processing." }, { "code": null, "e": 1087, "s": 847, "text": "An every growing number of companies and projects build their data processing pipelines using Apache Spark as the central data processing framework. And there are very good reasons to do that (more on those in another part of this series)." }, { "code": null, "e": 1463, "s": 1087, "text": "Apache Spark as being a framework per se does not provide much guidance to follow best practices when designing data pipelines nor does it take care of many details which are not directly part of the data transformation itself but which are important from a broader point of view like schema management and the ability to reprocess data in case of failures or logical errors." }, { "code": null, "e": 1687, "s": 1463, "text": "Before discussing various aspects to keep in mind while developing data processing pipelines (with whatever technology — although I prefer Apache Spark), let us first have a look what a typical data pipelines actually does." }, { "code": null, "e": 1757, "s": 1687, "text": "I would say that most data pipelines essentially contain three steps:" }, { "code": null, "e": 2146, "s": 1757, "text": "Extraction. Read data from some source system (be it a shared filesystem like HDFS or in an object store like S3 or some database like MySQL or MongoDB)Transformation. Apply some transformations like data extraction, filtering, joining or even aggregation.Loading. Store the results back again into some target system. Again this can be a shared filesystem, object store or some database." }, { "code": null, "e": 2299, "s": 2146, "text": "Extraction. Read data from some source system (be it a shared filesystem like HDFS or in an object store like S3 or some database like MySQL or MongoDB)" }, { "code": null, "e": 2404, "s": 2299, "text": "Transformation. Apply some transformations like data extraction, filtering, joining or even aggregation." }, { "code": null, "e": 2537, "s": 2404, "text": "Loading. Store the results back again into some target system. Again this can be a shared filesystem, object store or some database." }, { "code": null, "e": 3075, "s": 2537, "text": "Apache Spark well supports all these steps and you can implement a simple data pipeline with a couple of lines of code. Once you have it in production, some questions might arise over time leading to non-functional requirements and best practices. These are not directly implemented by Apache Spark, you have to take care of these yourself. This series is about supporting you with building rock solid data pipelines which also take care of many of those non-functional requirements which are nevertheless really important in production." }, { "code": null, "e": 3354, "s": 3075, "text": "This first part of the series is about best practices. This refers to specific ways of doing things in order to enable stable operations. The techniques to implement many of them is not revolutionary, but they are not discussed about very often (at least this is my impression)." }, { "code": null, "e": 3605, "s": 3354, "text": "The first requirement is to provide some form of logging. This is not very exciting, and many developers already provide that. But often the question is how verbose the logging should be: Should every detail be logged to the console or only problems?" }, { "code": null, "e": 3947, "s": 3605, "text": "This question is hard to answer, but I prefer to log all important decisions my application makes and to log all important variables and state information that has some influence on the application. You might want to ask yourself: What kind of information would be helpful for most incidents where your application does not work as expected?" }, { "code": null, "e": 3986, "s": 3947, "text": "Typical examples of what I am logging:" }, { "code": null, "e": 4118, "s": 3986, "text": "What are the custom settings for the current run? For example what date range is being processed? What customer is being processed?" }, { "code": null, "e": 4273, "s": 4118, "text": "What data is read? Where is the data stored? How many files? This information helps to validate that the application tries to read from the correct place." }, { "code": null, "e": 4425, "s": 4273, "text": "Where does the application tries to write its results to? Again this information helps to validate that all settings for the target system are correct." }, { "code": null, "e": 4591, "s": 4425, "text": "You should also log some sort of a success message at the end — this is invaluable for setting up automated alerts when this message is missing for some longer time." }, { "code": null, "e": 4837, "s": 4591, "text": "As mentioned in the last item, alerting is also something that you should think of. Most of the time it is desirable to store all logs in a central logging aggregator like Graylog where you can easily search for specific issues and setup alerts." }, { "code": null, "e": 5241, "s": 4837, "text": "Related to logging there is also the topic metrics. With this term I do not want to refer only to the internal technical metrics of Apache Spark, but also to some metrics with more business relevance. For example it might be interesting to provide metrics about the number of records read and written — both metrics are not directly available in Apache Spark, at least not per data source and data sink." }, { "code": null, "e": 5474, "s": 5241, "text": "A very important feature that you should plan in from the very beginning are so called reruns. In many batch processing applications, input data is provided in time slices (daily or hourly) and you only want to process the new data." }, { "code": null, "e": 6005, "s": 5474, "text": "But what happens if something goes wrong? For example what should be done if the input data is incomplete or corrupted? Or if your application contains some logic error and produces wrong results? The very simple answer to this situation is reruns. This term refers to the capability of your application to reprocess old data in case of any issue. But this capability doesn’t come automatically, you have to carefully think about your data management strategy how to organize both your input and our output data to support reruns." }, { "code": null, "e": 6107, "s": 6005, "text": "There are a couple of aspects required for reruns, which are discussed separately in the next topics." }, { "code": null, "e": 6321, "s": 6107, "text": "In order to support reruns, you have to think about the data organization. In case of any error, you ideally can simply remove the output of a specific batch run and replace it with the results of a new batch run." }, { "code": null, "e": 6684, "s": 6321, "text": "This is very easily possible, if you use some simple partitioning mechanism. With partitioning I refer to use subfolders (for file based outputs) or Hive partitions (when you are using Hive) to organize your data which logically belongs to the same output (like a single Hive table). The basic idea is that every batch run should write into a separate partition." }, { "code": null, "e": 6982, "s": 6684, "text": "For example if you application processes new data coming in every hour, simply create partitions using the data and hour as its identifier. In a file based workflow, the partition is a directory which might look as follows for some imaginary data warehouse containing customer and transaction data" }, { "code": null, "e": 7046, "s": 6982, "text": "/warehouse/shop_db/customer_transactions/hour=2020-09-12T08:00/" }, { "code": null, "e": 7241, "s": 7046, "text": "Inside the directory, all files are stored from the specific job run for 2020–09–12 08:00 . In case of any error in that batch run, you can simply remove the whole directory and restart the job." }, { "code": null, "e": 7536, "s": 7241, "text": "If you are using Hive (and I strongly recommend to do so if you are using Spark on top of some shared file system or object store), partitions are a core feature of Hive. Unfortunately Spark doesn’t support writing into a specific partition very well (but that limitation can be worked around)." }, { "code": null, "e": 7675, "s": 7536, "text": "Schema management is a very important topic. This term refers to all project and development tasks about the data input and output format." }, { "code": null, "e": 7932, "s": 7675, "text": "When you read in the data of some source system, you expect a specific format of the data. This includes both the technical file format (like CSV, JSON or Parquet) and the set of columns and data types used to store the data. I highly recommend two things:" }, { "code": null, "e": 8193, "s": 7932, "text": "Make the expectations about the input schema explicit. This means do not simply let your application infer the correct types.Prepare for change. Too often I was told “that the input schema will never change” — and that assumption always turned out to be wrong." }, { "code": null, "e": 8319, "s": 8193, "text": "Make the expectations about the input schema explicit. This means do not simply let your application infer the correct types." }, { "code": null, "e": 8455, "s": 8319, "text": "Prepare for change. Too often I was told “that the input schema will never change” — and that assumption always turned out to be wrong." }, { "code": null, "e": 9099, "s": 8455, "text": "The first advise improves the robustness of your application since silent schema changes are detected earlier, because the application should report an error if the input data does not match your expected schema any more (some relaxations are allowed and even advisable, more on that below). Many companies even have some lightweight organizational process for negotiating schemas — rightfully in my opinion, since a schema of a data export that is picked up by another application is a technical contract. And both parties (the delivering and the consuming side) should be aware of that by explicitly using the schema for writing and reading." }, { "code": null, "e": 9745, "s": 9099, "text": "The second advise is the more difficult one, especially combined with a rerun capability. Changing data processing to reflect a new version of the input schema can break the ability to reprocess old data, since it is probably stored using an older version of the schema. This means that you need to think about how your data pipeline can possibly work with different schema versions. A simple solution could be to use an older version of your data pipeline to process older data — but too often this is not a good option, because the older version of the application is missing some important features which should also be applied to older data." }, { "code": null, "e": 10279, "s": 9745, "text": "So my advise for reruns with different schema versions is to create some sort of super schema that is compatible with all versions of the input data — at least as an internal intermediate representation in your application before any business logic is applied. I also advise to try to negotiate with the source system to only allow compatible changes for new schema versions. Unfortunately the term compatible highly depends on the technology being used, for example Spring has other restrictions for changing types in JSON as Spark." }, { "code": null, "e": 10548, "s": 10279, "text": "Finally as an even broader concept, some sort of “data ownership” should be available in every project. This term actually refers to two possibly different aspects, where responsibilities should be clear in case of any question or incident that needs some care taking:" }, { "code": null, "e": 11456, "s": 10548, "text": "Phyisical Data Ownership. All data eventually is stored on some system — be it in the cloud or in the on-premise data center or even on the server below my desk (not recommended). There needs to be a team which is responsible for operating this system (yes, even cloud needs some operations), including backups, updates etc. This role is typically owned by the IT operations department.Business Data Ownership. In addition to the physical ownership, each data source also requires a business owner. That person or team is responsible for the kind of data stored, for the data schema and for the interfaces with other systems. This role has to be owned by the team who defines the data that is stored. I always recommend a simple rule: The team who writes the data also owns the data. That also implies that no other team is allowed to write into ones data — except for some interface area for data exchange." }, { "code": null, "e": 11843, "s": 11456, "text": "Phyisical Data Ownership. All data eventually is stored on some system — be it in the cloud or in the on-premise data center or even on the server below my desk (not recommended). There needs to be a team which is responsible for operating this system (yes, even cloud needs some operations), including backups, updates etc. This role is typically owned by the IT operations department." }, { "code": null, "e": 12365, "s": 11843, "text": "Business Data Ownership. In addition to the physical ownership, each data source also requires a business owner. That person or team is responsible for the kind of data stored, for the data schema and for the interfaces with other systems. This role has to be owned by the team who defines the data that is stored. I always recommend a simple rule: The team who writes the data also owns the data. That also implies that no other team is allowed to write into ones data — except for some interface area for data exchange." } ]
How to remove duplicate values inside a list in MongoDB?
You can use aggregate framework along with $setUnion operator. Let us first create a collection with documents − > db.removeDuplicatesDemo.insertOne({"InstructorName":"Chris","InstructorAge":34,"InstructorSubject": ["Java","C","Java","C++","MongoDB","MySQL","MongoDB"]}); { "acknowledged" : true, "insertedId" : ObjectId("5cb9d96c895c4fd159f80807") } Following is the query to display all documents from the collection with the help of find() method − > db.removeDuplicatesDemo.find().pretty(); This will produce the following output − { "_id" : ObjectId("5cb9d96c895c4fd159f80807"), "InstructorName" : "Chris", "InstructorAge" : 34, "InstructorSubject" : [ "Java", "C", "Java", "C++", "MongoDB", "MySQL", "MongoDB" ] } Following is the query to remove duplicate values inside a list in MongoDB − > db.removeDuplicatesDemo.aggregate([ ... { "$project": { ... "InstructorName":1, ... "InstructorAge" :1, ... "InstructorSubject" :{ "$setUnion": [ "$InstructorSubject", [] ] } ... }} ... ]).pretty(); This will produce the following output − { "_id" : ObjectId("5cb9d96c895c4fd159f80807"), "InstructorName" : "Chris", "InstructorAge" : 34, "InstructorSubject" : [ "C", "C++", "Java", "MongoDB", "MySQL" ] }
[ { "code": null, "e": 1175, "s": 1062, "text": "You can use aggregate framework along with $setUnion operator. Let us first create a collection with documents −" }, { "code": null, "e": 1422, "s": 1175, "text": "> db.removeDuplicatesDemo.insertOne({\"InstructorName\":\"Chris\",\"InstructorAge\":34,\"InstructorSubject\":\n [\"Java\",\"C\",\"Java\",\"C++\",\"MongoDB\",\"MySQL\",\"MongoDB\"]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cb9d96c895c4fd159f80807\")\n}" }, { "code": null, "e": 1523, "s": 1422, "text": "Following is the query to display all documents from the collection with the help of find() method −" }, { "code": null, "e": 1566, "s": 1523, "text": "> db.removeDuplicatesDemo.find().pretty();" }, { "code": null, "e": 1607, "s": 1566, "text": "This will produce the following output −" }, { "code": null, "e": 1848, "s": 1607, "text": "{\n \"_id\" : ObjectId(\"5cb9d96c895c4fd159f80807\"),\n \"InstructorName\" : \"Chris\",\n \"InstructorAge\" : 34,\n \"InstructorSubject\" : [\n \"Java\",\n \"C\",\n \"Java\",\n \"C++\",\n \"MongoDB\",\n \"MySQL\",\n \"MongoDB\"\n ]\n}" }, { "code": null, "e": 1925, "s": 1848, "text": "Following is the query to remove duplicate values inside a list in MongoDB −" }, { "code": null, "e": 2150, "s": 1925, "text": "> db.removeDuplicatesDemo.aggregate([\n... { \"$project\": {\n... \"InstructorName\":1,\n... \"InstructorAge\" :1,\n... \"InstructorSubject\" :{ \"$setUnion\": [ \"$InstructorSubject\", [] ] }\n... }}\n... ]).pretty();" }, { "code": null, "e": 2191, "s": 2150, "text": "This will produce the following output −" }, { "code": null, "e": 2401, "s": 2191, "text": "{\n \"_id\" : ObjectId(\"5cb9d96c895c4fd159f80807\"),\n \"InstructorName\" : \"Chris\",\n \"InstructorAge\" : 34,\n \"InstructorSubject\" : [\n \"C\",\n \"C++\",\n \"Java\",\n \"MongoDB\",\n \"MySQL\"\n ]\n}" } ]
Maximum Likelihood Estimation (MLE) and the Fisher Information | by Xichu Zhang | Towards Data Science
The number of articles on Medium about MLE is enormous, from theory to implementation in different languages. About the Fisher information, there are also quite a few tutorials. However, the connection between the Fisher information and MLE is rarely mentioned. Therefore, I’d like to contribute one post on this topic. The main idea of MLE is simple. It answers this question: What parameter will most likely make the model produce the sample we have? Formally, we consider a sequence of random variables X1, ..., Xn, such that they are identical independently distributed (iid) random variables. All of them come from the same distribution f(x; Θ), where Θ is a vector of parameters (we use this big theta to denote a vector of parameters, which means Θ ∈ Rp, if the model has only one parameter, we will use θ to denote it in this post) and Θ ∈ Ω, where Ω is the sample space of the parameters. This sounds strange, but in MLE, we pick the parameters from sample space, and we want the most likely one. How do we do this? We maximize a likelihood function, which is defined as The probability of each event can be multiplied together because we know that those observations are independent. In Eq 1.1, each Aj is an event, which can be an interval or a set containing a single point. When there is censoring at a particular value u, the observed event Aj is an interval [u, ∞). Without censoring, Aj contains a single point, and the likelihood of this observation given parameter Θ is not concerning censoring, the likelihood function can be written as which we usually see in textbooks. What do we want to do with L? We want to find out at which value of Θ, L is maximized. For example, if L can be maximized analytically and it is concave, we can calculate the derivative with regard to Θ and let it be zero. At this point, the value of L will be both global and local maximum. Let’s look at an example of multivariate data with normal distribution. consider the random variable X = (X1, X2, ..., Xn), with mean μ = (μ1, μ2, ..., μn); we assume that the standard variance is a constant σ, this property is also known as the homoscedasticity. The likelihood function is therefore The indices look a bit confusing, but think about the fact that each observation is arranged into the columns of the matrix X. Eq 1.3 is actually pretty straightforward. xij is just the ith component in the jth observation. And Eq[ex1] is used to estimate each μi. We know that logarithm can turn production into summation, and usually, the summation is easier to deal with. Therefore, we can try to take the logarithm on both sides of Eq 1.3. (It should be obvious that log refers to the natural logarithm) The rest is easy; we need to do some algebraic manipulation to Eq 1.4. And since σ is a constant, we can factor it out; then we arrive at Remember that we want to maximize L, which is equivalent to maximizing Eq 1.5 since log increases monotonically. And this is boils downing to minimize the following expression If you are familiar with ordinary linear models, this should remind you of the least square method. We can see that the least square method is the same as the MLE under the assumption of normality (the error terms have normal distribution). For the maximum likelihood estimation in practical use, we look at the following example: a dataset of the number of awards earned by students at one high school (available here). If we plot the number of awards awards <- read.csv2(file='data/Awards_R.csv', header=TRUE, sep=',')summary(awards)awards.num <- awards$num_awardsplot(table(awards.num), main='Awards in math', ylab='Frequency', xlab='Number of awards') we can see from the graph that it follows a Poisson distribution The maximum likelihood function of Poisson distribution is defined as We can implement this as follows L=function(x){ a=1 for (i in 1:length(awards.num)){ # Poisson probability mass function a=a*dpois(awards.num[i],x) } return(a)} and optimize this function # find the value for which L is maximizedsol <- optimize(L, c(0,2), maximum=TRUE)curve(L, from=0, to = 2)x1 <- sol$maximumx2 <- sol$objectivepoints(x1, x2, col="#FF0000", pch=19)abline(v=x1, col="#FF0000") The interval on which the maximized value is searched is chosen based on the graph of L (see Fig 1.8). The function is maximized numerically by optimize, which searches for the optimized value in the given interval (with a predetermined precision). This gives us $maximum[1] 0.970013$objective[1] 1.853119e-113 which means the maximum value is 1.853119e-113 and L(0.970013) = 1.853119e-113 — λ = 0.970013 is the optimized parameter. As shown in the graph The result shows that the sample mean and the value which optimizes L is very close mean(awards.num)# --> 0.97# sol$maximum = 0.970013 This makes sense since the parameter λ in Poisson distribution is the same as the expected value. To prove this formally, we can take the derivative of the loglikelihood function setting this derivative to zero, we acquire where λ with hat denotes the estimator. This tells us, in this example, the maximum likelihood estimator is given by the sample mean. Suppose the random variable X comes from a distribution f with parameter Θ The Fisher information measures the amount of information about Θ carried by X. Why is this quantification important? It turns out that in both Bayesian and frequentist approaches of statistics, Fisher information is applied. Bayesians use this to find the initial probability, and frequentists construct the confidence interval in MLE. (To read more about the Bayesian and frequentist approach, see here) A concrete example of the importance of Fisher information is talked about in [2]: The example is tossing a coin ten times in a row, the observation is thus a 10-dimensional array, a possible result looks like X = (1, 1, 1, 1, 1, 0, 0, 0, 0, 0). We want to estimate the probability of getting a head, θ. There are 210 = 1024 possible outcomes of X. We can let another random variable, T be the number of heads in X. T is a function of X, and it is known as a statistic. In some literature, the statistic is described as “a piece of information.” This is true, but to be more precise, it is a function of the observations (the dataset), and it summarizes the data. In this example, T has the binomial distribution, which is given by the probability density function In this example, n = 10. X has 1024 possible outcomes, yet T can take only 11 different values. Does it mean that X contains more information than T? Generally speaking, yes, since X takes the order of the coin tossing into account, but T doesn’t. But with regard to θ, no, since the order of the output of the coin-tossing does not influence θ. Also, the statistic T is sufficient, which means given the value of T, the probability of X taking on a particular value doesn’t depend on θ. This means, the conditional probability distribution P(X | T = t, θ) is uniform and is given by This can also be interpreted in this way: given the value of T, there’s no more information about θ left in X. To quantify the information about the parameter θ in a statistic T and the raw data X, the Fisher information comes into play where Ω denotes sample space. In case of continuous distribution the partial derivative of log f(x|θ) is called the score function. We can see that the Fisher information is the variance of the score function. If there are multiple parameters, we have the Fisher information in matrix form with elements This can also be written as The equivalence between Def 2.4 and Equation 2.5 is not trivial. This is an important property of Fisher information, and we will prove the one-dimensional case (θ is a single parameter) right now: let’s start with the identity: which is just the integration of density function f(x;θ) with θ being the parameter. Note that there is a slight difference between f(x|θ) and f(x;θ). The first one denotes a conditional probability — the probability distribution function is under the condition of a given parameter. Yet, the latter means that θ is the parameter of the function, nothing more. Then we take the derivative with regard to θ on both sides. Now we need to try to make log appear. The trick is as follows In equation 2.7, we use the multiply by one technique (“multiply by one”, “plus zero” — famous tricks in math), which means we multiply by f(x;θ) and then divide by f(x;θ). The combination of the red parts in Equation 2.8 gives us the derivative of the logarithm of f(x;θ). Equation 2.9 gives us another important property of Fisher information — the expectation of Fisher information equals zero. (It’s a side note, this property is not used in this post) Get back to the proof of the equivalence between Def 2.4 and Equation 2.5. We retake the derivative of Eq 2.9, with regard to θ since in Equation 2.10, both the gray and black parts are positive (f(x; θ) is probability measure after all), the only possible scenario is Equation (2.11). Starting from Equation 2.11, we move f(x; θ) from the LHS (left-hand side) to the RHS (right-hand side) Just like in Equation 2.8, in Equation 2.12, the combination of the red parts again gives us the derivative of the logarithm of f(x; θ). And the proof is done. Firstly, we are going to introduce the theorem of the asymptotic distribution of MLE, which tells us the asymptotic distribution of the estimator: Let X1, ..., Xn be a sample of size n from a distribution given by f(x) with unknown parameter θ. Let the true parameter be θ0, and the MLE of θ0 be θhat, then which indicates Since when the sample size approaches infinity, the MLE approaches the true parameter, which is also known as the consistency property of the MLE we can also argue that Equation 2.8 is also true (refer to Equation 2.5). (For proof of this theorem, see here, page 5.) Then we can establish the confidence interval from the following where z is the inverse of the cumulative function, and α is the critical value. The next thing is to find the Fisher information matrix. This is easy since, according to Equation 2,5 and the definition of Hessian, the negative Hessian of the loglikelihood function is the thing we are looking for. You might question why is the Fisher information matrix in Eq 2.5 the same as the Hessian, though it is an expected value? It’s because the function L is evaluated at the maximum likelihood estimation, which means L is evaluated for a particular θ. And this is the θ that maximizes L. Therefore, the weighted average (we know that the expectation is a weighted average) is not necessary anymore — the observed Fisher information is just the second-order differentiation. “Observed” means that the Fisher information is a function of the observed data. (This topic is also discussed on MathStackExchange). And we can find the confidence interval using the following code, using the same dataset. L.log = function(x){ a=1 for (i in 1:length(awards.num)){ # Poisson probability mass function a=a+dpois(awards.num[i],x, log=TRUE) } return(a)}# numerical approachopt.log = optim(par=1, L.log, method="Brent", control=list(fnscale=-1), hessian=TRUE, lower=0, upper=2)opt.logI.log <- opt.log$hessian# since we have only one parameter, there's no inverse of matrix calculatedest.log <- qnorm(1 - alpha/2) / sqrt(n * (-I.log[1,1]))l.est.log <- x1 - est.logh.est.log <- x1 + est.logl.est.logh.est.log# --> CI = [0.9603613, 0.9796647] Summary: In this post, the maximum likelihood estimation is quickly introduced, then we look at the Fisher information along with its matrix form. With those two concepts in mind, we then explore how the confidence interval is constructed. Throughout this post, a single example is used: the number of awards in a high school. The analysis is completely implemented in R. Resources: [1] Altham, P. M. E. (2005). Introduction to Generalized Linear Modelling in R. Statistical laboratory, giugno. [2] Ly, A., Marsman, M., Verhagen, J., Grasman, R. P., & Wagenmakers, E. J. (2017). A tutorial on Fisher information. Journal of Mathematical Psychology, 80, 40–55. [3] Taboga, Marco (2017). “Poisson distribution — Maximum Likelihood Estimation”, Lectures on probability theory and mathematical statistics, Third edition. Kindle Direct Publishing. Online appendix. https://www.statlect.com/fundamentals-of-statistics/Poisson-distribution-maximum-likelihood. [4] Klugman, S. A., Panjer, H. H., & Willmot, G. E. (2012). Loss models: from data to decisions (Vol. 715). John Wiley & Sons. [5] What is censored data? Available at: https://reliability.readthedocs.io/en/latest/What%20is%20censored%20data.html. Accessed on 13 October 2021 Error log adding the explanation of the notation in Eq 1.1 adding the explanation of the notation in Eq 1.1
[ { "code": null, "e": 366, "s": 46, "text": "The number of articles on Medium about MLE is enormous, from theory to implementation in different languages. About the Fisher information, there are also quite a few tutorials. However, the connection between the Fisher information and MLE is rarely mentioned. Therefore, I’d like to contribute one post on this topic." }, { "code": null, "e": 424, "s": 366, "text": "The main idea of MLE is simple. It answers this question:" }, { "code": null, "e": 499, "s": 424, "text": "What parameter will most likely make the model produce the sample we have?" }, { "code": null, "e": 1126, "s": 499, "text": "Formally, we consider a sequence of random variables X1, ..., Xn, such that they are identical independently distributed (iid) random variables. All of them come from the same distribution f(x; Θ), where Θ is a vector of parameters (we use this big theta to denote a vector of parameters, which means Θ ∈ Rp, if the model has only one parameter, we will use θ to denote it in this post) and Θ ∈ Ω, where Ω is the sample space of the parameters. This sounds strange, but in MLE, we pick the parameters from sample space, and we want the most likely one. How do we do this? We maximize a likelihood function, which is defined as" }, { "code": null, "e": 1534, "s": 1126, "text": "The probability of each event can be multiplied together because we know that those observations are independent. In Eq 1.1, each Aj is an event, which can be an interval or a set containing a single point. When there is censoring at a particular value u, the observed event Aj is an interval [u, ∞). Without censoring, Aj contains a single point, and the likelihood of this observation given parameter Θ is" }, { "code": null, "e": 1602, "s": 1534, "text": "not concerning censoring, the likelihood function can be written as" }, { "code": null, "e": 1637, "s": 1602, "text": "which we usually see in textbooks." }, { "code": null, "e": 2001, "s": 1637, "text": "What do we want to do with L? We want to find out at which value of Θ, L is maximized. For example, if L can be maximized analytically and it is concave, we can calculate the derivative with regard to Θ and let it be zero. At this point, the value of L will be both global and local maximum. Let’s look at an example of multivariate data with normal distribution." }, { "code": null, "e": 2230, "s": 2001, "text": "consider the random variable X = (X1, X2, ..., Xn), with mean μ = (μ1, μ2, ..., μn); we assume that the standard variance is a constant σ, this property is also known as the homoscedasticity. The likelihood function is therefore" }, { "code": null, "e": 2674, "s": 2230, "text": "The indices look a bit confusing, but think about the fact that each observation is arranged into the columns of the matrix X. Eq 1.3 is actually pretty straightforward. xij is just the ith component in the jth observation. And Eq[ex1] is used to estimate each μi. We know that logarithm can turn production into summation, and usually, the summation is easier to deal with. Therefore, we can try to take the logarithm on both sides of Eq 1.3." }, { "code": null, "e": 2876, "s": 2674, "text": "(It should be obvious that log refers to the natural logarithm) The rest is easy; we need to do some algebraic manipulation to Eq 1.4. And since σ is a constant, we can factor it out; then we arrive at" }, { "code": null, "e": 3052, "s": 2876, "text": "Remember that we want to maximize L, which is equivalent to maximizing Eq 1.5 since log increases monotonically. And this is boils downing to minimize the following expression" }, { "code": null, "e": 3293, "s": 3052, "text": "If you are familiar with ordinary linear models, this should remind you of the least square method. We can see that the least square method is the same as the MLE under the assumption of normality (the error terms have normal distribution)." }, { "code": null, "e": 3505, "s": 3293, "text": "For the maximum likelihood estimation in practical use, we look at the following example: a dataset of the number of awards earned by students at one high school (available here). If we plot the number of awards" }, { "code": null, "e": 3708, "s": 3505, "text": "awards <- read.csv2(file='data/Awards_R.csv', header=TRUE, sep=',')summary(awards)awards.num <- awards$num_awardsplot(table(awards.num), main='Awards in math', ylab='Frequency', xlab='Number of awards')" }, { "code": null, "e": 3773, "s": 3708, "text": "we can see from the graph that it follows a Poisson distribution" }, { "code": null, "e": 3843, "s": 3773, "text": "The maximum likelihood function of Poisson distribution is defined as" }, { "code": null, "e": 3876, "s": 3843, "text": "We can implement this as follows" }, { "code": null, "e": 4030, "s": 3876, "text": "L=function(x){ a=1 for (i in 1:length(awards.num)){ # Poisson probability mass function a=a*dpois(awards.num[i],x) } return(a)}" }, { "code": null, "e": 4057, "s": 4030, "text": "and optimize this function" }, { "code": null, "e": 4263, "s": 4057, "text": "# find the value for which L is maximizedsol <- optimize(L, c(0,2), maximum=TRUE)curve(L, from=0, to = 2)x1 <- sol$maximumx2 <- sol$objectivepoints(x1, x2, col=\"#FF0000\", pch=19)abline(v=x1, col=\"#FF0000\")" }, { "code": null, "e": 4526, "s": 4263, "text": "The interval on which the maximized value is searched is chosen based on the graph of L (see Fig 1.8). The function is maximized numerically by optimize, which searches for the optimized value in the given interval (with a predetermined precision). This gives us" }, { "code": null, "e": 4574, "s": 4526, "text": "$maximum[1] 0.970013$objective[1] 1.853119e-113" }, { "code": null, "e": 4718, "s": 4574, "text": "which means the maximum value is 1.853119e-113 and L(0.970013) = 1.853119e-113 — λ = 0.970013 is the optimized parameter. As shown in the graph" }, { "code": null, "e": 4802, "s": 4718, "text": "The result shows that the sample mean and the value which optimizes L is very close" }, { "code": null, "e": 4853, "s": 4802, "text": "mean(awards.num)# --> 0.97# sol$maximum = 0.970013" }, { "code": null, "e": 5032, "s": 4853, "text": "This makes sense since the parameter λ in Poisson distribution is the same as the expected value. To prove this formally, we can take the derivative of the loglikelihood function" }, { "code": null, "e": 5076, "s": 5032, "text": "setting this derivative to zero, we acquire" }, { "code": null, "e": 5210, "s": 5076, "text": "where λ with hat denotes the estimator. This tells us, in this example, the maximum likelihood estimator is given by the sample mean." }, { "code": null, "e": 5774, "s": 5210, "text": "Suppose the random variable X comes from a distribution f with parameter Θ The Fisher information measures the amount of information about Θ carried by X. Why is this quantification important? It turns out that in both Bayesian and frequentist approaches of statistics, Fisher information is applied. Bayesians use this to find the initial probability, and frequentists construct the confidence interval in MLE. (To read more about the Bayesian and frequentist approach, see here) A concrete example of the importance of Fisher information is talked about in [2]:" }, { "code": null, "e": 6355, "s": 5774, "text": "The example is tossing a coin ten times in a row, the observation is thus a 10-dimensional array, a possible result looks like X = (1, 1, 1, 1, 1, 0, 0, 0, 0, 0). We want to estimate the probability of getting a head, θ. There are 210 = 1024 possible outcomes of X. We can let another random variable, T be the number of heads in X. T is a function of X, and it is known as a statistic. In some literature, the statistic is described as “a piece of information.” This is true, but to be more precise, it is a function of the observations (the dataset), and it summarizes the data." }, { "code": null, "e": 6456, "s": 6355, "text": "In this example, T has the binomial distribution, which is given by the probability density function" }, { "code": null, "e": 7040, "s": 6456, "text": "In this example, n = 10. X has 1024 possible outcomes, yet T can take only 11 different values. Does it mean that X contains more information than T? Generally speaking, yes, since X takes the order of the coin tossing into account, but T doesn’t. But with regard to θ, no, since the order of the output of the coin-tossing does not influence θ. Also, the statistic T is sufficient, which means given the value of T, the probability of X taking on a particular value doesn’t depend on θ. This means, the conditional probability distribution P(X | T = t, θ) is uniform and is given by" }, { "code": null, "e": 7277, "s": 7040, "text": "This can also be interpreted in this way: given the value of T, there’s no more information about θ left in X. To quantify the information about the parameter θ in a statistic T and the raw data X, the Fisher information comes into play" }, { "code": null, "e": 7342, "s": 7277, "text": "where Ω denotes sample space. In case of continuous distribution" }, { "code": null, "e": 7581, "s": 7342, "text": "the partial derivative of log f(x|θ) is called the score function. We can see that the Fisher information is the variance of the score function. If there are multiple parameters, we have the Fisher information in matrix form with elements" }, { "code": null, "e": 7609, "s": 7581, "text": "This can also be written as" }, { "code": null, "e": 7838, "s": 7609, "text": "The equivalence between Def 2.4 and Equation 2.5 is not trivial. This is an important property of Fisher information, and we will prove the one-dimensional case (θ is a single parameter) right now: let’s start with the identity:" }, { "code": null, "e": 8259, "s": 7838, "text": "which is just the integration of density function f(x;θ) with θ being the parameter. Note that there is a slight difference between f(x|θ) and f(x;θ). The first one denotes a conditional probability — the probability distribution function is under the condition of a given parameter. Yet, the latter means that θ is the parameter of the function, nothing more. Then we take the derivative with regard to θ on both sides." }, { "code": null, "e": 8322, "s": 8259, "text": "Now we need to try to make log appear. The trick is as follows" }, { "code": null, "e": 8596, "s": 8322, "text": "In equation 2.7, we use the multiply by one technique (“multiply by one”, “plus zero” — famous tricks in math), which means we multiply by f(x;θ) and then divide by f(x;θ). The combination of the red parts in Equation 2.8 gives us the derivative of the logarithm of f(x;θ)." }, { "code": null, "e": 8907, "s": 8596, "text": "Equation 2.9 gives us another important property of Fisher information — the expectation of Fisher information equals zero. (It’s a side note, this property is not used in this post) Get back to the proof of the equivalence between Def 2.4 and Equation 2.5. We retake the derivative of Eq 2.9, with regard to θ" }, { "code": null, "e": 9169, "s": 8907, "text": "since in Equation 2.10, both the gray and black parts are positive (f(x; θ) is probability measure after all), the only possible scenario is Equation (2.11). Starting from Equation 2.11, we move f(x; θ) from the LHS (left-hand side) to the RHS (right-hand side)" }, { "code": null, "e": 9306, "s": 9169, "text": "Just like in Equation 2.8, in Equation 2.12, the combination of the red parts again gives us the derivative of the logarithm of f(x; θ)." }, { "code": null, "e": 9329, "s": 9306, "text": "And the proof is done." }, { "code": null, "e": 9476, "s": 9329, "text": "Firstly, we are going to introduce the theorem of the asymptotic distribution of MLE, which tells us the asymptotic distribution of the estimator:" }, { "code": null, "e": 9636, "s": 9476, "text": "Let X1, ..., Xn be a sample of size n from a distribution given by f(x) with unknown parameter θ. Let the true parameter be θ0, and the MLE of θ0 be θhat, then" }, { "code": null, "e": 9652, "s": 9636, "text": "which indicates" }, { "code": null, "e": 9798, "s": 9652, "text": "Since when the sample size approaches infinity, the MLE approaches the true parameter, which is also known as the consistency property of the MLE" }, { "code": null, "e": 9872, "s": 9798, "text": "we can also argue that Equation 2.8 is also true (refer to Equation 2.5)." }, { "code": null, "e": 9984, "s": 9872, "text": "(For proof of this theorem, see here, page 5.) Then we can establish the confidence interval from the following" }, { "code": null, "e": 10282, "s": 9984, "text": "where z is the inverse of the cumulative function, and α is the critical value. The next thing is to find the Fisher information matrix. This is easy since, according to Equation 2,5 and the definition of Hessian, the negative Hessian of the loglikelihood function is the thing we are looking for." }, { "code": null, "e": 10887, "s": 10282, "text": "You might question why is the Fisher information matrix in Eq 2.5 the same as the Hessian, though it is an expected value? It’s because the function L is evaluated at the maximum likelihood estimation, which means L is evaluated for a particular θ. And this is the θ that maximizes L. Therefore, the weighted average (we know that the expectation is a weighted average) is not necessary anymore — the observed Fisher information is just the second-order differentiation. “Observed” means that the Fisher information is a function of the observed data. (This topic is also discussed on MathStackExchange)." }, { "code": null, "e": 10977, "s": 10887, "text": "And we can find the confidence interval using the following code, using the same dataset." }, { "code": null, "e": 11532, "s": 10977, "text": "L.log = function(x){ a=1 for (i in 1:length(awards.num)){ # Poisson probability mass function a=a+dpois(awards.num[i],x, log=TRUE) } return(a)}# numerical approachopt.log = optim(par=1, L.log, method=\"Brent\", control=list(fnscale=-1), hessian=TRUE, lower=0, upper=2)opt.logI.log <- opt.log$hessian# since we have only one parameter, there's no inverse of matrix calculatedest.log <- qnorm(1 - alpha/2) / sqrt(n * (-I.log[1,1]))l.est.log <- x1 - est.logh.est.log <- x1 + est.logl.est.logh.est.log# --> CI = [0.9603613, 0.9796647]" }, { "code": null, "e": 11541, "s": 11532, "text": "Summary:" }, { "code": null, "e": 11904, "s": 11541, "text": "In this post, the maximum likelihood estimation is quickly introduced, then we look at the Fisher information along with its matrix form. With those two concepts in mind, we then explore how the confidence interval is constructed. Throughout this post, a single example is used: the number of awards in a high school. The analysis is completely implemented in R." }, { "code": null, "e": 11915, "s": 11904, "text": "Resources:" }, { "code": null, "e": 12027, "s": 11915, "text": "[1] Altham, P. M. E. (2005). Introduction to Generalized Linear Modelling in R. Statistical laboratory, giugno." }, { "code": null, "e": 12192, "s": 12027, "text": "[2] Ly, A., Marsman, M., Verhagen, J., Grasman, R. P., & Wagenmakers, E. J. (2017). A tutorial on Fisher information. Journal of Mathematical Psychology, 80, 40–55." }, { "code": null, "e": 12485, "s": 12192, "text": "[3] Taboga, Marco (2017). “Poisson distribution — Maximum Likelihood Estimation”, Lectures on probability theory and mathematical statistics, Third edition. Kindle Direct Publishing. Online appendix. https://www.statlect.com/fundamentals-of-statistics/Poisson-distribution-maximum-likelihood." }, { "code": null, "e": 12612, "s": 12485, "text": "[4] Klugman, S. A., Panjer, H. H., & Willmot, G. E. (2012). Loss models: from data to decisions (Vol. 715). John Wiley & Sons." }, { "code": null, "e": 12760, "s": 12612, "text": "[5] What is censored data? Available at: https://reliability.readthedocs.io/en/latest/What%20is%20censored%20data.html. Accessed on 13 October 2021" }, { "code": null, "e": 12770, "s": 12760, "text": "Error log" }, { "code": null, "e": 12819, "s": 12770, "text": "adding the explanation of the notation in Eq 1.1" } ]
Processing large data files with Python multithreading | by Miguel Albrecht | Towards Data Science
We spend a lot of time waiting for some data preparation task to finish —the destiny of data scientists, you would say. Well, we can speed things up. Here are two techniques that will come handy: memory mapped files and multithreading. I had recently to extract terms and term frequencies from the Google Books Ngram corpus and found myself wondering if there are ways to speed up the task. The corpus consists of twenty-six files totalling 24GB of data. Each of the files I was interested in contains a term and other meta data, tab separated. The brute force approach of reading these files as pandas data frames was ... slow. Since we wanted only the unique terms and their match counts, I thought I would try to make it faster :-) This technique is not new. It has been around for a long time and originated in Unix (before Linux!). Briefly, mmap bypasses the usual I/O buffering by loading the contents of a file into pages of memory. This works very well for computers with large memory footprints. That’s mostly OK with today’s desktops and laptops where having 32GB of memory is not anymore in the esoteric department. The Python library mimics most of the Unix functionality and offers a handy readline() function to extract the bytes one line at a time. # map the entire file into memorymm = mmap.mmap(fp.fileno(), 0)# iterate over the block, until next newlinefor line in iter(mm.readline, b""): # convert the bytes to a utf-8 string and split the fields term = line.decode("utf-8").split("\t") The fp is a file-pointer that was previously opened with the r+b access attribute. There you go, with this simple tweak you have made file reading twice as fast (well, the exact improvement will depend on a lot of things such as disk HW, etc). The next technique that always helps in making things faster is adding parallelism. In our case, the task was I/O bound. That is a good fit for scaling-up —i.e. adding threads. You will find good discussions on when it is better to scale-out (multi-processing) on search engines. Python3 has a great standard library for managing a pool of threads and dynamically assign tasks to them. All with an incredibly simple API. # use as many threads as possible, default: os.cpu_count()+4with ThreadPoolExecutor() as threads: t_res = threads.map(process_file, files) The default value of max_workers for ThreadPoolExecutor is 5 threads per CPU core (as of Python v3.8). The map()API will receive a function to be applied to each member of a list and will run the function automatically when threads become available. Wow. That simple. In less than fifty minutes I had converted the 24GB input into a handy 75MB dataset to be analysed with pandas—voilà. The complete code is on GitHub. Comments and remarks are always welcome. PS: I added a progress bar with tqdm for each thread. I really don’t know how they manage to avoid scrambling of the lines on the screen ... It works like a charm. UPDATE: Two years later, this came up :-) No rights reserved by the author.
[ { "code": null, "e": 283, "s": 47, "text": "We spend a lot of time waiting for some data preparation task to finish —the destiny of data scientists, you would say. Well, we can speed things up. Here are two techniques that will come handy: memory mapped files and multithreading." }, { "code": null, "e": 782, "s": 283, "text": "I had recently to extract terms and term frequencies from the Google Books Ngram corpus and found myself wondering if there are ways to speed up the task. The corpus consists of twenty-six files totalling 24GB of data. Each of the files I was interested in contains a term and other meta data, tab separated. The brute force approach of reading these files as pandas data frames was ... slow. Since we wanted only the unique terms and their match counts, I thought I would try to make it faster :-)" }, { "code": null, "e": 1311, "s": 782, "text": "This technique is not new. It has been around for a long time and originated in Unix (before Linux!). Briefly, mmap bypasses the usual I/O buffering by loading the contents of a file into pages of memory. This works very well for computers with large memory footprints. That’s mostly OK with today’s desktops and laptops where having 32GB of memory is not anymore in the esoteric department. The Python library mimics most of the Unix functionality and offers a handy readline() function to extract the bytes one line at a time." }, { "code": null, "e": 1559, "s": 1311, "text": "# map the entire file into memorymm = mmap.mmap(fp.fileno(), 0)# iterate over the block, until next newlinefor line in iter(mm.readline, b\"\"): # convert the bytes to a utf-8 string and split the fields term = line.decode(\"utf-8\").split(\"\\t\")" }, { "code": null, "e": 1803, "s": 1559, "text": "The fp is a file-pointer that was previously opened with the r+b access attribute. There you go, with this simple tweak you have made file reading twice as fast (well, the exact improvement will depend on a lot of things such as disk HW, etc)." }, { "code": null, "e": 2083, "s": 1803, "text": "The next technique that always helps in making things faster is adding parallelism. In our case, the task was I/O bound. That is a good fit for scaling-up —i.e. adding threads. You will find good discussions on when it is better to scale-out (multi-processing) on search engines." }, { "code": null, "e": 2224, "s": 2083, "text": "Python3 has a great standard library for managing a pool of threads and dynamically assign tasks to them. All with an incredibly simple API." }, { "code": null, "e": 2365, "s": 2224, "text": "# use as many threads as possible, default: os.cpu_count()+4with ThreadPoolExecutor() as threads: t_res = threads.map(process_file, files)" }, { "code": null, "e": 2752, "s": 2365, "text": "The default value of max_workers for ThreadPoolExecutor is 5 threads per CPU core (as of Python v3.8). The map()API will receive a function to be applied to each member of a list and will run the function automatically when threads become available. Wow. That simple. In less than fifty minutes I had converted the 24GB input into a handy 75MB dataset to be analysed with pandas—voilà." }, { "code": null, "e": 2825, "s": 2752, "text": "The complete code is on GitHub. Comments and remarks are always welcome." }, { "code": null, "e": 2989, "s": 2825, "text": "PS: I added a progress bar with tqdm for each thread. I really don’t know how they manage to avoid scrambling of the lines on the screen ... It works like a charm." }, { "code": null, "e": 3031, "s": 2989, "text": "UPDATE: Two years later, this came up :-)" }, { "code": null, "e": 3050, "s": 3031, "text": "No rights reserved" } ]
SQL - Quick Guide
SQL is a language to operate databases; it includes database creation, deletion, fetching rows, modifying rows, etc. SQL is an ANSI (American National Standards Institute) standard language, but there are many different versions of the SQL language. SQL is Structured Query Language, which is a computer language for storing, manipulating and retrieving data stored in a relational database. SQL is the standard language for Relational Database System. All the Relational Database Management Systems (RDMS) like MySQL, MS Access, Oracle, Sybase, Informix, Postgres and SQL Server use SQL as their standard database language. Also, they are using different dialects, such as − MS SQL Server using T-SQL, Oracle using PL/SQL, MS Access version of SQL is called JET SQL (native format) etc. SQL is widely popular because it offers the following advantages − Allows users to access data in the relational database management systems. Allows users to access data in the relational database management systems. Allows users to describe the data. Allows users to describe the data. Allows users to define the data in a database and manipulate that data. Allows users to define the data in a database and manipulate that data. Allows to embed within other languages using SQL modules, libraries & pre-compilers. Allows to embed within other languages using SQL modules, libraries & pre-compilers. Allows users to create and drop databases and tables. Allows users to create and drop databases and tables. Allows users to create view, stored procedure, functions in a database. Allows users to create view, stored procedure, functions in a database. Allows users to set permissions on tables, procedures and views. Allows users to set permissions on tables, procedures and views. 1970 − Dr. Edgar F. "Ted" Codd of IBM is known as the father of relational databases. He described a relational model for databases. 1970 − Dr. Edgar F. "Ted" Codd of IBM is known as the father of relational databases. He described a relational model for databases. 1974 − Structured Query Language appeared. 1974 − Structured Query Language appeared. 1978 − IBM worked to develop Codd's ideas and released a product named System/R. 1978 − IBM worked to develop Codd's ideas and released a product named System/R. 1986 − IBM developed the first prototype of relational database and standardized by ANSI. The first relational database was released by Relational Software which later came to be known as Oracle. 1986 − IBM developed the first prototype of relational database and standardized by ANSI. The first relational database was released by Relational Software which later came to be known as Oracle. When you are executing an SQL command for any RDBMS, the system determines the best way to carry out your request and SQL engine figures out how to interpret the task. There are various components included in this process. These components are − Query Dispatcher Optimization Engines Classic Query Engine SQL Query Engine, etc. A classic query engine handles all the non-SQL queries, but a SQL query engine won't handle logical files. Following is a simple diagram showing the SQL Architecture − The standard SQL commands to interact with relational databases are CREATE, SELECT, INSERT, UPDATE, DELETE and DROP. These commands can be classified into the following groups based on their nature − CREATE Creates a new table, a view of a table, or other object in the database. ALTER Modifies an existing database object, such as a table. DROP Deletes an entire table, a view of a table or other objects in the database. SELECT Retrieves certain records from one or more tables. INSERT Creates a record. UPDATE Modifies records. DELETE Deletes records. GRANT Gives a privilege to user. REVOKE Takes back privileges granted from user. RDBMS stands for Relational Database Management System. RDBMS is the basis for SQL, and for all modern database systems like MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access. A Relational database management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced by E. F. Codd. The data in an RDBMS is stored in database objects which are called as tables. This table is basically a collection of related data entries and it consists of numerous columns and rows. Remember, a table is the most common and simplest form of data storage in a relational database. The following program is an example of a CUSTOMERS table − +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ Every table is broken up into smaller entities called fields. The fields in the CUSTOMERS table consist of ID, NAME, AGE, ADDRESS and SALARY. A field is a column in a table that is designed to maintain specific information about every record in the table. A record is also called as a row of data is each individual entry that exists in a table. For example, there are 7 records in the above CUSTOMERS table. Following is a single row of data or record in the CUSTOMERS table − +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | +----+----------+-----+-----------+----------+ A record is a horizontal entity in a table. A column is a vertical entity in a table that contains all information associated with a specific field in a table. For example, a column in the CUSTOMERS table is ADDRESS, which represents location description and would be as shown below − +-----------+ | ADDRESS | +-----------+ | Ahmedabad | | Delhi | | Kota | | Mumbai | | Bhopal | | MP | | Indore | +----+------+ A NULL value in a table is a value in a field that appears to be blank, which means a field with a NULL value is a field with no value. It is very important to understand that a NULL value is different than a zero value or a field that contains spaces. A field with a NULL value is the one that has been left blank during a record creation. Constraints are the rules enforced on data columns on a table. These are used to limit the type of data that can go into a table. This ensures the accuracy and reliability of the data in the database. Constraints can either be column level or table level. Column level constraints are applied only to one column whereas, table level constraints are applied to the entire table. Following are some of the most commonly used constraints available in SQL − NOT NULL Constraint − Ensures that a column cannot have a NULL value. NOT NULL Constraint − Ensures that a column cannot have a NULL value. DEFAULT Constraint − Provides a default value for a column when none is specified. DEFAULT Constraint − Provides a default value for a column when none is specified. UNIQUE Constraint − Ensures that all the values in a column are different. UNIQUE Constraint − Ensures that all the values in a column are different. PRIMARY Key − Uniquely identifies each row/record in a database table. PRIMARY Key − Uniquely identifies each row/record in a database table. FOREIGN Key − Uniquely identifies a row/record in any another database table. FOREIGN Key − Uniquely identifies a row/record in any another database table. CHECK Constraint − The CHECK constraint ensures that all values in a column satisfy certain conditions. CHECK Constraint − The CHECK constraint ensures that all values in a column satisfy certain conditions. INDEX − Used to create and retrieve data from the database very quickly. INDEX − Used to create and retrieve data from the database very quickly. The following categories of data integrity exist with each RDBMS − Entity Integrity − There are no duplicate rows in a table. Entity Integrity − There are no duplicate rows in a table. Domain Integrity − Enforces valid entries for a given column by restricting the type, the format, or the range of values. Domain Integrity − Enforces valid entries for a given column by restricting the type, the format, or the range of values. Referential integrity − Rows cannot be deleted, which are used by other records. Referential integrity − Rows cannot be deleted, which are used by other records. User-Defined Integrity − Enforces some specific business rules that do not fall into entity, domain or referential integrity. User-Defined Integrity − Enforces some specific business rules that do not fall into entity, domain or referential integrity. Database normalization is the process of efficiently organizing data in a database. There are two reasons of this normalization process − Eliminating redundant data, for example, storing the same data in more than one table. Eliminating redundant data, for example, storing the same data in more than one table. Ensuring data dependencies make sense. Ensuring data dependencies make sense. Both these reasons are worthy goals as they reduce the amount of space a database consumes and ensures that data is logically stored. Normalization consists of a series of guidelines that help guide you in creating a good database structure. Normalization guidelines are divided into normal forms; think of a form as the format or the way a database structure is laid out. The aim of normal forms is to organize the database structure, so that it complies with the rules of first normal form, then second normal form and finally the third normal form. It is your choice to take it further and go to the fourth normal form, fifth normal form and so on, but in general, the third normal form is more than enough. First Normal Form (1NF) Second Normal Form (2NF) Third Normal Form (3NF) There are many popular RDBMS available to work with. This tutorial gives a brief overview of some of the most popular RDBMS’s. This would help you to compare their basic features. MySQL is an open source SQL database, which is developed by a Swedish company – MySQL AB. MySQL is pronounced as "my ess-que-ell," in contrast with SQL, pronounced "sequel." MySQL is supporting many different platforms including Microsoft Windows, the major Linux distributions, UNIX, and Mac OS X. MySQL has free and paid versions, depending on its usage (non-commercial/commercial) and features. MySQL comes with a very fast, multi-threaded, multi-user and robust SQL database server. Development of MySQL by Michael Widenius & David Axmark beginning in 1994. Development of MySQL by Michael Widenius & David Axmark beginning in 1994. First internal release on 23rd May 1995. First internal release on 23rd May 1995. Windows Version was released on the 8th January 1998 for Windows 95 and NT. Windows Version was released on the 8th January 1998 for Windows 95 and NT. Version 3.23: beta from June 2000, production release January 2001. Version 3.23: beta from June 2000, production release January 2001. Version 4.0: beta from August 2002, production release March 2003 (unions). Version 4.0: beta from August 2002, production release March 2003 (unions). Version 4.1: beta from June 2004, production release October 2004. Version 4.1: beta from June 2004, production release October 2004. Version 5.0: beta from March 2005, production release October 2005. Version 5.0: beta from March 2005, production release October 2005. Sun Microsystems acquired MySQL AB on the 26th February 2008. Sun Microsystems acquired MySQL AB on the 26th February 2008. Version 5.1: production release 27th November 2008. Version 5.1: production release 27th November 2008. High Performance. High Availability. Scalability and Flexibility Run anything. Robust Transactional Support. Web and Data Warehouse Strengths. Strong Data Protection. Comprehensive Application Development. Management Ease. Open Source Freedom and 24 x 7 Support. Lowest Total Cost of Ownership. MS SQL Server is a Relational Database Management System developed by Microsoft Inc. Its primary query languages are − T-SQL ANSI SQL 1987 - Sybase releases SQL Server for UNIX. 1987 - Sybase releases SQL Server for UNIX. 1988 - Microsoft, Sybase, and Aston-Tate port SQL Server to OS/2. 1988 - Microsoft, Sybase, and Aston-Tate port SQL Server to OS/2. 1989 - Microsoft, Sybase, and Aston-Tate release SQL Server 1.0 for OS/2. 1989 - Microsoft, Sybase, and Aston-Tate release SQL Server 1.0 for OS/2. 1990 - SQL Server 1.1 is released with support for Windows 3.0 clients. 1990 - SQL Server 1.1 is released with support for Windows 3.0 clients. Aston - Tate drops out of SQL Server development. Aston - Tate drops out of SQL Server development. 2000 - Microsoft releases SQL Server 2000. 2000 - Microsoft releases SQL Server 2000. 2001 - Microsoft releases XML for SQL Server Web Release 1 (download). 2001 - Microsoft releases XML for SQL Server Web Release 1 (download). 2002 - Microsoft releases SQLXML 2.0 (renamed from XML for SQL Server). 2002 - Microsoft releases SQLXML 2.0 (renamed from XML for SQL Server). 2002 - Microsoft releases SQLXML 3.0. 2002 - Microsoft releases SQLXML 3.0. 2005 - Microsoft releases SQL Server 2005 on November 7th, 2005. 2005 - Microsoft releases SQL Server 2005 on November 7th, 2005. High Performance High Availability Database mirroring Database snapshots CLR integration Service Broker DDL triggers Ranking functions Row version-based isolation levels XML integration TRY...CATCH Database Mail It is a very large multi-user based database management system. Oracle is a relational database management system developed by 'Oracle Corporation'. Oracle works to efficiently manage its resources, a database of information among the multiple clients requesting and sending data in the network. It is an excellent database server choice for client/server computing. Oracle supports all major operating systems for both clients and servers, including MSDOS, NetWare, UnixWare, OS/2 and most UNIX flavors. Oracle began in 1977 and celebrating its 32 wonderful years in the industry (from 1977 to 2009). 1977 - Larry Ellison, Bob Miner and Ed Oates founded Software Development Laboratories to undertake development work. 1977 - Larry Ellison, Bob Miner and Ed Oates founded Software Development Laboratories to undertake development work. 1979 - Version 2.0 of Oracle was released and it became first commercial relational database and first SQL database. The company changed its name to Relational Software Inc. (RSI). 1979 - Version 2.0 of Oracle was released and it became first commercial relational database and first SQL database. The company changed its name to Relational Software Inc. (RSI). 1981 - RSI started developing tools for Oracle. 1981 - RSI started developing tools for Oracle. 1982 - RSI was renamed to Oracle Corporation. 1982 - RSI was renamed to Oracle Corporation. 1983 - Oracle released version 3.0, rewritten in C language and ran on multiple platforms. 1983 - Oracle released version 3.0, rewritten in C language and ran on multiple platforms. 1984 - Oracle version 4.0 was released. It contained features like concurrency control - multi-version read consistency, etc. 1984 - Oracle version 4.0 was released. It contained features like concurrency control - multi-version read consistency, etc. 1985 - Oracle version 4.0 was released. It contained features like concurrency control - multi-version read consistency, etc. 1985 - Oracle version 4.0 was released. It contained features like concurrency control - multi-version read consistency, etc. 2007 - Oracle released Oracle11g. The new version focused on better partitioning, easy migration, etc. 2007 - Oracle released Oracle11g. The new version focused on better partitioning, easy migration, etc. Concurrency Read Consistency Locking Mechanisms Quiesce Database Portability Self-managing database SQL*Plus ASM Scheduler Resource Manager Data Warehousing Materialized views Bitmap indexes Table compression Parallel Execution Analytic SQL Data mining Partitioning This is one of the most popular Microsoft products. Microsoft Access is an entry-level database management software. MS Access database is not only inexpensive but also a powerful database for small-scale projects. MS Access uses the Jet database engine, which utilizes a specific SQL language dialect (sometimes referred to as Jet SQL). MS Access comes with the professional edition of MS Office package. MS Access has easyto-use intuitive graphical interface. 1992 - Access version 1.0 was released. 1992 - Access version 1.0 was released. 1993 - Access 1.1 released to improve compatibility with inclusion the Access Basic programming language. 1993 - Access 1.1 released to improve compatibility with inclusion the Access Basic programming language. The most significant transition was from Access 97 to Access 2000. The most significant transition was from Access 97 to Access 2000. 2007 - Access 2007, a new database format was introduced ACCDB which supports complex data types such as multi valued and attachment fields. 2007 - Access 2007, a new database format was introduced ACCDB which supports complex data types such as multi valued and attachment fields. Users can create tables, queries, forms and reports and connect them together with macros. Users can create tables, queries, forms and reports and connect them together with macros. Option of importing and exporting the data to many formats including Excel, Outlook, ASCII, dBase, Paradox, FoxPro, SQL Server, Oracle, ODBC, etc. Option of importing and exporting the data to many formats including Excel, Outlook, ASCII, dBase, Paradox, FoxPro, SQL Server, Oracle, ODBC, etc. There is also the Jet Database format (MDB or ACCDB in Access 2007), which can contain the application and data in one file. This makes it very convenient to distribute the entire application to another user, who can run it in disconnected environments. There is also the Jet Database format (MDB or ACCDB in Access 2007), which can contain the application and data in one file. This makes it very convenient to distribute the entire application to another user, who can run it in disconnected environments. Microsoft Access offers parameterized queries. These queries and Access tables can be referenced from other programs like VB6 and .NET through DAO or ADO. Microsoft Access offers parameterized queries. These queries and Access tables can be referenced from other programs like VB6 and .NET through DAO or ADO. The desktop editions of Microsoft SQL Server can be used with Access as an alternative to the Jet Database Engine. The desktop editions of Microsoft SQL Server can be used with Access as an alternative to the Jet Database Engine. Microsoft Access is a file server-based database. Unlike the client-server relational database management systems (RDBMS), Microsoft Access does not implement database triggers, stored procedures or transaction logging. Microsoft Access is a file server-based database. Unlike the client-server relational database management systems (RDBMS), Microsoft Access does not implement database triggers, stored procedures or transaction logging. SQL is followed by a unique set of rules and guidelines called Syntax. This tutorial gives you a quick start with SQL by listing all the basic SQL Syntax. All the SQL statements start with any of the keywords like SELECT, INSERT, UPDATE, DELETE, ALTER, DROP, CREATE, USE, SHOW and all the statements end with a semicolon (;). The most important point to be noted here is that SQL is case insensitive, which means SELECT and select have same meaning in SQL statements. Whereas, MySQL makes difference in table names. So, if you are working with MySQL, then you need to give table names as they exist in the database. SELECT column1, column2....columnN FROM table_name; SELECT DISTINCT column1, column2....columnN FROM table_name; SELECT column1, column2....columnN FROM table_name WHERE CONDITION; SELECT column1, column2....columnN FROM table_name WHERE CONDITION-1 {AND|OR} CONDITION-2; SELECT column1, column2....columnN FROM table_name WHERE column_name IN (val-1, val-2,...val-N); SELECT column1, column2....columnN FROM table_name WHERE column_name BETWEEN val-1 AND val-2; SELECT column1, column2....columnN FROM table_name WHERE column_name LIKE { PATTERN }; SELECT column1, column2....columnN FROM table_name WHERE CONDITION ORDER BY column_name {ASC|DESC}; SELECT SUM(column_name) FROM table_name WHERE CONDITION GROUP BY column_name; SELECT COUNT(column_name) FROM table_name WHERE CONDITION; SELECT SUM(column_name) FROM table_name WHERE CONDITION GROUP BY column_name HAVING (arithematic function condition); CREATE TABLE table_name( column1 datatype, column2 datatype, column3 datatype, ..... columnN datatype, PRIMARY KEY( one or more columns ) ); DROP TABLE table_name; CREATE UNIQUE INDEX index_name ON table_name ( column1, column2,...columnN); ALTER TABLE table_name DROP INDEX index_name; DESC table_name; TRUNCATE TABLE table_name; ALTER TABLE table_name {ADD|DROP|MODIFY} column_name {data_ype}; ALTER TABLE table_name RENAME TO new_table_name; INSERT INTO table_name( column1, column2....columnN) VALUES ( value1, value2....valueN); UPDATE table_name SET column1 = value1, column2 = value2....columnN=valueN [ WHERE CONDITION ]; DELETE FROM table_name WHERE {CONDITION}; CREATE DATABASE database_name; DROP DATABASE database_name; USE database_name; COMMIT; ROLLBACK; SQL Data Type is an attribute that specifies the type of data of any object. Each column, variable and expression has a related data type in SQL. You can use these data types while creating your tables. You can choose a data type for a table column based on your requirement. SQL Server offers six categories of data types for your use which are listed below − Note − Here, datetime has 3.33 milliseconds accuracy where as smalldatetime has 1 minute accuracy. char Maximum length of 8,000 characters.( Fixed length non-Unicode characters) varchar Maximum of 8,000 characters.(Variable-length non-Unicode data). varchar(max) Maximum length of 2E + 31 characters, Variable-length non-Unicode data (SQL Server 2005 only). text Variable-length non-Unicode data with a maximum length of 2,147,483,647 characters. nchar Maximum length of 4,000 characters.( Fixed length Unicode) nvarchar Maximum length of 4,000 characters.(Variable length Unicode) nvarchar(max) Maximum length of 2E + 31 characters (SQL Server 2005 only).( Variable length Unicode) ntext Maximum length of 1,073,741,823 characters. ( Variable length Unicode ) binary Maximum length of 8,000 bytes(Fixed-length binary data ) varbinary Maximum length of 8,000 bytes.(Variable length binary data) varbinary(max) Maximum length of 2E + 31 bytes (SQL Server 2005 only). ( Variable length Binary data) image Maximum length of 2,147,483,647 bytes. ( Variable length Binary Data) sql_variant Stores values of various SQL Server-supported data types, except text, ntext, and timestamp. timestamp Stores a database-wide unique number that gets updated every time a row gets updated uniqueidentifier Stores a globally unique identifier (GUID) xml Stores XML data. You can store xml instances in a column or a variable (SQL Server 2005 only). cursor Reference to a cursor object table Stores a result set for later processing An operator is a reserved word or a character used primarily in an SQL statement's WHERE clause to perform operation(s), such as comparisons and arithmetic operations. These Operators are used to specify conditions in an SQL statement and to serve as conjunctions for multiple conditions in a statement. Arithmetic operators Comparison operators Logical operators Operators used to negate conditions Assume 'variable a' holds 10 and 'variable b' holds 20, then − Show Examples Assume 'variable a' holds 10 and 'variable b' holds 20, then − Show Examples Here is a list of all the logical operators available in SQL. Show Examples ALL The ALL operator is used to compare a value to all values in another value set. AND The AND operator allows the existence of multiple conditions in an SQL statement's WHERE clause. ANY The ANY operator is used to compare a value to any applicable value in the list as per the condition. BETWEEN The BETWEEN operator is used to search for values that are within a set of values, given the minimum value and the maximum value. EXISTS The EXISTS operator is used to search for the presence of a row in a specified table that meets a certain criterion. IN The IN operator is used to compare a value to a list of literal values that have been specified. LIKE The LIKE operator is used to compare a value to similar values using wildcard operators. NOT The NOT operator reverses the meaning of the logical operator with which it is used. Eg: NOT EXISTS, NOT BETWEEN, NOT IN, etc. This is a negate operator. OR The OR operator is used to combine multiple conditions in an SQL statement's WHERE clause. IS NULL The NULL operator is used to compare a value with a NULL value. UNIQUE The UNIQUE operator searches every row of a specified table for uniqueness (no duplicates). An expression is a combination of one or more values, operators and SQL functions that evaluate to a value. These SQL EXPRESSIONs are like formulae and they are written in query language. You can also use them to query the database for a specific set of data. Consider the basic syntax of the SELECT statement as follows − SELECT column1, column2, columnN FROM table_name WHERE [CONDITION|EXPRESSION]; There are different types of SQL expressions, which are mentioned below − Boolean Numeric Date Let us now discuss each of these in detail. SQL Boolean Expressions fetch the data based on matching a single value. Following is the syntax − SELECT column1, column2, columnN FROM table_name WHERE SINGLE VALUE MATCHING EXPRESSION; Consider the CUSTOMERS table having the following records − SQL> SELECT * FROM CUSTOMERS; +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ 7 rows in set (0.00 sec) The following table is a simple example showing the usage of various SQL Boolean Expressions − SQL> SELECT * FROM CUSTOMERS WHERE SALARY = 10000; +----+-------+-----+---------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+-------+-----+---------+----------+ | 7 | Muffy | 24 | Indore | 10000.00 | +----+-------+-----+---------+----------+ 1 row in set (0.00 sec) These expressions are used to perform any mathematical operation in any query. Following is the syntax − SELECT numerical_expression as OPERATION_NAME [FROM table_name WHERE CONDITION] ; Here, the numerical_expression is used for a mathematical expression or any formula. Following is a simple example showing the usage of SQL Numeric Expressions − SQL> SELECT (15 + 6) AS ADDITION +----------+ | ADDITION | +----------+ | 21 | +----------+ 1 row in set (0.00 sec) There are several built-in functions like avg(), sum(), count(), etc., to perform what is known as the aggregate data calculations against a table or a specific table column. SQL> SELECT COUNT(*) AS "RECORDS" FROM CUSTOMERS; +---------+ | RECORDS | +---------+ | 7 | +---------+ 1 row in set (0.00 sec) Date Expressions return current system date and time values − SQL> SELECT CURRENT_TIMESTAMP; +---------------------+ | Current_Timestamp | +---------------------+ | 2009-11-12 06:40:23 | +---------------------+ 1 row in set (0.00 sec) Another date expression is as shown below − SQL> SELECT GETDATE();; +-------------------------+ | GETDATE | +-------------------------+ | 2009-10-22 12:07:18.140 | +-------------------------+ 1 row in set (0.00 sec) The SQL CREATE DATABASE statement is used to create a new SQL database. The basic syntax of this CREATE DATABASE statement is as follows − CREATE DATABASE DatabaseName; Always the database name should be unique within the RDBMS. If you want to create a new database <testDB>, then the CREATE DATABASE statement would be as shown below − SQL> CREATE DATABASE testDB; Make sure you have the admin privilege before creating any database. Once a database is created, you can check it in the list of databases as follows − SQL> SHOW DATABASES; +--------------------+ | Database | +--------------------+ | information_schema | | AMROOD | | TUTORIALSPOINT | | mysql | | orig | | test | | testDB | +--------------------+ 7 rows in set (0.00 sec) The SQL DROP DATABASE statement is used to drop an existing database in SQL schema. The basic syntax of DROP DATABASE statement is as follows − DROP DATABASE DatabaseName; Always the database name should be unique within the RDBMS. If you want to delete an existing database <testDB>, then the DROP DATABASE statement would be as shown below − SQL> DROP DATABASE testDB; NOTE − Be careful before using this operation because by deleting an existing database would result in loss of complete information stored in the database. Make sure you have the admin privilege before dropping any database. Once a database is dropped, you can check it in the list of the databases as shown below − SQL> SHOW DATABASES; +--------------------+ | Database | +--------------------+ | information_schema | | AMROOD | | TUTORIALSPOINT | | mysql | | orig | | test | +--------------------+ 6 rows in set (0.00 sec) When you have multiple databases in your SQL Schema, then before starting your operation, you would need to select a database where all the operations would be performed. The SQL USE statement is used to select any existing database in the SQL schema. The basic syntax of the USE statement is as shown below − USE DatabaseName; Always the database name should be unique within the RDBMS. You can check the available databases as shown below − SQL> SHOW DATABASES; +--------------------+ | Database | +--------------------+ | information_schema | | AMROOD | | TUTORIALSPOINT | | mysql | | orig | | test | +--------------------+ 6 rows in set (0.00 sec) Now, if you want to work with the AMROOD database, then you can execute the following SQL command and start working with the AMROOD database. SQL> USE AMROOD; Creating a basic table involves naming the table and defining its columns and each column's data type. The SQL CREATE TABLE statement is used to create a new table. The basic syntax of the CREATE TABLE statement is as follows − CREATE TABLE table_name( column1 datatype, column2 datatype, column3 datatype, ..... columnN datatype, PRIMARY KEY( one or more columns ) ); CREATE TABLE is the keyword telling the database system what you want to do. In this case, you want to create a new table. The unique name or identifier for the table follows the CREATE TABLE statement. Then in brackets comes the list defining each column in the table and what sort of data type it is. The syntax becomes clearer with the following example. A copy of an existing table can be created using a combination of the CREATE TABLE statement and the SELECT statement. You can check the complete details at Create Table Using another Table. The following code block is an example, which creates a CUSTOMERS table with an ID as a primary key and NOT NULL are the constraints showing that these fields cannot be NULL while creating records in this table − SQL> CREATE TABLE CUSTOMERS( ID INT NOT NULL, NAME VARCHAR (20) NOT NULL, AGE INT NOT NULL, ADDRESS CHAR (25) , SALARY DECIMAL (18, 2), PRIMARY KEY (ID) ); You can verify if your table has been created successfully by looking at the message displayed by the SQL server, otherwise you can use the DESC command as follows − SQL> DESC CUSTOMERS; +---------+---------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +---------+---------------+------+-----+---------+-------+ | ID | int(11) | NO | PRI | | | | NAME | varchar(20) | NO | | | | | AGE | int(11) | NO | | | | | ADDRESS | char(25) | YES | | NULL | | | SALARY | decimal(18,2) | YES | | NULL | | +---------+---------------+------+-----+---------+-------+ 5 rows in set (0.00 sec) Now, you have CUSTOMERS table available in your database which you can use to store the required information related to customers. The SQL DROP TABLE statement is used to remove a table definition and all the data, indexes, triggers, constraints and permission specifications for that table. NOTE − You should be very careful while using this command because once a table is deleted then all the information available in that table will also be lost forever. The basic syntax of this DROP TABLE statement is as follows − DROP TABLE table_name; Let us first verify the CUSTOMERS table and then we will delete it from the database as shown below − SQL> DESC CUSTOMERS; +---------+---------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +---------+---------------+------+-----+---------+-------+ | ID | int(11) | NO | PRI | | | | NAME | varchar(20) | NO | | | | | AGE | int(11) | NO | | | | | ADDRESS | char(25) | YES | | NULL | | | SALARY | decimal(18,2) | YES | | NULL | | +---------+---------------+------+-----+---------+-------+ 5 rows in set (0.00 sec) This means that the CUSTOMERS table is available in the database, so let us now drop it as shown below. SQL> DROP TABLE CUSTOMERS; Query OK, 0 rows affected (0.01 sec) Now, if you would try the DESC command, then you will get the following error − SQL> DESC CUSTOMERS; ERROR 1146 (42S02): Table 'TEST.CUSTOMERS' doesn't exist Here, TEST is the database name which we are using for our examples. The SQL INSERT INTO Statement is used to add new rows of data to a table in the database. There are two basic syntaxes of the INSERT INTO statement which are shown below. INSERT INTO TABLE_NAME (column1, column2, column3,...columnN) VALUES (value1, value2, value3,...valueN); Here, column1, column2, column3,...columnN are the names of the columns in the table into which you want to insert the data. You may not need to specify the column(s) name in the SQL query if you are adding values for all the columns of the table. But make sure the order of the values is in the same order as the columns in the table. The SQL INSERT INTO syntax will be as follows − INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN); The following statements would create six records in the CUSTOMERS table. INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 ); INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (2, 'Khilan', 25, 'Delhi', 1500.00 ); INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (3, 'kaushik', 23, 'Kota', 2000.00 ); INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (4, 'Chaitali', 25, 'Mumbai', 6500.00 ); INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (5, 'Hardik', 27, 'Bhopal', 8500.00 ); INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (6, 'Komal', 22, 'MP', 4500.00 ); You can create a record in the CUSTOMERS table by using the second syntax as shown below. INSERT INTO CUSTOMERS VALUES (7, 'Muffy', 24, 'Indore', 10000.00 ); All the above statements would produce the following records in the CUSTOMERS table as shown below. +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ You can populate the data into a table through the select statement over another table; provided the other table has a set of fields, which are required to populate the first table. Here is the syntax − INSERT INTO first_table_name [(column1, column2, ... columnN)] SELECT column1, column2, ...columnN FROM second_table_name [WHERE condition]; The SQL SELECT statement is used to fetch the data from a database table which returns this data in the form of a result table. These result tables are called result-sets. The basic syntax of the SELECT statement is as follows − SELECT column1, column2, columnN FROM table_name; Here, column1, column2... are the fields of a table whose values you want to fetch. If you want to fetch all the fields available in the field, then you can use the following syntax. SELECT * FROM table_name; Consider the CUSTOMERS table having the following records − +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ The following code is an example, which would fetch the ID, Name and Salary fields of the customers available in CUSTOMERS table. SQL> SELECT ID, NAME, SALARY FROM CUSTOMERS; This would produce the following result − +----+----------+----------+ | ID | NAME | SALARY | +----+----------+----------+ | 1 | Ramesh | 2000.00 | | 2 | Khilan | 1500.00 | | 3 | kaushik | 2000.00 | | 4 | Chaitali | 6500.00 | | 5 | Hardik | 8500.00 | | 6 | Komal | 4500.00 | | 7 | Muffy | 10000.00 | +----+----------+----------+ If you want to fetch all the fields of the CUSTOMERS table, then you should use the following query. SQL> SELECT * FROM CUSTOMERS; This would produce the result as shown below. +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ The SQL WHERE clause is used to specify a condition while fetching the data from a single table or by joining with multiple tables. If the given condition is satisfied, then only it returns a specific value from the table. You should use the WHERE clause to filter the records and fetching only the necessary records. The WHERE clause is not only used in the SELECT statement, but it is also used in the UPDATE, DELETE statement, etc., which we would examine in the subsequent chapters. The basic syntax of the SELECT statement with the WHERE clause is as shown below. SELECT column1, column2, columnN FROM table_name WHERE [condition] You can specify a condition using the comparison or logical operators like >, <, =, LIKE, NOT, etc. The following examples would make this concept clear. Consider the CUSTOMERS table having the following records − +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ The following code is an example which would fetch the ID, Name and Salary fields from the CUSTOMERS table, where the salary is greater than 2000 − SQL> SELECT ID, NAME, SALARY FROM CUSTOMERS WHERE SALARY > 2000; This would produce the following result − +----+----------+----------+ | ID | NAME | SALARY | +----+----------+----------+ | 4 | Chaitali | 6500.00 | | 5 | Hardik | 8500.00 | | 6 | Komal | 4500.00 | | 7 | Muffy | 10000.00 | +----+----------+----------+ The following query is an example, which would fetch the ID, Name and Salary fields from the CUSTOMERS table for a customer with the name Hardik. SQL> SELECT ID, NAME, SALARY FROM CUSTOMERS WHERE NAME = 'Hardik'; This would produce the following result − +----+----------+----------+ | ID | NAME | SALARY | +----+----------+----------+ | 5 | Hardik | 8500.00 | +----+----------+----------+ The SQL AND & OR operators are used to combine multiple conditions to narrow data in an SQL statement. These two operators are called as the conjunctive operators. These operators provide a means to make multiple comparisons with different operators in the same SQL statement. The AND operator allows the existence of multiple conditions in an SQL statement's WHERE clause. The basic syntax of the AND operator with a WHERE clause is as follows − SELECT column1, column2, columnN FROM table_name WHERE [condition1] AND [condition2]...AND [conditionN]; You can combine N number of conditions using the AND operator. For an action to be taken by the SQL statement, whether it be a transaction or a query, all conditions separated by the AND must be TRUE. Consider the CUSTOMERS table having the following records − +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ Following is an example, which would fetch the ID, Name and Salary fields from the CUSTOMERS table, where the salary is greater than 2000 and the age is less than 25 years − SQL> SELECT ID, NAME, SALARY FROM CUSTOMERS WHERE SALARY > 2000 AND age < 25; This would produce the following result − +----+-------+----------+ | ID | NAME | SALARY | +----+-------+----------+ | 6 | Komal | 4500.00 | | 7 | Muffy | 10000.00 | +----+-------+----------+ The OR operator is used to combine multiple conditions in an SQL statement's WHERE clause. The basic syntax of the OR operator with a WHERE clause is as follows − SELECT column1, column2, columnN FROM table_name WHERE [condition1] OR [condition2]...OR [conditionN] You can combine N number of conditions using the OR operator. For an action to be taken by the SQL statement, whether it be a transaction or query, the only any ONE of the conditions separated by the OR must be TRUE. Consider the CUSTOMERS table having the following records − +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ The following code block hasa query, which would fetch the ID, Name and Salary fields from the CUSTOMERS table, where the salary is greater than 2000 OR the age is less than 25 years. SQL> SELECT ID, NAME, SALARY FROM CUSTOMERS WHERE SALARY > 2000 OR age < 25; This would produce the following result − +----+----------+----------+ | ID | NAME | SALARY | +----+----------+----------+ | 3 | kaushik | 2000.00 | | 4 | Chaitali | 6500.00 | | 5 | Hardik | 8500.00 | | 6 | Komal | 4500.00 | | 7 | Muffy | 10000.00 | +----+----------+----------+ The SQL UPDATE Query is used to modify the existing records in a table. You can use the WHERE clause with the UPDATE query to update the selected rows, otherwise all the rows would be affected. The basic syntax of the UPDATE query with a WHERE clause is as follows − UPDATE table_name SET column1 = value1, column2 = value2...., columnN = valueN WHERE [condition]; You can combine N number of conditions using the AND or the OR operators. Consider the CUSTOMERS table having the following records − +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ The following query will update the ADDRESS for a customer whose ID number is 6 in the table. SQL> UPDATE CUSTOMERS SET ADDRESS = 'Pune' WHERE ID = 6; Now, the CUSTOMERS table would have the following records − +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | Pune | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ If you want to modify all the ADDRESS and the SALARY column values in the CUSTOMERS table, you do not need to use the WHERE clause as the UPDATE query would be enough as shown in the following code block. SQL> UPDATE CUSTOMERS SET ADDRESS = 'Pune', SALARY = 1000.00; Now, CUSTOMERS table would have the following records − +----+----------+-----+---------+---------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+---------+---------+ | 1 | Ramesh | 32 | Pune | 1000.00 | | 2 | Khilan | 25 | Pune | 1000.00 | | 3 | kaushik | 23 | Pune | 1000.00 | | 4 | Chaitali | 25 | Pune | 1000.00 | | 5 | Hardik | 27 | Pune | 1000.00 | | 6 | Komal | 22 | Pune | 1000.00 | | 7 | Muffy | 24 | Pune | 1000.00 | +----+----------+-----+---------+---------+ The SQL DELETE Query is used to delete the existing records from a table. You can use the WHERE clause with a DELETE query to delete the selected rows, otherwise all the records would be deleted. The basic syntax of the DELETE query with the WHERE clause is as follows − DELETE FROM table_name WHERE [condition]; You can combine N number of conditions using AND or OR operators. Consider the CUSTOMERS table having the following records − +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ The following code has a query, which will DELETE a customer, whose ID is 6. SQL> DELETE FROM CUSTOMERS WHERE ID = 6; Now, the CUSTOMERS table would have the following records. +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ If you want to DELETE all the records from the CUSTOMERS table, you do not need to use the WHERE clause and the DELETE query would be as follows − SQL> DELETE FROM CUSTOMERS; Now, the CUSTOMERS table would not have any record. The SQL LIKE clause is used to compare a value to similar values using wildcard operators. There are two wildcards used in conjunction with the LIKE operator. The percent sign (%) The underscore (_) The percent sign represents zero, one or multiple characters. The underscore represents a single number or character. These symbols can be used in combinations. The basic syntax of % and _ is as follows − SELECT FROM table_name WHERE column LIKE 'XXXX%' or SELECT FROM table_name WHERE column LIKE '%XXXX%' or SELECT FROM table_name WHERE column LIKE 'XXXX_' or SELECT FROM table_name WHERE column LIKE '_XXXX' or SELECT FROM table_name WHERE column LIKE '_XXXX_' You can combine N number of conditions using AND or OR operators. Here, XXXX could be any numeric or string value. The following table has a few examples showing the WHERE part having different LIKE clause with '%' and '_' operators − WHERE SALARY LIKE '200%' Finds any values that start with 200. WHERE SALARY LIKE '%200%' Finds any values that have 200 in any position. WHERE SALARY LIKE '_00%' Finds any values that have 00 in the second and third positions. WHERE SALARY LIKE '2_%_%' Finds any values that start with 2 and are at least 3 characters in length. WHERE SALARY LIKE '%2' Finds any values that end with 2. WHERE SALARY LIKE '_2%3' Finds any values that have a 2 in the second position and end with a 3. WHERE SALARY LIKE '2___3' Finds any values in a five-digit number that start with 2 and end with 3. Let us take a real example, consider the CUSTOMERS table having the records as shown below. +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ Following is an example, which would display all the records from the CUSTOMERS table, where the SALARY starts with 200. SQL> SELECT * FROM CUSTOMERS WHERE SALARY LIKE '200%'; This would produce the following result − +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 3 | kaushik | 23 | Kota | 2000.00 | +----+----------+-----+-----------+----------+ The SQL TOP clause is used to fetch a TOP N number or X percent records from a table. Note − All the databases do not support the TOP clause. For example MySQL supports the LIMIT clause to fetch limited number of records while Oracle uses the ROWNUM command to fetch a limited number of records. The basic syntax of the TOP clause with a SELECT statement would be as follows. SELECT TOP number|percent column_name(s) FROM table_name WHERE [condition] Consider the CUSTOMERS table having the following records − +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ The following query is an example on the SQL server, which would fetch the top 3 records from the CUSTOMERS table. SQL> SELECT TOP 3 * FROM CUSTOMERS; This would produce the following result − +----+---------+-----+-----------+---------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+---------+-----+-----------+---------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | +----+---------+-----+-----------+---------+ If you are using MySQL server, then here is an equivalent example − SQL> SELECT * FROM CUSTOMERS LIMIT 3; This would produce the following result − +----+---------+-----+-----------+---------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+---------+-----+-----------+---------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | +----+---------+-----+-----------+---------+ If you are using an Oracle server, then the following code block has an equivalent example. SQL> SELECT * FROM CUSTOMERS WHERE ROWNUM <= 3; This would produce the following result − +----+---------+-----+-----------+---------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+---------+-----+-----------+---------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | +----+---------+-----+-----------+---------+ The SQL ORDER BY clause is used to sort the data in ascending or descending order, based on one or more columns. Some databases sort the query results in an ascending order by default. The basic syntax of the ORDER BY clause is as follows − SELECT column-list FROM table_name [WHERE condition] [ORDER BY column1, column2, .. columnN] [ASC | DESC]; You can use more than one column in the ORDER BY clause. Make sure whatever column you are using to sort that column should be in the column-list. Consider the CUSTOMERS table having the following records − +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ The following code block has an example, which would sort the result in an ascending order by the NAME and the SALARY − SQL> SELECT * FROM CUSTOMERS ORDER BY NAME, SALARY; This would produce the following result − +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | +----+----------+-----+-----------+----------+ The following code block has an example, which would sort the result in the descending order by NAME. SQL> SELECT * FROM CUSTOMERS ORDER BY NAME DESC; This would produce the following result − +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 7 | Muffy | 24 | Indore | 10000.00 | | 6 | Komal | 22 | MP | 4500.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | +----+----------+-----+-----------+----------+ The SQL GROUP BY clause is used in collaboration with the SELECT statement to arrange identical data into groups. This GROUP BY clause follows the WHERE clause in a SELECT statement and precedes the ORDER BY clause. The basic syntax of a GROUP BY clause is shown in the following code block. The GROUP BY clause must follow the conditions in the WHERE clause and must precede the ORDER BY clause if one is used. SELECT column1, column2 FROM table_name WHERE [ conditions ] GROUP BY column1, column2 ORDER BY column1, column2 Consider the CUSTOMERS table is having the following records − +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ If you want to know the total amount of the salary on each customer, then the GROUP BY query would be as follows. SQL> SELECT NAME, SUM(SALARY) FROM CUSTOMERS GROUP BY NAME; This would produce the following result − +----------+-------------+ | NAME | SUM(SALARY) | +----------+-------------+ | Chaitali | 6500.00 | | Hardik | 8500.00 | | kaushik | 2000.00 | | Khilan | 1500.00 | | Komal | 4500.00 | | Muffy | 10000.00 | | Ramesh | 2000.00 | +----------+-------------+ Now, let us look at a table where the CUSTOMERS table has the following records with duplicate names − +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Ramesh | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | kaushik | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ Now again, if you want to know the total amount of salary on each customer, then the GROUP BY query would be as follows − SQL> SELECT NAME, SUM(SALARY) FROM CUSTOMERS GROUP BY NAME; This would produce the following result − +---------+-------------+ | NAME | SUM(SALARY) | +---------+-------------+ | Hardik | 8500.00 | | kaushik | 8500.00 | | Komal | 4500.00 | | Muffy | 10000.00 | | Ramesh | 3500.00 | +---------+-------------+ The SQL DISTINCT keyword is used in conjunction with the SELECT statement to eliminate all the duplicate records and fetching only unique records. There may be a situation when you have multiple duplicate records in a table. While fetching such records, it makes more sense to fetch only those unique records instead of fetching duplicate records. The basic syntax of DISTINCT keyword to eliminate the duplicate records is as follows − SELECT DISTINCT column1, column2,.....columnN FROM table_name WHERE [condition] Consider the CUSTOMERS table having the following records − +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ First, let us see how the following SELECT query returns the duplicate salary records. SQL> SELECT SALARY FROM CUSTOMERS ORDER BY SALARY; This would produce the following result, where the salary (2000) is coming twice which is a duplicate record from the original table. +----------+ | SALARY | +----------+ | 1500.00 | | 2000.00 | | 2000.00 | | 4500.00 | | 6500.00 | | 8500.00 | | 10000.00 | +----------+ Now, let us use the DISTINCT keyword with the above SELECT query and then see the result. SQL> SELECT DISTINCT SALARY FROM CUSTOMERS ORDER BY SALARY; This would produce the following result where we do not have any duplicate entry. +----------+ | SALARY | +----------+ | 1500.00 | | 2000.00 | | 4500.00 | | 6500.00 | | 8500.00 | | 10000.00 | +----------+ The SQL ORDER BY clause is used to sort the data in ascending or descending order, based on one or more columns. Some databases sort the query results in an ascending order by default. The basic syntax of the ORDER BY clause which would be used to sort the result in an ascending or descending order is as follows − SELECT column-list FROM table_name [WHERE condition] [ORDER BY column1, column2, .. columnN] [ASC | DESC]; You can use more than one column in the ORDER BY clause. Make sure that whatever column you are using to sort, that column should be in the column-list. Consider the CUSTOMERS table having the following records − +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ Following is an example, which would sort the result in an ascending order by NAME and SALARY. SQL> SELECT * FROM CUSTOMERS ORDER BY NAME, SALARY; This would produce the following result − +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | +----+----------+-----+-----------+----------+ The following code block has an example, which would sort the result in a descending order by NAME. SQL> SELECT * FROM CUSTOMERS ORDER BY NAME DESC; This would produce the following result − +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 7 | Muffy | 24 | Indore | 10000.00 | | 6 | Komal | 22 | MP | 4500.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | +----+----------+-----+-----------+----------+ To fetch the rows with their own preferred order, the SELECT query used would be as follows − SQL> SELECT * FROM CUSTOMERS ORDER BY (CASE ADDRESS WHEN 'DELHI' THEN 1 WHEN 'BHOPAL' THEN 2 WHEN 'KOTA' THEN 3 WHEN 'AHMEDABAD' THEN 4 WHEN 'MP' THEN 5 ELSE 100 END) ASC, ADDRESS DESC; This would produce the following result − +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 2 | Khilan | 25 | Delhi | 1500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 6 | Komal | 22 | MP | 4500.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | +----+----------+-----+-----------+----------+ This will sort the customers by ADDRESS in your ownoOrder of preference first and in a natural order for the remaining addresses. Also, the remaining Addresses will be sorted in the reverse alphabetical order. Constraints are the rules enforced on the data columns of a table. These are used to limit the type of data that can go into a table. This ensures the accuracy and reliability of the data in the database. Constraints could be either on a column level or a table level. The column level constraints are applied only to one column, whereas the table level constraints are applied to the whole table. Following are some of the most commonly used constraints available in SQL. These constraints have already been discussed in SQL - RDBMS Concepts chapter, but it’s worth to revise them at this point. NOT NULL Constraint − Ensures that a column cannot have NULL value. NOT NULL Constraint − Ensures that a column cannot have NULL value. DEFAULT Constraint − Provides a default value for a column when none is specified. DEFAULT Constraint − Provides a default value for a column when none is specified. UNIQUE Constraint − Ensures that all values in a column are different. UNIQUE Constraint − Ensures that all values in a column are different. PRIMARY Key − Uniquely identifies each row/record in a database table. PRIMARY Key − Uniquely identifies each row/record in a database table. FOREIGN Key − Uniquely identifies a row/record in any of the given database table. FOREIGN Key − Uniquely identifies a row/record in any of the given database table. CHECK Constraint − The CHECK constraint ensures that all the values in a column satisfies certain conditions. CHECK Constraint − The CHECK constraint ensures that all the values in a column satisfies certain conditions. INDEX − Used to create and retrieve data from the database very quickly. INDEX − Used to create and retrieve data from the database very quickly. Constraints can be specified when a table is created with the CREATE TABLE statement or you can use the ALTER TABLE statement to create constraints even after the table is created. Any constraint that you have defined can be dropped using the ALTER TABLE command with the DROP CONSTRAINT option. For example, to drop the primary key constraint in the EMPLOYEES table, you can use the following command. ALTER TABLE EMPLOYEES DROP CONSTRAINT EMPLOYEES_PK; Some implementations may provide shortcuts for dropping certain constraints. For example, to drop the primary key constraint for a table in Oracle, you can use the following command. ALTER TABLE EMPLOYEES DROP PRIMARY KEY; Some implementations allow you to disable constraints. Instead of permanently dropping a constraint from the database, you may want to temporarily disable the constraint and then enable it later. Integrity constraints are used to ensure accuracy and consistency of the data in a relational database. Data integrity is handled in a relational database through the concept of referential integrity. There are many types of integrity constraints that play a role in Referential Integrity (RI). These constraints include Primary Key, Foreign Key, Unique Constraints and other constraints which are mentioned above. The SQL Joins clause is used to combine records from two or more tables in a database. A JOIN is a means for combining fields from two tables by using values common to each. Consider the following two tables − Table 1 − CUSTOMERS Table +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ Table 2 − ORDERS Table +-----+---------------------+-------------+--------+ |OID | DATE | CUSTOMER_ID | AMOUNT | +-----+---------------------+-------------+--------+ | 102 | 2009-10-08 00:00:00 | 3 | 3000 | | 100 | 2009-10-08 00:00:00 | 3 | 1500 | | 101 | 2009-11-20 00:00:00 | 2 | 1560 | | 103 | 2008-05-20 00:00:00 | 4 | 2060 | +-----+---------------------+-------------+--------+ Now, let us join these two tables in our SELECT statement as shown below. SQL> SELECT ID, NAME, AGE, AMOUNT FROM CUSTOMERS, ORDERS WHERE CUSTOMERS.ID = ORDERS.CUSTOMER_ID; This would produce the following result. +----+----------+-----+--------+ | ID | NAME | AGE | AMOUNT | +----+----------+-----+--------+ | 3 | kaushik | 23 | 3000 | | 3 | kaushik | 23 | 1500 | | 2 | Khilan | 25 | 1560 | | 4 | Chaitali | 25 | 2060 | +----+----------+-----+--------+ Here, it is noticeable that the join is performed in the WHERE clause. Several operators can be used to join tables, such as =, <, >, <>, <=, >=, !=, BETWEEN, LIKE, and NOT; they can all be used to join tables. However, the most common operator is the equal to symbol. There are different types of joins available in SQL − INNER JOIN − returns rows when there is a match in both tables. INNER JOIN − returns rows when there is a match in both tables. LEFT JOIN − returns all rows from the left table, even if there are no matches in the right table. LEFT JOIN − returns all rows from the left table, even if there are no matches in the right table. RIGHT JOIN − returns all rows from the right table, even if there are no matches in the left table. RIGHT JOIN − returns all rows from the right table, even if there are no matches in the left table. FULL JOIN − returns rows when there is a match in one of the tables. FULL JOIN − returns rows when there is a match in one of the tables. SELF JOIN − is used to join a table to itself as if the table were two tables, temporarily renaming at least one table in the SQL statement. SELF JOIN − is used to join a table to itself as if the table were two tables, temporarily renaming at least one table in the SQL statement. CARTESIAN JOIN − returns the Cartesian product of the sets of records from the two or more joined tables. CARTESIAN JOIN − returns the Cartesian product of the sets of records from the two or more joined tables. Let us now discuss each of these joins in detail. The SQL UNION clause/operator is used to combine the results of two or more SELECT statements without returning any duplicate rows. To use this UNION clause, each SELECT statement must have The same number of columns selected The same number of column expressions The same data type and Have them in the same order But they need not have to be in the same length. The basic syntax of a UNION clause is as follows − SELECT column1 [, column2 ] FROM table1 [, table2 ] [WHERE condition] UNION SELECT column1 [, column2 ] FROM table1 [, table2 ] [WHERE condition] Here, the given condition could be any given expression based on your requirement. Consider the following two tables. Table 1 − CUSTOMERS Table is as follows. +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ Table 2 − ORDERS Table is as follows. +-----+---------------------+-------------+--------+ |OID | DATE | CUSTOMER_ID | AMOUNT | +-----+---------------------+-------------+--------+ | 102 | 2009-10-08 00:00:00 | 3 | 3000 | | 100 | 2009-10-08 00:00:00 | 3 | 1500 | | 101 | 2009-11-20 00:00:00 | 2 | 1560 | | 103 | 2008-05-20 00:00:00 | 4 | 2060 | +-----+---------------------+-------------+--------+ Now, let us join these two tables in our SELECT statement as follows − SQL> SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS LEFT JOIN ORDERS ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID UNION SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS RIGHT JOIN ORDERS ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID; This would produce the following result − +------+----------+--------+---------------------+ | ID | NAME | AMOUNT | DATE | +------+----------+--------+---------------------+ | 1 | Ramesh | NULL | NULL | | 2 | Khilan | 1560 | 2009-11-20 00:00:00 | | 3 | kaushik | 3000 | 2009-10-08 00:00:00 | | 3 | kaushik | 1500 | 2009-10-08 00:00:00 | | 4 | Chaitali | 2060 | 2008-05-20 00:00:00 | | 5 | Hardik | NULL | NULL | | 6 | Komal | NULL | NULL | | 7 | Muffy | NULL | NULL | +------+----------+--------+---------------------+ The UNION ALL operator is used to combine the results of two SELECT statements including duplicate rows. The same rules that apply to the UNION clause will apply to the UNION ALL operator. The basic syntax of the UNION ALL is as follows. SELECT column1 [, column2 ] FROM table1 [, table2 ] [WHERE condition] UNION ALL SELECT column1 [, column2 ] FROM table1 [, table2 ] [WHERE condition] Here, the given condition could be any given expression based on your requirement. Consider the following two tables, Table 1 − CUSTOMERS Table is as follows. +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ Table 2 − ORDERS table is as follows. +-----+---------------------+-------------+--------+ |OID | DATE | CUSTOMER_ID | AMOUNT | +-----+---------------------+-------------+--------+ | 102 | 2009-10-08 00:00:00 | 3 | 3000 | | 100 | 2009-10-08 00:00:00 | 3 | 1500 | | 101 | 2009-11-20 00:00:00 | 2 | 1560 | | 103 | 2008-05-20 00:00:00 | 4 | 2060 | +-----+---------------------+-------------+--------+ Now, let us join these two tables in our SELECT statement as follows − SQL> SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS LEFT JOIN ORDERS ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID UNION ALL SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS RIGHT JOIN ORDERS ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID; This would produce the following result − +------+----------+--------+---------------------+ | ID | NAME | AMOUNT | DATE | +------+----------+--------+---------------------+ | 1 | Ramesh | NULL | NULL | | 2 | Khilan | 1560 | 2009-11-20 00:00:00 | | 3 | kaushik | 3000 | 2009-10-08 00:00:00 | | 3 | kaushik | 1500 | 2009-10-08 00:00:00 | | 4 | Chaitali | 2060 | 2008-05-20 00:00:00 | | 5 | Hardik | NULL | NULL | | 6 | Komal | NULL | NULL | | 7 | Muffy | NULL | NULL | | 3 | kaushik | 3000 | 2009-10-08 00:00:00 | | 3 | kaushik | 1500 | 2009-10-08 00:00:00 | | 2 | Khilan | 1560 | 2009-11-20 00:00:00 | | 4 | Chaitali | 2060 | 2008-05-20 00:00:00 | +------+----------+--------+---------------------+ There are two other clauses (i.e., operators), which are like the UNION clause. SQL INTERSECT Clause − This is used to combine two SELECT statements, but returns rows only from the first SELECT statement that are identical to a row in the second SELECT statement. SQL INTERSECT Clause − This is used to combine two SELECT statements, but returns rows only from the first SELECT statement that are identical to a row in the second SELECT statement. SQL EXCEPT Clause − This combines two SELECT statements and returns rows from the first SELECT statement that are not returned by the second SELECT statement. SQL EXCEPT Clause − This combines two SELECT statements and returns rows from the first SELECT statement that are not returned by the second SELECT statement. The SQL NULL is the term used to represent a missing value. A NULL value in a table is a value in a field that appears to be blank. A field with a NULL value is a field with no value. It is very important to understand that a NULL value is different than a zero value or a field that contains spaces. The basic syntax of NULL while creating a table. SQL> CREATE TABLE CUSTOMERS( ID INT NOT NULL, NAME VARCHAR (20) NOT NULL, AGE INT NOT NULL, ADDRESS CHAR (25) , SALARY DECIMAL (18, 2), PRIMARY KEY (ID) ); Here, NOT NULL signifies that column should always accept an explicit value of the given data type. There are two columns where we did not use NOT NULL, which means these columns could be NULL. A field with a NULL value is the one that has been left blank during the record creation. The NULL value can cause problems when selecting data. However, because when comparing an unknown value to any other value, the result is always unknown and not included in the results. You must use the IS NULL or IS NOT NULL operators to check for a NULL value. Consider the following CUSTOMERS table having the records as shown below. +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | | | 7 | Muffy | 24 | Indore | | +----+----------+-----+-----------+----------+ Now, following is the usage of the IS NOT NULLoperator. SQL> SELECT ID, NAME, AGE, ADDRESS, SALARY FROM CUSTOMERS WHERE SALARY IS NOT NULL; This would produce the following result − +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | +----+----------+-----+-----------+----------+ Now, following is the usage of the IS NULL operator. SQL> SELECT ID, NAME, AGE, ADDRESS, SALARY FROM CUSTOMERS WHERE SALARY IS NULL; This would produce the following result − +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 6 | Komal | 22 | MP | | | 7 | Muffy | 24 | Indore | | +----+----------+-----+-----------+----------+ You can rename a table or a column temporarily by giving another name known as Alias. The use of table aliases is to rename a table in a specific SQL statement. The renaming is a temporary change and the actual table name does not change in the database. The column aliases are used to rename a table's columns for the purpose of a particular SQL query. The basic syntax of a table alias is as follows. SELECT column1, column2.... FROM table_name AS alias_name WHERE [condition]; The basic syntax of a column alias is as follows. SELECT column_name AS alias_name FROM table_name WHERE [condition]; Consider the following two tables. Table 1 − CUSTOMERS Table is as follows. +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ Table 2 − ORDERS Table is as follows. +-----+---------------------+-------------+--------+ |OID | DATE | CUSTOMER_ID | AMOUNT | +-----+---------------------+-------------+--------+ | 102 | 2009-10-08 00:00:00 | 3 | 3000 | | 100 | 2009-10-08 00:00:00 | 3 | 1500 | | 101 | 2009-11-20 00:00:00 | 2 | 1560 | | 103 | 2008-05-20 00:00:00 | 4 | 2060 | +-----+---------------------+-------------+--------+ Now, the following code block shows the usage of a table alias. SQL> SELECT C.ID, C.NAME, C.AGE, O.AMOUNT FROM CUSTOMERS AS C, ORDERS AS O WHERE C.ID = O.CUSTOMER_ID; This would produce the following result. +----+----------+-----+--------+ | ID | NAME | AGE | AMOUNT | +----+----------+-----+--------+ | 3 | kaushik | 23 | 3000 | | 3 | kaushik | 23 | 1500 | | 2 | Khilan | 25 | 1560 | | 4 | Chaitali | 25 | 2060 | +----+----------+-----+--------+ Following is the usage of a column alias. SQL> SELECT ID AS CUSTOMER_ID, NAME AS CUSTOMER_NAME FROM CUSTOMERS WHERE SALARY IS NOT NULL; This would produce the following result. +-------------+---------------+ | CUSTOMER_ID | CUSTOMER_NAME | +-------------+---------------+ | 1 | Ramesh | | 2 | Khilan | | 3 | kaushik | | 4 | Chaitali | | 5 | Hardik | | 6 | Komal | | 7 | Muffy | +-------------+---------------+ Indexes are special lookup tables that the database search engine can use to speed up data retrieval. Simply put, an index is a pointer to data in a table. An index in a database is very similar to an index in the back of a book. For example, if you want to reference all pages in a book that discusses a certain topic, you first refer to the index, which lists all the topics alphabetically and are then referred to one or more specific page numbers. An index helps to speed up SELECT queries and WHERE clauses, but it slows down data input, with the UPDATE and the INSERT statements. Indexes can be created or dropped with no effect on the data. Creating an index involves the CREATE INDEX statement, which allows you to name the index, to specify the table and which column or columns to index, and to indicate whether the index is in an ascending or descending order. Indexes can also be unique, like the UNIQUE constraint, in that the index prevents duplicate entries in the column or combination of columns on which there is an index. The basic syntax of a CREATE INDEX is as follows. CREATE INDEX index_name ON table_name; A single-column index is created based on only one table column. The basic syntax is as follows. CREATE INDEX index_name ON table_name (column_name); Unique indexes are used not only for performance, but also for data integrity. A unique index does not allow any duplicate values to be inserted into the table. The basic syntax is as follows. CREATE UNIQUE INDEX index_name on table_name (column_name); A composite index is an index on two or more columns of a table. Its basic syntax is as follows. CREATE INDEX index_name on table_name (column1, column2); Whether to create a single-column index or a composite index, take into consideration the column(s) that you may use very frequently in a query's WHERE clause as filter conditions. Should there be only one column used, a single-column index should be the choice. Should there be two or more columns that are frequently used in the WHERE clause as filters, the composite index would be the best choice. Implicit indexes are indexes that are automatically created by the database server when an object is created. Indexes are automatically created for primary key constraints and unique constraints. An index can be dropped using SQL DROP command. Care should be taken when dropping an index because the performance may either slow down or improve. The basic syntax is as follows − DROP INDEX index_name; You can check the INDEX Constraint chapter to see some actual examples on Indexes. Although indexes are intended to enhance a database's performance, there are times when they should be avoided. The following guidelines indicate when the use of an index should be reconsidered. Indexes should not be used on small tables. Indexes should not be used on small tables. Tables that have frequent, large batch updates or insert operations. Tables that have frequent, large batch updates or insert operations. Indexes should not be used on columns that contain a high number of NULL values. Indexes should not be used on columns that contain a high number of NULL values. Columns that are frequently manipulated should not be indexed. Columns that are frequently manipulated should not be indexed. The SQL ALTER TABLE command is used to add, delete or modify columns in an existing table. You should also use the ALTER TABLE command to add and drop various constraints on an existing table. The basic syntax of an ALTER TABLE command to add a New Column in an existing table is as follows. ALTER TABLE table_name ADD column_name datatype; The basic syntax of an ALTER TABLE command to DROP COLUMN in an existing table is as follows. ALTER TABLE table_name DROP COLUMN column_name; The basic syntax of an ALTER TABLE command to change the DATA TYPE of a column in a table is as follows. ALTER TABLE table_name MODIFY COLUMN column_name datatype; The basic syntax of an ALTER TABLE command to add a NOT NULL constraint to a column in a table is as follows. ALTER TABLE table_name MODIFY column_name datatype NOT NULL; The basic syntax of ALTER TABLE to ADD UNIQUE CONSTRAINT to a table is as follows. ALTER TABLE table_name ADD CONSTRAINT MyUniqueConstraint UNIQUE(column1, column2...); The basic syntax of an ALTER TABLE command to ADD CHECK CONSTRAINT to a table is as follows. ALTER TABLE table_name ADD CONSTRAINT MyUniqueConstraint CHECK (CONDITION); The basic syntax of an ALTER TABLE command to ADD PRIMARY KEY constraint to a table is as follows. ALTER TABLE table_name ADD CONSTRAINT MyPrimaryKey PRIMARY KEY (column1, column2...); The basic syntax of an ALTER TABLE command to DROP CONSTRAINT from a table is as follows. ALTER TABLE table_name DROP CONSTRAINT MyUniqueConstraint; If you're using MySQL, the code is as follows − ALTER TABLE table_name DROP INDEX MyUniqueConstraint; The basic syntax of an ALTER TABLE command to DROP PRIMARY KEY constraint from a table is as follows. ALTER TABLE table_name DROP CONSTRAINT MyPrimaryKey; If you're using MySQL, the code is as follows − ALTER TABLE table_name DROP PRIMARY KEY; Consider the CUSTOMERS table having the following records − +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ Following is the example to ADD a New Column to an existing table − ALTER TABLE CUSTOMERS ADD SEX char(1); Now, the CUSTOMERS table is changed and following would be output from the SELECT statement. +----+---------+-----+-----------+----------+------+ | ID | NAME | AGE | ADDRESS | SALARY | SEX | +----+---------+-----+-----------+----------+------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | NULL | | 2 | Ramesh | 25 | Delhi | 1500.00 | NULL | | 3 | kaushik | 23 | Kota | 2000.00 | NULL | | 4 | kaushik | 25 | Mumbai | 6500.00 | NULL | | 5 | Hardik | 27 | Bhopal | 8500.00 | NULL | | 6 | Komal | 22 | MP | 4500.00 | NULL | | 7 | Muffy | 24 | Indore | 10000.00 | NULL | +----+---------+-----+-----------+----------+------+ Following is the example to DROP sex column from the existing table. ALTER TABLE CUSTOMERS DROP SEX; Now, the CUSTOMERS table is changed and following would be the output from the SELECT statement. +----+---------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+---------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Ramesh | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | kaushik | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+---------+-----+-----------+----------+ The SQL TRUNCATE TABLE command is used to delete complete data from an existing table. You can also use DROP TABLE command to delete complete table but it would remove complete table structure form the database and you would need to re-create this table once again if you wish you store some data. The basic syntax of a TRUNCATE TABLE command is as follows. TRUNCATE TABLE table_name; Consider a CUSTOMERS table having the following records − +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ Following is the example of a Truncate command. SQL > TRUNCATE TABLE CUSTOMERS; Now, the CUSTOMERS table is truncated and the output from SELECT statement will be as shown in the code block below − SQL> SELECT * FROM CUSTOMERS; Empty set (0.00 sec) A view is nothing more than a SQL statement that is stored in the database with an associated name. A view is actually a composition of a table in the form of a predefined SQL query. A view can contain all rows of a table or select rows from a table. A view can be created from one or many tables which depends on the written SQL query to create a view. Views, which are a type of virtual tables allow users to do the following − Structure data in a way that users or classes of users find natural or intuitive. Structure data in a way that users or classes of users find natural or intuitive. Restrict access to the data in such a way that a user can see and (sometimes) modify exactly what they need and no more. Restrict access to the data in such a way that a user can see and (sometimes) modify exactly what they need and no more. Summarize data from various tables which can be used to generate reports. Summarize data from various tables which can be used to generate reports. Database views are created using the CREATE VIEW statement. Views can be created from a single table, multiple tables or another view. To create a view, a user must have the appropriate system privilege according to the specific implementation. The basic CREATE VIEW syntax is as follows − CREATE VIEW view_name AS SELECT column1, column2..... FROM table_name WHERE [condition]; You can include multiple tables in your SELECT statement in a similar way as you use them in a normal SQL SELECT query. Consider the CUSTOMERS table having the following records − +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ Following is an example to create a view from the CUSTOMERS table. This view would be used to have customer name and age from the CUSTOMERS table. SQL > CREATE VIEW CUSTOMERS_VIEW AS SELECT name, age FROM CUSTOMERS; Now, you can query CUSTOMERS_VIEW in a similar way as you query an actual table. Following is an example for the same. SQL > SELECT * FROM CUSTOMERS_VIEW; This would produce the following result. +----------+-----+ | name | age | +----------+-----+ | Ramesh | 32 | | Khilan | 25 | | kaushik | 23 | | Chaitali | 25 | | Hardik | 27 | | Komal | 22 | | Muffy | 24 | +----------+-----+ The WITH CHECK OPTION is a CREATE VIEW statement option. The purpose of the WITH CHECK OPTION is to ensure that all UPDATE and INSERTs satisfy the condition(s) in the view definition. If they do not satisfy the condition(s), the UPDATE or INSERT returns an error. The following code block has an example of creating same view CUSTOMERS_VIEW with the WITH CHECK OPTION. CREATE VIEW CUSTOMERS_VIEW AS SELECT name, age FROM CUSTOMERS WHERE age IS NOT NULL WITH CHECK OPTION; The WITH CHECK OPTION in this case should deny the entry of any NULL values in the view's AGE column, because the view is defined by data that does not have a NULL value in the AGE column. A view can be updated under certain conditions which are given below − The SELECT clause may not contain the keyword DISTINCT. The SELECT clause may not contain the keyword DISTINCT. The SELECT clause may not contain summary functions. The SELECT clause may not contain summary functions. The SELECT clause may not contain set functions. The SELECT clause may not contain set functions. The SELECT clause may not contain set operators. The SELECT clause may not contain set operators. The SELECT clause may not contain an ORDER BY clause. The SELECT clause may not contain an ORDER BY clause. The FROM clause may not contain multiple tables. The FROM clause may not contain multiple tables. The WHERE clause may not contain subqueries. The WHERE clause may not contain subqueries. The query may not contain GROUP BY or HAVING. The query may not contain GROUP BY or HAVING. Calculated columns may not be updated. Calculated columns may not be updated. All NOT NULL columns from the base table must be included in the view in order for the INSERT query to function. All NOT NULL columns from the base table must be included in the view in order for the INSERT query to function. So, if a view satisfies all the above-mentioned rules then you can update that view. The following code block has an example to update the age of Ramesh. SQL > UPDATE CUSTOMERS_VIEW SET AGE = 35 WHERE name = 'Ramesh'; This would ultimately update the base table CUSTOMERS and the same would reflect in the view itself. Now, try to query the base table and the SELECT statement would produce the following result. +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 35 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ Rows of data can be inserted into a view. The same rules that apply to the UPDATE command also apply to the INSERT command. Here, we cannot insert rows in the CUSTOMERS_VIEW because we have not included all the NOT NULL columns in this view, otherwise you can insert rows in a view in a similar way as you insert them in a table. Rows of data can be deleted from a view. The same rules that apply to the UPDATE and INSERT commands apply to the DELETE command. Following is an example to delete a record having AGE = 22. SQL > DELETE FROM CUSTOMERS_VIEW WHERE age = 22; This would ultimately delete a row from the base table CUSTOMERS and the same would reflect in the view itself. Now, try to query the base table and the SELECT statement would produce the following result. +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 35 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ Obviously, where you have a view, you need a way to drop the view if it is no longer needed. The syntax is very simple and is given below − DROP VIEW view_name; Following is an example to drop the CUSTOMERS_VIEW from the CUSTOMERS table. DROP VIEW CUSTOMERS_VIEW; The HAVING Clause enables you to specify conditions that filter which group results appear in the results. The WHERE clause places conditions on the selected columns, whereas the HAVING clause places conditions on groups created by the GROUP BY clause. The following code block shows the position of the HAVING Clause in a query. SELECT FROM WHERE GROUP BY HAVING ORDER BY The HAVING clause must follow the GROUP BY clause in a query and must also precede the ORDER BY clause if used. The following code block has the syntax of the SELECT statement including the HAVING clause − SELECT column1, column2 FROM table1, table2 WHERE [ conditions ] GROUP BY column1, column2 HAVING [ conditions ] ORDER BY column1, column2 Consider the CUSTOMERS table having the following records. +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ Following is an example, which would display a record for a similar age count that would be more than or equal to 2. SQL > SELECT ID, NAME, AGE, ADDRESS, SALARY FROM CUSTOMERS GROUP BY age HAVING COUNT(age) >= 2; This would produce the following result − +----+--------+-----+---------+---------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+--------+-----+---------+---------+ | 2 | Khilan | 25 | Delhi | 1500.00 | +----+--------+-----+---------+---------+ A transaction is a unit of work that is performed against a database. Transactions are units or sequences of work accomplished in a logical order, whether in a manual fashion by a user or automatically by some sort of a database program. A transaction is the propagation of one or more changes to the database. For example, if you are creating a record or updating a record or deleting a record from the table, then you are performing a transaction on that table. It is important to control these transactions to ensure the data integrity and to handle database errors. Practically, you will club many SQL queries into a group and you will execute all of them together as a part of a transaction. Transactions have the following four standard properties, usually referred to by the acronym ACID. Atomicity − ensures that all operations within the work unit are completed successfully. Otherwise, the transaction is aborted at the point of failure and all the previous operations are rolled back to their former state. Atomicity − ensures that all operations within the work unit are completed successfully. Otherwise, the transaction is aborted at the point of failure and all the previous operations are rolled back to their former state. Consistency − ensures that the database properly changes states upon a successfully committed transaction. Consistency − ensures that the database properly changes states upon a successfully committed transaction. Isolation − enables transactions to operate independently of and transparent to each other. Isolation − enables transactions to operate independently of and transparent to each other. Durability − ensures that the result or effect of a committed transaction persists in case of a system failure. Durability − ensures that the result or effect of a committed transaction persists in case of a system failure. The following commands are used to control transactions. COMMIT − to save the changes. COMMIT − to save the changes. ROLLBACK − to roll back the changes. ROLLBACK − to roll back the changes. SAVEPOINT − creates points within the groups of transactions in which to ROLLBACK. SAVEPOINT − creates points within the groups of transactions in which to ROLLBACK. SET TRANSACTION − Places a name on a transaction. SET TRANSACTION − Places a name on a transaction. Transactional control commands are only used with the DML Commands such as - INSERT, UPDATE and DELETE only. They cannot be used while creating tables or dropping them because these operations are automatically committed in the database. The COMMIT command is the transactional command used to save changes invoked by a transaction to the database. The COMMIT command is the transactional command used to save changes invoked by a transaction to the database. The COMMIT command saves all the transactions to the database since the last COMMIT or ROLLBACK command. The syntax for the COMMIT command is as follows. COMMIT; Example Consider the CUSTOMERS table having the following records − +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ Following is an example which would delete those records from the table which have age = 25 and then COMMIT the changes in the database. SQL> DELETE FROM CUSTOMERS WHERE AGE = 25; SQL> COMMIT; Thus, two rows from the table would be deleted and the SELECT statement would produce the following result. +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ The ROLLBACK command is the transactional command used to undo transactions that have not already been saved to the database. This command can only be used to undo transactions since the last COMMIT or ROLLBACK command was issued. The syntax for a ROLLBACK command is as follows − ROLLBACK; Example Consider the CUSTOMERS table having the following records − +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ Following is an example, which would delete those records from the table which have the age = 25 and then ROLLBACK the changes in the database. SQL> DELETE FROM CUSTOMERS WHERE AGE = 25; SQL> ROLLBACK; Thus, the delete operation would not impact the table and the SELECT statement would produce the following result. +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ A SAVEPOINT is a point in a transaction when you can roll the transaction back to a certain point without rolling back the entire transaction. The syntax for a SAVEPOINT command is as shown below. SAVEPOINT SAVEPOINT_NAME; This command serves only in the creation of a SAVEPOINT among all the transactional statements. The ROLLBACK command is used to undo a group of transactions. The syntax for rolling back to a SAVEPOINT is as shown below. ROLLBACK TO SAVEPOINT_NAME; Following is an example where you plan to delete the three different records from the CUSTOMERS table. You want to create a SAVEPOINT before each delete, so that you can ROLLBACK to any SAVEPOINT at any time to return the appropriate data to its original state. Example Consider the CUSTOMERS table having the following records. +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ The following code block contains the series of operations. SQL> SAVEPOINT SP1; Savepoint created. SQL> DELETE FROM CUSTOMERS WHERE ID=1; 1 row deleted. SQL> SAVEPOINT SP2; Savepoint created. SQL> DELETE FROM CUSTOMERS WHERE ID=2; 1 row deleted. SQL> SAVEPOINT SP3; Savepoint created. SQL> DELETE FROM CUSTOMERS WHERE ID=3; 1 row deleted. Now that the three deletions have taken place, let us assume that you have changed your mind and decided to ROLLBACK to the SAVEPOINT that you identified as SP2. Because SP2 was created after the first deletion, the last two deletions are undone − SQL> ROLLBACK TO SP2; Rollback complete. Notice that only the first deletion took place since you rolled back to SP2. SQL> SELECT * FROM CUSTOMERS; +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ 6 rows selected. The RELEASE SAVEPOINT command is used to remove a SAVEPOINT that you have created. The syntax for a RELEASE SAVEPOINT command is as follows. RELEASE SAVEPOINT SAVEPOINT_NAME; Once a SAVEPOINT has been released, you can no longer use the ROLLBACK command to undo transactions performed since the last SAVEPOINT. The SET TRANSACTION command can be used to initiate a database transaction. This command is used to specify characteristics for the transaction that follows. For example, you can specify a transaction to be read only or read write. The syntax for a SET TRANSACTION command is as follows. SET TRANSACTION [ READ WRITE | READ ONLY ]; We have already discussed about the SQL LIKE operator, which is used to compare a value to similar values using the wildcard operators. SQL supports two wildcard operators in conjunction with the LIKE operator which are explained in detail in the following table. The percent sign (%) Matches one or more characters. Note − MS Access uses the asterisk (*) wildcard character instead of the percent sign (%) wildcard character. The underscore (_) Matches one character. Note − MS Access uses a question mark (?) instead of the underscore (_) to match any one character. The percent sign represents zero, one or multiple characters. The underscore represents a single number or a character. These symbols can be used in combinations. The basic syntax of a '%' and a '_' operator is as follows. SELECT * FROM table_name WHERE column LIKE 'XXXX%' or SELECT * FROM table_name WHERE column LIKE '%XXXX%' or SELECT * FROM table_name WHERE column LIKE 'XXXX_' or SELECT * FROM table_name WHERE column LIKE '_XXXX' or SELECT * FROM table_name WHERE column LIKE '_XXXX_' You can combine N number of conditions using the AND or the OR operators. Here, XXXX could be any numeric or string value. The following table has a number of examples showing the WHERE part having different LIKE clauses with '%' and '_' operators. WHERE SALARY LIKE '200%' Finds any values that start with 200. WHERE SALARY LIKE '%200%' Finds any values that have 200 in any position. WHERE SALARY LIKE '_00%' Finds any values that have 00 in the second and third positions. WHERE SALARY LIKE '2_%_%' Finds any values that start with 2 and are at least 3 characters in length. WHERE SALARY LIKE '%2' Finds any values that end with 2. WHERE SALARY LIKE '_2%3' Finds any values that have a 2 in the second position and end with a 3. WHERE SALARY LIKE '2___3' Finds any values in a five-digit number that start with 2 and end with 3. Let us take a real example, consider the CUSTOMERS table having the following records. +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ The following code block is an example, which would display all the records from the CUSTOMERS table where the SALARY starts with 200. SQL> SELECT * FROM CUSTOMERS WHERE SALARY LIKE '200%'; This would produce the following result. +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 3 | kaushik | 23 | Kota | 2000.00 | +----+----------+-----+-----------+----------+ The following table has a list of all the important Date and Time related functions available through SQL. There are various other functions supported by your RDBMS. The given list is based on MySQL RDBMS. Adds dates Adds time Converts from one timezone to another Returns the current date Synonyms for CURDATE() Synonyms for CURTIME() Synonyms for NOW() Returns the current time Adds two dates Formats date as specified Subtracts two dates Extracts the date part of a date or datetime expression Subtracts two dates Synonym for DAYOFMONTH() Returns the name of the weekday Returns the day of the month (1-31) Returns the weekday index of the argument Returns the day of the year (1-366) Extracts part of a date Converts a day number to a date Formats date as a UNIX timestamp Extracts the hour Returns the last day of the month for the argument Synonym for NOW() Synonym for NOW() Creates a date from the year and day of year MAKETIME() Returns the microseconds from argument Returns the minute from the argument Return the month from the date passed Returns the name of the month Returns the current date and time Adds a period to a year-month Returns the number of months between periods Returns the quarter from a date argument Converts seconds to 'HH:MM:SS' format Returns the second (0-59) Converts a string to a date When invoked with three arguments a synonym for DATE_SUB() Subtracts times Returns the time at which the function executes Formats as time Returns the argument converted to seconds Extracts the time portion of the expression passed Subtracts time With a single argument this function returns the date or datetime expression. With two arguments, the sum of the arguments Adds an interval to a datetime expression Subtracts an interval from a datetime expression Returns the date argument converted to days Returns a UNIX timestamp Returns the current UTC date Returns the current UTC time Returns the current UTC date and time Returns the week number Returns the weekday index Returns the calendar week of the date (1-53) Returns the year Returns the year and week When invoked with the INTERVAL form of the second argument, ADDDATE() is a synonym for DATE_ADD(). The related function SUBDATE() is a synonym for DATE_SUB(). For information on the INTERVAL unit argument, see the discussion for DATE_ADD(). mysql> SELECT DATE_ADD('1998-01-02', INTERVAL 31 DAY); +---------------------------------------------------------+ | DATE_ADD('1998-01-02', INTERVAL 31 DAY) | +---------------------------------------------------------+ | 1998-02-02 | +---------------------------------------------------------+ 1 row in set (0.00 sec) mysql> SELECT ADDDATE('1998-01-02', INTERVAL 31 DAY); +---------------------------------------------------------+ | ADDDATE('1998-01-02', INTERVAL 31 DAY) | +---------------------------------------------------------+ | 1998-02-02 | +---------------------------------------------------------+ 1 row in set (0.00 sec) When invoked with the days form of the second argument, MySQL treats it as an integer number of days to be added to expr. mysql> SELECT ADDDATE('1998-01-02', 31); +---------------------------------------------------------+ | DATE_ADD('1998-01-02', INTERVAL 31 DAY) | +---------------------------------------------------------+ | 1998-02-02 | +---------------------------------------------------------+ 1 row in set (0.00 sec) ADDTIME() adds expr2 to expr1 and returns the result. The expr1 is a time or datetime expression, while the expr2 is a time expression. mysql> SELECT ADDTIME('1997-12-31 23:59:59.999999','1 1:1:1.000002'); +---------------------------------------------------------+ | DATE_ADD('1997-12-31 23:59:59.999999','1 1:1:1.000002') | +---------------------------------------------------------+ | 1998-01-02 01:01:01.000001 | +---------------------------------------------------------+ 1 row in set (0.00 sec) This converts a datetime value dt from the time zone given by from_tz to the time zone given by to_tz and returns the resulting value. This function returns NULL if the arguments are invalid. mysql> SELECT CONVERT_TZ('2004-01-01 12:00:00','GMT','MET'); +---------------------------------------------------------+ | CONVERT_TZ('2004-01-01 12:00:00','GMT','MET') | +---------------------------------------------------------+ | 2004-01-01 13:00:00 | +---------------------------------------------------------+ 1 row in set (0.00 sec) mysql> SELECT CONVERT_TZ('2004-01-01 12:00:00','+00:00','+10:00'); +---------------------------------------------------------+ | CONVERT_TZ('2004-01-01 12:00:00','+00:00','+10:00') | +---------------------------------------------------------+ | 2004-01-01 22:00:00 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns the current date as a value in 'YYYY-MM-DD' or YYYYMMDD format, depending on whether the function is used in a string or in a numeric context. mysql> SELECT CURDATE(); +---------------------------------------------------------+ | CURDATE() | +---------------------------------------------------------+ | 1997-12-15 | +---------------------------------------------------------+ 1 row in set (0.00 sec) mysql> SELECT CURDATE() + 0; +---------------------------------------------------------+ | CURDATE() + 0 | +---------------------------------------------------------+ | 19971215 | +---------------------------------------------------------+ 1 row in set (0.00 sec) CURRENT_DATE and CURRENT_DATE() are synonyms for CURDATE() Returns the current time as a value in 'HH:MM:SS' or HHMMSS format, depending on whether the function is used in a string or in a numeric context. The value is expressed in the current time zone. mysql> SELECT CURTIME(); +---------------------------------------------------------+ | CURTIME() | +---------------------------------------------------------+ | 23:50:26 | +---------------------------------------------------------+ 1 row in set (0.00 sec) mysql> SELECT CURTIME() + 0; +---------------------------------------------------------+ | CURTIME() + 0 | +---------------------------------------------------------+ | 235026 | +---------------------------------------------------------+ 1 row in set (0.00 sec) CURRENT_TIME and CURRENT_TIME() are synonyms for CURTIME(). CURRENT_TIMESTAMP and CURRENT_TIMESTAMP() are synonyms for NOW(). Extracts the date part of the date or datetime expression expr. mysql> SELECT DATE('2003-12-31 01:02:03'); +---------------------------------------------------------+ | DATE('2003-12-31 01:02:03') | +---------------------------------------------------------+ | 2003-12-31 | +---------------------------------------------------------+ 1 row in set (0.00 sec) DATEDIFF() returns expr1 . expr2 expressed as a value in days from one date to the other. Both expr1 and expr2 are date or date-and-time expressions. Only the date parts of the values are used in the calculation. mysql> SELECT DATEDIFF('1997-12-31 23:59:59','1997-12-30'); +---------------------------------------------------------+ | DATEDIFF('1997-12-31 23:59:59','1997-12-30') | +---------------------------------------------------------+ | 1 | +---------------------------------------------------------+ 1 row in set (0.00 sec) These functions perform date arithmetic. The date is a DATETIME or DATE value specifying the starting date. The expr is an expression specifying the interval value to be added or subtracted from the starting date. The expr is a string; it may start with a '-' for negative intervals. A unit is a keyword indicating the units in which the expression should be interpreted. The INTERVAL keyword and the unit specifier are not case sensitive. The following table shows the expected form of the expr argument for each unit value. The values QUARTER and WEEK are available from the MySQL 5.0.0. version. mysql> SELECT DATE_ADD('1997-12-31 23:59:59', -> INTERVAL '1:1' MINUTE_SECOND); +---------------------------------------------------------+ | DATE_ADD('1997-12-31 23:59:59', INTERVAL... | +---------------------------------------------------------+ | 1998-01-01 00:01:00 | +---------------------------------------------------------+ 1 row in set (0.00 sec) mysql> SELECT DATE_ADD('1999-01-01', INTERVAL 1 HOUR); +---------------------------------------------------------+ | DATE_ADD('1999-01-01', INTERVAL 1 HOUR) | +---------------------------------------------------------+ | 1999-01-01 01:00:00 | +---------------------------------------------------------+ 1 row in set (0.00 sec) This command formats the date value as per the format string. The following specifiers may be used in the format string. The '%' character is required before the format specifier characters. %a Abbreviated weekday name (Sun..Sat) %b Abbreviated month name (Jan..Dec) %c Month, numeric (0..12) %D Day of the month with English suffix (0th, 1st, 2nd, 3rd, .) %d Day of the month, numeric (00..31) %e Day of the month, numeric (0..31) %f Microseconds (000000..999999) %H Hour (00..23) %h Hour (01..12) %I Hour (01..12) %i Minutes, numeric (00..59) %j Day of year (001..366) %k Hour (0..23) %l Hour (1..12) %M Month name (January..December) %m Month, numeric (00..12) %p AM or PM %r Time, 12-hour (hh:mm:ss followed by AM or PM) %S Seconds (00..59) %s Seconds (00..59) %T Time, 24-hour (hh:mm:ss) %U Week (00..53), where Sunday is the first day of the week %u Week (00..53), where Monday is the first day of the week %V Week (01..53), where Sunday is the first day of the week; used with %X %v Week (01..53), where Monday is the first day of the week; used with %x %W Weekday name (Sunday..Saturday) %w Day of the week (0=Sunday..6=Saturday) %X Year for the week where Sunday is the first day of the week, numeric, four digits; used with %V %x Year for the week, where Monday is the first day of the week, numeric, four digits; used with %v %Y Year, numeric, four digits %y Year, numeric (two digits) %% A literal .%. character %x x, for any.x. not listed above mysql> SELECT DATE_FORMAT('1997-10-04 22:23:00', '%W %M %Y'); +---------------------------------------------------------+ | DATE_FORMAT('1997-10-04 22:23:00', '%W %M %Y') | +---------------------------------------------------------+ | Saturday October 1997 | +---------------------------------------------------------+ 1 row in set (0.00 sec) mysql> SELECT DATE_FORMAT('1997-10-04 22:23:00' -> '%H %k %I %r %T %S %w'); +---------------------------------------------------------+ | DATE_FORMAT('1997-10-04 22:23:00....... | +---------------------------------------------------------+ | 22 22 10 10:23:00 PM 22:23:00 00 6 | +---------------------------------------------------------+ 1 row in set (0.00 sec) This is similar to the DATE_ADD() function. The DAY() is a synonym for the DAYOFMONTH() function. Returns the name of the weekday for date. mysql> SELECT DAYNAME('1998-02-05'); +---------------------------------------------------------+ | DAYNAME('1998-02-05') | +---------------------------------------------------------+ | Thursday | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns the day of the month for date, in the range 0 to 31. mysql> SELECT DAYOFMONTH('1998-02-03'); +---------------------------------------------------------+ | DAYOFMONTH('1998-02-03') | +---------------------------------------------------------+ | 3 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns the weekday index for date (1 = Sunday, 2 = Monday, ., 7 = Saturday). These index values correspond to the ODBC standard. mysql> SELECT DAYOFWEEK('1998-02-03'); +---------------------------------------------------------+ |DAYOFWEEK('1998-02-03') | +---------------------------------------------------------+ | 3 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns the day of the year for date, in the range 1 to 366. mysql> SELECT DAYOFYEAR('1998-02-03'); +---------------------------------------------------------+ | DAYOFYEAR('1998-02-03') | +---------------------------------------------------------+ | 34 | +---------------------------------------------------------+ 1 row in set (0.00 sec) The EXTRACT() function uses the same kinds of unit specifiers as DATE_ADD() or DATE_SUB(), but extracts parts from the date rather than performing date arithmetic. mysql> SELECT EXTRACT(YEAR FROM '1999-07-02'); +---------------------------------------------------------+ | EXTRACT(YEAR FROM '1999-07-02') | +---------------------------------------------------------+ | 1999 | +---------------------------------------------------------+ 1 row in set (0.00 sec) mysql> SELECT EXTRACT(YEAR_MONTH FROM '1999-07-02 01:02:03'); +---------------------------------------------------------+ | EXTRACT(YEAR_MONTH FROM '1999-07-02 01:02:03') | +---------------------------------------------------------+ | 199907 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Given a day number N, returns a DATE value. mysql> SELECT FROM_DAYS(729669); +---------------------------------------------------------+ | FROM_DAYS(729669) | +---------------------------------------------------------+ | 1997-10-07 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Note − Use FROM_DAYS() with caution on old dates. It is not intended for use with values that precede the advent of the Gregorian calendar (1582). Returns a representation of the unix_timestamp argument as a value in 'YYYY-MM-DD HH:MM:SS or YYYYMMDDHHMMSS format, depending on whether the function is used in a string or in a numeric context. The value is expressed in the current time zone. The unix_timestamp argument is an internal timestamp values, which are produced by the UNIX_TIMESTAMP() function. If the format is given, the result is formatted according to the format string, which is used in the same way as is listed in the entry for the DATE_FORMAT() function. mysql> SELECT FROM_UNIXTIME(875996580); +---------------------------------------------------------+ | FROM_UNIXTIME(875996580) | +---------------------------------------------------------+ | 1997-10-04 22:23:00 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns the hour for time. The range of the return value is 0 to 23 for time-of-day values. However, the range of TIME values actually is much larger, so HOUR can return values greater than 23. mysql> SELECT HOUR('10:05:03'); +---------------------------------------------------------+ | HOUR('10:05:03') | +---------------------------------------------------------+ | 10 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Takes a date or datetime value and returns the corresponding value for the last day of the month. Returns NULL if the argument is invalid. mysql> SELECT LAST_DAY('2003-02-05'); +---------------------------------------------------------+ | LAST_DAY('2003-02-05') | +---------------------------------------------------------+ | 2003-02-28 | +---------------------------------------------------------+ 1 row in set (0.00 sec) LOCALTIME and LOCALTIME() are synonyms for NOW(). LOCALTIMESTAMP and LOCALTIMESTAMP() are synonyms for NOW(). Returns a date, given year and day-of-year values. The dayofyear value must be greater than 0 or the result will be NULL. mysql> SELECT MAKEDATE(2001,31), MAKEDATE(2001,32); +---------------------------------------------------------+ | MAKEDATE(2001,31), MAKEDATE(2001,32) | +---------------------------------------------------------+ | '2001-01-31', '2001-02-01' | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns a time value calculated from the hour, minute and second arguments. mysql> SELECT MAKETIME(12,15,30); +---------------------------------------------------------+ | MAKETIME(12,15,30) | +---------------------------------------------------------+ | '12:15:30' | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns the microseconds from the time or datetime expression (expr) as a number in the range from 0 to 999999. mysql> SELECT MICROSECOND('12:00:00.123456'); +---------------------------------------------------------+ | MICROSECOND('12:00:00.123456') | +---------------------------------------------------------+ | 123456 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns the minute for time, in the range 0 to 59. mysql> SELECT MINUTE('98-02-03 10:05:03'); +---------------------------------------------------------+ | MINUTE('98-02-03 10:05:03') | +---------------------------------------------------------+ | 5 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns the month for date, in the range 0 to 12. mysql> SELECT MONTH('1998-02-03') +---------------------------------------------------------+ | MONTH('1998-02-03') | +---------------------------------------------------------+ | 2 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns the full name of the month for a date. mysql> SELECT MONTHNAME('1998-02-05'); +---------------------------------------------------------+ | MONTHNAME('1998-02-05') | +---------------------------------------------------------+ | February | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns the current date and time as a value in 'YYYY-MM-DD HH:MM:SS' or YYYYMMDDHHMMSS format, depending on whether the function is used in a string or numeric context. This value is expressed in the current time zone. mysql> SELECT NOW(); +---------------------------------------------------------+ | NOW() | +---------------------------------------------------------+ | 1997-12-15 23:50:26 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Adds N months to a period P (in the format YYMM or YYYYMM). Returns a value in the format YYYYMM. Note that the period argument P is not a date value. mysql> SELECT PERIOD_ADD(9801,2); +---------------------------------------------------------+ | PERIOD_ADD(9801,2) | +---------------------------------------------------------+ | 199803 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns the number of months between periods P1 and P2. These periods P1 and P2 should be in the format YYMM or YYYYMM. Note that the period arguments P1 and P2 are not date values. mysql> SELECT PERIOD_DIFF(9802,199703); +---------------------------------------------------------+ | PERIOD_DIFF(9802,199703) | +---------------------------------------------------------+ | 11 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns the quarter of the year for date, in the range 1 to 4. mysql> SELECT QUARTER('98-04-01'); +---------------------------------------------------------+ | QUARTER('98-04-01') | +---------------------------------------------------------+ | 2 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns the second for time, in the range 0 to 59. mysql> SELECT SECOND('10:05:03'); +---------------------------------------------------------+ | SECOND('10:05:03') | +---------------------------------------------------------+ | 3 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns the seconds argument, converted to hours, minutes and seconds, as a value in 'HH:MM:SS' or HHMMSS format, depending on whether the function is used in a string or numeric context. mysql> SELECT SEC_TO_TIME(2378); +---------------------------------------------------------+ | SEC_TO_TIME(2378) | +---------------------------------------------------------+ | 00:39:38 | +---------------------------------------------------------+ 1 row in set (0.00 sec) This is the inverse of the DATE_FORMAT() function. It takes a string str and a format string format. The STR_TO_DATE() function returns a DATETIME value if the format string contains both date and time parts. Else, it returns a DATE or TIME value if the string contains only date or time parts. mysql> SELECT STR_TO_DATE('04/31/2004', '%m/%d/%Y'); +---------------------------------------------------------+ | STR_TO_DATE('04/31/2004', '%m/%d/%Y') | +---------------------------------------------------------+ | 2004-04-31 | +---------------------------------------------------------+ 1 row in set (0.00 sec) When invoked with the INTERVAL form of the second argument, SUBDATE() is a synonym for DATE_SUB(). For information on the INTERVAL unit argument, see the discussion for DATE_ADD(). mysql> SELECT DATE_SUB('1998-01-02', INTERVAL 31 DAY); +---------------------------------------------------------+ | DATE_SUB('1998-01-02', INTERVAL 31 DAY) | +---------------------------------------------------------+ | 1997-12-02 | +---------------------------------------------------------+ 1 row in set (0.00 sec) mysql> SELECT SUBDATE('1998-01-02', INTERVAL 31 DAY); +---------------------------------------------------------+ | SUBDATE('1998-01-02', INTERVAL 31 DAY) | +---------------------------------------------------------+ | 1997-12-02 | +---------------------------------------------------------+ 1 row in set (0.00 sec) The SUBTIME() function returns expr1 . expr2 expressed as a value in the same format as expr1. The expr1 value is a time or a datetime expression, while the expr2 value is a time expression. mysql> SELECT SUBTIME('1997-12-31 23:59:59.999999', -> '1 1:1:1.000002'); +---------------------------------------------------------+ | SUBTIME('1997-12-31 23:59:59.999999'... | +---------------------------------------------------------+ | 1997-12-30 22:58:58.999997 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns the current date and time as a value in 'YYYY-MM-DD HH:MM:SS' or YYYYMMDDHHMMSS format, depending on whether the function is used in a string or in a numeric context. mysql> SELECT SYSDATE(); +---------------------------------------------------------+ | SYSDATE() | +---------------------------------------------------------+ | 2006-04-12 13:47:44 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Extracts the time part of the time or datetime expression expr and returns it as a string. mysql> SELECT TIME('2003-12-31 01:02:03'); +---------------------------------------------------------+ | TIME('2003-12-31 01:02:03') | +---------------------------------------------------------+ | 01:02:03 | +---------------------------------------------------------+ 1 row in set (0.00 sec) The TIMEDIFF() function returns expr1 . expr2 expressed as a time value. These expr1 and expr2 values are time or date-and-time expressions, but both must be of the same type. mysql> SELECT TIMEDIFF('1997-12-31 23:59:59.000001', -> '1997-12-30 01:01:01.000002'); +---------------------------------------------------------+ | TIMEDIFF('1997-12-31 23:59:59.000001'..... | +---------------------------------------------------------+ | 46:58:57.999999 | +---------------------------------------------------------+ 1 row in set (0.00 sec) With a single argument, this function returns the date or datetime expression expr as a datetime value. With two arguments, it adds the time expression expr2 to the date or datetime expression expr1 and returns the result as a datetime value. mysql> SELECT TIMESTAMP('2003-12-31'); +---------------------------------------------------------+ | TIMESTAMP('2003-12-31') | +---------------------------------------------------------+ | 2003-12-31 00:00:00 | +---------------------------------------------------------+ 1 row in set (0.00 sec) This function adds the integer expression interval to the date or datetime expression datetime_expr. The unit for interval is given by the unit argument, which should be one of the following values − FRAC_SECOND SECOND, MINUTE HOUR, DAY WEEK MONTH QUARTER or YEAR The unit value may be specified using one of the keywords as shown or with a prefix of SQL_TSI_. For example, DAY and SQL_TSI_DAY both are legal. mysql> SELECT TIMESTAMPADD(MINUTE,1,'2003-01-02'); +---------------------------------------------------------+ | TIMESTAMPADD(MINUTE,1,'2003-01-02') | +---------------------------------------------------------+ | 2003-01-02 00:01:00 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns the integer difference between the date or datetime expressions datetime_expr1 and datetime_expr2. The unit for the result is given by the unit argument. The legal values for the unit are the same as those listed in the description of the TIMESTAMPADD() function. mysql> SELECT TIMESTAMPDIFF(MONTH,'2003-02-01','2003-05-01'); +---------------------------------------------------------+ | TIMESTAMPDIFF(MONTH,'2003-02-01','2003-05-01') | +---------------------------------------------------------+ | 3 | +---------------------------------------------------------+ 1 row in set (0.00 sec) This function is used like the DATE_FORMAT() function, but the format string may contain format specifiers only for hours, minutes and seconds. If the time value contains an hour part that is greater than 23, the %H and %k hour format specifiers produce a value larger than the usual range of 0 to 23. The other hour format specifiers produce the hour value modulo 12. mysql> SELECT TIME_FORMAT('100:00:00', '%H %k %h %I %l'); +---------------------------------------------------------+ | TIME_FORMAT('100:00:00', '%H %k %h %I %l') | +---------------------------------------------------------+ | 100 100 04 04 4 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns the time argument converted to seconds. mysql> SELECT TIME_TO_SEC('22:23:00'); +---------------------------------------------------------+ | TIME_TO_SEC('22:23:00') | +---------------------------------------------------------+ | 80580 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Given a date, returns a day number (the number of days since year 0). mysql> SELECT TO_DAYS(950501); +---------------------------------------------------------+ | TO_DAYS(950501) | +---------------------------------------------------------+ | 728779 | +---------------------------------------------------------+ 1 row in set (0.00 sec) If called with no argument, this function returns a Unix timestamp (seconds since '1970-01-01 00:00:00' UTC) as an unsigned integer. If UNIX_TIMESTAMP() is called with a date argument, it returns the value of the argument as seconds since '1970-01-01 00:00:00' UTC. date may be a DATE string, a DATETIME string, a TIMESTAMP, or a number in the format YYMMDD or YYYYMMDD. mysql> SELECT UNIX_TIMESTAMP(); +---------------------------------------------------------+ | UNIX_TIMESTAMP() | +---------------------------------------------------------+ | 882226357 | +---------------------------------------------------------+ 1 row in set (0.00 sec) mysql> SELECT UNIX_TIMESTAMP('1997-10-04 22:23:00'); +---------------------------------------------------------+ | UNIX_TIMESTAMP('1997-10-04 22:23:00') | +---------------------------------------------------------+ | 875996580 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns the current UTC date as a value in 'YYYY-MM-DD' or YYYYMMDD format, depending on whether the function is used in a string or numeric context. mysql> SELECT UTC_DATE(), UTC_DATE() + 0; +---------------------------------------------------------+ | UTC_DATE(), UTC_DATE() + 0 | +---------------------------------------------------------+ | 2003-08-14, 20030814 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns the current UTC time as a value in 'HH:MM:SS' or HHMMSS format, depending on whether the function is used in a string or numeric context. mysql> SELECT UTC_TIME(), UTC_TIME() + 0; +---------------------------------------------------------+ | UTC_TIME(), UTC_TIME() + 0 | +---------------------------------------------------------+ | 18:07:53, 180753 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns the current UTC date and time as a value in 'YYYY-MM-DD HH:MM:SS' or in a YYYYMMDDHHMMSS format, depending on whether the function is used in a string or in a numeric context. mysql> SELECT UTC_TIMESTAMP(), UTC_TIMESTAMP() + 0; +---------------------------------------------------------+ | UTC_TIMESTAMP(), UTC_TIMESTAMP() + 0 | +---------------------------------------------------------+ | 2003-08-14 18:08:04, 20030814180804 | +---------------------------------------------------------+ 1 row in set (0.00 sec) This function returns the week number for date. The two-argument form of WEEK() allows you to specify whether the week starts on a Sunday or a Monday and whether the return value should be in the range from 0 to 53 or from 1 to 53. If the mode argument is omitted, the value of the default_week_format system variable is used mysql> SELECT WEEK('1998-02-20'); +---------------------------------------------------------+ | WEEK('1998-02-20') | +---------------------------------------------------------+ | 7 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns the weekday index for date (0 = Monday, 1 = Tuesday, . 6 = Sunday). mysql> SELECT WEEKDAY('1998-02-03 22:23:00'); +---------------------------------------------------------+ | WEEKDAY('1998-02-03 22:23:00') | +---------------------------------------------------------+ | 1 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns the calendar week of the date as a number in the range from 1 to 53. WEEKOFYEAR() is a compatibility function that is equivalent to WEEK(date,3). mysql> SELECT WEEKOFYEAR('1998-02-20'); +---------------------------------------------------------+ | WEEKOFYEAR('1998-02-20') | +---------------------------------------------------------+ | 8 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns the year for date, in the range 1000 to 9999, or 0 for the .zero. date. mysql> SELECT YEAR('98-02-03'); +---------------------------------------------------------+ | YEAR('98-02-03') | +---------------------------------------------------------+ | 1998 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns the year and the week for a date. The mode argument works exactly like the mode argument to the WEEK() function. The year in the result may be different from the year in the date argument for the first and the last week of the year. mysql> SELECT YEARWEEK('1987-01-01'); +---------------------------------------------------------+ | YEAR('98-02-03')YEARWEEK('1987-01-01') | +---------------------------------------------------------+ | 198653 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Note − The week number is different from what the WEEK() function would return (0) for optional arguments 0 or 1, as WEEK() then returns the week in the context of the given year. There are RDBMS, which support temporary tables. Temporary Tables are a great feature that lets you store and process intermediate results by using the same selection, update, and join capabilities that you can use with typical SQL Server tables. The temporary tables could be very useful in some cases to keep temporary data. The most important thing that should be known for temporary tables is that they will be deleted when the current client session terminates. Temporary tables are available in MySQL version 3.23 onwards. If you use an older version of MySQL than 3.23, you can't use temporary tables, but you can use heap tables. As stated earlier, temporary tables will only last as long as the session is alive. If you run the code in a PHP script, the temporary table will be destroyed automatically when the script finishes executing. If you are connected to the MySQL database server through the MySQL client program, then the temporary table will exist until you close the client or manually destroy the table. Here is an example showing you the usage of a temporary table. mysql> CREATE TEMPORARY TABLE SALESSUMMARY ( -> product_name VARCHAR(50) NOT NULL -> , total_sales DECIMAL(12,2) NOT NULL DEFAULT 0.00 -> , avg_unit_price DECIMAL(7,2) NOT NULL DEFAULT 0.00 -> , total_units_sold INT UNSIGNED NOT NULL DEFAULT 0 ); Query OK, 0 rows affected (0.00 sec) mysql> INSERT INTO SALESSUMMARY -> (product_name, total_sales, avg_unit_price, total_units_sold) -> VALUES -> ('cucumber', 100.25, 90, 2); mysql> SELECT * FROM SALESSUMMARY; +--------------+-------------+----------------+------------------+ | product_name | total_sales | avg_unit_price | total_units_sold | +--------------+-------------+----------------+------------------+ | cucumber | 100.25 | 90.00 | 2 | +--------------+-------------+----------------+------------------+ 1 row in set (0.00 sec) When you issue a SHOW TABLES command, then your temporary table will not be listed out in the list. Now, if you log out of the MySQL session and then issue a SELECT command, you will find no data available in the database. Even your temporary table will not be existing. By default, all the temporary tables are deleted by MySQL when your database connection gets terminated. Still if you want to delete them in between, then you can do so by issuing a DROP TABLE command. Following is an example on dropping a temporary table. mysql> CREATE TEMPORARY TABLE SALESSUMMARY ( -> product_name VARCHAR(50) NOT NULL -> , total_sales DECIMAL(12,2) NOT NULL DEFAULT 0.00 -> , avg_unit_price DECIMAL(7,2) NOT NULL DEFAULT 0.00 -> , total_units_sold INT UNSIGNED NOT NULL DEFAULT 0 ); Query OK, 0 rows affected (0.00 sec) mysql> INSERT INTO SALESSUMMARY -> (product_name, total_sales, avg_unit_price, total_units_sold) -> VALUES -> ('cucumber', 100.25, 90, 2); mysql> SELECT * FROM SALESSUMMARY; +--------------+-------------+----------------+------------------+ | product_name | total_sales | avg_unit_price | total_units_sold | +--------------+-------------+----------------+------------------+ | cucumber | 100.25 | 90.00 | 2 | +--------------+-------------+----------------+------------------+ 1 row in set (0.00 sec) mysql> DROP TABLE SALESSUMMARY; mysql> SELECT * FROM SALESSUMMARY; ERROR 1146: Table 'TUTORIALS.SALESSUMMARY' doesn't exist There may be a situation when you need an exact copy of a table and the CREATE TABLE ... or the SELECT... commands does not suit your purposes because the copy must include the same indexes, default values and so forth. If you are using MySQL RDBMS, you can handle this situation by adhering to the steps given below − Use SHOW CREATE TABLE command to get a CREATE TABLE statement that specifies the source table's structure, indexes and all. Use SHOW CREATE TABLE command to get a CREATE TABLE statement that specifies the source table's structure, indexes and all. Modify the statement to change the table name to that of the clone table and execute the statement. This way you will have an exact clone table. Modify the statement to change the table name to that of the clone table and execute the statement. This way you will have an exact clone table. Optionally, if you need the table contents copied as well, issue an INSERT INTO or a SELECT statement too. Optionally, if you need the table contents copied as well, issue an INSERT INTO or a SELECT statement too. Try out the following example to create a clone table for TUTORIALS_TBL whose structure is as follows − Step 1 − Get the complete structure about the table. SQL> SHOW CREATE TABLE TUTORIALS_TBL \G; *************************** 1. row *************************** Table: TUTORIALS_TBL Create Table: CREATE TABLE 'TUTORIALS_TBL' ( 'tutorial_id' int(11) NOT NULL auto_increment, 'tutorial_title' varchar(100) NOT NULL default '', 'tutorial_author' varchar(40) NOT NULL default '', 'submission_date' date default NULL, PRIMARY KEY ('tutorial_id'), UNIQUE KEY 'AUTHOR_INDEX' ('tutorial_author') ) TYPE = MyISAM 1 row in set (0.00 sec) Step 2 − Rename this table and create another table. SQL> CREATE TABLE `CLONE_TBL` ( -> 'tutorial_id' int(11) NOT NULL auto_increment, -> 'tutorial_title' varchar(100) NOT NULL default '', -> 'tutorial_author' varchar(40) NOT NULL default '', -> 'submission_date' date default NULL, -> PRIMARY KEY (`tutorial_id'), -> UNIQUE KEY 'AUTHOR_INDEX' ('tutorial_author') -> ) TYPE = MyISAM; Query OK, 0 rows affected (1.80 sec) Step 3 − After executing step 2, you will clone a table in your database. If you want to copy data from an old table, then you can do it by using the INSERT INTO... SELECT statement. SQL> INSERT INTO CLONE_TBL (tutorial_id, -> tutorial_title, -> tutorial_author, -> submission_date) -> SELECT tutorial_id,tutorial_title, -> tutorial_author,submission_date, -> FROM TUTORIALS_TBL; Query OK, 3 rows affected (0.07 sec) Records: 3 Duplicates: 0 Warnings: 0 Finally, you will have an exact clone table as you wanted to have. A Subquery or Inner query or a Nested query is a query within another SQL query and embedded within the WHERE clause. A subquery is used to return data that will be used in the main query as a condition to further restrict the data to be retrieved. Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with the operators like =, <, >, >=, <=, IN, BETWEEN, etc. There are a few rules that subqueries must follow − Subqueries must be enclosed within parentheses. Subqueries must be enclosed within parentheses. A subquery can have only one column in the SELECT clause, unless multiple columns are in the main query for the subquery to compare its selected columns. A subquery can have only one column in the SELECT clause, unless multiple columns are in the main query for the subquery to compare its selected columns. An ORDER BY command cannot be used in a subquery, although the main query can use an ORDER BY. The GROUP BY command can be used to perform the same function as the ORDER BY in a subquery. An ORDER BY command cannot be used in a subquery, although the main query can use an ORDER BY. The GROUP BY command can be used to perform the same function as the ORDER BY in a subquery. Subqueries that return more than one row can only be used with multiple value operators such as the IN operator. Subqueries that return more than one row can only be used with multiple value operators such as the IN operator. The SELECT list cannot include any references to values that evaluate to a BLOB, ARRAY, CLOB, or NCLOB. The SELECT list cannot include any references to values that evaluate to a BLOB, ARRAY, CLOB, or NCLOB. A subquery cannot be immediately enclosed in a set function. A subquery cannot be immediately enclosed in a set function. The BETWEEN operator cannot be used with a subquery. However, the BETWEEN operator can be used within the subquery. The BETWEEN operator cannot be used with a subquery. However, the BETWEEN operator can be used within the subquery. Subqueries are most frequently used with the SELECT statement. The basic syntax is as follows − SELECT column_name [, column_name ] FROM table1 [, table2 ] WHERE column_name OPERATOR (SELECT column_name [, column_name ] FROM table1 [, table2 ] [WHERE]) Consider the CUSTOMERS table having the following records − +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 35 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ Now, let us check the following subquery with a SELECT statement. SQL> SELECT * FROM CUSTOMERS WHERE ID IN (SELECT ID FROM CUSTOMERS WHERE SALARY > 4500) ; This would produce the following result. +----+----------+-----+---------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+---------+----------+ | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+---------+----------+ Subqueries also can be used with INSERT statements. The INSERT statement uses the data returned from the subquery to insert into another table. The selected data in the subquery can be modified with any of the character, date or number functions. The basic syntax is as follows. INSERT INTO table_name [ (column1 [, column2 ]) ] SELECT [ *|column1 [, column2 ] FROM table1 [, table2 ] [ WHERE VALUE OPERATOR ] Consider a table CUSTOMERS_BKP with similar structure as CUSTOMERS table. Now to copy the complete CUSTOMERS table into the CUSTOMERS_BKP table, you can use the following syntax. SQL> INSERT INTO CUSTOMERS_BKP SELECT * FROM CUSTOMERS WHERE ID IN (SELECT ID FROM CUSTOMERS) ; The subquery can be used in conjunction with the UPDATE statement. Either single or multiple columns in a table can be updated when using a subquery with the UPDATE statement. The basic syntax is as follows. UPDATE table SET column_name = new_value [ WHERE OPERATOR [ VALUE ] (SELECT COLUMN_NAME FROM TABLE_NAME) [ WHERE) ] Assuming, we have CUSTOMERS_BKP table available which is backup of CUSTOMERS table. The following example updates SALARY by 0.25 times in the CUSTOMERS table for all the customers whose AGE is greater than or equal to 27. SQL> UPDATE CUSTOMERS SET SALARY = SALARY * 0.25 WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP WHERE AGE >= 27 ); This would impact two rows and finally CUSTOMERS table would have the following records. +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 35 | Ahmedabad | 125.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 2125.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ The subquery can be used in conjunction with the DELETE statement like with any other statements mentioned above. The basic syntax is as follows. DELETE FROM TABLE_NAME [ WHERE OPERATOR [ VALUE ] (SELECT COLUMN_NAME FROM TABLE_NAME) [ WHERE) ] Assuming, we have a CUSTOMERS_BKP table available which is a backup of the CUSTOMERS table. The following example deletes the records from the CUSTOMERS table for all the customers whose AGE is greater than or equal to 27. SQL> DELETE FROM CUSTOMERS WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP WHERE AGE >= 27 ); This would impact two rows and finally the CUSTOMERS table would have the following records. +----+----------+-----+---------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+---------+----------+ | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+---------+----------+ A sequence is a set of integers 1, 2, 3, ... that are generated in order on demand. Sequences are frequently used in databases because many applications require each row in a table to contain a unique value and sequences provide an easy way to generate them. This chapter describes how to use sequences in MySQL. The simplest way in MySQL to use sequences is to define a column as AUTO_INCREMENT and leave the rest to MySQL to take care. Try out the following example. This will create a table and after that it will insert a few rows in this table where it is not required to give a record ID because its auto-incremented by MySQL. mysql> CREATE TABLE INSECT -> ( -> id INT UNSIGNED NOT NULL AUTO_INCREMENT, -> PRIMARY KEY (id), -> name VARCHAR(30) NOT NULL, # type of insect -> date DATE NOT NULL, # date collected -> origin VARCHAR(30) NOT NULL # where collected ); Query OK, 0 rows affected (0.02 sec) mysql> INSERT INTO INSECT (id,name,date,origin) VALUES -> (NULL,'housefly','2001-09-10','kitchen'), -> (NULL,'millipede','2001-09-10','driveway'), -> (NULL,'grasshopper','2001-09-10','front yard'); Query OK, 3 rows affected (0.02 sec) Records: 3 Duplicates: 0 Warnings: 0 mysql> SELECT * FROM INSECT ORDER BY id; +----+-------------+------------+------------+ | id | name | date | origin | +----+-------------+------------+------------+ | 1 | housefly | 2001-09-10 | kitchen | | 2 | millipede | 2001-09-10 | driveway | | 3 | grasshopper | 2001-09-10 | front yard | +----+-------------+------------+------------+ 3 rows in set (0.00 sec) The LAST_INSERT_ID( ) is an SQL function, so you can use it from within any client that understands how to issue SQL statements. Otherwise PERL and PHP scripts provide exclusive functions to retrieve auto-incremented value of last record. Use the mysql_insertid attribute to obtain the AUTO_INCREMENT value generated by a query. This attribute is accessed through either a database handle or a statement handle, depending on how you issue the query. The following example references it through the database handle. $dbh->do ("INSERT INTO INSECT (name,date,origin) VALUES('moth','2001-09-14','windowsill')"); my $seq = $dbh->{mysql_insertid}; After issuing a query that generates an AUTO_INCREMENT value, retrieve the value by calling the mysql_insert_id( ) function. mysql_query ("INSERT INTO INSECT (name,date,origin) VALUES('moth','2001-09-14','windowsill')", $conn_id); $seq = mysql_insert_id ($conn_id); There may be a case when you have deleted many records from a table and you want to re-sequence all the records. This can be done by using a simple trick, but you should be very careful to do this and check if your table is having a join with another table or not. If you determine that resequencing an AUTO_INCREMENT column is unavoidable, the way to do it is to drop the column from the table, then add it again. The following example shows how to renumber the id values in the insect table using this technique. mysql> ALTER TABLE INSECT DROP id; mysql> ALTER TABLE insect -> ADD id INT UNSIGNED NOT NULL AUTO_INCREMENT FIRST, -> ADD PRIMARY KEY (id); By default, MySQL will start the sequence from 1, but you can specify any other number as well at the time of table creation. The following code block has an example where MySQL will start sequence from 100. mysql> CREATE TABLE INSECT -> ( -> id INT UNSIGNED NOT NULL AUTO_INCREMENT = 100, -> PRIMARY KEY (id), -> name VARCHAR(30) NOT NULL, # type of insect -> date DATE NOT NULL, # date collected -> origin VARCHAR(30) NOT NULL # where collected ); Alternatively, you can create the table and then set the initial sequence value with ALTER TABLE. mysql> ALTER TABLE t AUTO_INCREMENT = 100; There may be a situation when you have multiple duplicate records in a table. While fetching such records, it makes more sense to fetch only unique records instead of fetching duplicate records. The SQL DISTINCT keyword, which we have already discussed is used in conjunction with the SELECT statement to eliminate all the duplicate records and by fetching only the unique records. The basic syntax of a DISTINCT keyword to eliminate duplicate records is as follows. SELECT DISTINCT column1, column2,.....columnN FROM table_name WHERE [condition] Consider the CUSTOMERS table having the following records. +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ First, let us see how the following SELECT query returns duplicate salary records. SQL> SELECT SALARY FROM CUSTOMERS ORDER BY SALARY; This would produce the following result where the salary of 2000 is coming twice which is a duplicate record from the original table. +----------+ | SALARY | +----------+ | 1500.00 | | 2000.00 | | 2000.00 | | 4500.00 | | 6500.00 | | 8500.00 | | 10000.00 | +----------+ Now, let us use the DISTINCT keyword with the above SELECT query and see the result. SQL> SELECT DISTINCT SALARY FROM CUSTOMERS ORDER BY SALARY; This would produce the following result where we do not have any duplicate entry. +----------+ | SALARY | +----------+ | 1500.00 | | 2000.00 | | 4500.00 | | 6500.00 | | 8500.00 | | 10000.00 | +----------+ If you take a user input through a webpage and insert it into a SQL database, there is a chance that you have left yourself wide open for a security issue known as the SQL Injection. This chapter will teach you how to help prevent this from happening and help you secure your scripts and SQL statements in your server side scripts such as a PERL Script. Injection usually occurs when you ask a user for input, like their name and instead of a name they give you a SQL statement that you will unknowingly run on your database. Never trust user provided data, process this data only after validation; as a rule, this is done by Pattern Matching. In the example below, the name is restricted to the alphanumerical characters plus underscore and to a length between 8 and 20 characters (modify these rules as needed). if (preg_match("/^\w{8,20}$/", $_GET['username'], $matches)) { $result = mysql_query("SELECT * FROM CUSTOMERS WHERE name = $matches[0]"); } else { echo "user name not accepted"; } To demonstrate the problem, consider this excerpt − // supposed input $name = "Qadir'; DELETE FROM CUSTOMERS;"; mysql_query("SELECT * FROM CUSTOMSRS WHERE name='{$name}'"); The function call is supposed to retrieve a record from the CUSTOMERS table where the name column matches the name specified by the user. Under normal circumstances, $name would only contain alphanumeric characters and perhaps spaces, such as the string ilia. But here, by appending an entirely new query to $name, the call to the database turns into disaster; the injected DELETE query removes all records from the CUSTOMERS table. Fortunately, if you use MySQL, the mysql_query() function does not permit query stacking or executing multiple SQL queries in a single function call. If you try to stack queries, the call fails. However, other PHP database extensions, such as SQLite and PostgreSQL happily perform stacked queries, executing all the queries provided in one string and creating a serious security problem. You can handle all escape characters smartly in scripting languages like PERL and PHP. The MySQL extension for PHP provides the function mysql_real_escape_string() to escape input characters that are special to MySQL. if (get_magic_quotes_gpc()) { $name = stripslashes($name); } $name = mysql_real_escape_string($name); mysql_query("SELECT * FROM CUSTOMERS WHERE name='{$name}'"); To address the LIKE quandary, a custom escaping mechanism must convert user-supplied '%' and '_' characters to literals. Use addcslashes(), a function that lets you specify a character range to escape. $sub = addcslashes(mysql_real_escape_string("%str"), "%_"); // $sub == \%str\_ mysql_query("SELECT * FROM messages WHERE subject LIKE '{$sub}%'"); It takes time to become a Database Expert or an expert Database Administrator. This all comes with lot of experience in various database designs and good trainings. But the following list may be helpful for the beginners to have a nice database performance − Use 3BNF database design explained in this tutorial in RDBMS Concepts chapter. Use 3BNF database design explained in this tutorial in RDBMS Concepts chapter. Avoid number-to-character conversions because numbers and characters compare differently and lead to performance downgrade. Avoid number-to-character conversions because numbers and characters compare differently and lead to performance downgrade. While using SELECT statement, only fetch whatever information is required and avoid using * in your SELECT queries because it would load the system unnecessarily. While using SELECT statement, only fetch whatever information is required and avoid using * in your SELECT queries because it would load the system unnecessarily. Create your indexes carefully on all the tables where you have frequent search operations. Avoid index on the tables where you have less number of search operations and more number of insert and update operations. Create your indexes carefully on all the tables where you have frequent search operations. Avoid index on the tables where you have less number of search operations and more number of insert and update operations. A full-table scan occurs when the columns in the WHERE clause do not have an index associated with them. You can avoid a full-table scan by creating an index on columns that are used as conditions in the WHERE clause of an SQL statement. A full-table scan occurs when the columns in the WHERE clause do not have an index associated with them. You can avoid a full-table scan by creating an index on columns that are used as conditions in the WHERE clause of an SQL statement. Be very careful of equality operators with real numbers and date/time values. Both of these can have small differences that are not obvious to the eye but that make an exact match impossible, thus preventing your queries from ever returning rows. Be very careful of equality operators with real numbers and date/time values. Both of these can have small differences that are not obvious to the eye but that make an exact match impossible, thus preventing your queries from ever returning rows. Use pattern matching judiciously. LIKE COL% is a valid WHERE condition, reducing the returned set to only those records with data starting with the string COL. However, COL%Y does not further reduce the returned results set since %Y cannot be effectively evaluated. The effort to do the evaluation is too large to be considered. In this case, the COL% is used, but the %Y is thrown away. For the same reason, a leading wildcard %COL effectively prevents the entire filter from being used. Use pattern matching judiciously. LIKE COL% is a valid WHERE condition, reducing the returned set to only those records with data starting with the string COL. However, COL%Y does not further reduce the returned results set since %Y cannot be effectively evaluated. The effort to do the evaluation is too large to be considered. In this case, the COL% is used, but the %Y is thrown away. For the same reason, a leading wildcard %COL effectively prevents the entire filter from being used. Fine tune your SQL queries examining the structure of the queries (and subqueries), the SQL syntax, to discover whether you have designed your tables to support fast data manipulation and written the query in an optimum manner, allowing your DBMS to manipulate the data efficiently. Fine tune your SQL queries examining the structure of the queries (and subqueries), the SQL syntax, to discover whether you have designed your tables to support fast data manipulation and written the query in an optimum manner, allowing your DBMS to manipulate the data efficiently. For queries that are executed on a regular basis, try to use procedures. A procedure is a potentially large group of SQL statements. Procedures are compiled by the database engine and then executed. Unlike an SQL statement, the database engine need not optimize the procedure before it is executed. For queries that are executed on a regular basis, try to use procedures. A procedure is a potentially large group of SQL statements. Procedures are compiled by the database engine and then executed. Unlike an SQL statement, the database engine need not optimize the procedure before it is executed. Avoid using the logical operator OR in a query if possible. OR inevitably slows down nearly any query against a table of substantial size. Avoid using the logical operator OR in a query if possible. OR inevitably slows down nearly any query against a table of substantial size. You can optimize bulk data loads by dropping indexes. Imagine the history table with many thousands of rows. That history table is also likely to have one or more indexes. When you think of an index, you normally think of faster table access, but in the case of batch loads, you can benefit by dropping the index(es). You can optimize bulk data loads by dropping indexes. Imagine the history table with many thousands of rows. That history table is also likely to have one or more indexes. When you think of an index, you normally think of faster table access, but in the case of batch loads, you can benefit by dropping the index(es). When performing batch transactions, perform COMMIT at after a fair number of records creation in stead of creating them after every record creation. When performing batch transactions, perform COMMIT at after a fair number of records creation in stead of creating them after every record creation. Plan to defragment the database on a regular basis, even if doing so means developing a weekly routine. Plan to defragment the database on a regular basis, even if doing so means developing a weekly routine. Oracle has many tools for managing SQL statement performance but among them two are very popular. These two tools are − Explain plan − tool identifies the access path that will be taken when the SQL statement is executed. Explain plan − tool identifies the access path that will be taken when the SQL statement is executed. tkprof − measures the performance by time elapsed during each phase of SQL statement processing. tkprof − measures the performance by time elapsed during each phase of SQL statement processing. If you want to simply measure the elapsed time of a query in Oracle, you can use the SQL*Plus command SET TIMING ON. Check your RDBMS documentation for more detail on the above-mentioned tools and defragmenting the database. 42 Lectures 5 hours Anadi Sharma 14 Lectures 2 hours Anadi Sharma 44 Lectures 4.5 hours Anadi Sharma 94 Lectures 7 hours Abhishek And Pukhraj 80 Lectures 6.5 hours Oracle Master Training | 150,000+ Students Worldwide 31 Lectures 6 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2703, "s": 2453, "text": "SQL is a language to operate databases; it includes database creation, deletion, fetching rows, modifying rows, etc. SQL is an ANSI (American National Standards Institute) standard language, but there are many different versions of the SQL language." }, { "code": null, "e": 2845, "s": 2703, "text": "SQL is Structured Query Language, which is a computer language for storing, manipulating and retrieving data stored in a relational database." }, { "code": null, "e": 3078, "s": 2845, "text": "SQL is the standard language for Relational Database System. All the Relational Database Management Systems (RDMS) like MySQL, MS Access, Oracle, Sybase, Informix, Postgres and SQL Server use SQL as their standard database language." }, { "code": null, "e": 3129, "s": 3078, "text": "Also, they are using different dialects, such as −" }, { "code": null, "e": 3157, "s": 3129, "text": " MS SQL Server using T-SQL," }, { "code": null, "e": 3178, "s": 3157, "text": "Oracle using PL/SQL," }, { "code": null, "e": 3242, "s": 3178, "text": "MS Access version of SQL is called JET SQL (native format) etc." }, { "code": null, "e": 3309, "s": 3242, "text": "SQL is widely popular because it offers the following advantages −" }, { "code": null, "e": 3384, "s": 3309, "text": "Allows users to access data in the relational database management systems." }, { "code": null, "e": 3459, "s": 3384, "text": "Allows users to access data in the relational database management systems." }, { "code": null, "e": 3494, "s": 3459, "text": "Allows users to describe the data." }, { "code": null, "e": 3529, "s": 3494, "text": "Allows users to describe the data." }, { "code": null, "e": 3601, "s": 3529, "text": "Allows users to define the data in a database and manipulate that data." }, { "code": null, "e": 3673, "s": 3601, "text": "Allows users to define the data in a database and manipulate that data." }, { "code": null, "e": 3758, "s": 3673, "text": "Allows to embed within other languages using SQL modules, libraries & pre-compilers." }, { "code": null, "e": 3843, "s": 3758, "text": "Allows to embed within other languages using SQL modules, libraries & pre-compilers." }, { "code": null, "e": 3897, "s": 3843, "text": "Allows users to create and drop databases and tables." }, { "code": null, "e": 3951, "s": 3897, "text": "Allows users to create and drop databases and tables." }, { "code": null, "e": 4023, "s": 3951, "text": "Allows users to create view, stored procedure, functions in a database." }, { "code": null, "e": 4095, "s": 4023, "text": "Allows users to create view, stored procedure, functions in a database." }, { "code": null, "e": 4160, "s": 4095, "text": "Allows users to set permissions on tables, procedures and views." }, { "code": null, "e": 4225, "s": 4160, "text": "Allows users to set permissions on tables, procedures and views." }, { "code": null, "e": 4358, "s": 4225, "text": "1970 − Dr. Edgar F. \"Ted\" Codd of IBM is known as the father of relational databases. He described a relational model for databases." }, { "code": null, "e": 4491, "s": 4358, "text": "1970 − Dr. Edgar F. \"Ted\" Codd of IBM is known as the father of relational databases. He described a relational model for databases." }, { "code": null, "e": 4534, "s": 4491, "text": "1974 − Structured Query Language appeared." }, { "code": null, "e": 4577, "s": 4534, "text": "1974 − Structured Query Language appeared." }, { "code": null, "e": 4658, "s": 4577, "text": "1978 − IBM worked to develop Codd's ideas and released a product named System/R." }, { "code": null, "e": 4739, "s": 4658, "text": "1978 − IBM worked to develop Codd's ideas and released a product named System/R." }, { "code": null, "e": 4935, "s": 4739, "text": "1986 − IBM developed the first prototype of relational database and standardized by ANSI. The first relational database was released by Relational Software which later came to be known as Oracle." }, { "code": null, "e": 5131, "s": 4935, "text": "1986 − IBM developed the first prototype of relational database and standardized by ANSI. The first relational database was released by Relational Software which later came to be known as Oracle." }, { "code": null, "e": 5299, "s": 5131, "text": "When you are executing an SQL command for any RDBMS, the system determines the best way to carry out your request and SQL engine figures out how to interpret the task." }, { "code": null, "e": 5354, "s": 5299, "text": "There are various components included in this process." }, { "code": null, "e": 5377, "s": 5354, "text": "These components are −" }, { "code": null, "e": 5394, "s": 5377, "text": "Query Dispatcher" }, { "code": null, "e": 5415, "s": 5394, "text": "Optimization Engines" }, { "code": null, "e": 5436, "s": 5415, "text": "Classic Query Engine" }, { "code": null, "e": 5459, "s": 5436, "text": "SQL Query Engine, etc." }, { "code": null, "e": 5566, "s": 5459, "text": "A classic query engine handles all the non-SQL queries, but a SQL query engine won't handle logical files." }, { "code": null, "e": 5627, "s": 5566, "text": "Following is a simple diagram showing the SQL Architecture −" }, { "code": null, "e": 5827, "s": 5627, "text": "The standard SQL commands to interact with relational databases are CREATE, SELECT, INSERT, UPDATE, DELETE and DROP. These commands can be classified into the following groups based on their nature −" }, { "code": null, "e": 5834, "s": 5827, "text": "CREATE" }, { "code": null, "e": 5907, "s": 5834, "text": "Creates a new table, a view of a table, or other object in the database." }, { "code": null, "e": 5913, "s": 5907, "text": "ALTER" }, { "code": null, "e": 5968, "s": 5913, "text": "Modifies an existing database object, such as a table." }, { "code": null, "e": 5973, "s": 5968, "text": "DROP" }, { "code": null, "e": 6050, "s": 5973, "text": "Deletes an entire table, a view of a table or other objects in the database." }, { "code": null, "e": 6057, "s": 6050, "text": "SELECT" }, { "code": null, "e": 6108, "s": 6057, "text": "Retrieves certain records from one or more tables." }, { "code": null, "e": 6115, "s": 6108, "text": "INSERT" }, { "code": null, "e": 6133, "s": 6115, "text": "Creates a record." }, { "code": null, "e": 6140, "s": 6133, "text": "UPDATE" }, { "code": null, "e": 6158, "s": 6140, "text": "Modifies records." }, { "code": null, "e": 6165, "s": 6158, "text": "DELETE" }, { "code": null, "e": 6182, "s": 6165, "text": "Deletes records." }, { "code": null, "e": 6188, "s": 6182, "text": "GRANT" }, { "code": null, "e": 6215, "s": 6188, "text": "Gives a privilege to user." }, { "code": null, "e": 6222, "s": 6215, "text": "REVOKE" }, { "code": null, "e": 6263, "s": 6222, "text": "Takes back privileges granted from user." }, { "code": null, "e": 6449, "s": 6263, "text": "RDBMS stands for Relational Database Management System. RDBMS is the basis for SQL, and for all modern database systems like MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access." }, { "code": null, "e": 6603, "s": 6449, "text": "A Relational database management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced by E. F. Codd." }, { "code": null, "e": 6789, "s": 6603, "text": "The data in an RDBMS is stored in database objects which are called as tables. This table is basically a collection of related data entries and it consists of numerous columns and rows." }, { "code": null, "e": 6945, "s": 6789, "text": "Remember, a table is the most common and simplest form of data storage in a relational database. The following program is an example of a CUSTOMERS table −" }, { "code": null, "e": 7462, "s": 6945, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+" }, { "code": null, "e": 7604, "s": 7462, "text": "Every table is broken up into smaller entities called fields. The fields in the CUSTOMERS table consist of ID, NAME, AGE, ADDRESS and SALARY." }, { "code": null, "e": 7718, "s": 7604, "text": "A field is a column in a table that is designed to maintain specific information about every record in the table." }, { "code": null, "e": 7940, "s": 7718, "text": "A record is also called as a row of data is each individual entry that exists in a table. For example, there are 7 records in the above CUSTOMERS table. Following is a single row of data or record in the CUSTOMERS table −" }, { "code": null, "e": 8081, "s": 7940, "text": "+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n+----+----------+-----+-----------+----------+" }, { "code": null, "e": 8125, "s": 8081, "text": "A record is a horizontal entity in a table." }, { "code": null, "e": 8241, "s": 8125, "text": "A column is a vertical entity in a table that contains all information associated with a specific field in a table." }, { "code": null, "e": 8366, "s": 8241, "text": "For example, a column in the CUSTOMERS table is ADDRESS, which represents location description and would be as shown below −" }, { "code": null, "e": 8520, "s": 8366, "text": "+-----------+\n| ADDRESS |\n+-----------+\n| Ahmedabad |\n| Delhi |\n| Kota |\n| Mumbai |\n| Bhopal |\n| MP |\n| Indore |\n+----+------+" }, { "code": null, "e": 8656, "s": 8520, "text": "A NULL value in a table is a value in a field that appears to be blank, which means a field with a NULL value is a field with no value." }, { "code": null, "e": 8861, "s": 8656, "text": "It is very important to understand that a NULL value is different than a zero value or a field that contains spaces. A field with a NULL value is the one that has been left blank during a record creation." }, { "code": null, "e": 9062, "s": 8861, "text": "Constraints are the rules enforced on data columns on a table. These are used to limit the type of data that can go into a table. This ensures the accuracy and reliability of the data in the database." }, { "code": null, "e": 9239, "s": 9062, "text": "Constraints can either be column level or table level. Column level constraints are applied only to one column whereas, table level constraints are applied to the entire table." }, { "code": null, "e": 9315, "s": 9239, "text": "Following are some of the most commonly used constraints available in SQL −" }, { "code": null, "e": 9385, "s": 9315, "text": "NOT NULL Constraint − Ensures that a column cannot have a NULL value." }, { "code": null, "e": 9455, "s": 9385, "text": "NOT NULL Constraint − Ensures that a column cannot have a NULL value." }, { "code": null, "e": 9538, "s": 9455, "text": "DEFAULT Constraint − Provides a default value for a column when none is specified." }, { "code": null, "e": 9621, "s": 9538, "text": "DEFAULT Constraint − Provides a default value for a column when none is specified." }, { "code": null, "e": 9696, "s": 9621, "text": "UNIQUE Constraint − Ensures that all the values in a column are different." }, { "code": null, "e": 9771, "s": 9696, "text": "UNIQUE Constraint − Ensures that all the values in a column are different." }, { "code": null, "e": 9842, "s": 9771, "text": "PRIMARY Key − Uniquely identifies each row/record in a database table." }, { "code": null, "e": 9913, "s": 9842, "text": "PRIMARY Key − Uniquely identifies each row/record in a database table." }, { "code": null, "e": 9991, "s": 9913, "text": "FOREIGN Key − Uniquely identifies a row/record in any another database table." }, { "code": null, "e": 10069, "s": 9991, "text": "FOREIGN Key − Uniquely identifies a row/record in any another database table." }, { "code": null, "e": 10173, "s": 10069, "text": "CHECK Constraint − The CHECK constraint ensures that all values in a column satisfy certain conditions." }, { "code": null, "e": 10277, "s": 10173, "text": "CHECK Constraint − The CHECK constraint ensures that all values in a column satisfy certain conditions." }, { "code": null, "e": 10350, "s": 10277, "text": "INDEX − Used to create and retrieve data from the database very quickly." }, { "code": null, "e": 10423, "s": 10350, "text": "INDEX − Used to create and retrieve data from the database very quickly." }, { "code": null, "e": 10490, "s": 10423, "text": "The following categories of data integrity exist with each RDBMS −" }, { "code": null, "e": 10549, "s": 10490, "text": "Entity Integrity − There are no duplicate rows in a table." }, { "code": null, "e": 10608, "s": 10549, "text": "Entity Integrity − There are no duplicate rows in a table." }, { "code": null, "e": 10730, "s": 10608, "text": "Domain Integrity − Enforces valid entries for a given column by restricting the type, the format, or the range of values." }, { "code": null, "e": 10852, "s": 10730, "text": "Domain Integrity − Enforces valid entries for a given column by restricting the type, the format, or the range of values." }, { "code": null, "e": 10933, "s": 10852, "text": "Referential integrity − Rows cannot be deleted, which are used by other records." }, { "code": null, "e": 11014, "s": 10933, "text": "Referential integrity − Rows cannot be deleted, which are used by other records." }, { "code": null, "e": 11140, "s": 11014, "text": "User-Defined Integrity − Enforces some specific business rules that do not fall into entity, domain or referential integrity." }, { "code": null, "e": 11266, "s": 11140, "text": "User-Defined Integrity − Enforces some specific business rules that do not fall into entity, domain or referential integrity." }, { "code": null, "e": 11404, "s": 11266, "text": "Database normalization is the process of efficiently organizing data in a database. There are two reasons of this normalization process −" }, { "code": null, "e": 11491, "s": 11404, "text": "Eliminating redundant data, for example, storing the same data in more than one table." }, { "code": null, "e": 11578, "s": 11491, "text": "Eliminating redundant data, for example, storing the same data in more than one table." }, { "code": null, "e": 11617, "s": 11578, "text": "Ensuring data dependencies make sense." }, { "code": null, "e": 11656, "s": 11617, "text": "Ensuring data dependencies make sense." }, { "code": null, "e": 11898, "s": 11656, "text": "Both these reasons are worthy goals as they reduce the amount of space a database consumes and ensures that data is logically stored. Normalization consists of a series of guidelines that help guide you in creating a good database structure." }, { "code": null, "e": 12208, "s": 11898, "text": "Normalization guidelines are divided into normal forms; think of a form as the format or the way a database structure is laid out. The aim of normal forms is to organize the database structure, so that it complies with the rules of first normal form, then second normal form and finally the third normal form." }, { "code": null, "e": 12367, "s": 12208, "text": "It is your choice to take it further and go to the fourth normal form, fifth normal form and so on, but in general, the third normal form is more than enough." }, { "code": null, "e": 12391, "s": 12367, "text": "First Normal Form (1NF)" }, { "code": null, "e": 12416, "s": 12391, "text": "Second Normal Form (2NF)" }, { "code": null, "e": 12440, "s": 12416, "text": "Third Normal Form (3NF)" }, { "code": null, "e": 12620, "s": 12440, "text": "There are many popular RDBMS available to work with. This tutorial gives a brief overview of some of the most popular RDBMS’s. This would help you to compare their basic features." }, { "code": null, "e": 12794, "s": 12620, "text": "MySQL is an open source SQL database, which is developed by a Swedish company – MySQL AB. MySQL is pronounced as \"my ess-que-ell,\" in contrast with SQL, pronounced \"sequel.\"" }, { "code": null, "e": 12919, "s": 12794, "text": "MySQL is supporting many different platforms including Microsoft Windows, the major Linux distributions, UNIX, and Mac OS X." }, { "code": null, "e": 13107, "s": 12919, "text": "MySQL has free and paid versions, depending on its usage (non-commercial/commercial) and features. MySQL comes with a very fast, multi-threaded, multi-user and robust SQL database server." }, { "code": null, "e": 13182, "s": 13107, "text": "Development of MySQL by Michael Widenius & David Axmark beginning in 1994." }, { "code": null, "e": 13257, "s": 13182, "text": "Development of MySQL by Michael Widenius & David Axmark beginning in 1994." }, { "code": null, "e": 13300, "s": 13257, "text": "First internal release on 23rd May 1995. \n" }, { "code": null, "e": 13343, "s": 13300, "text": "First internal release on 23rd May 1995. \n" }, { "code": null, "e": 13419, "s": 13343, "text": "Windows Version was released on the 8th January 1998 for Windows 95 and NT." }, { "code": null, "e": 13495, "s": 13419, "text": "Windows Version was released on the 8th January 1998 for Windows 95 and NT." }, { "code": null, "e": 13563, "s": 13495, "text": "Version 3.23: beta from June 2000, production release January 2001." }, { "code": null, "e": 13631, "s": 13563, "text": "Version 3.23: beta from June 2000, production release January 2001." }, { "code": null, "e": 13707, "s": 13631, "text": "Version 4.0: beta from August 2002, production release March 2003 (unions)." }, { "code": null, "e": 13783, "s": 13707, "text": "Version 4.0: beta from August 2002, production release March 2003 (unions)." }, { "code": null, "e": 13850, "s": 13783, "text": "Version 4.1: beta from June 2004, production release October 2004." }, { "code": null, "e": 13917, "s": 13850, "text": "Version 4.1: beta from June 2004, production release October 2004." }, { "code": null, "e": 13985, "s": 13917, "text": "Version 5.0: beta from March 2005, production release October 2005." }, { "code": null, "e": 14053, "s": 13985, "text": "Version 5.0: beta from March 2005, production release October 2005." }, { "code": null, "e": 14115, "s": 14053, "text": "Sun Microsystems acquired MySQL AB on the 26th February 2008." }, { "code": null, "e": 14177, "s": 14115, "text": "Sun Microsystems acquired MySQL AB on the 26th February 2008." }, { "code": null, "e": 14229, "s": 14177, "text": "Version 5.1: production release 27th November 2008." }, { "code": null, "e": 14281, "s": 14229, "text": "Version 5.1: production release 27th November 2008." }, { "code": null, "e": 14299, "s": 14281, "text": "High Performance." }, { "code": null, "e": 14318, "s": 14299, "text": "High Availability." }, { "code": null, "e": 14360, "s": 14318, "text": "Scalability and Flexibility Run anything." }, { "code": null, "e": 14390, "s": 14360, "text": "Robust Transactional Support." }, { "code": null, "e": 14424, "s": 14390, "text": "Web and Data Warehouse Strengths." }, { "code": null, "e": 14448, "s": 14424, "text": "Strong Data Protection." }, { "code": null, "e": 14487, "s": 14448, "text": "Comprehensive Application Development." }, { "code": null, "e": 14504, "s": 14487, "text": "Management Ease." }, { "code": null, "e": 14544, "s": 14504, "text": "Open Source Freedom and 24 x 7 Support." }, { "code": null, "e": 14576, "s": 14544, "text": "Lowest Total Cost of Ownership." }, { "code": null, "e": 14695, "s": 14576, "text": "MS SQL Server is a Relational Database Management System developed by Microsoft Inc. Its primary query languages are −" }, { "code": null, "e": 14701, "s": 14695, "text": "T-SQL" }, { "code": null, "e": 14710, "s": 14701, "text": "ANSI SQL" }, { "code": null, "e": 14754, "s": 14710, "text": "1987 - Sybase releases SQL Server for UNIX." }, { "code": null, "e": 14798, "s": 14754, "text": "1987 - Sybase releases SQL Server for UNIX." }, { "code": null, "e": 14864, "s": 14798, "text": "1988 - Microsoft, Sybase, and Aston-Tate port SQL Server to OS/2." }, { "code": null, "e": 14930, "s": 14864, "text": "1988 - Microsoft, Sybase, and Aston-Tate port SQL Server to OS/2." }, { "code": null, "e": 15004, "s": 14930, "text": "1989 - Microsoft, Sybase, and Aston-Tate release SQL Server 1.0 for OS/2." }, { "code": null, "e": 15078, "s": 15004, "text": "1989 - Microsoft, Sybase, and Aston-Tate release SQL Server 1.0 for OS/2." }, { "code": null, "e": 15150, "s": 15078, "text": "1990 - SQL Server 1.1 is released with support for Windows 3.0 clients." }, { "code": null, "e": 15222, "s": 15150, "text": "1990 - SQL Server 1.1 is released with support for Windows 3.0 clients." }, { "code": null, "e": 15272, "s": 15222, "text": "Aston - Tate drops out of SQL Server development." }, { "code": null, "e": 15322, "s": 15272, "text": "Aston - Tate drops out of SQL Server development." }, { "code": null, "e": 15365, "s": 15322, "text": "2000 - Microsoft releases SQL Server 2000." }, { "code": null, "e": 15408, "s": 15365, "text": "2000 - Microsoft releases SQL Server 2000." }, { "code": null, "e": 15479, "s": 15408, "text": "2001 - Microsoft releases XML for SQL Server Web Release 1 (download)." }, { "code": null, "e": 15550, "s": 15479, "text": "2001 - Microsoft releases XML for SQL Server Web Release 1 (download)." }, { "code": null, "e": 15622, "s": 15550, "text": "2002 - Microsoft releases SQLXML 2.0 (renamed from XML for SQL Server)." }, { "code": null, "e": 15694, "s": 15622, "text": "2002 - Microsoft releases SQLXML 2.0 (renamed from XML for SQL Server)." }, { "code": null, "e": 15733, "s": 15694, "text": "2002 - Microsoft releases SQLXML 3.0." }, { "code": null, "e": 15772, "s": 15733, "text": "2002 - Microsoft releases SQLXML 3.0." }, { "code": null, "e": 15837, "s": 15772, "text": "2005 - Microsoft releases SQL Server 2005 on November 7th, 2005." }, { "code": null, "e": 15902, "s": 15837, "text": "2005 - Microsoft releases SQL Server 2005 on November 7th, 2005." }, { "code": null, "e": 15919, "s": 15902, "text": "High Performance" }, { "code": null, "e": 15937, "s": 15919, "text": "High Availability" }, { "code": null, "e": 15956, "s": 15937, "text": "Database mirroring" }, { "code": null, "e": 15975, "s": 15956, "text": "Database snapshots" }, { "code": null, "e": 15991, "s": 15975, "text": "CLR integration" }, { "code": null, "e": 16006, "s": 15991, "text": "Service Broker" }, { "code": null, "e": 16019, "s": 16006, "text": "DDL triggers" }, { "code": null, "e": 16037, "s": 16019, "text": "Ranking functions" }, { "code": null, "e": 16072, "s": 16037, "text": "Row version-based isolation levels" }, { "code": null, "e": 16088, "s": 16072, "text": "XML integration" }, { "code": null, "e": 16100, "s": 16088, "text": "TRY...CATCH" }, { "code": null, "e": 16114, "s": 16100, "text": "Database Mail" }, { "code": null, "e": 16263, "s": 16114, "text": "It is a very large multi-user based database management system. Oracle is a relational database management system developed by 'Oracle Corporation'." }, { "code": null, "e": 16410, "s": 16263, "text": "Oracle works to efficiently manage its resources, a database of information among the multiple clients requesting and sending data in the network." }, { "code": null, "e": 16619, "s": 16410, "text": "It is an excellent database server choice for client/server computing. Oracle supports all major operating systems for both clients and servers, including MSDOS, NetWare, UnixWare, OS/2 and most UNIX flavors." }, { "code": null, "e": 16716, "s": 16619, "text": "Oracle began in 1977 and celebrating its 32 wonderful years in the industry (from 1977 to 2009)." }, { "code": null, "e": 16834, "s": 16716, "text": "1977 - Larry Ellison, Bob Miner and Ed Oates founded Software Development Laboratories to undertake development work." }, { "code": null, "e": 16952, "s": 16834, "text": "1977 - Larry Ellison, Bob Miner and Ed Oates founded Software Development Laboratories to undertake development work." }, { "code": null, "e": 17133, "s": 16952, "text": "1979 - Version 2.0 of Oracle was released and it became first commercial relational database and first SQL database. The company changed its name to Relational Software Inc. (RSI)." }, { "code": null, "e": 17314, "s": 17133, "text": "1979 - Version 2.0 of Oracle was released and it became first commercial relational database and first SQL database. The company changed its name to Relational Software Inc. (RSI)." }, { "code": null, "e": 17362, "s": 17314, "text": "1981 - RSI started developing tools for Oracle." }, { "code": null, "e": 17410, "s": 17362, "text": "1981 - RSI started developing tools for Oracle." }, { "code": null, "e": 17456, "s": 17410, "text": "1982 - RSI was renamed to Oracle Corporation." }, { "code": null, "e": 17502, "s": 17456, "text": "1982 - RSI was renamed to Oracle Corporation." }, { "code": null, "e": 17593, "s": 17502, "text": "1983 - Oracle released version 3.0, rewritten in C language and ran on multiple platforms." }, { "code": null, "e": 17684, "s": 17593, "text": "1983 - Oracle released version 3.0, rewritten in C language and ran on multiple platforms." }, { "code": null, "e": 17810, "s": 17684, "text": "1984 - Oracle version 4.0 was released. It contained features like concurrency control - multi-version read consistency, etc." }, { "code": null, "e": 17936, "s": 17810, "text": "1984 - Oracle version 4.0 was released. It contained features like concurrency control - multi-version read consistency, etc." }, { "code": null, "e": 18062, "s": 17936, "text": "1985 - Oracle version 4.0 was released. It contained features like concurrency control - multi-version read consistency, etc." }, { "code": null, "e": 18188, "s": 18062, "text": "1985 - Oracle version 4.0 was released. It contained features like concurrency control - multi-version read consistency, etc." }, { "code": null, "e": 18291, "s": 18188, "text": "2007 - Oracle released Oracle11g. The new version focused on better partitioning, easy migration, etc." }, { "code": null, "e": 18394, "s": 18291, "text": "2007 - Oracle released Oracle11g. The new version focused on better partitioning, easy migration, etc." }, { "code": null, "e": 18406, "s": 18394, "text": "Concurrency" }, { "code": null, "e": 18423, "s": 18406, "text": "Read Consistency" }, { "code": null, "e": 18442, "s": 18423, "text": "Locking Mechanisms" }, { "code": null, "e": 18459, "s": 18442, "text": "Quiesce Database" }, { "code": null, "e": 18471, "s": 18459, "text": "Portability" }, { "code": null, "e": 18494, "s": 18471, "text": "Self-managing database" }, { "code": null, "e": 18503, "s": 18494, "text": "SQL*Plus" }, { "code": null, "e": 18507, "s": 18503, "text": "ASM" }, { "code": null, "e": 18517, "s": 18507, "text": "Scheduler" }, { "code": null, "e": 18534, "s": 18517, "text": "Resource Manager" }, { "code": null, "e": 18551, "s": 18534, "text": "Data Warehousing" }, { "code": null, "e": 18570, "s": 18551, "text": "Materialized views" }, { "code": null, "e": 18585, "s": 18570, "text": "Bitmap indexes" }, { "code": null, "e": 18603, "s": 18585, "text": "Table compression" }, { "code": null, "e": 18622, "s": 18603, "text": "Parallel Execution" }, { "code": null, "e": 18635, "s": 18622, "text": "Analytic SQL" }, { "code": null, "e": 18647, "s": 18635, "text": "Data mining" }, { "code": null, "e": 18660, "s": 18647, "text": "Partitioning" }, { "code": null, "e": 18875, "s": 18660, "text": "This is one of the most popular Microsoft products. Microsoft Access is an entry-level database management software. MS Access database is not only inexpensive but also a powerful database for small-scale projects." }, { "code": null, "e": 18998, "s": 18875, "text": "MS Access uses the Jet database engine, which utilizes a specific SQL language dialect (sometimes referred to as Jet SQL)." }, { "code": null, "e": 19122, "s": 18998, "text": "MS Access comes with the professional edition of MS Office package. MS Access has easyto-use intuitive graphical interface." }, { "code": null, "e": 19162, "s": 19122, "text": "1992 - Access version 1.0 was released." }, { "code": null, "e": 19202, "s": 19162, "text": "1992 - Access version 1.0 was released." }, { "code": null, "e": 19308, "s": 19202, "text": "1993 - Access 1.1 released to improve compatibility with inclusion the Access Basic programming language." }, { "code": null, "e": 19414, "s": 19308, "text": "1993 - Access 1.1 released to improve compatibility with inclusion the Access Basic programming language." }, { "code": null, "e": 19481, "s": 19414, "text": "The most significant transition was from Access 97 to Access 2000." }, { "code": null, "e": 19548, "s": 19481, "text": "The most significant transition was from Access 97 to Access 2000." }, { "code": null, "e": 19689, "s": 19548, "text": "2007 - Access 2007, a new database format was introduced ACCDB which supports complex data types such as multi valued and attachment fields." }, { "code": null, "e": 19830, "s": 19689, "text": "2007 - Access 2007, a new database format was introduced ACCDB which supports complex data types such as multi valued and attachment fields." }, { "code": null, "e": 19921, "s": 19830, "text": "Users can create tables, queries, forms and reports and connect them together with macros." }, { "code": null, "e": 20012, "s": 19921, "text": "Users can create tables, queries, forms and reports and connect them together with macros." }, { "code": null, "e": 20159, "s": 20012, "text": "Option of importing and exporting the data to many formats including Excel, Outlook, ASCII, dBase, Paradox, FoxPro, SQL Server, Oracle, ODBC, etc." }, { "code": null, "e": 20306, "s": 20159, "text": "Option of importing and exporting the data to many formats including Excel, Outlook, ASCII, dBase, Paradox, FoxPro, SQL Server, Oracle, ODBC, etc." }, { "code": null, "e": 20560, "s": 20306, "text": "There is also the Jet Database format (MDB or ACCDB in Access 2007), which can contain the application and data in one file. This makes it very convenient to distribute the entire application to another user, who can run it in disconnected environments." }, { "code": null, "e": 20814, "s": 20560, "text": "There is also the Jet Database format (MDB or ACCDB in Access 2007), which can contain the application and data in one file. This makes it very convenient to distribute the entire application to another user, who can run it in disconnected environments." }, { "code": null, "e": 20969, "s": 20814, "text": "Microsoft Access offers parameterized queries. These queries and Access tables can be referenced from other programs like VB6 and .NET through DAO or ADO." }, { "code": null, "e": 21124, "s": 20969, "text": "Microsoft Access offers parameterized queries. These queries and Access tables can be referenced from other programs like VB6 and .NET through DAO or ADO." }, { "code": null, "e": 21239, "s": 21124, "text": "The desktop editions of Microsoft SQL Server can be used with Access as an alternative to the Jet Database Engine." }, { "code": null, "e": 21354, "s": 21239, "text": "The desktop editions of Microsoft SQL Server can be used with Access as an alternative to the Jet Database Engine." }, { "code": null, "e": 21574, "s": 21354, "text": "Microsoft Access is a file server-based database. Unlike the client-server relational database management systems (RDBMS), Microsoft Access does not implement database triggers, stored procedures or transaction logging." }, { "code": null, "e": 21794, "s": 21574, "text": "Microsoft Access is a file server-based database. Unlike the client-server relational database management systems (RDBMS), Microsoft Access does not implement database triggers, stored procedures or transaction logging." }, { "code": null, "e": 21949, "s": 21794, "text": "SQL is followed by a unique set of rules and guidelines called Syntax. This tutorial gives you a quick start with SQL by listing all the basic SQL Syntax." }, { "code": null, "e": 22120, "s": 21949, "text": "All the SQL statements start with any of the keywords like SELECT, INSERT, UPDATE, DELETE, ALTER, DROP, CREATE, USE, SHOW and all the statements end with a semicolon (;)." }, { "code": null, "e": 22410, "s": 22120, "text": "The most important point to be noted here is that SQL is case insensitive, which means SELECT and select have same meaning in SQL statements. Whereas, MySQL makes difference in table names. So, if you are working with MySQL, then you need to give table names as they exist in the database." }, { "code": null, "e": 22465, "s": 22410, "text": "SELECT column1, column2....columnN\nFROM table_name;\n" }, { "code": null, "e": 22529, "s": 22465, "text": "SELECT DISTINCT column1, column2....columnN\nFROM table_name;\n" }, { "code": null, "e": 22601, "s": 22529, "text": "SELECT column1, column2....columnN\nFROM table_name\nWHERE CONDITION;\n" }, { "code": null, "e": 22696, "s": 22601, "text": "SELECT column1, column2....columnN\nFROM table_name\nWHERE CONDITION-1 {AND|OR} CONDITION-2;\n" }, { "code": null, "e": 22797, "s": 22696, "text": "SELECT column1, column2....columnN\nFROM table_name\nWHERE column_name IN (val-1, val-2,...val-N);\n" }, { "code": null, "e": 22895, "s": 22797, "text": "SELECT column1, column2....columnN\nFROM table_name\nWHERE column_name BETWEEN val-1 AND val-2;\n" }, { "code": null, "e": 22986, "s": 22895, "text": "SELECT column1, column2....columnN\nFROM table_name\nWHERE column_name LIKE { PATTERN };\n" }, { "code": null, "e": 23090, "s": 22986, "text": "SELECT column1, column2....columnN\nFROM table_name\nWHERE CONDITION\nORDER BY column_name {ASC|DESC};\n" }, { "code": null, "e": 23172, "s": 23090, "text": "SELECT SUM(column_name)\nFROM table_name\nWHERE CONDITION\nGROUP BY column_name;\n" }, { "code": null, "e": 23235, "s": 23172, "text": "SELECT COUNT(column_name)\nFROM table_name\nWHERE CONDITION;\n" }, { "code": null, "e": 23357, "s": 23235, "text": "SELECT SUM(column_name)\nFROM table_name\nWHERE CONDITION\nGROUP BY column_name\nHAVING (arithematic function condition);\n" }, { "code": null, "e": 23499, "s": 23357, "text": "CREATE TABLE table_name(\ncolumn1 datatype,\ncolumn2 datatype,\ncolumn3 datatype,\n.....\ncolumnN datatype,\nPRIMARY KEY( one or more columns )\n);\n" }, { "code": null, "e": 23523, "s": 23499, "text": "DROP TABLE table_name;\n" }, { "code": null, "e": 23601, "s": 23523, "text": "CREATE UNIQUE INDEX index_name\nON table_name ( column1, column2,...columnN);\n" }, { "code": null, "e": 23648, "s": 23601, "text": "ALTER TABLE table_name\nDROP INDEX index_name;\n" }, { "code": null, "e": 23666, "s": 23648, "text": "DESC table_name;\n" }, { "code": null, "e": 23694, "s": 23666, "text": "TRUNCATE TABLE table_name;\n" }, { "code": null, "e": 23760, "s": 23694, "text": "ALTER TABLE table_name {ADD|DROP|MODIFY} column_name {data_ype};\n" }, { "code": null, "e": 23810, "s": 23760, "text": "ALTER TABLE table_name RENAME TO new_table_name;\n" }, { "code": null, "e": 23900, "s": 23810, "text": "INSERT INTO table_name( column1, column2....columnN)\nVALUES ( value1, value2....valueN);\n" }, { "code": null, "e": 23998, "s": 23900, "text": "UPDATE table_name\nSET column1 = value1, column2 = value2....columnN=valueN\n[ WHERE CONDITION ];\n" }, { "code": null, "e": 24042, "s": 23998, "text": "DELETE FROM table_name\nWHERE {CONDITION};\n" }, { "code": null, "e": 24074, "s": 24042, "text": "CREATE DATABASE database_name;\n" }, { "code": null, "e": 24104, "s": 24074, "text": "DROP DATABASE database_name;\n" }, { "code": null, "e": 24124, "s": 24104, "text": "USE database_name;\n" }, { "code": null, "e": 24133, "s": 24124, "text": "COMMIT;\n" }, { "code": null, "e": 24144, "s": 24133, "text": "ROLLBACK;\n" }, { "code": null, "e": 24420, "s": 24144, "text": "SQL Data Type is an attribute that specifies the type of data of any object. Each column, variable and expression has a related data type in SQL. You can use these data types while creating your tables. You can choose a data type for a table column based on your requirement." }, { "code": null, "e": 24505, "s": 24420, "text": "SQL Server offers six categories of data types for your use which are listed below −" }, { "code": null, "e": 24604, "s": 24505, "text": "Note − Here, datetime has 3.33 milliseconds accuracy where as smalldatetime has 1 minute accuracy." }, { "code": null, "e": 24609, "s": 24604, "text": "char" }, { "code": null, "e": 24683, "s": 24609, "text": "Maximum length of 8,000 characters.( Fixed length non-Unicode characters)" }, { "code": null, "e": 24691, "s": 24683, "text": "varchar" }, { "code": null, "e": 24755, "s": 24691, "text": "Maximum of 8,000 characters.(Variable-length non-Unicode data)." }, { "code": null, "e": 24768, "s": 24755, "text": "varchar(max)" }, { "code": null, "e": 24863, "s": 24768, "text": "Maximum length of 2E + 31 characters, Variable-length non-Unicode data (SQL Server 2005 only)." }, { "code": null, "e": 24868, "s": 24863, "text": "text" }, { "code": null, "e": 24952, "s": 24868, "text": "Variable-length non-Unicode data with a maximum length of 2,147,483,647 characters." }, { "code": null, "e": 24958, "s": 24952, "text": "nchar" }, { "code": null, "e": 25017, "s": 24958, "text": "Maximum length of 4,000 characters.( Fixed length Unicode)" }, { "code": null, "e": 25026, "s": 25017, "text": "nvarchar" }, { "code": null, "e": 25087, "s": 25026, "text": "Maximum length of 4,000 characters.(Variable length Unicode)" }, { "code": null, "e": 25101, "s": 25087, "text": "nvarchar(max)" }, { "code": null, "e": 25188, "s": 25101, "text": "Maximum length of 2E + 31 characters (SQL Server 2005 only).( Variable length Unicode)" }, { "code": null, "e": 25194, "s": 25188, "text": "ntext" }, { "code": null, "e": 25266, "s": 25194, "text": "Maximum length of 1,073,741,823 characters. ( Variable length Unicode )" }, { "code": null, "e": 25273, "s": 25266, "text": "binary" }, { "code": null, "e": 25330, "s": 25273, "text": "Maximum length of 8,000 bytes(Fixed-length binary data )" }, { "code": null, "e": 25340, "s": 25330, "text": "varbinary" }, { "code": null, "e": 25400, "s": 25340, "text": "Maximum length of 8,000 bytes.(Variable length binary data)" }, { "code": null, "e": 25415, "s": 25400, "text": "varbinary(max)" }, { "code": null, "e": 25502, "s": 25415, "text": "Maximum length of 2E + 31 bytes (SQL Server 2005 only). ( Variable length Binary data)" }, { "code": null, "e": 25508, "s": 25502, "text": "image" }, { "code": null, "e": 25578, "s": 25508, "text": "Maximum length of 2,147,483,647 bytes. ( Variable length Binary Data)" }, { "code": null, "e": 25590, "s": 25578, "text": "sql_variant" }, { "code": null, "e": 25683, "s": 25590, "text": "Stores values of various SQL Server-supported data types, except text, ntext, and timestamp." }, { "code": null, "e": 25693, "s": 25683, "text": "timestamp" }, { "code": null, "e": 25778, "s": 25693, "text": "Stores a database-wide unique number that gets updated every time a row gets updated" }, { "code": null, "e": 25795, "s": 25778, "text": "uniqueidentifier" }, { "code": null, "e": 25838, "s": 25795, "text": "Stores a globally unique identifier (GUID)" }, { "code": null, "e": 25842, "s": 25838, "text": "xml" }, { "code": null, "e": 25937, "s": 25842, "text": "Stores XML data. You can store xml instances in a column or a variable (SQL Server 2005 only)." }, { "code": null, "e": 25944, "s": 25937, "text": "cursor" }, { "code": null, "e": 25973, "s": 25944, "text": "Reference to a cursor object" }, { "code": null, "e": 25979, "s": 25973, "text": "table" }, { "code": null, "e": 26020, "s": 25979, "text": "Stores a result set for later processing" }, { "code": null, "e": 26324, "s": 26020, "text": "An operator is a reserved word or a character used primarily in an SQL statement's WHERE clause to perform operation(s), such as comparisons and arithmetic operations. These Operators are used to specify conditions in an SQL statement and to serve as conjunctions for multiple conditions in a statement." }, { "code": null, "e": 26345, "s": 26324, "text": "Arithmetic operators" }, { "code": null, "e": 26366, "s": 26345, "text": "Comparison operators" }, { "code": null, "e": 26384, "s": 26366, "text": "Logical operators" }, { "code": null, "e": 26420, "s": 26384, "text": "Operators used to negate conditions" }, { "code": null, "e": 26483, "s": 26420, "text": "Assume 'variable a' holds 10 and 'variable b' holds 20, then −" }, { "code": null, "e": 26497, "s": 26483, "text": "Show Examples" }, { "code": null, "e": 26560, "s": 26497, "text": "Assume 'variable a' holds 10 and 'variable b' holds 20, then −" }, { "code": null, "e": 26574, "s": 26560, "text": "Show Examples" }, { "code": null, "e": 26636, "s": 26574, "text": "Here is a list of all the logical operators available in SQL." }, { "code": null, "e": 26650, "s": 26636, "text": "Show Examples" }, { "code": null, "e": 26654, "s": 26650, "text": "ALL" }, { "code": null, "e": 26734, "s": 26654, "text": "The ALL operator is used to compare a value to all values in another value set." }, { "code": null, "e": 26738, "s": 26734, "text": "AND" }, { "code": null, "e": 26835, "s": 26738, "text": "The AND operator allows the existence of multiple conditions in an SQL statement's WHERE clause." }, { "code": null, "e": 26839, "s": 26835, "text": "ANY" }, { "code": null, "e": 26941, "s": 26839, "text": "The ANY operator is used to compare a value to any applicable value in the list as per the condition." }, { "code": null, "e": 26949, "s": 26941, "text": "BETWEEN" }, { "code": null, "e": 27079, "s": 26949, "text": "The BETWEEN operator is used to search for values that are within a set of values, given the minimum value and the maximum value." }, { "code": null, "e": 27086, "s": 27079, "text": "EXISTS" }, { "code": null, "e": 27203, "s": 27086, "text": "The EXISTS operator is used to search for the presence of a row in a specified table that meets a certain criterion." }, { "code": null, "e": 27206, "s": 27203, "text": "IN" }, { "code": null, "e": 27303, "s": 27206, "text": "The IN operator is used to compare a value to a list of literal values that have been specified." }, { "code": null, "e": 27308, "s": 27303, "text": "LIKE" }, { "code": null, "e": 27397, "s": 27308, "text": "The LIKE operator is used to compare a value to similar values using wildcard operators." }, { "code": null, "e": 27401, "s": 27397, "text": "NOT" }, { "code": null, "e": 27555, "s": 27401, "text": "The NOT operator reverses the meaning of the logical operator with which it is used. Eg: NOT EXISTS, NOT BETWEEN, NOT IN, etc. This is a negate operator." }, { "code": null, "e": 27558, "s": 27555, "text": "OR" }, { "code": null, "e": 27649, "s": 27558, "text": "The OR operator is used to combine multiple conditions in an SQL statement's WHERE clause." }, { "code": null, "e": 27657, "s": 27649, "text": "IS NULL" }, { "code": null, "e": 27721, "s": 27657, "text": "The NULL operator is used to compare a value with a NULL value." }, { "code": null, "e": 27728, "s": 27721, "text": "UNIQUE" }, { "code": null, "e": 27820, "s": 27728, "text": "The UNIQUE operator searches every row of a specified table for uniqueness (no duplicates)." }, { "code": null, "e": 28080, "s": 27820, "text": "An expression is a combination of one or more values, operators and SQL functions that evaluate to a value. These SQL EXPRESSIONs are like formulae and they are written in query language. You can also use them to query the database for a specific set of data." }, { "code": null, "e": 28143, "s": 28080, "text": "Consider the basic syntax of the SELECT statement as follows −" }, { "code": null, "e": 28225, "s": 28143, "text": "SELECT column1, column2, columnN \nFROM table_name \nWHERE [CONDITION|EXPRESSION];\n" }, { "code": null, "e": 28299, "s": 28225, "text": "There are different types of SQL expressions, which are mentioned below −" }, { "code": null, "e": 28307, "s": 28299, "text": "Boolean" }, { "code": null, "e": 28315, "s": 28307, "text": "Numeric" }, { "code": null, "e": 28320, "s": 28315, "text": "Date" }, { "code": null, "e": 28364, "s": 28320, "text": "Let us now discuss each of these in detail." }, { "code": null, "e": 28463, "s": 28364, "text": "SQL Boolean Expressions fetch the data based on matching a single value. Following is the syntax −" }, { "code": null, "e": 28555, "s": 28463, "text": "SELECT column1, column2, columnN \nFROM table_name \nWHERE SINGLE VALUE MATCHING EXPRESSION;\n" }, { "code": null, "e": 28615, "s": 28555, "text": "Consider the CUSTOMERS table having the following records −" }, { "code": null, "e": 29187, "s": 28615, "text": "SQL> SELECT * FROM CUSTOMERS;\n+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+\n7 rows in set (0.00 sec)" }, { "code": null, "e": 29282, "s": 29187, "text": "The following table is a simple example showing the usage of various SQL Boolean Expressions −" }, { "code": null, "e": 29567, "s": 29282, "text": "SQL> SELECT * FROM CUSTOMERS WHERE SALARY = 10000;\n+----+-------+-----+---------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+-------+-----+---------+----------+\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+-------+-----+---------+----------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 29672, "s": 29567, "text": "These expressions are used to perform any mathematical operation in any query. Following is the syntax −" }, { "code": null, "e": 29756, "s": 29672, "text": "SELECT numerical_expression as OPERATION_NAME\n[FROM table_name\nWHERE CONDITION] ;\n" }, { "code": null, "e": 29918, "s": 29756, "text": "Here, the numerical_expression is used for a mathematical expression or any formula. Following is a simple example showing the usage of SQL Numeric Expressions −" }, { "code": null, "e": 30040, "s": 29918, "text": "SQL> SELECT (15 + 6) AS ADDITION\n+----------+\n| ADDITION |\n+----------+\n| 21 |\n+----------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 30215, "s": 30040, "text": "There are several built-in functions like avg(), sum(), count(), etc., to perform what is known as the aggregate data calculations against a table or a specific table column." }, { "code": null, "e": 30350, "s": 30215, "text": "SQL> SELECT COUNT(*) AS \"RECORDS\" FROM CUSTOMERS; \n+---------+\n| RECORDS |\n+---------+\n| 7 |\n+---------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 30412, "s": 30350, "text": "Date Expressions return current system date and time values −" }, { "code": null, "e": 30588, "s": 30412, "text": "SQL> SELECT CURRENT_TIMESTAMP;\n+---------------------+\n| Current_Timestamp |\n+---------------------+\n| 2009-11-12 06:40:23 |\n+---------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 30632, "s": 30588, "text": "Another date expression is as shown below −" }, { "code": null, "e": 30822, "s": 30632, "text": "SQL> SELECT GETDATE();;\n+-------------------------+\n| GETDATE |\n+-------------------------+\n| 2009-10-22 12:07:18.140 |\n+-------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 30894, "s": 30822, "text": "The SQL CREATE DATABASE statement is used to create a new SQL database." }, { "code": null, "e": 30961, "s": 30894, "text": "The basic syntax of this CREATE DATABASE statement is as follows −" }, { "code": null, "e": 30992, "s": 30961, "text": "CREATE DATABASE DatabaseName;\n" }, { "code": null, "e": 31052, "s": 30992, "text": "Always the database name should be unique within the RDBMS." }, { "code": null, "e": 31160, "s": 31052, "text": "If you want to create a new database <testDB>, then the CREATE DATABASE statement would be as shown below −" }, { "code": null, "e": 31189, "s": 31160, "text": "SQL> CREATE DATABASE testDB;" }, { "code": null, "e": 31341, "s": 31189, "text": "Make sure you have the admin privilege before creating any database. Once a database is created, you can check it in the list of databases as follows −" }, { "code": null, "e": 31641, "s": 31341, "text": "SQL> SHOW DATABASES;\n+--------------------+\n| Database |\n+--------------------+\n| information_schema |\n| AMROOD |\n| TUTORIALSPOINT |\n| mysql |\n| orig |\n| test |\n| testDB |\n+--------------------+\n7 rows in set (0.00 sec)\n" }, { "code": null, "e": 31725, "s": 31641, "text": "The SQL DROP DATABASE statement is used to drop an existing database in SQL schema." }, { "code": null, "e": 31785, "s": 31725, "text": "The basic syntax of DROP DATABASE statement is as follows −" }, { "code": null, "e": 31814, "s": 31785, "text": "DROP DATABASE DatabaseName;\n" }, { "code": null, "e": 31874, "s": 31814, "text": "Always the database name should be unique within the RDBMS." }, { "code": null, "e": 31986, "s": 31874, "text": "If you want to delete an existing database <testDB>, then the DROP DATABASE statement would be as shown below −" }, { "code": null, "e": 32013, "s": 31986, "text": "SQL> DROP DATABASE testDB;" }, { "code": null, "e": 32169, "s": 32013, "text": "NOTE − Be careful before using this operation because by deleting an existing database would result in loss of complete information stored in the database." }, { "code": null, "e": 32329, "s": 32169, "text": "Make sure you have the admin privilege before dropping any database. Once a database is dropped, you can check it in the list of the databases as shown below −" }, { "code": null, "e": 32605, "s": 32329, "text": "SQL> SHOW DATABASES;\n+--------------------+\n| Database |\n+--------------------+\n| information_schema |\n| AMROOD |\n| TUTORIALSPOINT |\n| mysql |\n| orig |\n| test |\n+--------------------+\n6 rows in set (0.00 sec)" }, { "code": null, "e": 32776, "s": 32605, "text": "When you have multiple databases in your SQL Schema, then before starting your operation, you would need to select a database where all the operations would be performed." }, { "code": null, "e": 32857, "s": 32776, "text": "The SQL USE statement is used to select any existing database in the SQL schema." }, { "code": null, "e": 32915, "s": 32857, "text": "The basic syntax of the USE statement is as shown below −" }, { "code": null, "e": 32934, "s": 32915, "text": "USE DatabaseName;\n" }, { "code": null, "e": 32994, "s": 32934, "text": "Always the database name should be unique within the RDBMS." }, { "code": null, "e": 33049, "s": 32994, "text": "You can check the available databases as shown below −" }, { "code": null, "e": 33325, "s": 33049, "text": "SQL> SHOW DATABASES;\n+--------------------+\n| Database |\n+--------------------+\n| information_schema |\n| AMROOD |\n| TUTORIALSPOINT |\n| mysql |\n| orig |\n| test |\n+--------------------+\n6 rows in set (0.00 sec)" }, { "code": null, "e": 33467, "s": 33325, "text": "Now, if you want to work with the AMROOD database, then you can execute the following SQL command and start working with the AMROOD database." }, { "code": null, "e": 33484, "s": 33467, "text": "SQL> USE AMROOD;" }, { "code": null, "e": 33587, "s": 33484, "text": "Creating a basic table involves naming the table and defining its columns and each column's data type." }, { "code": null, "e": 33649, "s": 33587, "text": "The SQL CREATE TABLE statement is used to create a new table." }, { "code": null, "e": 33712, "s": 33649, "text": "The basic syntax of the CREATE TABLE statement is as follows −" }, { "code": null, "e": 33872, "s": 33712, "text": "CREATE TABLE table_name(\n column1 datatype,\n column2 datatype,\n column3 datatype,\n .....\n columnN datatype,\n PRIMARY KEY( one or more columns )\n);\n" }, { "code": null, "e": 34075, "s": 33872, "text": "CREATE TABLE is the keyword telling the database system what you want to do. In this case, you want to create a new table. The unique name or identifier for the table follows the CREATE TABLE statement." }, { "code": null, "e": 34230, "s": 34075, "text": "Then in brackets comes the list defining each column in the table and what sort of data type it is. The syntax becomes clearer with the following example." }, { "code": null, "e": 34421, "s": 34230, "text": "A copy of an existing table can be created using a combination of the CREATE TABLE statement and the SELECT statement. You can check the complete details at Create Table Using another Table." }, { "code": null, "e": 34634, "s": 34421, "text": "The following code block is an example, which creates a CUSTOMERS table with an ID as a primary key and NOT NULL are the constraints showing that these fields cannot be NULL while creating records in this table −" }, { "code": null, "e": 34851, "s": 34634, "text": "SQL> CREATE TABLE CUSTOMERS(\n ID INT NOT NULL,\n NAME VARCHAR (20) NOT NULL,\n AGE INT NOT NULL,\n ADDRESS CHAR (25) ,\n SALARY DECIMAL (18, 2), \n PRIMARY KEY (ID)\n);" }, { "code": null, "e": 35017, "s": 34851, "text": "You can verify if your table has been created successfully by looking at the message displayed by the SQL server, otherwise you can use the DESC command as follows −" }, { "code": null, "e": 35595, "s": 35017, "text": "SQL> DESC CUSTOMERS;\n+---------+---------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+---------+---------------+------+-----+---------+-------+\n| ID | int(11) | NO | PRI | | |\n| NAME | varchar(20) | NO | | | |\n| AGE | int(11) | NO | | | |\n| ADDRESS | char(25) | YES | | NULL | |\n| SALARY | decimal(18,2) | YES | | NULL | |\n+---------+---------------+------+-----+---------+-------+\n5 rows in set (0.00 sec)\n" }, { "code": null, "e": 35726, "s": 35595, "text": "Now, you have CUSTOMERS table available in your database which you can use to store the required information related to customers." }, { "code": null, "e": 35887, "s": 35726, "text": "The SQL DROP TABLE statement is used to remove a table definition and all the data, indexes, triggers, constraints and permission specifications for that table." }, { "code": null, "e": 36054, "s": 35887, "text": "NOTE − You should be very careful while using this command because once a table is deleted then all the information available in that table will also be lost forever." }, { "code": null, "e": 36116, "s": 36054, "text": "The basic syntax of this DROP TABLE statement is as follows −" }, { "code": null, "e": 36140, "s": 36116, "text": "DROP TABLE table_name;\n" }, { "code": null, "e": 36242, "s": 36140, "text": "Let us first verify the CUSTOMERS table and then we will delete it from the database as shown below −" }, { "code": null, "e": 36819, "s": 36242, "text": "SQL> DESC CUSTOMERS;\n+---------+---------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+---------+---------------+------+-----+---------+-------+\n| ID | int(11) | NO | PRI | | |\n| NAME | varchar(20) | NO | | | |\n| AGE | int(11) | NO | | | |\n| ADDRESS | char(25) | YES | | NULL | |\n| SALARY | decimal(18,2) | YES | | NULL | |\n+---------+---------------+------+-----+---------+-------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 36923, "s": 36819, "text": "This means that the CUSTOMERS table is available in the database, so let us now drop it as shown below." }, { "code": null, "e": 36987, "s": 36923, "text": "SQL> DROP TABLE CUSTOMERS;\nQuery OK, 0 rows affected (0.01 sec)" }, { "code": null, "e": 37067, "s": 36987, "text": "Now, if you would try the DESC command, then you will get the following error −" }, { "code": null, "e": 37145, "s": 37067, "text": "SQL> DESC CUSTOMERS;\nERROR 1146 (42S02): Table 'TEST.CUSTOMERS' doesn't exist" }, { "code": null, "e": 37214, "s": 37145, "text": "Here, TEST is the database name which we are using for our examples." }, { "code": null, "e": 37304, "s": 37214, "text": "The SQL INSERT INTO Statement is used to add new rows of data to a table in the database." }, { "code": null, "e": 37385, "s": 37304, "text": "There are two basic syntaxes of the INSERT INTO statement which are shown below." }, { "code": null, "e": 37493, "s": 37385, "text": "INSERT INTO TABLE_NAME (column1, column2, column3,...columnN) \nVALUES (value1, value2, value3,...valueN);\n" }, { "code": null, "e": 37618, "s": 37493, "text": "Here, column1, column2, column3,...columnN are the names of the columns in the table into which you want to insert the data." }, { "code": null, "e": 37829, "s": 37618, "text": "You may not need to specify the column(s) name in the SQL query if you are adding values for all the columns of the table. But make sure the order of the values is in the same order as the columns in the table." }, { "code": null, "e": 37877, "s": 37829, "text": "The SQL INSERT INTO syntax will be as follows −" }, { "code": null, "e": 37942, "s": 37877, "text": "INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);\n" }, { "code": null, "e": 38016, "s": 37942, "text": "The following statements would create six records in the CUSTOMERS table." }, { "code": null, "e": 38601, "s": 38016, "text": "INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)\nVALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 );\n\nINSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)\nVALUES (2, 'Khilan', 25, 'Delhi', 1500.00 );\n\nINSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)\nVALUES (3, 'kaushik', 23, 'Kota', 2000.00 );\n\nINSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)\nVALUES (4, 'Chaitali', 25, 'Mumbai', 6500.00 );\n\nINSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)\nVALUES (5, 'Hardik', 27, 'Bhopal', 8500.00 );\n\nINSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)\nVALUES (6, 'Komal', 22, 'MP', 4500.00 );" }, { "code": null, "e": 38691, "s": 38601, "text": "You can create a record in the CUSTOMERS table by using the second syntax as shown below." }, { "code": null, "e": 38761, "s": 38691, "text": "INSERT INTO CUSTOMERS \nVALUES (7, 'Muffy', 24, 'Indore', 10000.00 );\n" }, { "code": null, "e": 38861, "s": 38761, "text": "All the above statements would produce the following records in the CUSTOMERS table as shown below." }, { "code": null, "e": 39378, "s": 38861, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+" }, { "code": null, "e": 39560, "s": 39378, "text": "You can populate the data into a table through the select statement over another table; provided the other table has a set of fields, which are required to populate the first table." }, { "code": null, "e": 39581, "s": 39560, "text": "Here is the syntax −" }, { "code": null, "e": 39734, "s": 39581, "text": "INSERT INTO first_table_name [(column1, column2, ... columnN)] \n SELECT column1, column2, ...columnN \n FROM second_table_name\n [WHERE condition];\n" }, { "code": null, "e": 39906, "s": 39734, "text": "The SQL SELECT statement is used to fetch the data from a database table which returns this data in the form of a result table. These result tables are called result-sets." }, { "code": null, "e": 39963, "s": 39906, "text": "The basic syntax of the SELECT statement is as follows −" }, { "code": null, "e": 40014, "s": 39963, "text": "SELECT column1, column2, columnN FROM table_name;\n" }, { "code": null, "e": 40197, "s": 40014, "text": "Here, column1, column2... are the fields of a table whose values you want to fetch. If you want to fetch all the fields available in the field, then you can use the following syntax." }, { "code": null, "e": 40223, "s": 40197, "text": "SELECT * FROM table_name;" }, { "code": null, "e": 40283, "s": 40223, "text": "Consider the CUSTOMERS table having the following records −" }, { "code": null, "e": 40800, "s": 40283, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+" }, { "code": null, "e": 40930, "s": 40800, "text": "The following code is an example, which would fetch the ID, Name and Salary fields of the customers available in CUSTOMERS table." }, { "code": null, "e": 40975, "s": 40930, "text": "SQL> SELECT ID, NAME, SALARY FROM CUSTOMERS;" }, { "code": null, "e": 41017, "s": 40975, "text": "This would produce the following result −" }, { "code": null, "e": 41337, "s": 41017, "text": "+----+----------+----------+\n| ID | NAME | SALARY |\n+----+----------+----------+\n| 1 | Ramesh | 2000.00 |\n| 2 | Khilan | 1500.00 |\n| 3 | kaushik | 2000.00 |\n| 4 | Chaitali | 6500.00 |\n| 5 | Hardik | 8500.00 |\n| 6 | Komal | 4500.00 |\n| 7 | Muffy | 10000.00 |\n+----+----------+----------+\n" }, { "code": null, "e": 41438, "s": 41337, "text": "If you want to fetch all the fields of the CUSTOMERS table, then you should use the following query." }, { "code": null, "e": 41468, "s": 41438, "text": "SQL> SELECT * FROM CUSTOMERS;" }, { "code": null, "e": 41514, "s": 41468, "text": "This would produce the result as shown below." }, { "code": null, "e": 42032, "s": 41514, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+\n" }, { "code": null, "e": 42350, "s": 42032, "text": "The SQL WHERE clause is used to specify a condition while fetching the data from a single table or by joining with multiple tables. If the given condition is satisfied, then only it returns a specific value from the table. You should use the WHERE clause to filter the records and fetching only the necessary records." }, { "code": null, "e": 42519, "s": 42350, "text": "The WHERE clause is not only used in the SELECT statement, but it is also used in the UPDATE, DELETE statement, etc., which we would examine in the subsequent chapters." }, { "code": null, "e": 42601, "s": 42519, "text": "The basic syntax of the SELECT statement with the WHERE clause is as shown below." }, { "code": null, "e": 42670, "s": 42601, "text": "SELECT column1, column2, columnN \nFROM table_name\nWHERE [condition]\n" }, { "code": null, "e": 42824, "s": 42670, "text": "You can specify a condition using the comparison or logical operators like >, <, =, LIKE, NOT, etc. The following examples would make this concept clear." }, { "code": null, "e": 42884, "s": 42824, "text": "Consider the CUSTOMERS table having the following records −" }, { "code": null, "e": 43401, "s": 42884, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+" }, { "code": null, "e": 43549, "s": 43401, "text": "The following code is an example which would fetch the ID, Name and Salary fields from the CUSTOMERS table, where the salary is greater than 2000 −" }, { "code": null, "e": 43615, "s": 43549, "text": "SQL> SELECT ID, NAME, SALARY \nFROM CUSTOMERS\nWHERE SALARY > 2000;" }, { "code": null, "e": 43657, "s": 43615, "text": "This would produce the following result −" }, { "code": null, "e": 43890, "s": 43657, "text": "+----+----------+----------+\n| ID | NAME | SALARY |\n+----+----------+----------+\n| 4 | Chaitali | 6500.00 |\n| 5 | Hardik | 8500.00 |\n| 6 | Komal | 4500.00 |\n| 7 | Muffy | 10000.00 |\n+----+----------+----------+\n" }, { "code": null, "e": 44036, "s": 43890, "text": "The following query is an example, which would fetch the ID, Name and Salary fields from the CUSTOMERS table for a customer with the name Hardik." }, { "code": null, "e": 44104, "s": 44036, "text": "SQL> SELECT ID, NAME, SALARY \nFROM CUSTOMERS\nWHERE NAME = 'Hardik';" }, { "code": null, "e": 44146, "s": 44104, "text": "This would produce the following result −" }, { "code": null, "e": 44292, "s": 44146, "text": "+----+----------+----------+\n| ID | NAME | SALARY |\n+----+----------+----------+\n| 5 | Hardik | 8500.00 |\n+----+----------+----------+\n" }, { "code": null, "e": 44456, "s": 44292, "text": "The SQL AND & OR operators are used to combine multiple conditions to narrow data in an SQL statement. These two operators are called as the conjunctive operators." }, { "code": null, "e": 44569, "s": 44456, "text": "These operators provide a means to make multiple comparisons with different operators in the same SQL statement." }, { "code": null, "e": 44666, "s": 44569, "text": "The AND operator allows the existence of multiple conditions in an SQL statement's WHERE clause." }, { "code": null, "e": 44739, "s": 44666, "text": "The basic syntax of the AND operator with a WHERE clause is as follows −" }, { "code": null, "e": 44846, "s": 44739, "text": "SELECT column1, column2, columnN \nFROM table_name\nWHERE [condition1] AND [condition2]...AND [conditionN];\n" }, { "code": null, "e": 45047, "s": 44846, "text": "You can combine N number of conditions using the AND operator. For an action to be taken by the SQL statement, whether it be a transaction or a query, all conditions separated by the AND must be TRUE." }, { "code": null, "e": 45107, "s": 45047, "text": "Consider the CUSTOMERS table having the following records −" }, { "code": null, "e": 45625, "s": 45107, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+\n" }, { "code": null, "e": 45799, "s": 45625, "text": "Following is an example, which would fetch the ID, Name and Salary fields from the CUSTOMERS table, where the salary is greater than 2000 and the age is less than 25 years −" }, { "code": null, "e": 45878, "s": 45799, "text": "SQL> SELECT ID, NAME, SALARY \nFROM CUSTOMERS\nWHERE SALARY > 2000 AND age < 25;" }, { "code": null, "e": 45920, "s": 45878, "text": "This would produce the following result −" }, { "code": null, "e": 46077, "s": 45920, "text": "+----+-------+----------+\n| ID | NAME | SALARY |\n+----+-------+----------+\n| 6 | Komal | 4500.00 |\n| 7 | Muffy | 10000.00 |\n+----+-------+----------+\n" }, { "code": null, "e": 46168, "s": 46077, "text": "The OR operator is used to combine multiple conditions in an SQL statement's WHERE clause." }, { "code": null, "e": 46240, "s": 46168, "text": "The basic syntax of the OR operator with a WHERE clause is as follows −" }, { "code": null, "e": 46344, "s": 46240, "text": "SELECT column1, column2, columnN \nFROM table_name\nWHERE [condition1] OR [condition2]...OR [conditionN]\n" }, { "code": null, "e": 46561, "s": 46344, "text": "You can combine N number of conditions using the OR operator. For an action to be taken by the SQL statement, whether it be a transaction or query, the only any ONE of the conditions separated by the OR must be TRUE." }, { "code": null, "e": 46621, "s": 46561, "text": "Consider the CUSTOMERS table having the following records −" }, { "code": null, "e": 47138, "s": 46621, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+" }, { "code": null, "e": 47322, "s": 47138, "text": "The following code block hasa query, which would fetch the ID, Name and Salary fields from the CUSTOMERS table, where the salary is greater than 2000 OR the age is less than 25 years." }, { "code": null, "e": 47400, "s": 47322, "text": "SQL> SELECT ID, NAME, SALARY \nFROM CUSTOMERS\nWHERE SALARY > 2000 OR age < 25;" }, { "code": null, "e": 47442, "s": 47400, "text": "This would produce the following result −" }, { "code": null, "e": 47704, "s": 47442, "text": "+----+----------+----------+\n| ID | NAME | SALARY |\n+----+----------+----------+\n| 3 | kaushik | 2000.00 |\n| 4 | Chaitali | 6500.00 |\n| 5 | Hardik | 8500.00 |\n| 6 | Komal | 4500.00 |\n| 7 | Muffy | 10000.00 |\n+----+----------+----------+\n" }, { "code": null, "e": 47898, "s": 47704, "text": "The SQL UPDATE Query is used to modify the existing records in a table. You can use the WHERE clause with the UPDATE query to update the selected rows, otherwise all the rows would be affected." }, { "code": null, "e": 47971, "s": 47898, "text": "The basic syntax of the UPDATE query with a WHERE clause is as follows −" }, { "code": null, "e": 48070, "s": 47971, "text": "UPDATE table_name\nSET column1 = value1, column2 = value2...., columnN = valueN\nWHERE [condition];\n" }, { "code": null, "e": 48144, "s": 48070, "text": "You can combine N number of conditions using the AND or the OR operators." }, { "code": null, "e": 48204, "s": 48144, "text": "Consider the CUSTOMERS table having the following records −" }, { "code": null, "e": 48721, "s": 48204, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+" }, { "code": null, "e": 48815, "s": 48721, "text": "The following query will update the ADDRESS for a customer whose ID number is 6 in the table." }, { "code": null, "e": 48872, "s": 48815, "text": "SQL> UPDATE CUSTOMERS\nSET ADDRESS = 'Pune'\nWHERE ID = 6;" }, { "code": null, "e": 48932, "s": 48872, "text": "Now, the CUSTOMERS table would have the following records −" }, { "code": null, "e": 49450, "s": 48932, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | Pune | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+\n" }, { "code": null, "e": 49655, "s": 49450, "text": "If you want to modify all the ADDRESS and the SALARY column values in the CUSTOMERS table, you do not need to use the WHERE clause as the UPDATE query would be enough as shown in the following code block." }, { "code": null, "e": 49717, "s": 49655, "text": "SQL> UPDATE CUSTOMERS\nSET ADDRESS = 'Pune', SALARY = 1000.00;" }, { "code": null, "e": 49773, "s": 49717, "text": "Now, CUSTOMERS table would have the following records −" }, { "code": null, "e": 50258, "s": 49773, "text": "+----+----------+-----+---------+---------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+---------+---------+\n| 1 | Ramesh | 32 | Pune | 1000.00 |\n| 2 | Khilan | 25 | Pune | 1000.00 |\n| 3 | kaushik | 23 | Pune | 1000.00 |\n| 4 | Chaitali | 25 | Pune | 1000.00 |\n| 5 | Hardik | 27 | Pune | 1000.00 |\n| 6 | Komal | 22 | Pune | 1000.00 |\n| 7 | Muffy | 24 | Pune | 1000.00 |\n+----+----------+-----+---------+---------+\n" }, { "code": null, "e": 50332, "s": 50258, "text": "The SQL DELETE Query is used to delete the existing records from a table." }, { "code": null, "e": 50454, "s": 50332, "text": "You can use the WHERE clause with a DELETE query to delete the selected rows, otherwise all the records would be deleted." }, { "code": null, "e": 50529, "s": 50454, "text": "The basic syntax of the DELETE query with the WHERE clause is as follows −" }, { "code": null, "e": 50572, "s": 50529, "text": "DELETE FROM table_name\nWHERE [condition];\n" }, { "code": null, "e": 50638, "s": 50572, "text": "You can combine N number of conditions using AND or OR operators." }, { "code": null, "e": 50698, "s": 50638, "text": "Consider the CUSTOMERS table having the following records −" }, { "code": null, "e": 51216, "s": 50698, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+\n" }, { "code": null, "e": 51293, "s": 51216, "text": "The following code has a query, which will DELETE a customer, whose ID is 6." }, { "code": null, "e": 51334, "s": 51293, "text": "SQL> DELETE FROM CUSTOMERS\nWHERE ID = 6;" }, { "code": null, "e": 51393, "s": 51334, "text": "Now, the CUSTOMERS table would have the following records." }, { "code": null, "e": 51864, "s": 51393, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+\n" }, { "code": null, "e": 52011, "s": 51864, "text": "If you want to DELETE all the records from the CUSTOMERS table, you do not need to use the WHERE clause and the DELETE query would be as follows −" }, { "code": null, "e": 52039, "s": 52011, "text": "SQL> DELETE FROM CUSTOMERS;" }, { "code": null, "e": 52091, "s": 52039, "text": "Now, the CUSTOMERS table would not have any record." }, { "code": null, "e": 52250, "s": 52091, "text": "The SQL LIKE clause is used to compare a value to similar values using wildcard operators. There are two wildcards used in conjunction with the LIKE operator." }, { "code": null, "e": 52271, "s": 52250, "text": "The percent sign (%)" }, { "code": null, "e": 52290, "s": 52271, "text": "The underscore (_)" }, { "code": null, "e": 52451, "s": 52290, "text": "The percent sign represents zero, one or multiple characters. The underscore represents a single number or character. These symbols can be used in combinations." }, { "code": null, "e": 52495, "s": 52451, "text": "The basic syntax of % and _ is as follows −" }, { "code": null, "e": 52764, "s": 52495, "text": "SELECT FROM table_name\nWHERE column LIKE 'XXXX%'\n\nor \n\nSELECT FROM table_name\nWHERE column LIKE '%XXXX%'\n\nor\n\nSELECT FROM table_name\nWHERE column LIKE 'XXXX_'\n\nor\n\nSELECT FROM table_name\nWHERE column LIKE '_XXXX'\n\nor\n\nSELECT FROM table_name\nWHERE column LIKE '_XXXX_'\n" }, { "code": null, "e": 52879, "s": 52764, "text": "You can combine N number of conditions using AND or OR operators. Here, XXXX could be any numeric or string value." }, { "code": null, "e": 52999, "s": 52879, "text": "The following table has a few examples showing the WHERE part having different LIKE clause with '%' and '_' operators −" }, { "code": null, "e": 53024, "s": 52999, "text": "WHERE SALARY LIKE '200%'" }, { "code": null, "e": 53062, "s": 53024, "text": "Finds any values that start with 200." }, { "code": null, "e": 53088, "s": 53062, "text": "WHERE SALARY LIKE '%200%'" }, { "code": null, "e": 53136, "s": 53088, "text": "Finds any values that have 200 in any position." }, { "code": null, "e": 53161, "s": 53136, "text": "WHERE SALARY LIKE '_00%'" }, { "code": null, "e": 53226, "s": 53161, "text": "Finds any values that have 00 in the second and third positions." }, { "code": null, "e": 53252, "s": 53226, "text": "WHERE SALARY LIKE '2_%_%'" }, { "code": null, "e": 53328, "s": 53252, "text": "Finds any values that start with 2 and are at least 3 characters in length." }, { "code": null, "e": 53351, "s": 53328, "text": "WHERE SALARY LIKE '%2'" }, { "code": null, "e": 53385, "s": 53351, "text": "Finds any values that end with 2." }, { "code": null, "e": 53410, "s": 53385, "text": "WHERE SALARY LIKE '_2%3'" }, { "code": null, "e": 53482, "s": 53410, "text": "Finds any values that have a 2 in the second position and end with a 3." }, { "code": null, "e": 53508, "s": 53482, "text": "WHERE SALARY LIKE '2___3'" }, { "code": null, "e": 53582, "s": 53508, "text": "Finds any values in a five-digit number that start with 2 and end with 3." }, { "code": null, "e": 53674, "s": 53582, "text": "Let us take a real example, consider the CUSTOMERS table having the records as shown below." }, { "code": null, "e": 54192, "s": 53674, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+\n" }, { "code": null, "e": 54313, "s": 54192, "text": "Following is an example, which would display all the records from the CUSTOMERS table, where the SALARY starts with 200." }, { "code": null, "e": 54368, "s": 54313, "text": "SQL> SELECT * FROM CUSTOMERS\nWHERE SALARY LIKE '200%';" }, { "code": null, "e": 54410, "s": 54368, "text": "This would produce the following result −" }, { "code": null, "e": 54693, "s": 54410, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n+----+----------+-----+-----------+----------+\n" }, { "code": null, "e": 54779, "s": 54693, "text": "The SQL TOP clause is used to fetch a TOP N number or X percent records from a table." }, { "code": null, "e": 54989, "s": 54779, "text": "Note − All the databases do not support the TOP clause. For example MySQL supports the LIMIT clause to fetch limited number of records while Oracle uses the ROWNUM command to fetch a limited number of records." }, { "code": null, "e": 55069, "s": 54989, "text": "The basic syntax of the TOP clause with a SELECT statement would be as follows." }, { "code": null, "e": 55145, "s": 55069, "text": "SELECT TOP number|percent column_name(s)\nFROM table_name\nWHERE [condition]\n" }, { "code": null, "e": 55205, "s": 55145, "text": "Consider the CUSTOMERS table having the following records −" }, { "code": null, "e": 55723, "s": 55205, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+\n" }, { "code": null, "e": 55838, "s": 55723, "text": "The following query is an example on the SQL server, which would fetch the top 3 records from the CUSTOMERS table." }, { "code": null, "e": 55874, "s": 55838, "text": "SQL> SELECT TOP 3 * FROM CUSTOMERS;" }, { "code": null, "e": 55916, "s": 55874, "text": "This would produce the following result −" }, { "code": null, "e": 56232, "s": 55916, "text": "+----+---------+-----+-----------+---------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+---------+-----+-----------+---------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n+----+---------+-----+-----------+---------+\n" }, { "code": null, "e": 56300, "s": 56232, "text": "If you are using MySQL server, then here is an equivalent example −" }, { "code": null, "e": 56338, "s": 56300, "text": "SQL> SELECT * FROM CUSTOMERS\nLIMIT 3;" }, { "code": null, "e": 56380, "s": 56338, "text": "This would produce the following result −" }, { "code": null, "e": 56696, "s": 56380, "text": "+----+---------+-----+-----------+---------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+---------+-----+-----------+---------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n+----+---------+-----+-----------+---------+\n" }, { "code": null, "e": 56788, "s": 56696, "text": "If you are using an Oracle server, then the following code block has an equivalent example." }, { "code": null, "e": 56836, "s": 56788, "text": "SQL> SELECT * FROM CUSTOMERS\nWHERE ROWNUM <= 3;" }, { "code": null, "e": 56878, "s": 56836, "text": "This would produce the following result −" }, { "code": null, "e": 57194, "s": 56878, "text": "+----+---------+-----+-----------+---------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+---------+-----+-----------+---------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n+----+---------+-----+-----------+---------+\n" }, { "code": null, "e": 57379, "s": 57194, "text": "The SQL ORDER BY clause is used to sort the data in ascending or descending order, based on one or more columns. Some databases sort the query results in an ascending order by default." }, { "code": null, "e": 57435, "s": 57379, "text": "The basic syntax of the ORDER BY clause is as follows −" }, { "code": null, "e": 57546, "s": 57435, "text": "SELECT column-list \nFROM table_name \n[WHERE condition] \n[ORDER BY column1, column2, .. columnN] [ASC | DESC];\n" }, { "code": null, "e": 57693, "s": 57546, "text": "You can use more than one column in the ORDER BY clause. Make sure whatever column you are using to sort that column should be in the column-list." }, { "code": null, "e": 57753, "s": 57693, "text": "Consider the CUSTOMERS table having the following records −" }, { "code": null, "e": 58271, "s": 57753, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+\n" }, { "code": null, "e": 58391, "s": 58271, "text": "The following code block has an example, which would sort the result in an ascending order by the NAME and the SALARY −" }, { "code": null, "e": 58446, "s": 58391, "text": "SQL> SELECT * FROM CUSTOMERS\n ORDER BY NAME, SALARY;" }, { "code": null, "e": 58488, "s": 58446, "text": "This would produce the following result −" }, { "code": null, "e": 59006, "s": 58488, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n+----+----------+-----+-----------+----------+\n" }, { "code": null, "e": 59108, "s": 59006, "text": "The following code block has an example, which would sort the result in the descending order by NAME." }, { "code": null, "e": 59160, "s": 59108, "text": "SQL> SELECT * FROM CUSTOMERS\n ORDER BY NAME DESC;" }, { "code": null, "e": 59202, "s": 59160, "text": "This would produce the following result −" }, { "code": null, "e": 59720, "s": 59202, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n+----+----------+-----+-----------+----------+\n" }, { "code": null, "e": 59936, "s": 59720, "text": "The SQL GROUP BY clause is used in collaboration with the SELECT statement to arrange identical data into groups. This GROUP BY clause follows the WHERE clause in a SELECT statement and precedes the ORDER BY clause." }, { "code": null, "e": 60132, "s": 59936, "text": "The basic syntax of a GROUP BY clause is shown in the following code block. The GROUP BY clause must follow the conditions in the WHERE clause and must precede the ORDER BY clause if one is used." }, { "code": null, "e": 60246, "s": 60132, "text": "SELECT column1, column2\nFROM table_name\nWHERE [ conditions ]\nGROUP BY column1, column2\nORDER BY column1, column2\n" }, { "code": null, "e": 60309, "s": 60246, "text": "Consider the CUSTOMERS table is having the following records −" }, { "code": null, "e": 60827, "s": 60309, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+\n" }, { "code": null, "e": 60941, "s": 60827, "text": "If you want to know the total amount of the salary on each customer, then the GROUP BY query would be as follows." }, { "code": null, "e": 61004, "s": 60941, "text": "SQL> SELECT NAME, SUM(SALARY) FROM CUSTOMERS\n GROUP BY NAME;" }, { "code": null, "e": 61046, "s": 61004, "text": "This would produce the following result −" }, { "code": null, "e": 61344, "s": 61046, "text": "+----------+-------------+\n| NAME | SUM(SALARY) |\n+----------+-------------+\n| Chaitali | 6500.00 |\n| Hardik | 8500.00 |\n| kaushik | 2000.00 |\n| Khilan | 1500.00 |\n| Komal | 4500.00 |\n| Muffy | 10000.00 |\n| Ramesh | 2000.00 |\n+----------+-------------+\n" }, { "code": null, "e": 61447, "s": 61344, "text": "Now, let us look at a table where the CUSTOMERS table has the following records with duplicate names −" }, { "code": null, "e": 61964, "s": 61447, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Ramesh | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | kaushik | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+" }, { "code": null, "e": 62086, "s": 61964, "text": "Now again, if you want to know the total amount of salary on each customer, then the GROUP BY query would be as follows −" }, { "code": null, "e": 62149, "s": 62086, "text": "SQL> SELECT NAME, SUM(SALARY) FROM CUSTOMERS\n GROUP BY NAME;" }, { "code": null, "e": 62191, "s": 62149, "text": "This would produce the following result −" }, { "code": null, "e": 62426, "s": 62191, "text": "+---------+-------------+\n| NAME | SUM(SALARY) |\n+---------+-------------+\n| Hardik | 8500.00 |\n| kaushik | 8500.00 |\n| Komal | 4500.00 |\n| Muffy | 10000.00 |\n| Ramesh | 3500.00 |\n+---------+-------------+\n" }, { "code": null, "e": 62573, "s": 62426, "text": "The SQL DISTINCT keyword is used in conjunction with the SELECT statement to eliminate all the duplicate records and fetching only unique records." }, { "code": null, "e": 62774, "s": 62573, "text": "There may be a situation when you have multiple duplicate records in a table. While fetching such records, it makes more sense to fetch only those unique records instead of fetching duplicate records." }, { "code": null, "e": 62862, "s": 62774, "text": "The basic syntax of DISTINCT keyword to eliminate the duplicate records is as follows −" }, { "code": null, "e": 62944, "s": 62862, "text": "SELECT DISTINCT column1, column2,.....columnN \nFROM table_name\nWHERE [condition]\n" }, { "code": null, "e": 63004, "s": 62944, "text": "Consider the CUSTOMERS table having the following records −" }, { "code": null, "e": 63522, "s": 63004, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+\n" }, { "code": null, "e": 63609, "s": 63522, "text": "First, let us see how the following SELECT query returns the duplicate salary records." }, { "code": null, "e": 63663, "s": 63609, "text": "SQL> SELECT SALARY FROM CUSTOMERS\n ORDER BY SALARY;" }, { "code": null, "e": 63797, "s": 63663, "text": "This would produce the following result, where the salary (2000) is coming twice which is a duplicate record from the original table." }, { "code": null, "e": 63941, "s": 63797, "text": "+----------+\n| SALARY |\n+----------+\n| 1500.00 |\n| 2000.00 |\n| 2000.00 |\n| 4500.00 |\n| 6500.00 |\n| 8500.00 |\n| 10000.00 |\n+----------+\n" }, { "code": null, "e": 64031, "s": 63941, "text": "Now, let us use the DISTINCT keyword with the above SELECT query and then see the result." }, { "code": null, "e": 64094, "s": 64031, "text": "SQL> SELECT DISTINCT SALARY FROM CUSTOMERS\n ORDER BY SALARY;" }, { "code": null, "e": 64176, "s": 64094, "text": "This would produce the following result where we do not have any duplicate entry." }, { "code": null, "e": 64307, "s": 64176, "text": "+----------+\n| SALARY |\n+----------+\n| 1500.00 |\n| 2000.00 |\n| 4500.00 |\n| 6500.00 |\n| 8500.00 |\n| 10000.00 |\n+----------+\n" }, { "code": null, "e": 64492, "s": 64307, "text": "The SQL ORDER BY clause is used to sort the data in ascending or descending order, based on one or more columns. Some databases sort the query results in an ascending order by default." }, { "code": null, "e": 64623, "s": 64492, "text": "The basic syntax of the ORDER BY clause which would be used to sort the result in an ascending or descending order is as follows −" }, { "code": null, "e": 64734, "s": 64623, "text": "SELECT column-list \nFROM table_name \n[WHERE condition] \n[ORDER BY column1, column2, .. columnN] [ASC | DESC];\n" }, { "code": null, "e": 64887, "s": 64734, "text": "You can use more than one column in the ORDER BY clause. Make sure that whatever column you are using to sort, that column should be in the column-list." }, { "code": null, "e": 64947, "s": 64887, "text": "Consider the CUSTOMERS table having the following records −" }, { "code": null, "e": 65464, "s": 64947, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+" }, { "code": null, "e": 65559, "s": 65464, "text": "Following is an example, which would sort the result in an ascending order by NAME and SALARY." }, { "code": null, "e": 65614, "s": 65559, "text": "SQL> SELECT * FROM CUSTOMERS\n ORDER BY NAME, SALARY;" }, { "code": null, "e": 65656, "s": 65614, "text": "This would produce the following result −" }, { "code": null, "e": 66173, "s": 65656, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n+----+----------+-----+-----------+----------+" }, { "code": null, "e": 66273, "s": 66173, "text": "The following code block has an example, which would sort the result in a descending order by NAME." }, { "code": null, "e": 66325, "s": 66273, "text": "SQL> SELECT * FROM CUSTOMERS\n ORDER BY NAME DESC;" }, { "code": null, "e": 66367, "s": 66325, "text": "This would produce the following result −" }, { "code": null, "e": 66884, "s": 66367, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n+----+----------+-----+-----------+----------+" }, { "code": null, "e": 66978, "s": 66884, "text": "To fetch the rows with their own preferred order, the SELECT query used would be as follows −" }, { "code": null, "e": 67192, "s": 66978, "text": "SQL> SELECT * FROM CUSTOMERS\n ORDER BY (CASE ADDRESS\n WHEN 'DELHI' \t THEN 1\n WHEN 'BHOPAL' \t THEN 2\n WHEN 'KOTA' \t THEN 3\n WHEN 'AHMEDABAD' THEN 4\n WHEN 'MP' \tTHEN 5\n ELSE 100 END) ASC, ADDRESS DESC;" }, { "code": null, "e": 67234, "s": 67192, "text": "This would produce the following result −" }, { "code": null, "e": 67752, "s": 67234, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n+----+----------+-----+-----------+----------+\n" }, { "code": null, "e": 67962, "s": 67752, "text": "This will sort the customers by ADDRESS in your ownoOrder of preference first and in a natural order for the remaining addresses. Also, the remaining Addresses will be sorted in the reverse alphabetical order." }, { "code": null, "e": 68167, "s": 67962, "text": "Constraints are the rules enforced on the data columns of a table. These are used to limit the type of data that can go into a table. This ensures the accuracy and reliability of the data in the database." }, { "code": null, "e": 68360, "s": 68167, "text": "Constraints could be either on a column level or a table level. The column level constraints are applied only to one column, whereas the table level constraints are applied to the whole table." }, { "code": null, "e": 68560, "s": 68360, "text": "Following are some of the most commonly used constraints available in SQL. These constraints have already been discussed in SQL - RDBMS Concepts chapter, but it’s worth to revise them at this point." }, { "code": null, "e": 68628, "s": 68560, "text": "NOT NULL Constraint − Ensures that a column cannot have NULL value." }, { "code": null, "e": 68696, "s": 68628, "text": "NOT NULL Constraint − Ensures that a column cannot have NULL value." }, { "code": null, "e": 68779, "s": 68696, "text": "DEFAULT Constraint − Provides a default value for a column when none is specified." }, { "code": null, "e": 68862, "s": 68779, "text": "DEFAULT Constraint − Provides a default value for a column when none is specified." }, { "code": null, "e": 68933, "s": 68862, "text": "UNIQUE Constraint − Ensures that all values in a column are different." }, { "code": null, "e": 69004, "s": 68933, "text": "UNIQUE Constraint − Ensures that all values in a column are different." }, { "code": null, "e": 69075, "s": 69004, "text": "PRIMARY Key − Uniquely identifies each row/record in a database table." }, { "code": null, "e": 69146, "s": 69075, "text": "PRIMARY Key − Uniquely identifies each row/record in a database table." }, { "code": null, "e": 69229, "s": 69146, "text": "FOREIGN Key − Uniquely identifies a row/record in any of the given database table." }, { "code": null, "e": 69312, "s": 69229, "text": "FOREIGN Key − Uniquely identifies a row/record in any of the given database table." }, { "code": null, "e": 69422, "s": 69312, "text": "CHECK Constraint − The CHECK constraint ensures that all the values in a column satisfies certain conditions." }, { "code": null, "e": 69532, "s": 69422, "text": "CHECK Constraint − The CHECK constraint ensures that all the values in a column satisfies certain conditions." }, { "code": null, "e": 69605, "s": 69532, "text": "INDEX − Used to create and retrieve data from the database very quickly." }, { "code": null, "e": 69678, "s": 69605, "text": "INDEX − Used to create and retrieve data from the database very quickly." }, { "code": null, "e": 69859, "s": 69678, "text": "Constraints can be specified when a table is created with the CREATE TABLE statement or you can use the ALTER TABLE statement to create constraints even after the table is created." }, { "code": null, "e": 69974, "s": 69859, "text": "Any constraint that you have defined can be dropped using the ALTER TABLE command with the DROP CONSTRAINT option." }, { "code": null, "e": 70081, "s": 69974, "text": "For example, to drop the primary key constraint in the EMPLOYEES table, you can use the following command." }, { "code": null, "e": 70133, "s": 70081, "text": "ALTER TABLE EMPLOYEES DROP CONSTRAINT EMPLOYEES_PK;" }, { "code": null, "e": 70316, "s": 70133, "text": "Some implementations may provide shortcuts for dropping certain constraints. For example, to drop the primary key constraint for a table in Oracle, you can use the following command." }, { "code": null, "e": 70356, "s": 70316, "text": "ALTER TABLE EMPLOYEES DROP PRIMARY KEY;" }, { "code": null, "e": 70552, "s": 70356, "text": "Some implementations allow you to disable constraints. Instead of permanently dropping a constraint from the database, you may want to temporarily disable the constraint and then enable it later." }, { "code": null, "e": 70753, "s": 70552, "text": "Integrity constraints are used to ensure accuracy and consistency of the data in a relational database. Data integrity is handled in a relational database through the concept of referential integrity." }, { "code": null, "e": 70967, "s": 70753, "text": "There are many types of integrity constraints that play a role in Referential Integrity (RI). These constraints include Primary Key, Foreign Key, Unique Constraints and other constraints which are mentioned above." }, { "code": null, "e": 71141, "s": 70967, "text": "The SQL Joins clause is used to combine records from two or more tables in a database. A JOIN is a means for combining fields from two tables by using values common to each." }, { "code": null, "e": 71177, "s": 71141, "text": "Consider the following two tables −" }, { "code": null, "e": 71203, "s": 71177, "text": "Table 1 − CUSTOMERS Table" }, { "code": null, "e": 71720, "s": 71203, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+" }, { "code": null, "e": 71743, "s": 71720, "text": "Table 2 − ORDERS Table" }, { "code": null, "e": 72167, "s": 71743, "text": "+-----+---------------------+-------------+--------+\n|OID | DATE | CUSTOMER_ID | AMOUNT |\n+-----+---------------------+-------------+--------+\n| 102 | 2009-10-08 00:00:00 | 3 | 3000 |\n| 100 | 2009-10-08 00:00:00 | 3 | 1500 |\n| 101 | 2009-11-20 00:00:00 | 2 | 1560 |\n| 103 | 2008-05-20 00:00:00 | 4 | 2060 |\n+-----+---------------------+-------------+--------+" }, { "code": null, "e": 72241, "s": 72167, "text": "Now, let us join these two tables in our SELECT statement as shown below." }, { "code": null, "e": 72346, "s": 72241, "text": "SQL> SELECT ID, NAME, AGE, AMOUNT\n FROM CUSTOMERS, ORDERS\n WHERE CUSTOMERS.ID = ORDERS.CUSTOMER_ID;" }, { "code": null, "e": 72387, "s": 72346, "text": "This would produce the following result." }, { "code": null, "e": 72652, "s": 72387, "text": "+----+----------+-----+--------+\n| ID | NAME | AGE | AMOUNT |\n+----+----------+-----+--------+\n| 3 | kaushik | 23 | 3000 |\n| 3 | kaushik | 23 | 1500 |\n| 2 | Khilan | 25 | 1560 |\n| 4 | Chaitali | 25 | 2060 |\n+----+----------+-----+--------+\n" }, { "code": null, "e": 72921, "s": 72652, "text": "Here, it is noticeable that the join is performed in the WHERE clause. Several operators can be used to join tables, such as =, <, >, <>, <=, >=, !=, BETWEEN, LIKE, and NOT; they can all be used to join tables. However, the most common operator is the equal to symbol." }, { "code": null, "e": 72975, "s": 72921, "text": "There are different types of joins available in SQL −" }, { "code": null, "e": 73039, "s": 72975, "text": "INNER JOIN − returns rows when there is a match in both tables." }, { "code": null, "e": 73103, "s": 73039, "text": "INNER JOIN − returns rows when there is a match in both tables." }, { "code": null, "e": 73202, "s": 73103, "text": "LEFT JOIN − returns all rows from the left table, even if there are no matches in the right table." }, { "code": null, "e": 73301, "s": 73202, "text": "LEFT JOIN − returns all rows from the left table, even if there are no matches in the right table." }, { "code": null, "e": 73401, "s": 73301, "text": "RIGHT JOIN − returns all rows from the right table, even if there are no matches in the left table." }, { "code": null, "e": 73501, "s": 73401, "text": "RIGHT JOIN − returns all rows from the right table, even if there are no matches in the left table." }, { "code": null, "e": 73570, "s": 73501, "text": "FULL JOIN − returns rows when there is a match in one of the tables." }, { "code": null, "e": 73639, "s": 73570, "text": "FULL JOIN − returns rows when there is a match in one of the tables." }, { "code": null, "e": 73780, "s": 73639, "text": "SELF JOIN − is used to join a table to itself as if the table were two tables, temporarily renaming at least one table in the SQL statement." }, { "code": null, "e": 73921, "s": 73780, "text": "SELF JOIN − is used to join a table to itself as if the table were two tables, temporarily renaming at least one table in the SQL statement." }, { "code": null, "e": 74027, "s": 73921, "text": "CARTESIAN JOIN − returns the Cartesian product of the sets of records from the two or more joined tables." }, { "code": null, "e": 74133, "s": 74027, "text": "CARTESIAN JOIN − returns the Cartesian product of the sets of records from the two or more joined tables." }, { "code": null, "e": 74183, "s": 74133, "text": "Let us now discuss each of these joins in detail." }, { "code": null, "e": 74315, "s": 74183, "text": "The SQL UNION clause/operator is used to combine the results of two or more SELECT statements without returning any duplicate rows." }, { "code": null, "e": 74373, "s": 74315, "text": "To use this UNION clause, each SELECT statement must have" }, { "code": null, "e": 74409, "s": 74373, "text": "The same number of columns selected" }, { "code": null, "e": 74447, "s": 74409, "text": "The same number of column expressions" }, { "code": null, "e": 74470, "s": 74447, "text": "The same data type and" }, { "code": null, "e": 74498, "s": 74470, "text": "Have them in the same order" }, { "code": null, "e": 74547, "s": 74498, "text": "But they need not have to be in the same length." }, { "code": null, "e": 74598, "s": 74547, "text": "The basic syntax of a UNION clause is as follows −" }, { "code": null, "e": 74747, "s": 74598, "text": "SELECT column1 [, column2 ]\nFROM table1 [, table2 ]\n[WHERE condition]\n\nUNION\n\nSELECT column1 [, column2 ]\nFROM table1 [, table2 ]\n[WHERE condition]\n" }, { "code": null, "e": 74830, "s": 74747, "text": "Here, the given condition could be any given expression based on your requirement." }, { "code": null, "e": 74865, "s": 74830, "text": "Consider the following two tables." }, { "code": null, "e": 74906, "s": 74865, "text": "Table 1 − CUSTOMERS Table is as follows." }, { "code": null, "e": 75423, "s": 74906, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+" }, { "code": null, "e": 75461, "s": 75423, "text": "Table 2 − ORDERS Table is as follows." }, { "code": null, "e": 75885, "s": 75461, "text": "+-----+---------------------+-------------+--------+\n|OID | DATE | CUSTOMER_ID | AMOUNT |\n+-----+---------------------+-------------+--------+\n| 102 | 2009-10-08 00:00:00 | 3 | 3000 |\n| 100 | 2009-10-08 00:00:00 | 3 | 1500 |\n| 101 | 2009-11-20 00:00:00 | 2 | 1560 |\n| 103 | 2008-05-20 00:00:00 | 4 | 2060 |\n+-----+---------------------+-------------+--------+" }, { "code": null, "e": 75956, "s": 75885, "text": "Now, let us join these two tables in our SELECT statement as follows −" }, { "code": null, "e": 76190, "s": 75956, "text": "SQL> SELECT ID, NAME, AMOUNT, DATE\n FROM CUSTOMERS\n LEFT JOIN ORDERS\n ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID\nUNION\n SELECT ID, NAME, AMOUNT, DATE\n FROM CUSTOMERS\n RIGHT JOIN ORDERS\n ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;" }, { "code": null, "e": 76232, "s": 76190, "text": "This would produce the following result −" }, { "code": null, "e": 76845, "s": 76232, "text": "+------+----------+--------+---------------------+\n| ID | NAME | AMOUNT | DATE |\n+------+----------+--------+---------------------+\n| 1 | Ramesh | NULL | NULL |\n| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |\n| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |\n| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |\n| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |\n| 5 | Hardik | NULL | NULL |\n| 6 | Komal | NULL | NULL |\n| 7 | Muffy | NULL | NULL |\n+------+----------+--------+---------------------+\n" }, { "code": null, "e": 76950, "s": 76845, "text": "The UNION ALL operator is used to combine the results of two SELECT statements including duplicate rows." }, { "code": null, "e": 77034, "s": 76950, "text": "The same rules that apply to the UNION clause will apply to the UNION ALL operator." }, { "code": null, "e": 77083, "s": 77034, "text": "The basic syntax of the UNION ALL is as follows." }, { "code": null, "e": 77236, "s": 77083, "text": "SELECT column1 [, column2 ]\nFROM table1 [, table2 ]\n[WHERE condition]\n\nUNION ALL\n\nSELECT column1 [, column2 ]\nFROM table1 [, table2 ]\n[WHERE condition]\n" }, { "code": null, "e": 77319, "s": 77236, "text": "Here, the given condition could be any given expression based on your requirement." }, { "code": null, "e": 77354, "s": 77319, "text": "Consider the following two tables," }, { "code": null, "e": 77395, "s": 77354, "text": "Table 1 − CUSTOMERS Table is as follows." }, { "code": null, "e": 77912, "s": 77395, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+" }, { "code": null, "e": 77950, "s": 77912, "text": "Table 2 − ORDERS table is as follows." }, { "code": null, "e": 78374, "s": 77950, "text": "+-----+---------------------+-------------+--------+\n|OID | DATE | CUSTOMER_ID | AMOUNT |\n+-----+---------------------+-------------+--------+\n| 102 | 2009-10-08 00:00:00 | 3 | 3000 |\n| 100 | 2009-10-08 00:00:00 | 3 | 1500 |\n| 101 | 2009-11-20 00:00:00 | 2 | 1560 |\n| 103 | 2008-05-20 00:00:00 | 4 | 2060 |\n+-----+---------------------+-------------+--------+" }, { "code": null, "e": 78445, "s": 78374, "text": "Now, let us join these two tables in our SELECT statement as follows −" }, { "code": null, "e": 78683, "s": 78445, "text": "SQL> SELECT ID, NAME, AMOUNT, DATE\n FROM CUSTOMERS\n LEFT JOIN ORDERS\n ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID\nUNION ALL\n SELECT ID, NAME, AMOUNT, DATE\n FROM CUSTOMERS\n RIGHT JOIN ORDERS\n ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;" }, { "code": null, "e": 78725, "s": 78683, "text": "This would produce the following result −" }, { "code": null, "e": 79542, "s": 78725, "text": "+------+----------+--------+---------------------+\n| ID | NAME | AMOUNT | DATE |\n+------+----------+--------+---------------------+\n| 1 | Ramesh | NULL | NULL |\n| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |\n| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |\n| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |\n| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |\n| 5 | Hardik | NULL | NULL |\n| 6 | Komal | NULL | NULL |\n| 7 | Muffy | NULL | NULL |\n| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |\n| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |\n| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |\n| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |\n+------+----------+--------+---------------------+\n" }, { "code": null, "e": 79622, "s": 79542, "text": "There are two other clauses (i.e., operators), which are like the UNION clause." }, { "code": null, "e": 79806, "s": 79622, "text": "SQL INTERSECT Clause − This is used to combine two SELECT statements, but returns rows only from the first SELECT statement that are identical to a row in the second SELECT statement." }, { "code": null, "e": 79990, "s": 79806, "text": "SQL INTERSECT Clause − This is used to combine two SELECT statements, but returns rows only from the first SELECT statement that are identical to a row in the second SELECT statement." }, { "code": null, "e": 80149, "s": 79990, "text": "SQL EXCEPT Clause − This combines two SELECT statements and returns rows from the first SELECT statement that are not returned by the second SELECT statement." }, { "code": null, "e": 80308, "s": 80149, "text": "SQL EXCEPT Clause − This combines two SELECT statements and returns rows from the first SELECT statement that are not returned by the second SELECT statement." }, { "code": null, "e": 80440, "s": 80308, "text": "The SQL NULL is the term used to represent a missing value. A NULL value in a table is a value in a field that appears to be blank." }, { "code": null, "e": 80609, "s": 80440, "text": "A field with a NULL value is a field with no value. It is very important to understand that a NULL value is different than a zero value or a field that contains spaces." }, { "code": null, "e": 80658, "s": 80609, "text": "The basic syntax of NULL while creating a table." }, { "code": null, "e": 80876, "s": 80658, "text": "SQL> CREATE TABLE CUSTOMERS(\n ID INT NOT NULL,\n NAME VARCHAR (20) NOT NULL,\n AGE INT NOT NULL,\n ADDRESS CHAR (25) ,\n SALARY DECIMAL (18, 2), \n PRIMARY KEY (ID)\n);\n" }, { "code": null, "e": 81070, "s": 80876, "text": "Here, NOT NULL signifies that column should always accept an explicit value of the given data type. There are two columns where we did not use NOT NULL, which means these columns could be NULL." }, { "code": null, "e": 81160, "s": 81070, "text": "A field with a NULL value is the one that has been left blank during the record creation." }, { "code": null, "e": 81423, "s": 81160, "text": "The NULL value can cause problems when selecting data. However, because when comparing an unknown value to any other value, the result is always unknown and not included in the results. You must use the IS NULL or IS NOT NULL operators to check for a NULL value." }, { "code": null, "e": 81497, "s": 81423, "text": "Consider the following CUSTOMERS table having the records as shown below." }, { "code": null, "e": 82014, "s": 81497, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | |\n| 7 | Muffy | 24 | Indore | |\n+----+----------+-----+-----------+----------+" }, { "code": null, "e": 82070, "s": 82014, "text": "Now, following is the usage of the IS NOT NULLoperator." }, { "code": null, "e": 82161, "s": 82070, "text": "SQL> SELECT ID, NAME, AGE, ADDRESS, SALARY\n FROM CUSTOMERS\n WHERE SALARY IS NOT NULL;" }, { "code": null, "e": 82203, "s": 82161, "text": "This would produce the following result −" }, { "code": null, "e": 82627, "s": 82203, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n+----+----------+-----+-----------+----------+\n" }, { "code": null, "e": 82680, "s": 82627, "text": "Now, following is the usage of the IS NULL operator." }, { "code": null, "e": 82767, "s": 82680, "text": "SQL> SELECT ID, NAME, AGE, ADDRESS, SALARY\n FROM CUSTOMERS\n WHERE SALARY IS NULL;" }, { "code": null, "e": 82809, "s": 82767, "text": "This would produce the following result −" }, { "code": null, "e": 83092, "s": 82809, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 6 | Komal | 22 | MP | |\n| 7 | Muffy | 24 | Indore | |\n+----+----------+-----+-----------+----------+\n" }, { "code": null, "e": 83446, "s": 83092, "text": "You can rename a table or a column temporarily by giving another name known as Alias. The use of table aliases is to rename a table in a specific SQL statement. The renaming is a temporary change and the actual table name does not change in the database. The column aliases are used to rename a table's columns for the purpose of a particular SQL query." }, { "code": null, "e": 83495, "s": 83446, "text": "The basic syntax of a table alias is as follows." }, { "code": null, "e": 83573, "s": 83495, "text": "SELECT column1, column2....\nFROM table_name AS alias_name\nWHERE [condition];\n" }, { "code": null, "e": 83623, "s": 83573, "text": "The basic syntax of a column alias is as follows." }, { "code": null, "e": 83692, "s": 83623, "text": "SELECT column_name AS alias_name\nFROM table_name\nWHERE [condition];\n" }, { "code": null, "e": 83727, "s": 83692, "text": "Consider the following two tables." }, { "code": null, "e": 83768, "s": 83727, "text": "Table 1 − CUSTOMERS Table is as follows." }, { "code": null, "e": 84285, "s": 83768, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+" }, { "code": null, "e": 84323, "s": 84285, "text": "Table 2 − ORDERS Table is as follows." }, { "code": null, "e": 84747, "s": 84323, "text": "+-----+---------------------+-------------+--------+\n|OID | DATE | CUSTOMER_ID | AMOUNT |\n+-----+---------------------+-------------+--------+\n| 102 | 2009-10-08 00:00:00 | 3 | 3000 |\n| 100 | 2009-10-08 00:00:00 | 3 | 1500 |\n| 101 | 2009-11-20 00:00:00 | 2 | 1560 |\n| 103 | 2008-05-20 00:00:00 | 4 | 2060 |\n+-----+---------------------+-------------+--------+" }, { "code": null, "e": 84811, "s": 84747, "text": "Now, the following code block shows the usage of a table alias." }, { "code": null, "e": 84922, "s": 84811, "text": "SQL> SELECT C.ID, C.NAME, C.AGE, O.AMOUNT \n FROM CUSTOMERS AS C, ORDERS AS O\n WHERE C.ID = O.CUSTOMER_ID;" }, { "code": null, "e": 84963, "s": 84922, "text": "This would produce the following result." }, { "code": null, "e": 85228, "s": 84963, "text": "+----+----------+-----+--------+\n| ID | NAME | AGE | AMOUNT |\n+----+----------+-----+--------+\n| 3 | kaushik | 23 | 3000 |\n| 3 | kaushik | 23 | 1500 |\n| 2 | Khilan | 25 | 1560 |\n| 4 | Chaitali | 25 | 2060 |\n+----+----------+-----+--------+\n" }, { "code": null, "e": 85270, "s": 85228, "text": "Following is the usage of a column alias." }, { "code": null, "e": 85371, "s": 85270, "text": "SQL> SELECT ID AS CUSTOMER_ID, NAME AS CUSTOMER_NAME\n FROM CUSTOMERS\n WHERE SALARY IS NOT NULL;" }, { "code": null, "e": 85412, "s": 85371, "text": "This would produce the following result." }, { "code": null, "e": 85765, "s": 85412, "text": "+-------------+---------------+\n| CUSTOMER_ID | CUSTOMER_NAME |\n+-------------+---------------+\n| 1 | Ramesh |\n| 2 | Khilan |\n| 3 | kaushik |\n| 4 | Chaitali |\n| 5 | Hardik |\n| 6 | Komal |\n| 7 | Muffy |\n+-------------+---------------+\n" }, { "code": null, "e": 85995, "s": 85765, "text": "Indexes are special lookup tables that the database search engine can use to speed up data retrieval. Simply put, an index is a pointer to data in a table. An index in a database is very similar to an index in the back of a book." }, { "code": null, "e": 86217, "s": 85995, "text": "For example, if you want to reference all pages in a book that discusses a certain topic, you first refer to the index, which lists all the topics alphabetically and are then referred to one or more specific page numbers." }, { "code": null, "e": 86413, "s": 86217, "text": "An index helps to speed up SELECT queries and WHERE clauses, but it slows down data input, with the UPDATE and the INSERT statements. Indexes can be created or dropped with no effect on the data." }, { "code": null, "e": 86637, "s": 86413, "text": "Creating an index involves the CREATE INDEX statement, which allows you to name the index, to specify the table and which column or columns to index, and to indicate whether the index is in an ascending or descending order." }, { "code": null, "e": 86806, "s": 86637, "text": "Indexes can also be unique, like the UNIQUE constraint, in that the index prevents duplicate entries in the column or combination of columns on which there is an index." }, { "code": null, "e": 86856, "s": 86806, "text": "The basic syntax of a CREATE INDEX is as follows." }, { "code": null, "e": 86896, "s": 86856, "text": "CREATE INDEX index_name ON table_name;\n" }, { "code": null, "e": 86993, "s": 86896, "text": "A single-column index is created based on only one table column. The basic syntax is as follows." }, { "code": null, "e": 87047, "s": 86993, "text": "CREATE INDEX index_name\nON table_name (column_name);\n" }, { "code": null, "e": 87240, "s": 87047, "text": "Unique indexes are used not only for performance, but also for data integrity. A unique index does not allow any duplicate values to be inserted into the table. The basic syntax is as follows." }, { "code": null, "e": 87301, "s": 87240, "text": "CREATE UNIQUE INDEX index_name\non table_name (column_name);\n" }, { "code": null, "e": 87398, "s": 87301, "text": "A composite index is an index on two or more columns of a table. Its basic syntax is as follows." }, { "code": null, "e": 87457, "s": 87398, "text": "CREATE INDEX index_name\non table_name (column1, column2);\n" }, { "code": null, "e": 87638, "s": 87457, "text": "Whether to create a single-column index or a composite index, take into consideration the column(s) that you may use very frequently in a query's WHERE clause as filter conditions." }, { "code": null, "e": 87859, "s": 87638, "text": "Should there be only one column used, a single-column index should be the choice. Should there be two or more columns that are frequently used in the WHERE clause as filters, the composite index would be the best choice." }, { "code": null, "e": 88055, "s": 87859, "text": "Implicit indexes are indexes that are automatically created by the database server when an object is created. Indexes are automatically created for primary key constraints and unique constraints." }, { "code": null, "e": 88204, "s": 88055, "text": "An index can be dropped using SQL DROP command. Care should be taken when dropping an index because the performance may either slow down or improve." }, { "code": null, "e": 88237, "s": 88204, "text": "The basic syntax is as follows −" }, { "code": null, "e": 88261, "s": 88237, "text": "DROP INDEX index_name;\n" }, { "code": null, "e": 88344, "s": 88261, "text": "You can check the INDEX Constraint chapter to see some actual examples on Indexes." }, { "code": null, "e": 88456, "s": 88344, "text": "Although indexes are intended to enhance a database's performance, there are times when they should be avoided." }, { "code": null, "e": 88539, "s": 88456, "text": "The following guidelines indicate when the use of an index should be reconsidered." }, { "code": null, "e": 88583, "s": 88539, "text": "Indexes should not be used on small tables." }, { "code": null, "e": 88627, "s": 88583, "text": "Indexes should not be used on small tables." }, { "code": null, "e": 88696, "s": 88627, "text": "Tables that have frequent, large batch updates or insert operations." }, { "code": null, "e": 88765, "s": 88696, "text": "Tables that have frequent, large batch updates or insert operations." }, { "code": null, "e": 88846, "s": 88765, "text": "Indexes should not be used on columns that contain a high number of NULL values." }, { "code": null, "e": 88927, "s": 88846, "text": "Indexes should not be used on columns that contain a high number of NULL values." }, { "code": null, "e": 88990, "s": 88927, "text": "Columns that are frequently manipulated should not be indexed." }, { "code": null, "e": 89053, "s": 88990, "text": "Columns that are frequently manipulated should not be indexed." }, { "code": null, "e": 89246, "s": 89053, "text": "The SQL ALTER TABLE command is used to add, delete or modify columns in an existing table. You should also use the ALTER TABLE command to add and drop various constraints on an existing table." }, { "code": null, "e": 89345, "s": 89246, "text": "The basic syntax of an ALTER TABLE command to add a New Column in an existing table is as follows." }, { "code": null, "e": 89395, "s": 89345, "text": "ALTER TABLE table_name ADD column_name datatype;\n" }, { "code": null, "e": 89489, "s": 89395, "text": "The basic syntax of an ALTER TABLE command to DROP COLUMN in an existing table is as follows." }, { "code": null, "e": 89538, "s": 89489, "text": "ALTER TABLE table_name DROP COLUMN column_name;\n" }, { "code": null, "e": 89643, "s": 89538, "text": "The basic syntax of an ALTER TABLE command to change the DATA TYPE of a column in a table is as follows." }, { "code": null, "e": 89703, "s": 89643, "text": "ALTER TABLE table_name MODIFY COLUMN column_name datatype;\n" }, { "code": null, "e": 89813, "s": 89703, "text": "The basic syntax of an ALTER TABLE command to add a NOT NULL constraint to a column in a table is as follows." }, { "code": null, "e": 89875, "s": 89813, "text": "ALTER TABLE table_name MODIFY column_name datatype NOT NULL;\n" }, { "code": null, "e": 89958, "s": 89875, "text": "The basic syntax of ALTER TABLE to ADD UNIQUE CONSTRAINT to a table is as follows." }, { "code": null, "e": 90046, "s": 89958, "text": "ALTER TABLE table_name \nADD CONSTRAINT MyUniqueConstraint UNIQUE(column1, column2...);\n" }, { "code": null, "e": 90139, "s": 90046, "text": "The basic syntax of an ALTER TABLE command to ADD CHECK CONSTRAINT to a table is as follows." }, { "code": null, "e": 90217, "s": 90139, "text": "ALTER TABLE table_name \nADD CONSTRAINT MyUniqueConstraint CHECK (CONDITION);\n" }, { "code": null, "e": 90316, "s": 90217, "text": "The basic syntax of an ALTER TABLE command to ADD PRIMARY KEY constraint to a table is as follows." }, { "code": null, "e": 90404, "s": 90316, "text": "ALTER TABLE table_name \nADD CONSTRAINT MyPrimaryKey PRIMARY KEY (column1, column2...);\n" }, { "code": null, "e": 90494, "s": 90404, "text": "The basic syntax of an ALTER TABLE command to DROP CONSTRAINT from a table is as follows." }, { "code": null, "e": 90555, "s": 90494, "text": "ALTER TABLE table_name \nDROP CONSTRAINT MyUniqueConstraint;\n" }, { "code": null, "e": 90603, "s": 90555, "text": "If you're using MySQL, the code is as follows −" }, { "code": null, "e": 90658, "s": 90603, "text": "ALTER TABLE table_name \nDROP INDEX MyUniqueConstraint;" }, { "code": null, "e": 90760, "s": 90658, "text": "The basic syntax of an ALTER TABLE command to DROP PRIMARY KEY constraint from a table is as follows." }, { "code": null, "e": 90815, "s": 90760, "text": "ALTER TABLE table_name \nDROP CONSTRAINT MyPrimaryKey;\n" }, { "code": null, "e": 90863, "s": 90815, "text": "If you're using MySQL, the code is as follows −" }, { "code": null, "e": 90905, "s": 90863, "text": "ALTER TABLE table_name \nDROP PRIMARY KEY;" }, { "code": null, "e": 90965, "s": 90905, "text": "Consider the CUSTOMERS table having the following records −" }, { "code": null, "e": 91482, "s": 90965, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+" }, { "code": null, "e": 91550, "s": 91482, "text": "Following is the example to ADD a New Column to an existing table −" }, { "code": null, "e": 91589, "s": 91550, "text": "ALTER TABLE CUSTOMERS ADD SEX char(1);" }, { "code": null, "e": 91682, "s": 91589, "text": "Now, the CUSTOMERS table is changed and following would be output from the SELECT statement." }, { "code": null, "e": 92266, "s": 91682, "text": "+----+---------+-----+-----------+----------+------+\n| ID | NAME | AGE | ADDRESS | SALARY | SEX |\n+----+---------+-----+-----------+----------+------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 | NULL |\n| 2 | Ramesh | 25 | Delhi | 1500.00 | NULL |\n| 3 | kaushik | 23 | Kota | 2000.00 | NULL |\n| 4 | kaushik | 25 | Mumbai | 6500.00 | NULL |\n| 5 | Hardik | 27 | Bhopal | 8500.00 | NULL |\n| 6 | Komal | 22 | MP | 4500.00 | NULL |\n| 7 | Muffy | 24 | Indore | 10000.00 | NULL |\n+----+---------+-----+-----------+----------+------+\n" }, { "code": null, "e": 92335, "s": 92266, "text": "Following is the example to DROP sex column from the existing table." }, { "code": null, "e": 92367, "s": 92335, "text": "ALTER TABLE CUSTOMERS DROP SEX;" }, { "code": null, "e": 92464, "s": 92367, "text": "Now, the CUSTOMERS table is changed and following would be the output from the SELECT statement." }, { "code": null, "e": 92971, "s": 92464, "text": "+----+---------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+---------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Ramesh | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | kaushik | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+---------+-----+-----------+----------+\n" }, { "code": null, "e": 93058, "s": 92971, "text": "The SQL TRUNCATE TABLE command is used to delete complete data from an existing table." }, { "code": null, "e": 93269, "s": 93058, "text": "You can also use DROP TABLE command to delete complete table but it would remove complete table structure form the database and you would need to re-create this table once again if you wish you store some data." }, { "code": null, "e": 93329, "s": 93269, "text": "The basic syntax of a TRUNCATE TABLE command is as follows." }, { "code": null, "e": 93358, "s": 93329, "text": "TRUNCATE TABLE table_name;\n" }, { "code": null, "e": 93416, "s": 93358, "text": "Consider a CUSTOMERS table having the following records −" }, { "code": null, "e": 93934, "s": 93416, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+\n" }, { "code": null, "e": 93982, "s": 93934, "text": "Following is the example of a Truncate command." }, { "code": null, "e": 94014, "s": 93982, "text": "SQL > TRUNCATE TABLE CUSTOMERS;" }, { "code": null, "e": 94132, "s": 94014, "text": "Now, the CUSTOMERS table is truncated and the output from SELECT statement will be as shown in the code block below −" }, { "code": null, "e": 94184, "s": 94132, "text": "SQL> SELECT * FROM CUSTOMERS;\nEmpty set (0.00 sec)\n" }, { "code": null, "e": 94367, "s": 94184, "text": "A view is nothing more than a SQL statement that is stored in the database with an associated name. A view is actually a composition of a table in the form of a predefined SQL query." }, { "code": null, "e": 94538, "s": 94367, "text": "A view can contain all rows of a table or select rows from a table. A view can be created from one or many tables which depends on the written SQL query to create a view." }, { "code": null, "e": 94614, "s": 94538, "text": "Views, which are a type of virtual tables allow users to do the following −" }, { "code": null, "e": 94696, "s": 94614, "text": "Structure data in a way that users or classes of users find natural or intuitive." }, { "code": null, "e": 94778, "s": 94696, "text": "Structure data in a way that users or classes of users find natural or intuitive." }, { "code": null, "e": 94899, "s": 94778, "text": "Restrict access to the data in such a way that a user can see and (sometimes) modify exactly what they need and no more." }, { "code": null, "e": 95020, "s": 94899, "text": "Restrict access to the data in such a way that a user can see and (sometimes) modify exactly what they need and no more." }, { "code": null, "e": 95094, "s": 95020, "text": "Summarize data from various tables which can be used to generate reports." }, { "code": null, "e": 95168, "s": 95094, "text": "Summarize data from various tables which can be used to generate reports." }, { "code": null, "e": 95303, "s": 95168, "text": "Database views are created using the CREATE VIEW statement. Views can be created from a single table, multiple tables or another view." }, { "code": null, "e": 95413, "s": 95303, "text": "To create a view, a user must have the appropriate system privilege according to the specific implementation." }, { "code": null, "e": 95458, "s": 95413, "text": "The basic CREATE VIEW syntax is as follows −" }, { "code": null, "e": 95548, "s": 95458, "text": "CREATE VIEW view_name AS\nSELECT column1, column2.....\nFROM table_name\nWHERE [condition];\n" }, { "code": null, "e": 95668, "s": 95548, "text": "You can include multiple tables in your SELECT statement in a similar way as you use them in a normal SQL SELECT query." }, { "code": null, "e": 95728, "s": 95668, "text": "Consider the CUSTOMERS table having the following records −" }, { "code": null, "e": 96245, "s": 95728, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+" }, { "code": null, "e": 96392, "s": 96245, "text": "Following is an example to create a view from the CUSTOMERS table. This view would be used to have customer name and age from the CUSTOMERS table." }, { "code": null, "e": 96462, "s": 96392, "text": "SQL > CREATE VIEW CUSTOMERS_VIEW AS\nSELECT name, age\nFROM CUSTOMERS;" }, { "code": null, "e": 96581, "s": 96462, "text": "Now, you can query CUSTOMERS_VIEW in a similar way as you query an actual table. Following is an example for the same." }, { "code": null, "e": 96617, "s": 96581, "text": "SQL > SELECT * FROM CUSTOMERS_VIEW;" }, { "code": null, "e": 96658, "s": 96617, "text": "This would produce the following result." }, { "code": null, "e": 96868, "s": 96658, "text": "+----------+-----+\n| name | age |\n+----------+-----+\n| Ramesh | 32 |\n| Khilan | 25 |\n| kaushik | 23 |\n| Chaitali | 25 |\n| Hardik | 27 |\n| Komal | 22 |\n| Muffy | 24 |\n+----------+-----+\n" }, { "code": null, "e": 97052, "s": 96868, "text": "The WITH CHECK OPTION is a CREATE VIEW statement option. The purpose of the WITH CHECK OPTION is to ensure that all UPDATE and INSERTs satisfy the condition(s) in the view definition." }, { "code": null, "e": 97132, "s": 97052, "text": "If they do not satisfy the condition(s), the UPDATE or INSERT returns an error." }, { "code": null, "e": 97237, "s": 97132, "text": "The following code block has an example of creating same view CUSTOMERS_VIEW with the WITH CHECK OPTION." }, { "code": null, "e": 97341, "s": 97237, "text": "CREATE VIEW CUSTOMERS_VIEW AS\nSELECT name, age\nFROM CUSTOMERS\nWHERE age IS NOT NULL\nWITH CHECK OPTION;" }, { "code": null, "e": 97530, "s": 97341, "text": "The WITH CHECK OPTION in this case should deny the entry of any NULL values in the view's AGE column, because the view is defined by data that does not have a NULL value in the AGE column." }, { "code": null, "e": 97601, "s": 97530, "text": "A view can be updated under certain conditions which are given below −" }, { "code": null, "e": 97657, "s": 97601, "text": "The SELECT clause may not contain the keyword DISTINCT." }, { "code": null, "e": 97713, "s": 97657, "text": "The SELECT clause may not contain the keyword DISTINCT." }, { "code": null, "e": 97766, "s": 97713, "text": "The SELECT clause may not contain summary functions." }, { "code": null, "e": 97819, "s": 97766, "text": "The SELECT clause may not contain summary functions." }, { "code": null, "e": 97868, "s": 97819, "text": "The SELECT clause may not contain set functions." }, { "code": null, "e": 97917, "s": 97868, "text": "The SELECT clause may not contain set functions." }, { "code": null, "e": 97966, "s": 97917, "text": "The SELECT clause may not contain set operators." }, { "code": null, "e": 98015, "s": 97966, "text": "The SELECT clause may not contain set operators." }, { "code": null, "e": 98069, "s": 98015, "text": "The SELECT clause may not contain an ORDER BY clause." }, { "code": null, "e": 98123, "s": 98069, "text": "The SELECT clause may not contain an ORDER BY clause." }, { "code": null, "e": 98172, "s": 98123, "text": "The FROM clause may not contain multiple tables." }, { "code": null, "e": 98221, "s": 98172, "text": "The FROM clause may not contain multiple tables." }, { "code": null, "e": 98266, "s": 98221, "text": "The WHERE clause may not contain subqueries." }, { "code": null, "e": 98311, "s": 98266, "text": "The WHERE clause may not contain subqueries." }, { "code": null, "e": 98357, "s": 98311, "text": "The query may not contain GROUP BY or HAVING." }, { "code": null, "e": 98403, "s": 98357, "text": "The query may not contain GROUP BY or HAVING." }, { "code": null, "e": 98442, "s": 98403, "text": "Calculated columns may not be updated." }, { "code": null, "e": 98481, "s": 98442, "text": "Calculated columns may not be updated." }, { "code": null, "e": 98594, "s": 98481, "text": "All NOT NULL columns from the base table must be included in the view in order for the INSERT query to function." }, { "code": null, "e": 98707, "s": 98594, "text": "All NOT NULL columns from the base table must be included in the view in order for the INSERT query to function." }, { "code": null, "e": 98861, "s": 98707, "text": "So, if a view satisfies all the above-mentioned rules then you can update that view. The following code block has an example to update the age of Ramesh." }, { "code": null, "e": 98931, "s": 98861, "text": "SQL > UPDATE CUSTOMERS_VIEW\n SET AGE = 35\n WHERE name = 'Ramesh';" }, { "code": null, "e": 99126, "s": 98931, "text": "This would ultimately update the base table CUSTOMERS and the same would reflect in the view itself. Now, try to query the base table and the SELECT statement would produce the following result." }, { "code": null, "e": 99644, "s": 99126, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+\n" }, { "code": null, "e": 99768, "s": 99644, "text": "Rows of data can be inserted into a view. The same rules that apply to the UPDATE command also apply to the INSERT command." }, { "code": null, "e": 99974, "s": 99768, "text": "Here, we cannot insert rows in the CUSTOMERS_VIEW because we have not included all the NOT NULL columns in this view, otherwise you can insert rows in a view in a similar way as you insert them in a table." }, { "code": null, "e": 100104, "s": 99974, "text": "Rows of data can be deleted from a view. The same rules that apply to the UPDATE and INSERT commands apply to the DELETE command." }, { "code": null, "e": 100164, "s": 100104, "text": "Following is an example to delete a record having AGE = 22." }, { "code": null, "e": 100216, "s": 100164, "text": "SQL > DELETE FROM CUSTOMERS_VIEW\n WHERE age = 22;" }, { "code": null, "e": 100422, "s": 100216, "text": "This would ultimately delete a row from the base table CUSTOMERS and the same would reflect in the view itself. Now, try to query the base table and the SELECT statement would produce the following result." }, { "code": null, "e": 100893, "s": 100422, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+\n" }, { "code": null, "e": 101033, "s": 100893, "text": "Obviously, where you have a view, you need a way to drop the view if it is no longer needed. The syntax is very simple and is given below −" }, { "code": null, "e": 101055, "s": 101033, "text": "DROP VIEW view_name;\n" }, { "code": null, "e": 101132, "s": 101055, "text": "Following is an example to drop the CUSTOMERS_VIEW from the CUSTOMERS table." }, { "code": null, "e": 101158, "s": 101132, "text": "DROP VIEW CUSTOMERS_VIEW;" }, { "code": null, "e": 101265, "s": 101158, "text": "The HAVING Clause enables you to specify conditions that filter which group results appear in the results." }, { "code": null, "e": 101411, "s": 101265, "text": "The WHERE clause places conditions on the selected columns, whereas the HAVING clause places conditions on groups created by the GROUP BY clause." }, { "code": null, "e": 101488, "s": 101411, "text": "The following code block shows the position of the HAVING Clause in a query." }, { "code": null, "e": 101532, "s": 101488, "text": "SELECT\nFROM\nWHERE\nGROUP BY\nHAVING\nORDER BY\n" }, { "code": null, "e": 101738, "s": 101532, "text": "The HAVING clause must follow the GROUP BY clause in a query and must also precede the ORDER BY clause if used. The following code block has the syntax of the SELECT statement including the HAVING clause −" }, { "code": null, "e": 101878, "s": 101738, "text": "SELECT column1, column2\nFROM table1, table2\nWHERE [ conditions ]\nGROUP BY column1, column2\nHAVING [ conditions ]\nORDER BY column1, column2\n" }, { "code": null, "e": 101937, "s": 101878, "text": "Consider the CUSTOMERS table having the following records." }, { "code": null, "e": 102454, "s": 101937, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+" }, { "code": null, "e": 102571, "s": 102454, "text": "Following is an example, which would display a record for a similar age count that would be more than or equal to 2." }, { "code": null, "e": 102667, "s": 102571, "text": "SQL > SELECT ID, NAME, AGE, ADDRESS, SALARY\nFROM CUSTOMERS\nGROUP BY age\nHAVING COUNT(age) >= 2;" }, { "code": null, "e": 102709, "s": 102667, "text": "This would produce the following result −" }, { "code": null, "e": 102920, "s": 102709, "text": "+----+--------+-----+---------+---------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+--------+-----+---------+---------+\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n+----+--------+-----+---------+---------+\n" }, { "code": null, "e": 103158, "s": 102920, "text": "A transaction is a unit of work that is performed against a database. Transactions are units or sequences of work accomplished in a logical order, whether in a manual fashion by a user or automatically by some sort of a database program." }, { "code": null, "e": 103490, "s": 103158, "text": "A transaction is the propagation of one or more changes to the database. For example, if you are creating a record or updating a record or deleting a record from the table, then you are performing a transaction on that table. It is important to control these transactions to ensure the data integrity and to handle database errors." }, { "code": null, "e": 103617, "s": 103490, "text": "Practically, you will club many SQL queries into a group and you will execute all of them together as a part of a transaction." }, { "code": null, "e": 103716, "s": 103617, "text": "Transactions have the following four standard properties, usually referred to by the acronym ACID." }, { "code": null, "e": 103938, "s": 103716, "text": "Atomicity − ensures that all operations within the work unit are completed successfully. Otherwise, the transaction is aborted at the point of failure and all the previous operations are rolled back to their former state." }, { "code": null, "e": 104160, "s": 103938, "text": "Atomicity − ensures that all operations within the work unit are completed successfully. Otherwise, the transaction is aborted at the point of failure and all the previous operations are rolled back to their former state." }, { "code": null, "e": 104267, "s": 104160, "text": "Consistency − ensures that the database properly changes states upon a successfully committed transaction." }, { "code": null, "e": 104374, "s": 104267, "text": "Consistency − ensures that the database properly changes states upon a successfully committed transaction." }, { "code": null, "e": 104466, "s": 104374, "text": "Isolation − enables transactions to operate independently of and transparent to each other." }, { "code": null, "e": 104558, "s": 104466, "text": "Isolation − enables transactions to operate independently of and transparent to each other." }, { "code": null, "e": 104670, "s": 104558, "text": "Durability − ensures that the result or effect of a committed transaction persists in case of a system failure." }, { "code": null, "e": 104782, "s": 104670, "text": "Durability − ensures that the result or effect of a committed transaction persists in case of a system failure." }, { "code": null, "e": 104839, "s": 104782, "text": "The following commands are used to control transactions." }, { "code": null, "e": 104869, "s": 104839, "text": "COMMIT − to save the changes." }, { "code": null, "e": 104899, "s": 104869, "text": "COMMIT − to save the changes." }, { "code": null, "e": 104936, "s": 104899, "text": "ROLLBACK − to roll back the changes." }, { "code": null, "e": 104973, "s": 104936, "text": "ROLLBACK − to roll back the changes." }, { "code": null, "e": 105056, "s": 104973, "text": "SAVEPOINT − creates points within the groups of transactions in which to ROLLBACK." }, { "code": null, "e": 105139, "s": 105056, "text": "SAVEPOINT − creates points within the groups of transactions in which to ROLLBACK." }, { "code": null, "e": 105189, "s": 105139, "text": "SET TRANSACTION − Places a name on a transaction." }, { "code": null, "e": 105239, "s": 105189, "text": "SET TRANSACTION − Places a name on a transaction." }, { "code": null, "e": 105477, "s": 105239, "text": "Transactional control commands are only used with the DML Commands such as - INSERT, UPDATE and DELETE only. They cannot be used while creating tables or dropping them because these operations are automatically committed in the database." }, { "code": null, "e": 105588, "s": 105477, "text": "The COMMIT command is the transactional command used to save changes invoked by a transaction to the database." }, { "code": null, "e": 105804, "s": 105588, "text": "The COMMIT command is the transactional command used to save changes invoked by a transaction to the database. The COMMIT command saves all the transactions to the database since the last COMMIT or ROLLBACK command." }, { "code": null, "e": 105853, "s": 105804, "text": "The syntax for the COMMIT command is as follows." }, { "code": null, "e": 105862, "s": 105853, "text": "COMMIT;\n" }, { "code": null, "e": 105870, "s": 105862, "text": "Example" }, { "code": null, "e": 105930, "s": 105870, "text": "Consider the CUSTOMERS table having the following records −" }, { "code": null, "e": 106447, "s": 105930, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+" }, { "code": null, "e": 106584, "s": 106447, "text": "Following is an example which would delete those records from the table which have age = 25 and then COMMIT the changes in the database." }, { "code": null, "e": 106643, "s": 106584, "text": "SQL> DELETE FROM CUSTOMERS\n WHERE AGE = 25;\nSQL> COMMIT;" }, { "code": null, "e": 106751, "s": 106643, "text": "Thus, two rows from the table would be deleted and the SELECT statement would produce the following result." }, { "code": null, "e": 107175, "s": 106751, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+\n" }, { "code": null, "e": 107406, "s": 107175, "text": "The ROLLBACK command is the transactional command used to undo transactions that have not already been saved to the database. This command can only be used to undo transactions since the last COMMIT or ROLLBACK command was issued." }, { "code": null, "e": 107456, "s": 107406, "text": "The syntax for a ROLLBACK command is as follows −" }, { "code": null, "e": 107467, "s": 107456, "text": "ROLLBACK;\n" }, { "code": null, "e": 107475, "s": 107467, "text": "Example" }, { "code": null, "e": 107535, "s": 107475, "text": "Consider the CUSTOMERS table having the following records −" }, { "code": null, "e": 108052, "s": 107535, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+" }, { "code": null, "e": 108196, "s": 108052, "text": "Following is an example, which would delete those records from the table which have the age = 25 and then ROLLBACK the changes in the database." }, { "code": null, "e": 108257, "s": 108196, "text": "SQL> DELETE FROM CUSTOMERS\n WHERE AGE = 25;\nSQL> ROLLBACK;" }, { "code": null, "e": 108372, "s": 108257, "text": "Thus, the delete operation would not impact the table and the SELECT statement would produce the following result." }, { "code": null, "e": 108890, "s": 108372, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+\n" }, { "code": null, "e": 109033, "s": 108890, "text": "A SAVEPOINT is a point in a transaction when you can roll the transaction back to a certain point without rolling back the entire transaction." }, { "code": null, "e": 109087, "s": 109033, "text": "The syntax for a SAVEPOINT command is as shown below." }, { "code": null, "e": 109114, "s": 109087, "text": "SAVEPOINT SAVEPOINT_NAME;\n" }, { "code": null, "e": 109272, "s": 109114, "text": "This command serves only in the creation of a SAVEPOINT among all the transactional statements. The ROLLBACK command is used to undo a group of transactions." }, { "code": null, "e": 109334, "s": 109272, "text": "The syntax for rolling back to a SAVEPOINT is as shown below." }, { "code": null, "e": 109363, "s": 109334, "text": "ROLLBACK TO SAVEPOINT_NAME;\n" }, { "code": null, "e": 109625, "s": 109363, "text": "Following is an example where you plan to delete the three different records from the CUSTOMERS table. You want to create a SAVEPOINT before each delete, so that you can ROLLBACK to any SAVEPOINT at any time to return the appropriate data to its original state." }, { "code": null, "e": 109633, "s": 109625, "text": "Example" }, { "code": null, "e": 109692, "s": 109633, "text": "Consider the CUSTOMERS table having the following records." }, { "code": null, "e": 110209, "s": 109692, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+" }, { "code": null, "e": 110269, "s": 110209, "text": "The following code block contains the series of operations." }, { "code": null, "e": 110548, "s": 110269, "text": "SQL> SAVEPOINT SP1;\nSavepoint created.\nSQL> DELETE FROM CUSTOMERS WHERE ID=1;\n1 row deleted.\nSQL> SAVEPOINT SP2;\nSavepoint created.\nSQL> DELETE FROM CUSTOMERS WHERE ID=2;\n1 row deleted.\nSQL> SAVEPOINT SP3;\nSavepoint created.\nSQL> DELETE FROM CUSTOMERS WHERE ID=3;\n1 row deleted." }, { "code": null, "e": 110796, "s": 110548, "text": "Now that the three deletions have taken place, let us assume that you have changed your mind and decided to ROLLBACK to the SAVEPOINT that you identified as SP2. Because SP2 was created after the first deletion, the last two deletions are undone −" }, { "code": null, "e": 110837, "s": 110796, "text": "SQL> ROLLBACK TO SP2;\nRollback complete." }, { "code": null, "e": 110914, "s": 110837, "text": "Notice that only the first deletion took place since you rolled back to SP2." }, { "code": null, "e": 111431, "s": 110914, "text": "SQL> SELECT * FROM CUSTOMERS;\n+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+\n6 rows selected." }, { "code": null, "e": 111514, "s": 111431, "text": "The RELEASE SAVEPOINT command is used to remove a SAVEPOINT that you have created." }, { "code": null, "e": 111572, "s": 111514, "text": "The syntax for a RELEASE SAVEPOINT command is as follows." }, { "code": null, "e": 111607, "s": 111572, "text": "RELEASE SAVEPOINT SAVEPOINT_NAME;\n" }, { "code": null, "e": 111743, "s": 111607, "text": "Once a SAVEPOINT has been released, you can no longer use the ROLLBACK command to undo transactions performed since the last SAVEPOINT." }, { "code": null, "e": 111975, "s": 111743, "text": "The SET TRANSACTION command can be used to initiate a database transaction. This command is used to specify characteristics for the transaction that follows. For example, you can specify a transaction to be read only or read write." }, { "code": null, "e": 112031, "s": 111975, "text": "The syntax for a SET TRANSACTION command is as follows." }, { "code": null, "e": 112076, "s": 112031, "text": "SET TRANSACTION [ READ WRITE | READ ONLY ];\n" }, { "code": null, "e": 112212, "s": 112076, "text": "We have already discussed about the SQL LIKE operator, which is used to compare a value to similar values using the wildcard operators." }, { "code": null, "e": 112340, "s": 112212, "text": "SQL supports two wildcard operators in conjunction with the LIKE operator which are explained in detail in the following table." }, { "code": null, "e": 112361, "s": 112340, "text": "The percent sign (%)" }, { "code": null, "e": 112393, "s": 112361, "text": "Matches one or more characters." }, { "code": null, "e": 112503, "s": 112393, "text": "Note − MS Access uses the asterisk (*) wildcard character instead of the percent sign (%) wildcard character." }, { "code": null, "e": 112522, "s": 112503, "text": "The underscore (_)" }, { "code": null, "e": 112545, "s": 112522, "text": "Matches one character." }, { "code": null, "e": 112645, "s": 112545, "text": "Note − MS Access uses a question mark (?) instead of the underscore (_) to match any one character." }, { "code": null, "e": 112808, "s": 112645, "text": "The percent sign represents zero, one or multiple characters. The underscore represents a single number or a character. These symbols can be used in combinations." }, { "code": null, "e": 112868, "s": 112808, "text": "The basic syntax of a '%' and a '_' operator is as follows." }, { "code": null, "e": 113147, "s": 112868, "text": "SELECT * FROM table_name\nWHERE column LIKE 'XXXX%'\n\nor \n\nSELECT * FROM table_name\nWHERE column LIKE '%XXXX%'\n\nor\n\nSELECT * FROM table_name\nWHERE column LIKE 'XXXX_'\n\nor\n\nSELECT * FROM table_name\nWHERE column LIKE '_XXXX'\n\nor\n\nSELECT * FROM table_name\nWHERE column LIKE '_XXXX_'\n" }, { "code": null, "e": 113270, "s": 113147, "text": "You can combine N number of conditions using the AND or the OR operators. Here, XXXX could be any numeric or string value." }, { "code": null, "e": 113396, "s": 113270, "text": "The following table has a number of examples showing the WHERE part having different LIKE clauses with '%' and '_' operators." }, { "code": null, "e": 113421, "s": 113396, "text": "WHERE SALARY LIKE '200%'" }, { "code": null, "e": 113459, "s": 113421, "text": "Finds any values that start with 200." }, { "code": null, "e": 113485, "s": 113459, "text": "WHERE SALARY LIKE '%200%'" }, { "code": null, "e": 113533, "s": 113485, "text": "Finds any values that have 200 in any position." }, { "code": null, "e": 113558, "s": 113533, "text": "WHERE SALARY LIKE '_00%'" }, { "code": null, "e": 113623, "s": 113558, "text": "Finds any values that have 00 in the second and third positions." }, { "code": null, "e": 113649, "s": 113623, "text": "WHERE SALARY LIKE '2_%_%'" }, { "code": null, "e": 113725, "s": 113649, "text": "Finds any values that start with 2 and are at least 3 characters in length." }, { "code": null, "e": 113748, "s": 113725, "text": "WHERE SALARY LIKE '%2'" }, { "code": null, "e": 113782, "s": 113748, "text": "Finds any values that end with 2." }, { "code": null, "e": 113807, "s": 113782, "text": "WHERE SALARY LIKE '_2%3'" }, { "code": null, "e": 113879, "s": 113807, "text": "Finds any values that have a 2 in the second position and end with a 3." }, { "code": null, "e": 113905, "s": 113879, "text": "WHERE SALARY LIKE '2___3'" }, { "code": null, "e": 113979, "s": 113905, "text": "Finds any values in a five-digit number that start with 2 and end with 3." }, { "code": null, "e": 114066, "s": 113979, "text": "Let us take a real example, consider the CUSTOMERS table having the following records." }, { "code": null, "e": 114583, "s": 114066, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+" }, { "code": null, "e": 114718, "s": 114583, "text": "The following code block is an example, which would display all the records from the CUSTOMERS table where the SALARY starts with 200." }, { "code": null, "e": 114773, "s": 114718, "text": "SQL> SELECT * FROM CUSTOMERS\nWHERE SALARY LIKE '200%';" }, { "code": null, "e": 114814, "s": 114773, "text": "This would produce the following result." }, { "code": null, "e": 115097, "s": 114814, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n+----+----------+-----+-----------+----------+\n" }, { "code": null, "e": 115303, "s": 115097, "text": "The following table has a list of all the important Date and Time related functions available through SQL. There are various other functions supported by your RDBMS. The given list is based on MySQL RDBMS." }, { "code": null, "e": 115314, "s": 115303, "text": "Adds dates" }, { "code": null, "e": 115324, "s": 115314, "text": "Adds time" }, { "code": null, "e": 115362, "s": 115324, "text": "Converts from one timezone to another" }, { "code": null, "e": 115387, "s": 115362, "text": "Returns the current date" }, { "code": null, "e": 115410, "s": 115387, "text": "Synonyms for CURDATE()" }, { "code": null, "e": 115433, "s": 115410, "text": "Synonyms for CURTIME()" }, { "code": null, "e": 115452, "s": 115433, "text": "Synonyms for NOW()" }, { "code": null, "e": 115477, "s": 115452, "text": "Returns the current time" }, { "code": null, "e": 115492, "s": 115477, "text": "Adds two dates" }, { "code": null, "e": 115518, "s": 115492, "text": "Formats date as specified" }, { "code": null, "e": 115538, "s": 115518, "text": "Subtracts two dates" }, { "code": null, "e": 115594, "s": 115538, "text": "Extracts the date part of a date or datetime expression" }, { "code": null, "e": 115614, "s": 115594, "text": "Subtracts two dates" }, { "code": null, "e": 115639, "s": 115614, "text": "Synonym for DAYOFMONTH()" }, { "code": null, "e": 115671, "s": 115639, "text": "Returns the name of the weekday" }, { "code": null, "e": 115707, "s": 115671, "text": "Returns the day of the month (1-31)" }, { "code": null, "e": 115749, "s": 115707, "text": "Returns the weekday index of the argument" }, { "code": null, "e": 115785, "s": 115749, "text": "Returns the day of the year (1-366)" }, { "code": null, "e": 115809, "s": 115785, "text": "Extracts part of a date" }, { "code": null, "e": 115841, "s": 115809, "text": "Converts a day number to a date" }, { "code": null, "e": 115874, "s": 115841, "text": "Formats date as a UNIX timestamp" }, { "code": null, "e": 115892, "s": 115874, "text": "Extracts the hour" }, { "code": null, "e": 115943, "s": 115892, "text": "Returns the last day of the month for the argument" }, { "code": null, "e": 115961, "s": 115943, "text": "Synonym for NOW()" }, { "code": null, "e": 115979, "s": 115961, "text": "Synonym for NOW()" }, { "code": null, "e": 116024, "s": 115979, "text": "Creates a date from the year and day of year" }, { "code": null, "e": 116035, "s": 116024, "text": "MAKETIME()" }, { "code": null, "e": 116074, "s": 116035, "text": "Returns the microseconds from argument" }, { "code": null, "e": 116111, "s": 116074, "text": "Returns the minute from the argument" }, { "code": null, "e": 116149, "s": 116111, "text": "Return the month from the date passed" }, { "code": null, "e": 116179, "s": 116149, "text": "Returns the name of the month" }, { "code": null, "e": 116213, "s": 116179, "text": "Returns the current date and time" }, { "code": null, "e": 116243, "s": 116213, "text": "Adds a period to a year-month" }, { "code": null, "e": 116288, "s": 116243, "text": "Returns the number of months between periods" }, { "code": null, "e": 116329, "s": 116288, "text": "Returns the quarter from a date argument" }, { "code": null, "e": 116367, "s": 116329, "text": "Converts seconds to 'HH:MM:SS' format" }, { "code": null, "e": 116393, "s": 116367, "text": "Returns the second (0-59)" }, { "code": null, "e": 116421, "s": 116393, "text": "Converts a string to a date" }, { "code": null, "e": 116480, "s": 116421, "text": "When invoked with three arguments a synonym for DATE_SUB()" }, { "code": null, "e": 116496, "s": 116480, "text": "Subtracts times" }, { "code": null, "e": 116544, "s": 116496, "text": "Returns the time at which the function executes" }, { "code": null, "e": 116560, "s": 116544, "text": "Formats as time" }, { "code": null, "e": 116602, "s": 116560, "text": "Returns the argument converted to seconds" }, { "code": null, "e": 116653, "s": 116602, "text": "Extracts the time portion of the expression passed" }, { "code": null, "e": 116668, "s": 116653, "text": "Subtracts time" }, { "code": null, "e": 116791, "s": 116668, "text": "With a single argument this function returns the date or datetime expression. With two arguments, the sum of the arguments" }, { "code": null, "e": 116833, "s": 116791, "text": "Adds an interval to a datetime expression" }, { "code": null, "e": 116882, "s": 116833, "text": "Subtracts an interval from a datetime expression" }, { "code": null, "e": 116926, "s": 116882, "text": "Returns the date argument converted to days" }, { "code": null, "e": 116951, "s": 116926, "text": "Returns a UNIX timestamp" }, { "code": null, "e": 116980, "s": 116951, "text": "Returns the current UTC date" }, { "code": null, "e": 117009, "s": 116980, "text": "Returns the current UTC time" }, { "code": null, "e": 117047, "s": 117009, "text": "Returns the current UTC date and time" }, { "code": null, "e": 117071, "s": 117047, "text": "Returns the week number" }, { "code": null, "e": 117097, "s": 117071, "text": "Returns the weekday index" }, { "code": null, "e": 117142, "s": 117097, "text": "Returns the calendar week of the date (1-53)" }, { "code": null, "e": 117159, "s": 117142, "text": "Returns the year" }, { "code": null, "e": 117185, "s": 117159, "text": "Returns the year and week" }, { "code": null, "e": 117426, "s": 117185, "text": "When invoked with the INTERVAL form of the second argument, ADDDATE() is a synonym for DATE_ADD(). The related function SUBDATE() is a synonym for DATE_SUB(). For information on the INTERVAL unit argument, see the discussion for DATE_ADD()." }, { "code": null, "e": 118184, "s": 117426, "text": "mysql> SELECT DATE_ADD('1998-01-02', INTERVAL 31 DAY);\n+---------------------------------------------------------+\n| DATE_ADD('1998-01-02', INTERVAL 31 DAY) |\n+---------------------------------------------------------+\n| 1998-02-02 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)\n\nmysql> SELECT ADDDATE('1998-01-02', INTERVAL 31 DAY);\n+---------------------------------------------------------+\n| ADDDATE('1998-01-02', INTERVAL 31 DAY) |\n+---------------------------------------------------------+\n| 1998-02-02 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 118306, "s": 118184, "text": "When invoked with the days form of the second argument, MySQL treats it as an integer number of days to be added to expr." }, { "code": null, "e": 118671, "s": 118306, "text": "mysql> SELECT ADDDATE('1998-01-02', 31);\n+---------------------------------------------------------+\n| DATE_ADD('1998-01-02', INTERVAL 31 DAY) |\n+---------------------------------------------------------+\n| 1998-02-02 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 118807, "s": 118671, "text": "ADDTIME() adds expr2 to expr1 and returns the result. The expr1 is a time or datetime expression, while the expr2 is a time expression." }, { "code": null, "e": 119201, "s": 118807, "text": "mysql> SELECT ADDTIME('1997-12-31 23:59:59.999999','1 1:1:1.000002');\n+---------------------------------------------------------+\n| DATE_ADD('1997-12-31 23:59:59.999999','1 1:1:1.000002') |\n+---------------------------------------------------------+\n| 1998-01-02 01:01:01.000001 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 119393, "s": 119201, "text": "This converts a datetime value dt from the time zone given by from_tz to the time zone given by to_tz and returns the resulting value. This function returns NULL if the arguments are invalid." }, { "code": null, "e": 120170, "s": 119393, "text": "mysql> SELECT CONVERT_TZ('2004-01-01 12:00:00','GMT','MET');\n+---------------------------------------------------------+\n| CONVERT_TZ('2004-01-01 12:00:00','GMT','MET') |\n+---------------------------------------------------------+\n| 2004-01-01 13:00:00 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)\n\nmysql> SELECT CONVERT_TZ('2004-01-01 12:00:00','+00:00','+10:00');\n+---------------------------------------------------------+\n| CONVERT_TZ('2004-01-01 12:00:00','+00:00','+10:00') |\n+---------------------------------------------------------+\n| 2004-01-01 22:00:00 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 120321, "s": 120170, "text": "Returns the current date as a value in 'YYYY-MM-DD' or YYYYMMDD format, depending on whether the function is used in a string or in a numeric context." }, { "code": null, "e": 121024, "s": 120321, "text": "mysql> SELECT CURDATE();\n+---------------------------------------------------------+\n| CURDATE() |\n+---------------------------------------------------------+\n| 1997-12-15 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)\n\nmysql> SELECT CURDATE() + 0;\n+---------------------------------------------------------+\n| CURDATE() + 0 |\n+---------------------------------------------------------+\n| 19971215 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 121083, "s": 121024, "text": "CURRENT_DATE and CURRENT_DATE() are synonyms for CURDATE()" }, { "code": null, "e": 121279, "s": 121083, "text": "Returns the current time as a value in 'HH:MM:SS' or HHMMSS format, depending on whether the function is used in a string or in a numeric context. The value is expressed in the current time zone." }, { "code": null, "e": 121982, "s": 121279, "text": "mysql> SELECT CURTIME();\n+---------------------------------------------------------+\n| CURTIME() |\n+---------------------------------------------------------+\n| 23:50:26 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)\n\nmysql> SELECT CURTIME() + 0;\n+---------------------------------------------------------+\n| CURTIME() + 0 |\n+---------------------------------------------------------+\n| 235026 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 122042, "s": 121982, "text": "CURRENT_TIME and CURRENT_TIME() are synonyms for CURTIME()." }, { "code": null, "e": 122108, "s": 122042, "text": "CURRENT_TIMESTAMP and CURRENT_TIMESTAMP() are synonyms for NOW()." }, { "code": null, "e": 122172, "s": 122108, "text": "Extracts the date part of the date or datetime expression expr." }, { "code": null, "e": 122539, "s": 122172, "text": "mysql> SELECT DATE('2003-12-31 01:02:03');\n+---------------------------------------------------------+\n| DATE('2003-12-31 01:02:03') |\n+---------------------------------------------------------+\n| 2003-12-31 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 122752, "s": 122539, "text": "DATEDIFF() returns expr1 . expr2 expressed as a value in days from one date to the other. Both expr1 and expr2 are date or date-and-time expressions. Only the date parts of the values are used in the calculation." }, { "code": null, "e": 123136, "s": 122752, "text": "mysql> SELECT DATEDIFF('1997-12-31 23:59:59','1997-12-30');\n+---------------------------------------------------------+\n| DATEDIFF('1997-12-31 23:59:59','1997-12-30') |\n+---------------------------------------------------------+\n| 1 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 123420, "s": 123136, "text": "These functions perform date arithmetic. The date is a DATETIME or DATE value specifying the starting date. The expr is an expression specifying the interval value to be added or subtracted from the starting date. The expr is a string; it may start with a '-' for negative intervals." }, { "code": null, "e": 123508, "s": 123420, "text": "A unit is a keyword indicating the units in which the expression should be interpreted." }, { "code": null, "e": 123576, "s": 123508, "text": "The INTERVAL keyword and the unit specifier are not case sensitive." }, { "code": null, "e": 123662, "s": 123576, "text": "The following table shows the expected form of the expr argument for each unit value." }, { "code": null, "e": 123735, "s": 123662, "text": "The values QUARTER and WEEK are available from the MySQL 5.0.0. version." }, { "code": null, "e": 124523, "s": 123735, "text": "mysql> SELECT DATE_ADD('1997-12-31 23:59:59', \n -> INTERVAL '1:1' MINUTE_SECOND);\n+---------------------------------------------------------+\n| DATE_ADD('1997-12-31 23:59:59', INTERVAL... |\n+---------------------------------------------------------+\n| 1998-01-01 00:01:00 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)\n\nmysql> SELECT DATE_ADD('1999-01-01', INTERVAL 1 HOUR);\n+---------------------------------------------------------+\n| DATE_ADD('1999-01-01', INTERVAL 1 HOUR) |\n+---------------------------------------------------------+\n| 1999-01-01 01:00:00 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 124585, "s": 124523, "text": "This command formats the date value as per the format string." }, { "code": null, "e": 124714, "s": 124585, "text": "The following specifiers may be used in the format string. The '%' character is required before the format specifier characters." }, { "code": null, "e": 124717, "s": 124714, "text": "%a" }, { "code": null, "e": 124753, "s": 124717, "text": "Abbreviated weekday name (Sun..Sat)" }, { "code": null, "e": 124756, "s": 124753, "text": "%b" }, { "code": null, "e": 124790, "s": 124756, "text": "Abbreviated month name (Jan..Dec)" }, { "code": null, "e": 124793, "s": 124790, "text": "%c" }, { "code": null, "e": 124816, "s": 124793, "text": "Month, numeric (0..12)" }, { "code": null, "e": 124819, "s": 124816, "text": "%D" }, { "code": null, "e": 124880, "s": 124819, "text": "Day of the month with English suffix (0th, 1st, 2nd, 3rd, .)" }, { "code": null, "e": 124883, "s": 124880, "text": "%d" }, { "code": null, "e": 124918, "s": 124883, "text": "Day of the month, numeric (00..31)" }, { "code": null, "e": 124921, "s": 124918, "text": "%e" }, { "code": null, "e": 124955, "s": 124921, "text": "Day of the month, numeric (0..31)" }, { "code": null, "e": 124958, "s": 124955, "text": "%f" }, { "code": null, "e": 124988, "s": 124958, "text": "Microseconds (000000..999999)" }, { "code": null, "e": 124991, "s": 124988, "text": "%H" }, { "code": null, "e": 125005, "s": 124991, "text": "Hour (00..23)" }, { "code": null, "e": 125008, "s": 125005, "text": "%h" }, { "code": null, "e": 125022, "s": 125008, "text": "Hour (01..12)" }, { "code": null, "e": 125025, "s": 125022, "text": "%I" }, { "code": null, "e": 125039, "s": 125025, "text": "Hour (01..12)" }, { "code": null, "e": 125042, "s": 125039, "text": "%i" }, { "code": null, "e": 125068, "s": 125042, "text": "Minutes, numeric (00..59)" }, { "code": null, "e": 125071, "s": 125068, "text": "%j" }, { "code": null, "e": 125094, "s": 125071, "text": "Day of year (001..366)" }, { "code": null, "e": 125097, "s": 125094, "text": "%k" }, { "code": null, "e": 125110, "s": 125097, "text": "Hour (0..23)" }, { "code": null, "e": 125113, "s": 125110, "text": "%l" }, { "code": null, "e": 125126, "s": 125113, "text": "Hour (1..12)" }, { "code": null, "e": 125129, "s": 125126, "text": "%M" }, { "code": null, "e": 125160, "s": 125129, "text": "Month name (January..December)" }, { "code": null, "e": 125163, "s": 125160, "text": "%m" }, { "code": null, "e": 125187, "s": 125163, "text": "Month, numeric (00..12)" }, { "code": null, "e": 125190, "s": 125187, "text": "%p" }, { "code": null, "e": 125199, "s": 125190, "text": "AM or PM" }, { "code": null, "e": 125202, "s": 125199, "text": "%r" }, { "code": null, "e": 125249, "s": 125202, "text": "Time, 12-hour (hh:mm:ss followed by AM or PM)" }, { "code": null, "e": 125252, "s": 125249, "text": "%S" }, { "code": null, "e": 125269, "s": 125252, "text": "Seconds (00..59)" }, { "code": null, "e": 125272, "s": 125269, "text": "%s" }, { "code": null, "e": 125289, "s": 125272, "text": "Seconds (00..59)" }, { "code": null, "e": 125292, "s": 125289, "text": "%T" }, { "code": null, "e": 125317, "s": 125292, "text": "Time, 24-hour (hh:mm:ss)" }, { "code": null, "e": 125320, "s": 125317, "text": "%U" }, { "code": null, "e": 125377, "s": 125320, "text": "Week (00..53), where Sunday is the first day of the week" }, { "code": null, "e": 125380, "s": 125377, "text": "%u" }, { "code": null, "e": 125437, "s": 125380, "text": "Week (00..53), where Monday is the first day of the week" }, { "code": null, "e": 125440, "s": 125437, "text": "%V" }, { "code": null, "e": 125511, "s": 125440, "text": "Week (01..53), where Sunday is the first day of the week; used with %X" }, { "code": null, "e": 125514, "s": 125511, "text": "%v" }, { "code": null, "e": 125585, "s": 125514, "text": "Week (01..53), where Monday is the first day of the week; used with %x" }, { "code": null, "e": 125588, "s": 125585, "text": "%W" }, { "code": null, "e": 125620, "s": 125588, "text": "Weekday name (Sunday..Saturday)" }, { "code": null, "e": 125623, "s": 125620, "text": "%w" }, { "code": null, "e": 125662, "s": 125623, "text": "Day of the week (0=Sunday..6=Saturday)" }, { "code": null, "e": 125665, "s": 125662, "text": "%X" }, { "code": null, "e": 125762, "s": 125665, "text": "Year for the week where Sunday is the first day of the week, numeric, four digits; used with %V\n" }, { "code": null, "e": 125765, "s": 125762, "text": "%x" }, { "code": null, "e": 125863, "s": 125765, "text": "Year for the week, where Monday is the first day of the week, numeric, four digits; used with %v\n" }, { "code": null, "e": 125866, "s": 125863, "text": "%Y" }, { "code": null, "e": 125893, "s": 125866, "text": "Year, numeric, four digits" }, { "code": null, "e": 125896, "s": 125893, "text": "%y" }, { "code": null, "e": 125923, "s": 125896, "text": "Year, numeric (two digits)" }, { "code": null, "e": 125926, "s": 125923, "text": "%%" }, { "code": null, "e": 125950, "s": 125926, "text": "A literal .%. character" }, { "code": null, "e": 125953, "s": 125950, "text": "%x" }, { "code": null, "e": 125984, "s": 125953, "text": "x, for any.x. not listed above" }, { "code": null, "e": 126774, "s": 125984, "text": "mysql> SELECT DATE_FORMAT('1997-10-04 22:23:00', '%W %M %Y');\n+---------------------------------------------------------+\n| DATE_FORMAT('1997-10-04 22:23:00', '%W %M %Y') |\n+---------------------------------------------------------+\n| Saturday October 1997 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)\n\nmysql> SELECT DATE_FORMAT('1997-10-04 22:23:00'\n -> '%H %k %I %r %T %S %w');\n+---------------------------------------------------------+\n| DATE_FORMAT('1997-10-04 22:23:00....... |\n+---------------------------------------------------------+\n| 22 22 10 10:23:00 PM 22:23:00 00 6 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 126818, "s": 126774, "text": "This is similar to the DATE_ADD() function." }, { "code": null, "e": 126872, "s": 126818, "text": "The DAY() is a synonym for the DAYOFMONTH() function." }, { "code": null, "e": 126914, "s": 126872, "text": "Returns the name of the weekday for date." }, { "code": null, "e": 127275, "s": 126914, "text": "mysql> SELECT DAYNAME('1998-02-05');\n+---------------------------------------------------------+\n| DAYNAME('1998-02-05') |\n+---------------------------------------------------------+\n| Thursday |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 127336, "s": 127275, "text": "Returns the day of the month for date, in the range 0 to 31." }, { "code": null, "e": 127700, "s": 127336, "text": "mysql> SELECT DAYOFMONTH('1998-02-03');\n+---------------------------------------------------------+\n| DAYOFMONTH('1998-02-03') |\n+---------------------------------------------------------+\n| 3 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 127830, "s": 127700, "text": "Returns the weekday index for date (1 = Sunday, 2 = Monday, ., 7 = Saturday). These index values correspond to the ODBC standard." }, { "code": null, "e": 128193, "s": 127830, "text": "mysql> SELECT DAYOFWEEK('1998-02-03');\n+---------------------------------------------------------+\n|DAYOFWEEK('1998-02-03') |\n+---------------------------------------------------------+\n| 3 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 128254, "s": 128193, "text": "Returns the day of the year for date, in the range 1 to 366." }, { "code": null, "e": 128617, "s": 128254, "text": "mysql> SELECT DAYOFYEAR('1998-02-03');\n+---------------------------------------------------------+\n| DAYOFYEAR('1998-02-03') |\n+---------------------------------------------------------+\n| 34 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 128781, "s": 128617, "text": "The EXTRACT() function uses the same kinds of unit specifiers as DATE_ADD() or DATE_SUB(), but extracts parts from the date rather than performing date arithmetic." }, { "code": null, "e": 129539, "s": 128781, "text": "mysql> SELECT EXTRACT(YEAR FROM '1999-07-02');\n+---------------------------------------------------------+\n| EXTRACT(YEAR FROM '1999-07-02') |\n+---------------------------------------------------------+\n| 1999 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)\n\nmysql> SELECT EXTRACT(YEAR_MONTH FROM '1999-07-02 01:02:03');\n+---------------------------------------------------------+\n| EXTRACT(YEAR_MONTH FROM '1999-07-02 01:02:03') |\n+---------------------------------------------------------+\n| 199907 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 129583, "s": 129539, "text": "Given a day number N, returns a DATE value." }, { "code": null, "e": 129940, "s": 129583, "text": "mysql> SELECT FROM_DAYS(729669);\n+---------------------------------------------------------+\n| FROM_DAYS(729669) |\n+---------------------------------------------------------+\n| 1997-10-07 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 130087, "s": 129940, "text": "Note − Use FROM_DAYS() with caution on old dates. It is not intended for use with values that precede the advent of the Gregorian calendar (1582)." }, { "code": null, "e": 130446, "s": 130087, "text": "Returns a representation of the unix_timestamp argument as a value in 'YYYY-MM-DD HH:MM:SS or YYYYMMDDHHMMSS format, depending on whether the function is used in a string or in a numeric context. The value is expressed in the current time zone. The unix_timestamp argument is an internal timestamp values, which are produced by the UNIX_TIMESTAMP() function." }, { "code": null, "e": 130614, "s": 130446, "text": "If the format is given, the result is formatted according to the format string, which is used in the same way as is listed in the entry for the DATE_FORMAT() function." }, { "code": null, "e": 130978, "s": 130614, "text": "mysql> SELECT FROM_UNIXTIME(875996580);\n+---------------------------------------------------------+\n| FROM_UNIXTIME(875996580) |\n+---------------------------------------------------------+\n| 1997-10-04 22:23:00 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 131172, "s": 130978, "text": "Returns the hour for time. The range of the return value is 0 to 23 for time-of-day values. However, the range of TIME values actually is much larger, so HOUR can return values greater than 23." }, { "code": null, "e": 131528, "s": 131172, "text": "mysql> SELECT HOUR('10:05:03');\n+---------------------------------------------------------+\n| HOUR('10:05:03') |\n+---------------------------------------------------------+\n| 10 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 131667, "s": 131528, "text": "Takes a date or datetime value and returns the corresponding value for the last day of the month. Returns NULL if the argument is invalid." }, { "code": null, "e": 132029, "s": 131667, "text": "mysql> SELECT LAST_DAY('2003-02-05');\n+---------------------------------------------------------+\n| LAST_DAY('2003-02-05') |\n+---------------------------------------------------------+\n| 2003-02-28 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 132079, "s": 132029, "text": "LOCALTIME and LOCALTIME() are synonyms for NOW()." }, { "code": null, "e": 132139, "s": 132079, "text": "LOCALTIMESTAMP and LOCALTIMESTAMP() are synonyms for NOW()." }, { "code": null, "e": 132261, "s": 132139, "text": "Returns a date, given year and day-of-year values. The dayofyear value must be greater than 0 or the result will be NULL." }, { "code": null, "e": 132637, "s": 132261, "text": "mysql> SELECT MAKEDATE(2001,31), MAKEDATE(2001,32);\n+---------------------------------------------------------+\n| MAKEDATE(2001,31), MAKEDATE(2001,32) |\n+---------------------------------------------------------+\n| '2001-01-31', '2001-02-01' |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 132713, "s": 132637, "text": "Returns a time value calculated from the hour, minute and second arguments." }, { "code": null, "e": 133071, "s": 132713, "text": "mysql> SELECT MAKETIME(12,15,30);\n+---------------------------------------------------------+\n| MAKETIME(12,15,30) |\n+---------------------------------------------------------+\n| '12:15:30' |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 133183, "s": 133071, "text": "Returns the microseconds from the time or datetime expression (expr) as a number in the range from 0 to 999999." }, { "code": null, "e": 133553, "s": 133183, "text": "mysql> SELECT MICROSECOND('12:00:00.123456');\n+---------------------------------------------------------+\n| MICROSECOND('12:00:00.123456') |\n+---------------------------------------------------------+\n| 123456 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 133604, "s": 133553, "text": "Returns the minute for time, in the range 0 to 59." }, { "code": null, "e": 133971, "s": 133604, "text": "mysql> SELECT MINUTE('98-02-03 10:05:03');\n+---------------------------------------------------------+\n| MINUTE('98-02-03 10:05:03') |\n+---------------------------------------------------------+\n| 5 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 134021, "s": 133971, "text": "Returns the month for date, in the range 0 to 12." }, { "code": null, "e": 134379, "s": 134021, "text": "mysql> SELECT MONTH('1998-02-03')\n+---------------------------------------------------------+\n| MONTH('1998-02-03') |\n+---------------------------------------------------------+\n| 2 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 134426, "s": 134379, "text": "Returns the full name of the month for a date." }, { "code": null, "e": 134789, "s": 134426, "text": "mysql> SELECT MONTHNAME('1998-02-05');\n+---------------------------------------------------------+\n| MONTHNAME('1998-02-05') |\n+---------------------------------------------------------+\n| February |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 135009, "s": 134789, "text": "Returns the current date and time as a value in 'YYYY-MM-DD HH:MM:SS' or YYYYMMDDHHMMSS format, depending on whether the function is used in a string or numeric context. This value is expressed in the current time zone." }, { "code": null, "e": 135354, "s": 135009, "text": "mysql> SELECT NOW();\n+---------------------------------------------------------+\n| NOW() |\n+---------------------------------------------------------+\n| 1997-12-15 23:50:26 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 135505, "s": 135354, "text": "Adds N months to a period P (in the format YYMM or YYYYMM). Returns a value in the format YYYYMM. Note that the period argument P is not a date value." }, { "code": null, "e": 135863, "s": 135505, "text": "mysql> SELECT PERIOD_ADD(9801,2);\n+---------------------------------------------------------+\n| PERIOD_ADD(9801,2) |\n+---------------------------------------------------------+\n| 199803 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 136045, "s": 135863, "text": "Returns the number of months between periods P1 and P2. These periods P1 and P2 should be in the format YYMM or YYYYMM. Note that the period arguments P1 and P2 are not date values." }, { "code": null, "e": 136409, "s": 136045, "text": "mysql> SELECT PERIOD_DIFF(9802,199703);\n+---------------------------------------------------------+\n| PERIOD_DIFF(9802,199703) |\n+---------------------------------------------------------+\n| 11 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 136472, "s": 136409, "text": "Returns the quarter of the year for date, in the range 1 to 4." }, { "code": null, "e": 136831, "s": 136472, "text": "mysql> SELECT QUARTER('98-04-01');\n+---------------------------------------------------------+\n| QUARTER('98-04-01') |\n+---------------------------------------------------------+\n| 2 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 136882, "s": 136831, "text": "Returns the second for time, in the range 0 to 59." }, { "code": null, "e": 137240, "s": 136882, "text": "mysql> SELECT SECOND('10:05:03');\n+---------------------------------------------------------+\n| SECOND('10:05:03') |\n+---------------------------------------------------------+\n| 3 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 137428, "s": 137240, "text": "Returns the seconds argument, converted to hours, minutes and seconds, as a value in 'HH:MM:SS' or HHMMSS format, depending on whether the function is used in a string or numeric context." }, { "code": null, "e": 137785, "s": 137428, "text": "mysql> SELECT SEC_TO_TIME(2378);\n+---------------------------------------------------------+\n| SEC_TO_TIME(2378) |\n+---------------------------------------------------------+\n| 00:39:38 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 138080, "s": 137785, "text": "This is the inverse of the DATE_FORMAT() function. It takes a string str and a format string format. The STR_TO_DATE() function returns a DATETIME value if the format string contains both date and time parts. Else, it returns a DATE or TIME value if the string contains only date or time parts." }, { "code": null, "e": 138457, "s": 138080, "text": "mysql> SELECT STR_TO_DATE('04/31/2004', '%m/%d/%Y');\n+---------------------------------------------------------+\n| STR_TO_DATE('04/31/2004', '%m/%d/%Y') |\n+---------------------------------------------------------+\n| 2004-04-31 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 138638, "s": 138457, "text": "When invoked with the INTERVAL form of the second argument, SUBDATE() is a synonym for DATE_SUB(). For information on the INTERVAL unit argument, see the discussion for DATE_ADD()." }, { "code": null, "e": 139396, "s": 138638, "text": "mysql> SELECT DATE_SUB('1998-01-02', INTERVAL 31 DAY);\n+---------------------------------------------------------+\n| DATE_SUB('1998-01-02', INTERVAL 31 DAY) |\n+---------------------------------------------------------+\n| 1997-12-02 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)\n\nmysql> SELECT SUBDATE('1998-01-02', INTERVAL 31 DAY);\n+---------------------------------------------------------+\n| SUBDATE('1998-01-02', INTERVAL 31 DAY) |\n+---------------------------------------------------------+\n| 1997-12-02 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 139587, "s": 139396, "text": "The SUBTIME() function returns expr1 . expr2 expressed as a value in the same format as expr1. The expr1 value is a time or a datetime expression, while the expr2 value is a time expression." }, { "code": null, "e": 139988, "s": 139587, "text": "mysql> SELECT SUBTIME('1997-12-31 23:59:59.999999',\n -> '1 1:1:1.000002');\n+---------------------------------------------------------+\n| SUBTIME('1997-12-31 23:59:59.999999'... |\n+---------------------------------------------------------+\n| 1997-12-30 22:58:58.999997 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 140163, "s": 139988, "text": "Returns the current date and time as a value in 'YYYY-MM-DD HH:MM:SS' or YYYYMMDDHHMMSS format, depending on whether the function is used in a string or in a numeric context." }, { "code": null, "e": 140512, "s": 140163, "text": "mysql> SELECT SYSDATE();\n+---------------------------------------------------------+\n| SYSDATE() |\n+---------------------------------------------------------+\n| 2006-04-12 13:47:44 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 140603, "s": 140512, "text": "Extracts the time part of the time or datetime expression expr and returns it as a string." }, { "code": null, "e": 140970, "s": 140603, "text": "mysql> SELECT TIME('2003-12-31 01:02:03');\n+---------------------------------------------------------+\n| TIME('2003-12-31 01:02:03') |\n+---------------------------------------------------------+\n| 01:02:03 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 141146, "s": 140970, "text": "The TIMEDIFF() function returns expr1 . expr2 expressed as a time value. These expr1 and expr2 values are time or date-and-time expressions, but both must be of the same type." }, { "code": null, "e": 141560, "s": 141146, "text": "mysql> SELECT TIMEDIFF('1997-12-31 23:59:59.000001',\n -> '1997-12-30 01:01:01.000002');\n+---------------------------------------------------------+\n| TIMEDIFF('1997-12-31 23:59:59.000001'..... |\n+---------------------------------------------------------+\n| 46:58:57.999999 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 141803, "s": 141560, "text": "With a single argument, this function returns the date or datetime expression expr as a datetime value. With two arguments, it adds the time expression expr2 to the date or datetime expression expr1 and returns the result as a datetime value." }, { "code": null, "e": 142166, "s": 141803, "text": "mysql> SELECT TIMESTAMP('2003-12-31');\n+---------------------------------------------------------+\n| TIMESTAMP('2003-12-31') |\n+---------------------------------------------------------+\n| 2003-12-31 00:00:00 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 142366, "s": 142166, "text": "This function adds the integer expression interval to the date or datetime expression datetime_expr. The unit for interval is given by the unit argument, which should be one of the following values −" }, { "code": null, "e": 142378, "s": 142366, "text": "FRAC_SECOND" }, { "code": null, "e": 142393, "s": 142378, "text": "SECOND, MINUTE" }, { "code": null, "e": 142403, "s": 142393, "text": "HOUR, DAY" }, { "code": null, "e": 142408, "s": 142403, "text": "WEEK" }, { "code": null, "e": 142414, "s": 142408, "text": "MONTH" }, { "code": null, "e": 142425, "s": 142414, "text": "QUARTER or" }, { "code": null, "e": 142430, "s": 142425, "text": "YEAR" }, { "code": null, "e": 142527, "s": 142430, "text": "The unit value may be specified using one of the keywords as shown or with a prefix of SQL_TSI_." }, { "code": null, "e": 142576, "s": 142527, "text": "For example, DAY and SQL_TSI_DAY both are legal." }, { "code": null, "e": 142951, "s": 142576, "text": "mysql> SELECT TIMESTAMPADD(MINUTE,1,'2003-01-02');\n+---------------------------------------------------------+\n| TIMESTAMPADD(MINUTE,1,'2003-01-02') |\n+---------------------------------------------------------+\n| 2003-01-02 00:01:00 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 143223, "s": 142951, "text": "Returns the integer difference between the date or datetime expressions datetime_expr1 and datetime_expr2. The unit for the result is given by the unit argument. The legal values for the unit are the same as those listed in the description of the TIMESTAMPADD() function." }, { "code": null, "e": 143609, "s": 143223, "text": "mysql> SELECT TIMESTAMPDIFF(MONTH,'2003-02-01','2003-05-01');\n+---------------------------------------------------------+\n| TIMESTAMPDIFF(MONTH,'2003-02-01','2003-05-01') |\n+---------------------------------------------------------+\n| 3 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 143753, "s": 143609, "text": "This function is used like the DATE_FORMAT() function, but the format string may contain format specifiers only for hours, minutes and seconds." }, { "code": null, "e": 143978, "s": 143753, "text": "If the time value contains an hour part that is greater than 23, the %H and %k hour format specifiers produce a value larger than the usual range of 0 to 23. The other hour format specifiers produce the hour value modulo 12." }, { "code": null, "e": 144360, "s": 143978, "text": "mysql> SELECT TIME_FORMAT('100:00:00', '%H %k %h %I %l');\n+---------------------------------------------------------+\n| TIME_FORMAT('100:00:00', '%H %k %h %I %l') |\n+---------------------------------------------------------+\n| 100 100 04 04 4 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 144408, "s": 144360, "text": "Returns the time argument converted to seconds." }, { "code": null, "e": 144771, "s": 144408, "text": "mysql> SELECT TIME_TO_SEC('22:23:00');\n+---------------------------------------------------------+\n| TIME_TO_SEC('22:23:00') |\n+---------------------------------------------------------+\n| 80580 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 144841, "s": 144771, "text": "Given a date, returns a day number (the number of days since year 0)." }, { "code": null, "e": 145196, "s": 144841, "text": "mysql> SELECT TO_DAYS(950501);\n+---------------------------------------------------------+\n| TO_DAYS(950501) |\n+---------------------------------------------------------+\n| 728779 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 145567, "s": 145196, "text": "If called with no argument, this function returns a Unix timestamp (seconds since '1970-01-01 00:00:00' UTC) as an unsigned integer. If UNIX_TIMESTAMP() is called with a date argument, it returns the value of the argument as seconds since '1970-01-01 00:00:00' UTC. date may be a DATE string, a DATETIME string, a TIMESTAMP, or a number in the format YYMMDD or YYYYMMDD." }, { "code": null, "e": 146301, "s": 145567, "text": "mysql> SELECT UNIX_TIMESTAMP();\n+---------------------------------------------------------+\n| UNIX_TIMESTAMP() |\n+---------------------------------------------------------+\n| 882226357 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)\n\nmysql> SELECT UNIX_TIMESTAMP('1997-10-04 22:23:00');\n+---------------------------------------------------------+\n| UNIX_TIMESTAMP('1997-10-04 22:23:00') |\n+---------------------------------------------------------+\n| 875996580 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 146451, "s": 146301, "text": "Returns the current UTC date as a value in 'YYYY-MM-DD' or YYYYMMDD format, depending on whether the function is used in a string or numeric context." }, { "code": null, "e": 146817, "s": 146451, "text": "mysql> SELECT UTC_DATE(), UTC_DATE() + 0;\n+---------------------------------------------------------+\n| UTC_DATE(), UTC_DATE() + 0 |\n+---------------------------------------------------------+\n| 2003-08-14, 20030814 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 146963, "s": 146817, "text": "Returns the current UTC time as a value in 'HH:MM:SS' or HHMMSS format, depending on whether the function is used in a string or numeric context." }, { "code": null, "e": 147329, "s": 146963, "text": "mysql> SELECT UTC_TIME(), UTC_TIME() + 0;\n+---------------------------------------------------------+\n| UTC_TIME(), UTC_TIME() + 0 |\n+---------------------------------------------------------+\n| 18:07:53, 180753 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 147513, "s": 147329, "text": "Returns the current UTC date and time as a value in 'YYYY-MM-DD HH:MM:SS' or in a YYYYMMDDHHMMSS format, depending on whether the function is used in a string or in a numeric context." }, { "code": null, "e": 147889, "s": 147513, "text": "mysql> SELECT UTC_TIMESTAMP(), UTC_TIMESTAMP() + 0;\n+---------------------------------------------------------+\n| UTC_TIMESTAMP(), UTC_TIMESTAMP() + 0 |\n+---------------------------------------------------------+\n| 2003-08-14 18:08:04, 20030814180804 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 148215, "s": 147889, "text": "This function returns the week number for date. The two-argument form of WEEK() allows you to specify whether the week starts on a Sunday or a Monday and whether the return value should be in the range from 0 to 53 or from 1 to 53. If the mode argument is omitted, the value of the default_week_format system variable is used" }, { "code": null, "e": 148573, "s": 148215, "text": "mysql> SELECT WEEK('1998-02-20');\n+---------------------------------------------------------+\n| WEEK('1998-02-20') |\n+---------------------------------------------------------+\n| 7 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 148649, "s": 148573, "text": "Returns the weekday index for date (0 = Monday, 1 = Tuesday, . 6 = Sunday)." }, { "code": null, "e": 149019, "s": 148649, "text": "mysql> SELECT WEEKDAY('1998-02-03 22:23:00');\n+---------------------------------------------------------+\n| WEEKDAY('1998-02-03 22:23:00') |\n+---------------------------------------------------------+\n| 1 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 149173, "s": 149019, "text": "Returns the calendar week of the date as a number in the range from 1 to 53. WEEKOFYEAR() is a compatibility function that is equivalent to WEEK(date,3)." }, { "code": null, "e": 149537, "s": 149173, "text": "mysql> SELECT WEEKOFYEAR('1998-02-20');\n+---------------------------------------------------------+\n| WEEKOFYEAR('1998-02-20') |\n+---------------------------------------------------------+\n| 8 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 149617, "s": 149537, "text": "Returns the year for date, in the range 1000 to 9999, or 0 for the .zero. date." }, { "code": null, "e": 149973, "s": 149617, "text": "mysql> SELECT YEAR('98-02-03');\n+---------------------------------------------------------+\n| YEAR('98-02-03') |\n+---------------------------------------------------------+\n| 1998 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 150214, "s": 149973, "text": "Returns the year and the week for a date. The mode argument works exactly like the mode argument to the WEEK() function. The year in the result may be different from the year in the date argument for the first and the last week of the year." }, { "code": null, "e": 150576, "s": 150214, "text": "mysql> SELECT YEARWEEK('1987-01-01');\n+---------------------------------------------------------+\n| YEAR('98-02-03')YEARWEEK('1987-01-01') |\n+---------------------------------------------------------+\n| 198653 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 150756, "s": 150576, "text": "Note − The week number is different from what the WEEK() function would return (0) for optional arguments 0 or 1, as WEEK() then returns the week in the context of the given year." }, { "code": null, "e": 151003, "s": 150756, "text": "There are RDBMS, which support temporary tables. Temporary Tables are a great feature that lets you store and process intermediate results by using the same selection, update, and join capabilities that you can use with typical SQL Server tables." }, { "code": null, "e": 151223, "s": 151003, "text": "The temporary tables could be very useful in some cases to keep temporary data. The most important thing that should be known for temporary tables is that they will be deleted when the current client session terminates." }, { "code": null, "e": 151394, "s": 151223, "text": "Temporary tables are available in MySQL version 3.23 onwards. If you use an older version of MySQL than 3.23, you can't use temporary tables, but you can use heap tables." }, { "code": null, "e": 151781, "s": 151394, "text": "As stated earlier, temporary tables will only last as long as the session is alive. If you run the code in a PHP script, the temporary table will be destroyed automatically when the script finishes executing. If you are connected to the MySQL database server through the MySQL client program, then the temporary table will exist until you close the client or manually destroy the table." }, { "code": null, "e": 151844, "s": 151781, "text": "Here is an example showing you the usage of a temporary table." }, { "code": null, "e": 152684, "s": 151844, "text": "mysql> CREATE TEMPORARY TABLE SALESSUMMARY (\n -> product_name VARCHAR(50) NOT NULL\n -> , total_sales DECIMAL(12,2) NOT NULL DEFAULT 0.00\n -> , avg_unit_price DECIMAL(7,2) NOT NULL DEFAULT 0.00\n -> , total_units_sold INT UNSIGNED NOT NULL DEFAULT 0\n);\nQuery OK, 0 rows affected (0.00 sec)\n\nmysql> INSERT INTO SALESSUMMARY\n -> (product_name, total_sales, avg_unit_price, total_units_sold)\n -> VALUES\n -> ('cucumber', 100.25, 90, 2);\n\nmysql> SELECT * FROM SALESSUMMARY;\n+--------------+-------------+----------------+------------------+\n| product_name | total_sales | avg_unit_price | total_units_sold |\n+--------------+-------------+----------------+------------------+\n| cucumber | 100.25 | 90.00 | 2 |\n+--------------+-------------+----------------+------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 152955, "s": 152684, "text": "When you issue a SHOW TABLES command, then your temporary table will not be listed out in the list. Now, if you log out of the MySQL session and then issue a SELECT command, you will find no data available in the database. Even your temporary table will not be existing." }, { "code": null, "e": 153157, "s": 152955, "text": "By default, all the temporary tables are deleted by MySQL when your database connection gets terminated. Still if you want to delete them in between, then you can do so by issuing a DROP TABLE command." }, { "code": null, "e": 153212, "s": 153157, "text": "Following is an example on dropping a temporary table." }, { "code": null, "e": 154177, "s": 153212, "text": "mysql> CREATE TEMPORARY TABLE SALESSUMMARY (\n -> product_name VARCHAR(50) NOT NULL\n -> , total_sales DECIMAL(12,2) NOT NULL DEFAULT 0.00\n -> , avg_unit_price DECIMAL(7,2) NOT NULL DEFAULT 0.00\n -> , total_units_sold INT UNSIGNED NOT NULL DEFAULT 0\n);\nQuery OK, 0 rows affected (0.00 sec)\n\nmysql> INSERT INTO SALESSUMMARY\n -> (product_name, total_sales, avg_unit_price, total_units_sold)\n -> VALUES\n -> ('cucumber', 100.25, 90, 2);\n\nmysql> SELECT * FROM SALESSUMMARY;\n+--------------+-------------+----------------+------------------+\n| product_name | total_sales | avg_unit_price | total_units_sold |\n+--------------+-------------+----------------+------------------+\n| cucumber | 100.25 | 90.00 | 2 |\n+--------------+-------------+----------------+------------------+\n1 row in set (0.00 sec)\nmysql> DROP TABLE SALESSUMMARY;\nmysql> SELECT * FROM SALESSUMMARY;\nERROR 1146: Table 'TUTORIALS.SALESSUMMARY' doesn't exist" }, { "code": null, "e": 154397, "s": 154177, "text": "There may be a situation when you need an exact copy of a table and the CREATE TABLE ... or the SELECT... commands does not suit your purposes because the copy must include the same indexes, default values and so forth." }, { "code": null, "e": 154496, "s": 154397, "text": "If you are using MySQL RDBMS, you can handle this situation by adhering to the steps given below −" }, { "code": null, "e": 154620, "s": 154496, "text": "Use SHOW CREATE TABLE command to get a CREATE TABLE statement that specifies the source table's structure, indexes and all." }, { "code": null, "e": 154744, "s": 154620, "text": "Use SHOW CREATE TABLE command to get a CREATE TABLE statement that specifies the source table's structure, indexes and all." }, { "code": null, "e": 154889, "s": 154744, "text": "Modify the statement to change the table name to that of the clone table and execute the statement. This way you will have an exact clone table." }, { "code": null, "e": 155034, "s": 154889, "text": "Modify the statement to change the table name to that of the clone table and execute the statement. This way you will have an exact clone table." }, { "code": null, "e": 155141, "s": 155034, "text": "Optionally, if you need the table contents copied as well, issue an INSERT INTO or a SELECT statement too." }, { "code": null, "e": 155248, "s": 155141, "text": "Optionally, if you need the table contents copied as well, issue an INSERT INTO or a SELECT statement too." }, { "code": null, "e": 155352, "s": 155248, "text": "Try out the following example to create a clone table for TUTORIALS_TBL whose structure is as follows −" }, { "code": null, "e": 155405, "s": 155352, "text": "Step 1 − Get the complete structure about the table." }, { "code": null, "e": 155906, "s": 155405, "text": "SQL> SHOW CREATE TABLE TUTORIALS_TBL \\G; \n*************************** 1. row *************************** \n Table: TUTORIALS_TBL \nCreate Table: CREATE TABLE 'TUTORIALS_TBL' ( \n 'tutorial_id' int(11) NOT NULL auto_increment, \n 'tutorial_title' varchar(100) NOT NULL default '', \n 'tutorial_author' varchar(40) NOT NULL default '', \n 'submission_date' date default NULL, \n PRIMARY KEY ('tutorial_id'), \n UNIQUE KEY 'AUTHOR_INDEX' ('tutorial_author') \n) TYPE = MyISAM \n1 row in set (0.00 sec)" }, { "code": null, "e": 155959, "s": 155906, "text": "Step 2 − Rename this table and create another table." }, { "code": null, "e": 156349, "s": 155959, "text": "SQL> CREATE TABLE `CLONE_TBL` ( \n -> 'tutorial_id' int(11) NOT NULL auto_increment, \n -> 'tutorial_title' varchar(100) NOT NULL default '', \n -> 'tutorial_author' varchar(40) NOT NULL default '', \n -> 'submission_date' date default NULL, \n -> PRIMARY KEY (`tutorial_id'), \n -> UNIQUE KEY 'AUTHOR_INDEX' ('tutorial_author') \n-> ) TYPE = MyISAM; \nQuery OK, 0 rows affected (1.80 sec) " }, { "code": null, "e": 156532, "s": 156349, "text": "Step 3 − After executing step 2, you will clone a table in your database. If you want to copy data from an old table, then you can do it by using the INSERT INTO... SELECT statement." }, { "code": null, "e": 156908, "s": 156532, "text": "SQL> INSERT INTO CLONE_TBL (tutorial_id, \n -> tutorial_title, \n -> tutorial_author, \n -> submission_date) \n -> SELECT tutorial_id,tutorial_title, \n -> tutorial_author,submission_date, \n -> FROM TUTORIALS_TBL; \nQuery OK, 3 rows affected (0.07 sec) \nRecords: 3 Duplicates: 0 Warnings: 0 " }, { "code": null, "e": 156975, "s": 156908, "text": "Finally, you will have an exact clone table as you wanted to have." }, { "code": null, "e": 157093, "s": 156975, "text": "A Subquery or Inner query or a Nested query is a query within another SQL query and embedded within the WHERE clause." }, { "code": null, "e": 157224, "s": 157093, "text": "A subquery is used to return data that will be used in the main query as a condition to further restrict the data to be retrieved." }, { "code": null, "e": 157367, "s": 157224, "text": "Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with the operators like =, <, >, >=, <=, IN, BETWEEN, etc." }, { "code": null, "e": 157419, "s": 157367, "text": "There are a few rules that subqueries must follow −" }, { "code": null, "e": 157467, "s": 157419, "text": "Subqueries must be enclosed within parentheses." }, { "code": null, "e": 157515, "s": 157467, "text": "Subqueries must be enclosed within parentheses." }, { "code": null, "e": 157669, "s": 157515, "text": "A subquery can have only one column in the SELECT clause, unless multiple columns are in the main query for the subquery to compare its selected columns." }, { "code": null, "e": 157823, "s": 157669, "text": "A subquery can have only one column in the SELECT clause, unless multiple columns are in the main query for the subquery to compare its selected columns." }, { "code": null, "e": 158011, "s": 157823, "text": "An ORDER BY command cannot be used in a subquery, although the main query can use an ORDER BY. The GROUP BY command can be used to perform the same function as the ORDER BY in a subquery." }, { "code": null, "e": 158199, "s": 158011, "text": "An ORDER BY command cannot be used in a subquery, although the main query can use an ORDER BY. The GROUP BY command can be used to perform the same function as the ORDER BY in a subquery." }, { "code": null, "e": 158312, "s": 158199, "text": "Subqueries that return more than one row can only be used with multiple value operators such as the IN operator." }, { "code": null, "e": 158425, "s": 158312, "text": "Subqueries that return more than one row can only be used with multiple value operators such as the IN operator." }, { "code": null, "e": 158529, "s": 158425, "text": "The SELECT list cannot include any references to values that evaluate to a BLOB, ARRAY, CLOB, or NCLOB." }, { "code": null, "e": 158633, "s": 158529, "text": "The SELECT list cannot include any references to values that evaluate to a BLOB, ARRAY, CLOB, or NCLOB." }, { "code": null, "e": 158694, "s": 158633, "text": "A subquery cannot be immediately enclosed in a set function." }, { "code": null, "e": 158755, "s": 158694, "text": "A subquery cannot be immediately enclosed in a set function." }, { "code": null, "e": 158871, "s": 158755, "text": "The BETWEEN operator cannot be used with a subquery. However, the BETWEEN operator can be used within the subquery." }, { "code": null, "e": 158987, "s": 158871, "text": "The BETWEEN operator cannot be used with a subquery. However, the BETWEEN operator can be used within the subquery." }, { "code": null, "e": 159083, "s": 158987, "text": "Subqueries are most frequently used with the SELECT statement. The basic syntax is as follows −" }, { "code": null, "e": 159253, "s": 159083, "text": "SELECT column_name [, column_name ]\nFROM table1 [, table2 ]\nWHERE column_name OPERATOR\n (SELECT column_name [, column_name ]\n FROM table1 [, table2 ]\n [WHERE])\n" }, { "code": null, "e": 159313, "s": 159253, "text": "Consider the CUSTOMERS table having the following records −" }, { "code": null, "e": 159830, "s": 159313, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+" }, { "code": null, "e": 159896, "s": 159830, "text": "Now, let us check the following subquery with a SELECT statement." }, { "code": null, "e": 160014, "s": 159896, "text": "SQL> SELECT * \n FROM CUSTOMERS \n WHERE ID IN (SELECT ID \n FROM CUSTOMERS \n WHERE SALARY > 4500) ;" }, { "code": null, "e": 160055, "s": 160014, "text": "This would produce the following result." }, { "code": null, "e": 160371, "s": 160055, "text": "+----+----------+-----+---------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+---------+----------+\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+---------+----------+\n" }, { "code": null, "e": 160619, "s": 160371, "text": "Subqueries also can be used with INSERT statements. The INSERT statement uses the data returned from the subquery to insert into another table. The selected data in the subquery can be modified with any of the character, date or number functions." }, { "code": null, "e": 160651, "s": 160619, "text": "The basic syntax is as follows." }, { "code": null, "e": 160792, "s": 160651, "text": "INSERT INTO table_name [ (column1 [, column2 ]) ]\n SELECT [ *|column1 [, column2 ]\n FROM table1 [, table2 ]\n [ WHERE VALUE OPERATOR ]\n" }, { "code": null, "e": 160971, "s": 160792, "text": "Consider a table CUSTOMERS_BKP with similar structure as CUSTOMERS table. Now to copy the complete CUSTOMERS table into the CUSTOMERS_BKP table, you can use the following syntax." }, { "code": null, "e": 161079, "s": 160971, "text": "SQL> INSERT INTO CUSTOMERS_BKP\n SELECT * FROM CUSTOMERS \n WHERE ID IN (SELECT ID \n FROM CUSTOMERS) ;\n" }, { "code": null, "e": 161255, "s": 161079, "text": "The subquery can be used in conjunction with the UPDATE statement. Either single or multiple columns in a table can be updated when using a subquery with the UPDATE statement." }, { "code": null, "e": 161287, "s": 161255, "text": "The basic syntax is as follows." }, { "code": null, "e": 161413, "s": 161287, "text": "UPDATE table\nSET column_name = new_value\n[ WHERE OPERATOR [ VALUE ]\n (SELECT COLUMN_NAME\n FROM TABLE_NAME)\n [ WHERE) ]\n" }, { "code": null, "e": 161635, "s": 161413, "text": "Assuming, we have CUSTOMERS_BKP table available which is backup of CUSTOMERS table. The following example updates SALARY by 0.25 times in the CUSTOMERS table for all the customers whose AGE is greater than or equal to 27." }, { "code": null, "e": 161759, "s": 161635, "text": "SQL> UPDATE CUSTOMERS\n SET SALARY = SALARY * 0.25\n WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP\n WHERE AGE >= 27 );" }, { "code": null, "e": 161848, "s": 161759, "text": "This would impact two rows and finally CUSTOMERS table would have the following records." }, { "code": null, "e": 162366, "s": 161848, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 35 | Ahmedabad | 125.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 2125.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+\n" }, { "code": null, "e": 162480, "s": 162366, "text": "The subquery can be used in conjunction with the DELETE statement like with any other statements mentioned above." }, { "code": null, "e": 162512, "s": 162480, "text": "The basic syntax is as follows." }, { "code": null, "e": 162620, "s": 162512, "text": "DELETE FROM TABLE_NAME\n[ WHERE OPERATOR [ VALUE ]\n (SELECT COLUMN_NAME\n FROM TABLE_NAME)\n [ WHERE) ]\n" }, { "code": null, "e": 162843, "s": 162620, "text": "Assuming, we have a CUSTOMERS_BKP table available which is a backup of the CUSTOMERS table. The following example deletes the records from the CUSTOMERS table for all the customers whose AGE is greater than or equal to 27." }, { "code": null, "e": 162942, "s": 162843, "text": "SQL> DELETE FROM CUSTOMERS\n WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP\n WHERE AGE >= 27 );" }, { "code": null, "e": 163035, "s": 162942, "text": "This would impact two rows and finally the CUSTOMERS table would have the following records." }, { "code": null, "e": 163441, "s": 163035, "text": "+----+----------+-----+---------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+---------+----------+\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+---------+----------+\n" }, { "code": null, "e": 163700, "s": 163441, "text": "A sequence is a set of integers 1, 2, 3, ... that are generated in order on demand. Sequences are frequently used in databases because many applications require each row in a table to contain a unique value and sequences provide an easy way to generate them." }, { "code": null, "e": 163754, "s": 163700, "text": "This chapter describes how to use sequences in MySQL." }, { "code": null, "e": 163879, "s": 163754, "text": "The simplest way in MySQL to use sequences is to define a column as AUTO_INCREMENT and leave the rest to MySQL to take care." }, { "code": null, "e": 164074, "s": 163879, "text": "Try out the following example. This will create a table and after that it will insert a few rows in this table where it is not required to give a record ID because its auto-incremented by MySQL." }, { "code": null, "e": 165043, "s": 164074, "text": "mysql> CREATE TABLE INSECT\n -> (\n -> id INT UNSIGNED NOT NULL AUTO_INCREMENT,\n -> PRIMARY KEY (id),\n -> name VARCHAR(30) NOT NULL, # type of insect\n -> date DATE NOT NULL, # date collected\n -> origin VARCHAR(30) NOT NULL # where collected\n);\nQuery OK, 0 rows affected (0.02 sec)\nmysql> INSERT INTO INSECT (id,name,date,origin) VALUES\n -> (NULL,'housefly','2001-09-10','kitchen'),\n -> (NULL,'millipede','2001-09-10','driveway'),\n -> (NULL,'grasshopper','2001-09-10','front yard');\nQuery OK, 3 rows affected (0.02 sec)\nRecords: 3 Duplicates: 0 Warnings: 0\nmysql> SELECT * FROM INSECT ORDER BY id;\n+----+-------------+------------+------------+\n| id | name | date | origin |\n+----+-------------+------------+------------+\n| 1 | housefly | 2001-09-10 | kitchen |\n| 2 | millipede | 2001-09-10 | driveway |\n| 3 | grasshopper | 2001-09-10 | front yard |\n+----+-------------+------------+------------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 165282, "s": 165043, "text": "The LAST_INSERT_ID( ) is an SQL function, so you can use it from within any client that understands how to issue SQL statements. Otherwise PERL and PHP scripts provide exclusive functions to retrieve auto-incremented value of last record." }, { "code": null, "e": 165558, "s": 165282, "text": "Use the mysql_insertid attribute to obtain the AUTO_INCREMENT value generated by a query. This attribute is accessed through either a database handle or a statement handle, depending on how you issue the query. The following example references it through the database handle." }, { "code": null, "e": 165685, "s": 165558, "text": "$dbh->do (\"INSERT INTO INSECT (name,date,origin)\nVALUES('moth','2001-09-14','windowsill')\");\nmy $seq = $dbh->{mysql_insertid};" }, { "code": null, "e": 165810, "s": 165685, "text": "After issuing a query that generates an AUTO_INCREMENT value, retrieve the value by calling the mysql_insert_id( ) function." }, { "code": null, "e": 165951, "s": 165810, "text": "mysql_query (\"INSERT INTO INSECT (name,date,origin)\nVALUES('moth','2001-09-14','windowsill')\", $conn_id);\n$seq = mysql_insert_id ($conn_id);" }, { "code": null, "e": 166216, "s": 165951, "text": "There may be a case when you have deleted many records from a table and you want to re-sequence all the records. This can be done by using a simple trick, but you should be very careful to do this and check if your table is having a join with another table or not." }, { "code": null, "e": 166366, "s": 166216, "text": "If you determine that resequencing an AUTO_INCREMENT column is unavoidable, the way to do it is to drop the column from the table, then add it again." }, { "code": null, "e": 166466, "s": 166366, "text": "The following example shows how to renumber the id values in the insect table using this technique." }, { "code": null, "e": 166612, "s": 166466, "text": "mysql> ALTER TABLE INSECT DROP id;\nmysql> ALTER TABLE insect\n -> ADD id INT UNSIGNED NOT NULL AUTO_INCREMENT FIRST,\n -> ADD PRIMARY KEY (id);" }, { "code": null, "e": 166738, "s": 166612, "text": "By default, MySQL will start the sequence from 1, but you can specify any other number as well at the time of table creation." }, { "code": null, "e": 166820, "s": 166738, "text": "The following code block has an example where MySQL will start sequence from 100." }, { "code": null, "e": 167080, "s": 166820, "text": "mysql> CREATE TABLE INSECT\n -> (\n -> id INT UNSIGNED NOT NULL AUTO_INCREMENT = 100,\n -> PRIMARY KEY (id),\n -> name VARCHAR(30) NOT NULL, # type of insect\n -> date DATE NOT NULL, # date collected\n -> origin VARCHAR(30) NOT NULL # where collected\n);" }, { "code": null, "e": 167178, "s": 167080, "text": "Alternatively, you can create the table and then set the initial sequence value with ALTER TABLE." }, { "code": null, "e": 167221, "s": 167178, "text": "mysql> ALTER TABLE t AUTO_INCREMENT = 100;" }, { "code": null, "e": 167416, "s": 167221, "text": "There may be a situation when you have multiple duplicate records in a table. While fetching such records, it makes more sense to fetch only unique records instead of fetching duplicate records." }, { "code": null, "e": 167603, "s": 167416, "text": "The SQL DISTINCT keyword, which we have already discussed is used in conjunction with the SELECT statement to eliminate all the duplicate records and by fetching only the unique records." }, { "code": null, "e": 167688, "s": 167603, "text": "The basic syntax of a DISTINCT keyword to eliminate duplicate records is as follows." }, { "code": null, "e": 167770, "s": 167688, "text": "SELECT DISTINCT column1, column2,.....columnN \nFROM table_name\nWHERE [condition]\n" }, { "code": null, "e": 167829, "s": 167770, "text": "Consider the CUSTOMERS table having the following records." }, { "code": null, "e": 168346, "s": 167829, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+" }, { "code": null, "e": 168429, "s": 168346, "text": "First, let us see how the following SELECT query returns duplicate salary records." }, { "code": null, "e": 168483, "s": 168429, "text": "SQL> SELECT SALARY FROM CUSTOMERS\n ORDER BY SALARY;" }, { "code": null, "e": 168617, "s": 168483, "text": "This would produce the following result where the salary of 2000 is coming twice which is a duplicate record from the original table." }, { "code": null, "e": 168761, "s": 168617, "text": "+----------+\n| SALARY |\n+----------+\n| 1500.00 |\n| 2000.00 |\n| 2000.00 |\n| 4500.00 |\n| 6500.00 |\n| 8500.00 |\n| 10000.00 |\n+----------+\n" }, { "code": null, "e": 168846, "s": 168761, "text": "Now, let us use the DISTINCT keyword with the above SELECT query and see the result." }, { "code": null, "e": 168909, "s": 168846, "text": "SQL> SELECT DISTINCT SALARY FROM CUSTOMERS\n ORDER BY SALARY;" }, { "code": null, "e": 168991, "s": 168909, "text": "This would produce the following result where we do not have any duplicate entry." }, { "code": null, "e": 169122, "s": 168991, "text": "+----------+\n| SALARY |\n+----------+\n| 1500.00 |\n| 2000.00 |\n| 4500.00 |\n| 6500.00 |\n| 8500.00 |\n| 10000.00 |\n+----------+\n" }, { "code": null, "e": 169476, "s": 169122, "text": "If you take a user input through a webpage and insert it into a SQL database, there is a chance that you have left yourself wide open for a security issue known as the SQL Injection. This chapter will teach you how to help prevent this from happening and help you secure your scripts and SQL statements in your server side scripts such as a PERL Script." }, { "code": null, "e": 169766, "s": 169476, "text": "Injection usually occurs when you ask a user for input, like their name and instead of a name they give you a SQL statement that you will unknowingly run on your database. Never trust user provided data, process this data only after validation; as a rule, this is done by Pattern Matching." }, { "code": null, "e": 169936, "s": 169766, "text": "In the example below, the name is restricted to the alphanumerical characters plus underscore and to a length between 8 and 20 characters (modify these rules as needed)." }, { "code": null, "e": 170129, "s": 169936, "text": "if (preg_match(\"/^\\w{8,20}$/\", $_GET['username'], $matches)) {\n $result = mysql_query(\"SELECT * FROM CUSTOMERS \n WHERE name = $matches[0]\");\n} else {\n echo \"user name not accepted\";\n}" }, { "code": null, "e": 170181, "s": 170129, "text": "To demonstrate the problem, consider this excerpt −" }, { "code": null, "e": 170302, "s": 170181, "text": "// supposed input\n$name = \"Qadir'; DELETE FROM CUSTOMERS;\";\nmysql_query(\"SELECT * FROM CUSTOMSRS WHERE name='{$name}'\");" }, { "code": null, "e": 170735, "s": 170302, "text": "The function call is supposed to retrieve a record from the CUSTOMERS table where the name column matches the name specified by the user. Under normal circumstances, $name would only contain alphanumeric characters and perhaps spaces, such as the string ilia. But here, by appending an entirely new query to $name, the call to the database turns into disaster; the injected DELETE query removes all records from the CUSTOMERS table." }, { "code": null, "e": 170930, "s": 170735, "text": "Fortunately, if you use MySQL, the mysql_query() function does not permit query stacking or executing multiple SQL queries in a single function call. If you try to stack queries, the call fails." }, { "code": null, "e": 171123, "s": 170930, "text": "However, other PHP database extensions, such as SQLite and PostgreSQL happily perform stacked queries, executing all the queries provided in one string and creating a serious security problem." }, { "code": null, "e": 171341, "s": 171123, "text": "You can handle all escape characters smartly in scripting languages like PERL and PHP. The MySQL extension for PHP provides the function mysql_real_escape_string() to escape input characters that are special to MySQL." }, { "code": null, "e": 171507, "s": 171341, "text": "if (get_magic_quotes_gpc()) {\n $name = stripslashes($name);\n}\n$name = mysql_real_escape_string($name);\nmysql_query(\"SELECT * FROM CUSTOMERS WHERE name='{$name}'\");" }, { "code": null, "e": 171709, "s": 171507, "text": "To address the LIKE quandary, a custom escaping mechanism must convert user-supplied '%' and '_' characters to literals. Use addcslashes(), a function that lets you specify a character range to escape." }, { "code": null, "e": 171860, "s": 171709, "text": "$sub = addcslashes(mysql_real_escape_string(\"%str\"), \"%_\");\n// $sub == \\%str\\_\nmysql_query(\"SELECT * FROM messages \n WHERE subject LIKE '{$sub}%'\");" }, { "code": null, "e": 172025, "s": 171860, "text": "It takes time to become a Database Expert or an expert Database Administrator. This all comes with lot of experience in various database designs and good trainings." }, { "code": null, "e": 172119, "s": 172025, "text": "But the following list may be helpful for the beginners to have a nice database performance −" }, { "code": null, "e": 172198, "s": 172119, "text": "Use 3BNF database design explained in this tutorial in RDBMS Concepts chapter." }, { "code": null, "e": 172277, "s": 172198, "text": "Use 3BNF database design explained in this tutorial in RDBMS Concepts chapter." }, { "code": null, "e": 172402, "s": 172277, "text": "Avoid number-to-character conversions because numbers and characters compare differently and lead to performance downgrade." }, { "code": null, "e": 172527, "s": 172402, "text": "Avoid number-to-character conversions because numbers and characters compare differently and lead to performance downgrade." }, { "code": null, "e": 172690, "s": 172527, "text": "While using SELECT statement, only fetch whatever information is required and avoid using * in your SELECT queries because it would load the system unnecessarily." }, { "code": null, "e": 172853, "s": 172690, "text": "While using SELECT statement, only fetch whatever information is required and avoid using * in your SELECT queries because it would load the system unnecessarily." }, { "code": null, "e": 173067, "s": 172853, "text": "Create your indexes carefully on all the tables where you have frequent search operations. Avoid index on the tables where you have less number of search operations and more number of insert and update operations." }, { "code": null, "e": 173281, "s": 173067, "text": "Create your indexes carefully on all the tables where you have frequent search operations. Avoid index on the tables where you have less number of search operations and more number of insert and update operations." }, { "code": null, "e": 173519, "s": 173281, "text": "A full-table scan occurs when the columns in the WHERE clause do not have an index associated with them. You can avoid a full-table scan by creating an index on columns that are used as conditions in the WHERE clause of an SQL statement." }, { "code": null, "e": 173757, "s": 173519, "text": "A full-table scan occurs when the columns in the WHERE clause do not have an index associated with them. You can avoid a full-table scan by creating an index on columns that are used as conditions in the WHERE clause of an SQL statement." }, { "code": null, "e": 174004, "s": 173757, "text": "Be very careful of equality operators with real numbers and date/time values. Both of these can have small differences that are not obvious to the eye but that make an exact match impossible, thus preventing your queries from ever returning rows." }, { "code": null, "e": 174251, "s": 174004, "text": "Be very careful of equality operators with real numbers and date/time values. Both of these can have small differences that are not obvious to the eye but that make an exact match impossible, thus preventing your queries from ever returning rows." }, { "code": null, "e": 174740, "s": 174251, "text": "Use pattern matching judiciously. LIKE COL% is a valid WHERE condition, reducing the returned set to only those records with data starting with the string COL. However, COL%Y does not further reduce the returned results set since %Y cannot be effectively evaluated. The effort to do the evaluation is too large to be considered. In this case, the COL% is used, but the %Y is thrown away. For the same reason, a leading wildcard %COL effectively prevents the entire filter from being used." }, { "code": null, "e": 175229, "s": 174740, "text": "Use pattern matching judiciously. LIKE COL% is a valid WHERE condition, reducing the returned set to only those records with data starting with the string COL. However, COL%Y does not further reduce the returned results set since %Y cannot be effectively evaluated. The effort to do the evaluation is too large to be considered. In this case, the COL% is used, but the %Y is thrown away. For the same reason, a leading wildcard %COL effectively prevents the entire filter from being used." }, { "code": null, "e": 175512, "s": 175229, "text": "Fine tune your SQL queries examining the structure of the queries (and subqueries), the SQL syntax, to discover whether you have designed your tables to support fast data manipulation and written the query in an optimum manner, allowing your DBMS to manipulate the data efficiently." }, { "code": null, "e": 175795, "s": 175512, "text": "Fine tune your SQL queries examining the structure of the queries (and subqueries), the SQL syntax, to discover whether you have designed your tables to support fast data manipulation and written the query in an optimum manner, allowing your DBMS to manipulate the data efficiently." }, { "code": null, "e": 176094, "s": 175795, "text": "For queries that are executed on a regular basis, try to use procedures. A procedure is a potentially large group of SQL statements. Procedures are compiled by the database engine and then executed. Unlike an SQL statement, the database engine need not optimize the procedure before it is executed." }, { "code": null, "e": 176393, "s": 176094, "text": "For queries that are executed on a regular basis, try to use procedures. A procedure is a potentially large group of SQL statements. Procedures are compiled by the database engine and then executed. Unlike an SQL statement, the database engine need not optimize the procedure before it is executed." }, { "code": null, "e": 176532, "s": 176393, "text": "Avoid using the logical operator OR in a query if possible. OR inevitably slows down nearly any query against a table of substantial size." }, { "code": null, "e": 176671, "s": 176532, "text": "Avoid using the logical operator OR in a query if possible. OR inevitably slows down nearly any query against a table of substantial size." }, { "code": null, "e": 176990, "s": 176671, "text": "You can optimize bulk data loads by dropping indexes. Imagine the history table with many thousands of rows. That history table is also likely to have one or more indexes. When you think of an index, you normally think of faster table access, but in the case of batch loads, you can benefit by dropping the index(es)." }, { "code": null, "e": 177309, "s": 176990, "text": "You can optimize bulk data loads by dropping indexes. Imagine the history table with many thousands of rows. That history table is also likely to have one or more indexes. When you think of an index, you normally think of faster table access, but in the case of batch loads, you can benefit by dropping the index(es)." }, { "code": null, "e": 177458, "s": 177309, "text": "When performing batch transactions, perform COMMIT at after a fair number of records creation in stead of creating them after every record creation." }, { "code": null, "e": 177607, "s": 177458, "text": "When performing batch transactions, perform COMMIT at after a fair number of records creation in stead of creating them after every record creation." }, { "code": null, "e": 177711, "s": 177607, "text": "Plan to defragment the database on a regular basis, even if doing so means developing a weekly routine." }, { "code": null, "e": 177815, "s": 177711, "text": "Plan to defragment the database on a regular basis, even if doing so means developing a weekly routine." }, { "code": null, "e": 177935, "s": 177815, "text": "Oracle has many tools for managing SQL statement performance but among them two are very popular. These two tools are −" }, { "code": null, "e": 178037, "s": 177935, "text": "Explain plan − tool identifies the access path that will be taken when the SQL statement is executed." }, { "code": null, "e": 178139, "s": 178037, "text": "Explain plan − tool identifies the access path that will be taken when the SQL statement is executed." }, { "code": null, "e": 178236, "s": 178139, "text": "tkprof − measures the performance by time elapsed during each phase of SQL statement processing." }, { "code": null, "e": 178333, "s": 178236, "text": "tkprof − measures the performance by time elapsed during each phase of SQL statement processing." }, { "code": null, "e": 178450, "s": 178333, "text": "If you want to simply measure the elapsed time of a query in Oracle, you can use the SQL*Plus command SET TIMING ON." }, { "code": null, "e": 178559, "s": 178450, "text": "Check your RDBMS documentation for more detail on the above-mentioned tools and defragmenting the database." }, { "code": null, "e": 178592, "s": 178559, "text": "\n 42 Lectures \n 5 hours \n" }, { "code": null, "e": 178606, "s": 178592, "text": " Anadi Sharma" }, { "code": null, "e": 178639, "s": 178606, "text": "\n 14 Lectures \n 2 hours \n" }, { "code": null, "e": 178653, "s": 178639, "text": " Anadi Sharma" }, { "code": null, "e": 178688, "s": 178653, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 178702, "s": 178688, "text": " Anadi Sharma" }, { "code": null, "e": 178735, "s": 178702, "text": "\n 94 Lectures \n 7 hours \n" }, { "code": null, "e": 178757, "s": 178735, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 178792, "s": 178757, "text": "\n 80 Lectures \n 6.5 hours \n" }, { "code": null, "e": 178846, "s": 178792, "text": " Oracle Master Training | 150,000+ Students Worldwide" }, { "code": null, "e": 178879, "s": 178846, "text": "\n 31 Lectures \n 6 hours \n" }, { "code": null, "e": 178907, "s": 178879, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 178914, "s": 178907, "text": " Print" }, { "code": null, "e": 178925, "s": 178914, "text": " Add Notes" } ]
Count of distinct graphs that can be formed with N vertices - GeeksforGeeks
28 Mar, 2022 Given an integer N which is the number of vertices. The task is to find the number of distinct graphs that can be formed. Since the answer can be very large, print the answer % 1000000007.Examples: Input: N = 3 Output: 8Input: N = 4 Output: 64 Approach: The maximum number of edges a graph with N vertices can contain is X = N * (N – 1) / 2. The total number of graphs containing 0 edge and N vertices will be XC0 The total number of graphs containing 1 edge and N vertices will be XC1 And so on from a number of edges 1 to X with N vertices Hence, the total number of graphs that can be formed with n vertices will be:XC0 + XC1 + XC2 + ... + XCX = 2X. Below is the implementation of the above approach: C++ Java Python C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; const int MOD = 1e9 + 7; // Function to return (x^y) % MOD// in O(log(y))long long power(long long x, long long y, const int& MOD){ long long res = 1; while (y > 0) { if (y & 1) res = (res * x) % MOD; x = (x * x) % MOD; y /= 2; } return res;} // Function to return the count of distinct// graphs possible with n verticeslong long countGraphs(int n){ // Maximum number of edges for a // graph with n vertices long long x = n * (n - 1) / 2; // Function to calculate // (2^x) % mod return power(2, x, MOD);} // Driver codeint main(){ int n = 5; cout << countGraphs(n); return 0;} // Java implementation of the approachclass GFG{ static final int MOD = (int)1e9 + 7; // Function to return (x^y) % MOD // in O(log(y)) static long power(long x, long y) { long res = 1; while (y > 0) { if ((y & 1) != 0) res = (res * x) % MOD; x = (x * x) % MOD; y /= 2; } return res; } // Function to return the count of distinct // graphs possible with n vertices static long countGraphs(int n) { // Maximum number of edges for a // graph with n vertices long x = n * (n - 1) / 2; // Function to calculate // (2^x) % mod return power(2, x); } // Driver code public static void main (String[] args) { int n = 5; System.out.println(countGraphs(n)); }} // This code is contributed by AnkitRai01 MOD = int(1e9 + 7) # Function to return the count of distinct# graphs possible with n verticesdef countGraphs(n): # Maximum number of edges for a # graph with n vertices x = (n *( n - 1 )) //2 # Return 2 ^ x return (pow(2, x, MOD)) # Driver coden = 5print(countGraphs(n)) // C# implementation of the approachusing System; class GFG{ static int MOD = (int)1e9 + 7; // Function to return (x^y) % MOD // in O(log(y)) static long power(long x, long y) { long res = 1; while (y > 0) { if ((y & 1) != 0) res = (res * x) % MOD; x = (x * x) % MOD; y /= 2; } return res; } // Function to return the count of distinct // graphs possible with n vertices static long countGraphs(int n) { // Maximum number of edges for a // graph with n vertices long x = n * (n - 1) / 2; // Function to calculate // (2^x) % mod return power(2, x); } // Driver code static public void Main () { int n = 5; Console.Write(countGraphs(n)); }} // This code is contributed by ajit. <script> // Javascript implementation of the approach const MOD = 1000000000 + 7; // Function to return (x^y) % MOD// in O(log(y))function power(x, y, MOD){ let res = 1; while (y > 0) { if (y & 1) res = (res * x) % MOD; x = (x * x) % MOD; y = parseInt(y / 2); } return res;} // Function to return the count of distinct// graphs possible with n verticesfunction countGraphs(n){ // Maximum number of edges for a // graph with n vertices let x = parseInt(n * (n - 1) / 2); // Function to calculate // (2^x) % mod return power(2, x, MOD);} // Driver code let n = 5; document.write(countGraphs(n)); </script> 1024 Time Complexity: O(log(n2)) Auxiliary Space: O(1) ankthon jit_t souravmahato348 subhammahato348 Combinatorial Mathematical Mathematical Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Combinational Sum Count ways to reach the nth stair using step 1, 2 or 3 Count of subsets with sum equal to X Python program to get all subsets of given size of a set Lexicographic rank of a string Program for Fibonacci numbers C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7 Merge two sorted arrays
[ { "code": null, "e": 25219, "s": 25191, "text": "\n28 Mar, 2022" }, { "code": null, "e": 25419, "s": 25219, "text": "Given an integer N which is the number of vertices. The task is to find the number of distinct graphs that can be formed. Since the answer can be very large, print the answer % 1000000007.Examples: " }, { "code": null, "e": 25467, "s": 25419, "text": "Input: N = 3 Output: 8Input: N = 4 Output: 64 " }, { "code": null, "e": 25481, "s": 25469, "text": "Approach: " }, { "code": null, "e": 25569, "s": 25481, "text": "The maximum number of edges a graph with N vertices can contain is X = N * (N – 1) / 2." }, { "code": null, "e": 25641, "s": 25569, "text": "The total number of graphs containing 0 edge and N vertices will be XC0" }, { "code": null, "e": 25713, "s": 25641, "text": "The total number of graphs containing 1 edge and N vertices will be XC1" }, { "code": null, "e": 25769, "s": 25713, "text": "And so on from a number of edges 1 to X with N vertices" }, { "code": null, "e": 25880, "s": 25769, "text": "Hence, the total number of graphs that can be formed with n vertices will be:XC0 + XC1 + XC2 + ... + XCX = 2X." }, { "code": null, "e": 25933, "s": 25880, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25937, "s": 25933, "text": "C++" }, { "code": null, "e": 25942, "s": 25937, "text": "Java" }, { "code": null, "e": 25949, "s": 25942, "text": "Python" }, { "code": null, "e": 25952, "s": 25949, "text": "C#" }, { "code": null, "e": 25963, "s": 25952, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; const int MOD = 1e9 + 7; // Function to return (x^y) % MOD// in O(log(y))long long power(long long x, long long y, const int& MOD){ long long res = 1; while (y > 0) { if (y & 1) res = (res * x) % MOD; x = (x * x) % MOD; y /= 2; } return res;} // Function to return the count of distinct// graphs possible with n verticeslong long countGraphs(int n){ // Maximum number of edges for a // graph with n vertices long long x = n * (n - 1) / 2; // Function to calculate // (2^x) % mod return power(2, x, MOD);} // Driver codeint main(){ int n = 5; cout << countGraphs(n); return 0;}", "e": 26727, "s": 25963, "text": null }, { "code": "// Java implementation of the approachclass GFG{ static final int MOD = (int)1e9 + 7; // Function to return (x^y) % MOD // in O(log(y)) static long power(long x, long y) { long res = 1; while (y > 0) { if ((y & 1) != 0) res = (res * x) % MOD; x = (x * x) % MOD; y /= 2; } return res; } // Function to return the count of distinct // graphs possible with n vertices static long countGraphs(int n) { // Maximum number of edges for a // graph with n vertices long x = n * (n - 1) / 2; // Function to calculate // (2^x) % mod return power(2, x); } // Driver code public static void main (String[] args) { int n = 5; System.out.println(countGraphs(n)); }} // This code is contributed by AnkitRai01", "e": 27655, "s": 26727, "text": null }, { "code": "MOD = int(1e9 + 7) # Function to return the count of distinct# graphs possible with n verticesdef countGraphs(n): # Maximum number of edges for a # graph with n vertices x = (n *( n - 1 )) //2 # Return 2 ^ x return (pow(2, x, MOD)) # Driver coden = 5print(countGraphs(n))", "e": 27948, "s": 27655, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ static int MOD = (int)1e9 + 7; // Function to return (x^y) % MOD // in O(log(y)) static long power(long x, long y) { long res = 1; while (y > 0) { if ((y & 1) != 0) res = (res * x) % MOD; x = (x * x) % MOD; y /= 2; } return res; } // Function to return the count of distinct // graphs possible with n vertices static long countGraphs(int n) { // Maximum number of edges for a // graph with n vertices long x = n * (n - 1) / 2; // Function to calculate // (2^x) % mod return power(2, x); } // Driver code static public void Main () { int n = 5; Console.Write(countGraphs(n)); }} // This code is contributed by ajit.", "e": 28838, "s": 27948, "text": null }, { "code": "<script> // Javascript implementation of the approach const MOD = 1000000000 + 7; // Function to return (x^y) % MOD// in O(log(y))function power(x, y, MOD){ let res = 1; while (y > 0) { if (y & 1) res = (res * x) % MOD; x = (x * x) % MOD; y = parseInt(y / 2); } return res;} // Function to return the count of distinct// graphs possible with n verticesfunction countGraphs(n){ // Maximum number of edges for a // graph with n vertices let x = parseInt(n * (n - 1) / 2); // Function to calculate // (2^x) % mod return power(2, x, MOD);} // Driver code let n = 5; document.write(countGraphs(n)); </script>", "e": 29513, "s": 28838, "text": null }, { "code": null, "e": 29518, "s": 29513, "text": "1024" }, { "code": null, "e": 29548, "s": 29520, "text": "Time Complexity: O(log(n2))" }, { "code": null, "e": 29570, "s": 29548, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 29578, "s": 29570, "text": "ankthon" }, { "code": null, "e": 29584, "s": 29578, "text": "jit_t" }, { "code": null, "e": 29600, "s": 29584, "text": "souravmahato348" }, { "code": null, "e": 29616, "s": 29600, "text": "subhammahato348" }, { "code": null, "e": 29630, "s": 29616, "text": "Combinatorial" }, { "code": null, "e": 29643, "s": 29630, "text": "Mathematical" }, { "code": null, "e": 29656, "s": 29643, "text": "Mathematical" }, { "code": null, "e": 29670, "s": 29656, "text": "Combinatorial" }, { "code": null, "e": 29768, "s": 29670, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29786, "s": 29768, "text": "Combinational Sum" }, { "code": null, "e": 29841, "s": 29786, "text": "Count ways to reach the nth stair using step 1, 2 or 3" }, { "code": null, "e": 29878, "s": 29841, "text": "Count of subsets with sum equal to X" }, { "code": null, "e": 29935, "s": 29878, "text": "Python program to get all subsets of given size of a set" }, { "code": null, "e": 29966, "s": 29935, "text": "Lexicographic rank of a string" }, { "code": null, "e": 29996, "s": 29966, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 30011, "s": 29996, "text": "C++ Data Types" }, { "code": null, "e": 30054, "s": 30011, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 30073, "s": 30054, "text": "Coin Change | DP-7" } ]
Pair Sum Existence- Revisited | Practice | GeeksforGeeks
You are given an array A of size N, and you are also given a sum. You need to find if two numbers in A exists that have sum equal to the given sum. Input Format: The first line of input contains T denoting the number of testcases. T testcases follow. Each testcase contains three lines of input. The first line contains N denoting the size of the array A. The second line contains N elements of the array. The third line contains element sum. Output Format: For each testcase, in a new line, print the required output. Your Task: Since this is a function problem, you don't need to take any input. Just complete the provided function sumExists(). Constraints: 1 <= T <= 100 1 <= N <= 1000 1 <= Ai <= 106 Examples: Input: 1 10 1 2 3 4 5 6 7 8 9 10 14 Output: 1 +2 yogeshrajendra10106 months ago // Easy JAVA Solution Using HashSet. TC:- O(n) , SC:-O(n) public static int sumExists(int arr[], int n, int sum) { // your code here HashSet<Integer>hs=new HashSet<>(); for(int i=0;i<arr.length;i++){ if(hs.contains(sum-arr[i])){ return 1; } else{ hs.add(arr[i]); } } return 0; } 0 Jayesh Badgujar8 months ago Jayesh Badgujar https://uploads.disquscdn.c... 0 Amir Ansari1 year ago Amir Ansari Correct AnswerExecution Time:0.75 public static int sumExists(int arr[], int n, int sum) { Map<integer, integer="">map = new HashMap<integer, integer="">(); for(int i = 0; i < n;i++) { if(map.get(sum-arr[i]) != null) { return 1; } map.put(arr[i], i); } return 0; } 0 Sumit Pardhiya1 year ago Sumit Pardhiya Arrays.sort(arr); int l=0; int r=n-1; int c=0; while(l<r) {="" if(arr[l]+arr[r]="=sum)" {="" c++;="" l++;="" r--;="" }="" else="" if(arr[l]+arr[r]<sum)="" {="" l++;="" }="" else="" {="" r--;="" }="" }="" if(c="=0)" return="" 0;="" return="" 1;=""> 0 Sanjit Paul1 year ago Sanjit Paul Easy Java solution in O(n) timehttps://ide.geeksforgeeks.o... 0 pranav kul1 year ago pranav kul public static boolean isDoublyFrequent(int[] arr, int num){ int count = 0; for(int x : arr){ if(x==num){ count++; } } return count==2; } // function to check if any pair having specified sum // and return 1 if so, else 0 public static int sumExists(int arr[], int n, int sum) { // your code here HashMap<integer, integer=""> diff = new HashMap<>(); for(Integer x: arr){ diff.putIfAbsent(x, sum-x); } for(Integer y: arr){ if( y == (sum/2) ){ if( isDoublyFrequent(arr,y) ){ return 1; } } else if( diff.containsValue(y) ){ return 1; } } return 0; } 0 Isha Gupta2 years ago Isha Gupta // SIMPLE CLEAN SOLUTION//class Geeks{ // function to check if any pair having specified sum // and return 1 if so, else 0 public static int sumExists(int arr[], int n, int sum) { for(int i=0;i<n-1;i++){ for(int="" j="i+1;j&lt;n;j++)" if(arr[i]+arr[j]="=" sum)="" return="" 1;="" }="" return="" 0;="" }="" }=""> 0 Ansh Gupta2 years ago Ansh Gupta JAVA SOLUTION: public static int sumExists(int arr[], int n, int sum) { HashSet<integer> set=new HashSet<>(); set.add(arr[0]); for(int i=1;i<n;i++){ if(set.contains(sum-arr[i]))="" return="" 1;="" else="" set.add(arr[i]);="" }="" return="" 0;="" }=""> 0 Toshik Langade2 years ago Toshik Langade First line should contain the number of test cases but in some test cases the line is missing.How to solve this problem? 0 Sneha Bandi3 years ago Sneha Bandi https://uploads.disquscdn.c... This code can be referred 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": 374, "s": 226, "text": "You are given an array A of size N, and you are also given a sum. You need to find if two numbers in A exists that have sum equal to the given sum." }, { "code": null, "e": 669, "s": 374, "text": "Input Format:\nThe first line of input contains T denoting the number of testcases. T testcases follow. Each testcase contains three lines of input. The first line contains N denoting the size of the array A. The second line contains N elements of the array. The third line contains element sum." }, { "code": null, "e": 745, "s": 669, "text": "Output Format:\nFor each testcase, in a new line, print the required output." }, { "code": null, "e": 873, "s": 745, "text": "Your Task:\nSince this is a function problem, you don't need to take any input. Just complete the provided function sumExists()." }, { "code": null, "e": 930, "s": 873, "text": "Constraints:\n1 <= T <= 100\n1 <= N <= 1000\n1 <= Ai <= 106" }, { "code": null, "e": 986, "s": 930, "text": "Examples:\nInput:\n1\n10\n1 2 3 4 5 6 7 8 9 10\n14\nOutput:\n1" }, { "code": null, "e": 989, "s": 986, "text": "+2" }, { "code": null, "e": 1020, "s": 989, "text": "yogeshrajendra10106 months ago" }, { "code": null, "e": 1057, "s": 1020, "text": "// Easy JAVA Solution Using HashSet." }, { "code": null, "e": 1078, "s": 1057, "text": "TC:- O(n) , SC:-O(n)" }, { "code": null, "e": 1401, "s": 1078, "text": "public static int sumExists(int arr[], int n, int sum) { // your code here HashSet<Integer>hs=new HashSet<>(); for(int i=0;i<arr.length;i++){ if(hs.contains(sum-arr[i])){ return 1; } else{ hs.add(arr[i]); } } return 0; }" }, { "code": null, "e": 1403, "s": 1401, "text": "0" }, { "code": null, "e": 1431, "s": 1403, "text": "Jayesh Badgujar8 months ago" }, { "code": null, "e": 1447, "s": 1431, "text": "Jayesh Badgujar" }, { "code": null, "e": 1478, "s": 1447, "text": "https://uploads.disquscdn.c..." }, { "code": null, "e": 1480, "s": 1478, "text": "0" }, { "code": null, "e": 1502, "s": 1480, "text": "Amir Ansari1 year ago" }, { "code": null, "e": 1514, "s": 1502, "text": "Amir Ansari" }, { "code": null, "e": 1548, "s": 1514, "text": "Correct AnswerExecution Time:0.75" }, { "code": null, "e": 1683, "s": 1548, "text": "public static int sumExists(int arr[], int n, int sum) { Map<integer, integer=\"\">map = new HashMap<integer, integer=\"\">();" }, { "code": null, "e": 1824, "s": 1683, "text": " for(int i = 0; i < n;i++) { if(map.get(sum-arr[i]) != null) { return 1; } map.put(arr[i], i); } return 0; }" }, { "code": null, "e": 1826, "s": 1824, "text": "0" }, { "code": null, "e": 1851, "s": 1826, "text": "Sumit Pardhiya1 year ago" }, { "code": null, "e": 1866, "s": 1851, "text": "Sumit Pardhiya" }, { "code": null, "e": 2142, "s": 1866, "text": "Arrays.sort(arr); int l=0; int r=n-1; int c=0; while(l<r) {=\"\" if(arr[l]+arr[r]=\"=sum)\" {=\"\" c++;=\"\" l++;=\"\" r--;=\"\" }=\"\" else=\"\" if(arr[l]+arr[r]<sum)=\"\" {=\"\" l++;=\"\" }=\"\" else=\"\" {=\"\" r--;=\"\" }=\"\" }=\"\" if(c=\"=0)\" return=\"\" 0;=\"\" return=\"\" 1;=\"\">" }, { "code": null, "e": 2144, "s": 2142, "text": "0" }, { "code": null, "e": 2166, "s": 2144, "text": "Sanjit Paul1 year ago" }, { "code": null, "e": 2178, "s": 2166, "text": "Sanjit Paul" }, { "code": null, "e": 2240, "s": 2178, "text": "Easy Java solution in O(n) timehttps://ide.geeksforgeeks.o..." }, { "code": null, "e": 2242, "s": 2240, "text": "0" }, { "code": null, "e": 2263, "s": 2242, "text": "pranav kul1 year ago" }, { "code": null, "e": 2274, "s": 2263, "text": "pranav kul" }, { "code": null, "e": 2793, "s": 2274, "text": "public static boolean isDoublyFrequent(int[] arr, int num){ int count = 0; for(int x : arr){ if(x==num){ count++; } } return count==2; } // function to check if any pair having specified sum // and return 1 if so, else 0 public static int sumExists(int arr[], int n, int sum) { // your code here HashMap<integer, integer=\"\"> diff = new HashMap<>(); for(Integer x: arr){ diff.putIfAbsent(x, sum-x); }" }, { "code": null, "e": 3051, "s": 2793, "text": " for(Integer y: arr){ if( y == (sum/2) ){ if( isDoublyFrequent(arr,y) ){ return 1; } } else if( diff.containsValue(y) ){ return 1; } }" }, { "code": null, "e": 3074, "s": 3051, "text": " return 0; }" }, { "code": null, "e": 3076, "s": 3074, "text": "0" }, { "code": null, "e": 3098, "s": 3076, "text": "Isha Gupta2 years ago" }, { "code": null, "e": 3109, "s": 3098, "text": "Isha Gupta" }, { "code": null, "e": 3440, "s": 3109, "text": "// SIMPLE CLEAN SOLUTION//class Geeks{ // function to check if any pair having specified sum // and return 1 if so, else 0 public static int sumExists(int arr[], int n, int sum) { for(int i=0;i<n-1;i++){ for(int=\"\" j=\"i+1;j&lt;n;j++)\" if(arr[i]+arr[j]=\"=\" sum)=\"\" return=\"\" 1;=\"\" }=\"\" return=\"\" 0;=\"\" }=\"\" }=\"\">" }, { "code": null, "e": 3442, "s": 3440, "text": "0" }, { "code": null, "e": 3464, "s": 3442, "text": "Ansh Gupta2 years ago" }, { "code": null, "e": 3475, "s": 3464, "text": "Ansh Gupta" }, { "code": null, "e": 3490, "s": 3475, "text": "JAVA SOLUTION:" }, { "code": null, "e": 3751, "s": 3490, "text": "public static int sumExists(int arr[], int n, int sum) { HashSet<integer> set=new HashSet<>(); set.add(arr[0]); for(int i=1;i<n;i++){ if(set.contains(sum-arr[i]))=\"\" return=\"\" 1;=\"\" else=\"\" set.add(arr[i]);=\"\" }=\"\" return=\"\" 0;=\"\" }=\"\">" }, { "code": null, "e": 3753, "s": 3751, "text": "0" }, { "code": null, "e": 3779, "s": 3753, "text": "Toshik Langade2 years ago" }, { "code": null, "e": 3794, "s": 3779, "text": "Toshik Langade" }, { "code": null, "e": 3915, "s": 3794, "text": "First line should contain the number of test cases but in some test cases the line is missing.How to solve this problem?" }, { "code": null, "e": 3917, "s": 3915, "text": "0" }, { "code": null, "e": 3940, "s": 3917, "text": "Sneha Bandi3 years ago" }, { "code": null, "e": 3952, "s": 3940, "text": "Sneha Bandi" }, { "code": null, "e": 3983, "s": 3952, "text": "https://uploads.disquscdn.c..." }, { "code": null, "e": 4009, "s": 3983, "text": "This code can be referred" }, { "code": null, "e": 4155, "s": 4009, "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": 4191, "s": 4155, "text": " Login to access your submissions. " }, { "code": null, "e": 4201, "s": 4191, "text": "\nProblem\n" }, { "code": null, "e": 4211, "s": 4201, "text": "\nContest\n" }, { "code": null, "e": 4274, "s": 4211, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4422, "s": 4274, "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": 4630, "s": 4422, "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": 4736, "s": 4630, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Predicting Diabetes using Logistic Regression with TensorFlow.js | by Venelin Valkov | Towards Data Science
TL;DR Build a Logistic Regression model in TensorFlow.js using the high-level layers API, and predict whether or not a patient has Diabetes. Learn how to visualize the data, create a Dataset, train and evaluate multiple models. You’ve been living in this forgotten city for the past 8+ months. You never felt comfortable anywhere but home. However, this place sets a new standard. The constant changes between dry and humid heat are killing you, fast. The Internet connection is spotty at best, and you haven’t heard from your closed ones for more than two weeks. You have no idea how your partner is and how your kids are doing. You sometimes question the love for your country. This morning you feel even worse. Constantly hungry and thirsty. You urinated four times, already, and your vision is somewhat blurry. It is not just today you were feeling like that for a week, at least. You went to the doctor, and she said you might have Diabetes. Both your mother and father suffer from it, so it seems likely. She wasn’t that sure and did a glucose test. Unfortunately, you’re being called and should go before the results are in. You’re going away for two weeks. Only a couple of guys and your laptop! You have a couple of minutes and download a Diabetes patient dataset. You have TensorFlow.js already installed and a copy of the whole API. Can you build a model to predict whether or not you have Diabetes? We're so pumped to have you! Already have an account? Sign In Run the complete source code for this tutorial right in your browser: Diabetes mellitus (DM), commonly known as diabetes, is a group of metabolic disorders characterized by high blood sugar levels over a prolonged period. Symptoms of high blood sugar include frequent urination, increased thirst, and increased hunger. If left untreated, diabetes can cause many complications. Acute complications can include diabetic ketoacidosis, hyperosmolar hyperglycemic state, or death. Serious long-term complications include cardiovascular disease, stroke, chronic kidney disease, foot ulcers, and damage to the eyes. As of 2017, an estimated 425 million people had diabetes worldwide (around 5.5%) Our data comes from Kaggle but was first introduced in the paper: Using the ADAP Learning Algorithm to Forecast the Onset of Diabetes Mellitus The population for this study was the Pima Indian population near Phoenix, Arizona. That population has been under continuous study since 1965 by the National Institute of Diabetes and Digestive and Kidney Diseases because of its high incidence rate of diabetes. Each community resident over 5 years of age was asked to undergo a standardized examination every two years, which included an oral glucose tolerance test. Diabetes was diagnosed according to World Health Organization Criteria; that is, if the 2 hour post-load plasma glucose was at least 200 mg/dl (11.1 mmol/l) at any survey examination or if the Indian Health Service Hospital serving the community found a glucose concentration of at least 200 mg/dl during the course of routine medical care. Here is a summary of the data: Pregnancies - Number of times pregnant Glucose - Plasma glucose concentration a 2 hours in an oral glucose tolerance test BloodPressure - Diastolic blood pressure (mm Hg) SkinThickness - Triceps skin fold thickness (mm) Insulin - 2-Hour serum insulin (mu U/ml) BMI - Body mass index (\frac{weight}{height^2}height2weight​ in kg/m) DiabetesPedigreeFunction - Diabetes Pedigree Function (DPF) Age - Age (years) Outcome - Class variable (0 - healthy or 1 - diabetic) According to Estimating Probabilities of Diabetes Mellitus Using Neural Networkspaper, the DPF provides: A synthesis of the diabetes mellitus history in relatives and the genetic relationship of those relatives to the subject. The DPF uses information from parents, grandparents, siblings, aunts and uncles, and first cousins. It provides a measure of the expected genetic influence of affected and unaffected relatives on the subject’s eventual diabetes risk. The Pima (or Akimel Oʼodham, also spelled Akimel Oʼotham, “River People”, formerly known as Pima) are a group of Native Americans living in an area consisting of what is now central and southern Arizona. The majority population of the surviving two bands of the Akimel Oʼodham are based in two reservations: the Keli Akimel Oʼotham on the Gila River Indian Community (GRIC) and the On’k Akimel Oʼodham on the Salt River Pima-Maricopa Indian Community (SRPMIC). We’ll use the Papa Parse library to read the csv file. Unfortunately, Papa Parse doesn’t work well with await/async. Let’s change that: We use the dynamicTyping parameter to instruct Papa Parse to convert the numbers in the dataset from strings. Let’s define a function that loads the data: and use it: Good job! We have the data, let get familiar with it! While tfjs-vis is nice and well integrated with TensorFlow.js, it lacks (at the time of this writing) a ton of features you might need — overlay plots, color changes, scale customization, etc. That’s why we’ll use Plotly’s Javascript library to make some beautiful plots for our data exploration. Let’s have a look at the distribution of healthy vs diabetic people: Little above 65% of the patients in our dataset are healthy. That means that our model should be more accurate than 65% of the time, to be any good. Next up — the insulin levels: Note that there is a big overlap between the two distributions. Also, we have a lot of 0s in the dataset. Seems like we have a lot of missing values. NaNs are replaced with 0s. Another important one is the glucose levels after the test: While there is some overlap, this test seems like it separates the healthy from diabetic patients pretty well. Let’s have a look at the age: Generally speaking, it seems like older people are more likely to have diabetes. Maybe we should take a look at the relationship between age and glucose levels: The combination of those two seems to separate healthy and diabetic patients very well. That might do wonders for our model. Another combination you might want to try is the skin thickness vs BMI: Yep, this one is horrible and doesn’t tell us much :) Currently, our data sits in an array of objects. Unfortunately, TensorFlow doesn’t work well with those. Luckily, there is the tfjs-data package. We’re going to create a Dataset from our CSV file and use it to train our model with the createDatasets() function: The features parameter specifies which columns are in the dataset. testSize is the fraction of the data that is going to be used for testing. batchSize controls the number of data points when the dataset is split into chunks (batches). Let’s start by extracting the features from the data: We’re replacing missing values in our features with 0s. You might try to train your model without this step and see what happens? Let’s prepare the labels: Here’s the definition of oneHot: One-hot encoding turns categorical variables (healthy — 0 and diabetic — 1) into an array where 1 corresponds to the position of the category and all other variables are 0. Here are some examples: 1; // diabetic =>[0, 1]; and healthy: 0; // healthy =>[1, 0]; Let’s create a Dataset from our data: Note that we also shuffle the data with a seed of 42 :) Finally, let’s split the data into training and validation datasets: We use take to create the training dataset, skip to omit the training examples for the validation dataset and finally, split the data into chunks using batch. Additionally, we return data for testing our model (more on this later). Logistic Regression (contrary to its name) allows you to get binary (yes/no) answers from your data. Moreover, it gives you the probability for each answer. Questions like: Is this email spam? Should I ask my boss for a higher salary? Does this patient have diabetes? Is this person a real friend? Does my partner cheat on me? Do I cheat on my partner? Do you get where I am getting at? are answerable using Logistic Regression if sufficient data is available and you’re lucky enough to believe there are answers to all of these? But I digress, let’s have a look at the mathematical formulation of the Logistic Regression. First, let’s start with the Linear Model: where x is the data we’re going to use to train our model, b1​ controls the slope and b0​ the interception point with the y axis. We’re going to use the softmax function to get probabilities out of the Linear Model and obtain a generalized model of Logistic Regression. Softmax Regression allows us to create a model with more than 2 output classes (binary response): where b1​ defines the steepness of the curve and b0​ moves the curve left and right. We want to use our data X and some training magic to learn the parameters b1​ and b0​. Let’s use TensorFlow.js for that! Note that this model will give us a probabilistic answer instead of just a binary response. You might decide to ignore a prediction if the model is not sure about it — e.g. below 80%. Let’s put the theory into practice by building a model into TensorFlow.js and predict the outcome for a patient. Remember that the key to building a Logistic Regression model was the Linear Model and applying a softmax function to it: Note that we have 2 outputs because of the one-hot encoding and dynamic input count, based on the features we’ve chosen to train the model. Yes, it is that easy to build a Logistic Regression model in TensorFlow.js. The next step is to compile the model: The training process of our model consists of minimizing the loss function. This gets done by the Adam optimizer we’re providing. Note that we’re providing a learning rate of 0.001. The learning rate is known as a hyperparameter since it is a parameter you provide for your model to use. It controls how much each new update should “override” what your model already knows. Choosing the “correct” learning rate is somewhat of voodoo magic. We’re using Cross-Entropy loss (known as log loss) to evaluate how well our model is doing. It (harshly) penalizes wrong answers given from classification models, based on the probabilities they give for each class. Here is the definition: where C is the number of classes, y is a binary indicator if the class label is the correct classification for the observation and p is the predicted probability that o is of class c. Note that we request from TensorFlow to record the accuracy metrics. Let’s use fitDataset to train our model using the training and validation datasets we’ve prepared: We train our model for 100 epochs (number of times the whole training set is shown to the model) and record the training logs for visualization using the onEpochEndcallback. We’re going to wrap all of this into a function called trainLogisticRegressionwhich is defined as: Let’s use everything we’ve built so far to evaluate how well our model is doing: Note that we only use the glucose levels for training our model. Here are the results: Not good at all. Our model performs worse than a dummy that predicts healthy 65% of the time. Also, the loss never really starts dropping. Let’s try with more data: Much better, the loss value is reduced significantly during training, and we obtain about 79% accuracy on the validation set. Let’s take a closer look at the classification performance with a confusion matrix: The confusion matrix can be obtained using the model predictions and test set: Even though our model might’ve obtained better accuracy, the results are still horrible. Being healthy is vastly overpredicted compared to having diabetes. What if we try with a more complex model: Here is the confusion matrix for this model: We’ll not look into this model for now, but note that we obtain much better results by increasing the complexity of the model. Congratulations! You built and trained not one, but a couple of models, including Logistic Regression, that predicts whether or not a patient has Diabetes. You’ve also met the real-world — processing data, training and building models, are hard things to do. Moreover, not everything is predictable, no matter how many data points you have. Run the complete source code for this tutorial right in your browser: That said, there are ways to improve the process of building and training models. We know that using some techniques is better than others, in a certain context. Well, Machine Learning is nuanced :) Logistic Regression by Dr. Saed Sayad A Gentle Introduction to TensorFlow.js Originally published at https://www.curiousily.com. Build Machine Learning models (especially Deep Neural Networks) that you can easily integrate with existing or new web apps. Think of your ReactJs, Vue, or Angular app enhanced with the power of Machine Learning models:
[ { "code": null, "e": 274, "s": 46, "text": "TL;DR Build a Logistic Regression model in TensorFlow.js using the high-level layers API, and predict whether or not a patient has Diabetes. Learn how to visualize the data, create a Dataset, train and evaluate multiple models." }, { "code": null, "e": 498, "s": 274, "text": "You’ve been living in this forgotten city for the past 8+ months. You never felt comfortable anywhere but home. However, this place sets a new standard. The constant changes between dry and humid heat are killing you, fast." }, { "code": null, "e": 726, "s": 498, "text": "The Internet connection is spotty at best, and you haven’t heard from your closed ones for more than two weeks. You have no idea how your partner is and how your kids are doing. You sometimes question the love for your country." }, { "code": null, "e": 931, "s": 726, "text": "This morning you feel even worse. Constantly hungry and thirsty. You urinated four times, already, and your vision is somewhat blurry. It is not just today you were feeling like that for a week, at least." }, { "code": null, "e": 1178, "s": 931, "text": "You went to the doctor, and she said you might have Diabetes. Both your mother and father suffer from it, so it seems likely. She wasn’t that sure and did a glucose test. Unfortunately, you’re being called and should go before the results are in." }, { "code": null, "e": 1457, "s": 1178, "text": "You’re going away for two weeks. Only a couple of guys and your laptop! You have a couple of minutes and download a Diabetes patient dataset. You have TensorFlow.js already installed and a copy of the whole API. Can you build a model to predict whether or not you have Diabetes?" }, { "code": null, "e": 1486, "s": 1457, "text": "We're so pumped to have you!" }, { "code": null, "e": 1521, "s": 1486, "text": "\nAlready have an account? Sign In\n" }, { "code": null, "e": 1591, "s": 1521, "text": "Run the complete source code for this tutorial right in your browser:" }, { "code": null, "e": 2130, "s": 1591, "text": "Diabetes mellitus (DM), commonly known as diabetes, is a group of metabolic disorders characterized by high blood sugar levels over a prolonged period. Symptoms of high blood sugar include frequent urination, increased thirst, and increased hunger. If left untreated, diabetes can cause many complications. Acute complications can include diabetic ketoacidosis, hyperosmolar hyperglycemic state, or death. Serious long-term complications include cardiovascular disease, stroke, chronic kidney disease, foot ulcers, and damage to the eyes." }, { "code": null, "e": 2211, "s": 2130, "text": "As of 2017, an estimated 425 million people had diabetes worldwide (around 5.5%)" }, { "code": null, "e": 2354, "s": 2211, "text": "Our data comes from Kaggle but was first introduced in the paper: Using the ADAP Learning Algorithm to Forecast the Onset of Diabetes Mellitus" }, { "code": null, "e": 3114, "s": 2354, "text": "The population for this study was the Pima Indian population near Phoenix, Arizona. That population has been under continuous study since 1965 by the National Institute of Diabetes and Digestive and Kidney Diseases because of its high incidence rate of diabetes. Each community resident over 5 years of age was asked to undergo a standardized examination every two years, which included an oral glucose tolerance test. Diabetes was diagnosed according to World Health Organization Criteria; that is, if the 2 hour post-load plasma glucose was at least 200 mg/dl (11.1 mmol/l) at any survey examination or if the Indian Health Service Hospital serving the community found a glucose concentration of at least 200 mg/dl during the course of routine medical care." }, { "code": null, "e": 3145, "s": 3114, "text": "Here is a summary of the data:" }, { "code": null, "e": 3184, "s": 3145, "text": "Pregnancies - Number of times pregnant" }, { "code": null, "e": 3267, "s": 3184, "text": "Glucose - Plasma glucose concentration a 2 hours in an oral glucose tolerance test" }, { "code": null, "e": 3316, "s": 3267, "text": "BloodPressure - Diastolic blood pressure (mm Hg)" }, { "code": null, "e": 3365, "s": 3316, "text": "SkinThickness - Triceps skin fold thickness (mm)" }, { "code": null, "e": 3406, "s": 3365, "text": "Insulin - 2-Hour serum insulin (mu U/ml)" }, { "code": null, "e": 3476, "s": 3406, "text": "BMI - Body mass index (\\frac{weight}{height^2}height2weight​ in kg/m)" }, { "code": null, "e": 3536, "s": 3476, "text": "DiabetesPedigreeFunction - Diabetes Pedigree Function (DPF)" }, { "code": null, "e": 3554, "s": 3536, "text": "Age - Age (years)" }, { "code": null, "e": 3609, "s": 3554, "text": "Outcome - Class variable (0 - healthy or 1 - diabetic)" }, { "code": null, "e": 3714, "s": 3609, "text": "According to Estimating Probabilities of Diabetes Mellitus Using Neural Networkspaper, the DPF provides:" }, { "code": null, "e": 4070, "s": 3714, "text": "A synthesis of the diabetes mellitus history in relatives and the genetic relationship of those relatives to the subject. The DPF uses information from parents, grandparents, siblings, aunts and uncles, and first cousins. It provides a measure of the expected genetic influence of affected and unaffected relatives on the subject’s eventual diabetes risk." }, { "code": null, "e": 4531, "s": 4070, "text": "The Pima (or Akimel Oʼodham, also spelled Akimel Oʼotham, “River People”, formerly known as Pima) are a group of Native Americans living in an area consisting of what is now central and southern Arizona. The majority population of the surviving two bands of the Akimel Oʼodham are based in two reservations: the Keli Akimel Oʼotham on the Gila River Indian Community (GRIC) and the On’k Akimel Oʼodham on the Salt River Pima-Maricopa Indian Community (SRPMIC)." }, { "code": null, "e": 4667, "s": 4531, "text": "We’ll use the Papa Parse library to read the csv file. Unfortunately, Papa Parse doesn’t work well with await/async. Let’s change that:" }, { "code": null, "e": 4822, "s": 4667, "text": "We use the dynamicTyping parameter to instruct Papa Parse to convert the numbers in the dataset from strings. Let’s define a function that loads the data:" }, { "code": null, "e": 4834, "s": 4822, "text": "and use it:" }, { "code": null, "e": 4888, "s": 4834, "text": "Good job! We have the data, let get familiar with it!" }, { "code": null, "e": 5185, "s": 4888, "text": "While tfjs-vis is nice and well integrated with TensorFlow.js, it lacks (at the time of this writing) a ton of features you might need — overlay plots, color changes, scale customization, etc. That’s why we’ll use Plotly’s Javascript library to make some beautiful plots for our data exploration." }, { "code": null, "e": 5254, "s": 5185, "text": "Let’s have a look at the distribution of healthy vs diabetic people:" }, { "code": null, "e": 5433, "s": 5254, "text": "Little above 65% of the patients in our dataset are healthy. That means that our model should be more accurate than 65% of the time, to be any good. Next up — the insulin levels:" }, { "code": null, "e": 5610, "s": 5433, "text": "Note that there is a big overlap between the two distributions. Also, we have a lot of 0s in the dataset. Seems like we have a lot of missing values. NaNs are replaced with 0s." }, { "code": null, "e": 5670, "s": 5610, "text": "Another important one is the glucose levels after the test:" }, { "code": null, "e": 5781, "s": 5670, "text": "While there is some overlap, this test seems like it separates the healthy from diabetic patients pretty well." }, { "code": null, "e": 5811, "s": 5781, "text": "Let’s have a look at the age:" }, { "code": null, "e": 5892, "s": 5811, "text": "Generally speaking, it seems like older people are more likely to have diabetes." }, { "code": null, "e": 5972, "s": 5892, "text": "Maybe we should take a look at the relationship between age and glucose levels:" }, { "code": null, "e": 6097, "s": 5972, "text": "The combination of those two seems to separate healthy and diabetic patients very well. That might do wonders for our model." }, { "code": null, "e": 6169, "s": 6097, "text": "Another combination you might want to try is the skin thickness vs BMI:" }, { "code": null, "e": 6223, "s": 6169, "text": "Yep, this one is horrible and doesn’t tell us much :)" }, { "code": null, "e": 6485, "s": 6223, "text": "Currently, our data sits in an array of objects. Unfortunately, TensorFlow doesn’t work well with those. Luckily, there is the tfjs-data package. We’re going to create a Dataset from our CSV file and use it to train our model with the createDatasets() function:" }, { "code": null, "e": 6721, "s": 6485, "text": "The features parameter specifies which columns are in the dataset. testSize is the fraction of the data that is going to be used for testing. batchSize controls the number of data points when the dataset is split into chunks (batches)." }, { "code": null, "e": 6775, "s": 6721, "text": "Let’s start by extracting the features from the data:" }, { "code": null, "e": 6905, "s": 6775, "text": "We’re replacing missing values in our features with 0s. You might try to train your model without this step and see what happens?" }, { "code": null, "e": 6931, "s": 6905, "text": "Let’s prepare the labels:" }, { "code": null, "e": 6964, "s": 6931, "text": "Here’s the definition of oneHot:" }, { "code": null, "e": 7161, "s": 6964, "text": "One-hot encoding turns categorical variables (healthy — 0 and diabetic — 1) into an array where 1 corresponds to the position of the category and all other variables are 0. Here are some examples:" }, { "code": null, "e": 7186, "s": 7161, "text": "1; // diabetic =>[0, 1];" }, { "code": null, "e": 7199, "s": 7186, "text": "and healthy:" }, { "code": null, "e": 7223, "s": 7199, "text": "0; // healthy =>[1, 0];" }, { "code": null, "e": 7261, "s": 7223, "text": "Let’s create a Dataset from our data:" }, { "code": null, "e": 7317, "s": 7261, "text": "Note that we also shuffle the data with a seed of 42 :)" }, { "code": null, "e": 7386, "s": 7317, "text": "Finally, let’s split the data into training and validation datasets:" }, { "code": null, "e": 7545, "s": 7386, "text": "We use take to create the training dataset, skip to omit the training examples for the validation dataset and finally, split the data into chunks using batch." }, { "code": null, "e": 7618, "s": 7545, "text": "Additionally, we return data for testing our model (more on this later)." }, { "code": null, "e": 7791, "s": 7618, "text": "Logistic Regression (contrary to its name) allows you to get binary (yes/no) answers from your data. Moreover, it gives you the probability for each answer. Questions like:" }, { "code": null, "e": 7811, "s": 7791, "text": "Is this email spam?" }, { "code": null, "e": 7853, "s": 7811, "text": "Should I ask my boss for a higher salary?" }, { "code": null, "e": 7886, "s": 7853, "text": "Does this patient have diabetes?" }, { "code": null, "e": 7916, "s": 7886, "text": "Is this person a real friend?" }, { "code": null, "e": 7945, "s": 7916, "text": "Does my partner cheat on me?" }, { "code": null, "e": 7971, "s": 7945, "text": "Do I cheat on my partner?" }, { "code": null, "e": 8005, "s": 7971, "text": "Do you get where I am getting at?" }, { "code": null, "e": 8148, "s": 8005, "text": "are answerable using Logistic Regression if sufficient data is available and you’re lucky enough to believe there are answers to all of these?" }, { "code": null, "e": 8283, "s": 8148, "text": "But I digress, let’s have a look at the mathematical formulation of the Logistic Regression. First, let’s start with the Linear Model:" }, { "code": null, "e": 8413, "s": 8283, "text": "where x is the data we’re going to use to train our model, b1​ controls the slope and b0​ the interception point with the y axis." }, { "code": null, "e": 8651, "s": 8413, "text": "We’re going to use the softmax function to get probabilities out of the Linear Model and obtain a generalized model of Logistic Regression. Softmax Regression allows us to create a model with more than 2 output classes (binary response):" }, { "code": null, "e": 8736, "s": 8651, "text": "where b1​ defines the steepness of the curve and b0​ moves the curve left and right." }, { "code": null, "e": 8857, "s": 8736, "text": "We want to use our data X and some training magic to learn the parameters b1​ and b0​. Let’s use TensorFlow.js for that!" }, { "code": null, "e": 9041, "s": 8857, "text": "Note that this model will give us a probabilistic answer instead of just a binary response. You might decide to ignore a prediction if the model is not sure about it — e.g. below 80%." }, { "code": null, "e": 9154, "s": 9041, "text": "Let’s put the theory into practice by building a model into TensorFlow.js and predict the outcome for a patient." }, { "code": null, "e": 9276, "s": 9154, "text": "Remember that the key to building a Logistic Regression model was the Linear Model and applying a softmax function to it:" }, { "code": null, "e": 9492, "s": 9276, "text": "Note that we have 2 outputs because of the one-hot encoding and dynamic input count, based on the features we’ve chosen to train the model. Yes, it is that easy to build a Logistic Regression model in TensorFlow.js." }, { "code": null, "e": 9531, "s": 9492, "text": "The next step is to compile the model:" }, { "code": null, "e": 9713, "s": 9531, "text": "The training process of our model consists of minimizing the loss function. This gets done by the Adam optimizer we’re providing. Note that we’re providing a learning rate of 0.001." }, { "code": null, "e": 9971, "s": 9713, "text": "The learning rate is known as a hyperparameter since it is a parameter you provide for your model to use. It controls how much each new update should “override” what your model already knows. Choosing the “correct” learning rate is somewhat of voodoo magic." }, { "code": null, "e": 10211, "s": 9971, "text": "We’re using Cross-Entropy loss (known as log loss) to evaluate how well our model is doing. It (harshly) penalizes wrong answers given from classification models, based on the probabilities they give for each class. Here is the definition:" }, { "code": null, "e": 10395, "s": 10211, "text": "where C is the number of classes, y is a binary indicator if the class label is the correct classification for the observation and p is the predicted probability that o is of class c." }, { "code": null, "e": 10464, "s": 10395, "text": "Note that we request from TensorFlow to record the accuracy metrics." }, { "code": null, "e": 10563, "s": 10464, "text": "Let’s use fitDataset to train our model using the training and validation datasets we’ve prepared:" }, { "code": null, "e": 10737, "s": 10563, "text": "We train our model for 100 epochs (number of times the whole training set is shown to the model) and record the training logs for visualization using the onEpochEndcallback." }, { "code": null, "e": 10836, "s": 10737, "text": "We’re going to wrap all of this into a function called trainLogisticRegressionwhich is defined as:" }, { "code": null, "e": 10917, "s": 10836, "text": "Let’s use everything we’ve built so far to evaluate how well our model is doing:" }, { "code": null, "e": 11004, "s": 10917, "text": "Note that we only use the glucose levels for training our model. Here are the results:" }, { "code": null, "e": 11169, "s": 11004, "text": "Not good at all. Our model performs worse than a dummy that predicts healthy 65% of the time. Also, the loss never really starts dropping. Let’s try with more data:" }, { "code": null, "e": 11379, "s": 11169, "text": "Much better, the loss value is reduced significantly during training, and we obtain about 79% accuracy on the validation set. Let’s take a closer look at the classification performance with a confusion matrix:" }, { "code": null, "e": 11458, "s": 11379, "text": "The confusion matrix can be obtained using the model predictions and test set:" }, { "code": null, "e": 11656, "s": 11458, "text": "Even though our model might’ve obtained better accuracy, the results are still horrible. Being healthy is vastly overpredicted compared to having diabetes. What if we try with a more complex model:" }, { "code": null, "e": 11701, "s": 11656, "text": "Here is the confusion matrix for this model:" }, { "code": null, "e": 11828, "s": 11701, "text": "We’ll not look into this model for now, but note that we obtain much better results by increasing the complexity of the model." }, { "code": null, "e": 12169, "s": 11828, "text": "Congratulations! You built and trained not one, but a couple of models, including Logistic Regression, that predicts whether or not a patient has Diabetes. You’ve also met the real-world — processing data, training and building models, are hard things to do. Moreover, not everything is predictable, no matter how many data points you have." }, { "code": null, "e": 12239, "s": 12169, "text": "Run the complete source code for this tutorial right in your browser:" }, { "code": null, "e": 12438, "s": 12239, "text": "That said, there are ways to improve the process of building and training models. We know that using some techniques is better than others, in a certain context. Well, Machine Learning is nuanced :)" }, { "code": null, "e": 12476, "s": 12438, "text": "Logistic Regression by Dr. Saed Sayad" }, { "code": null, "e": 12515, "s": 12476, "text": "A Gentle Introduction to TensorFlow.js" }, { "code": null, "e": 12567, "s": 12515, "text": "Originally published at https://www.curiousily.com." } ]
Database Backup from MySQL - GeeksforGeeks
19 Nov, 2019 Here, The database creating now a day is very important for daily work. The database creates from the MySQL that can be transferred from one system to another and also make it secure from the destroy. Sometimes the system gets corrupted by some faults, so the created database is clear. So there is an option to create a backup of a database from the MySQL wamp server. The following is the step to create the backup from the wamp server: Go to the c drive.Open the Wamp server name folder.Open the folder named bin, then open folder the MySQL.Now open the folder mysql5.7.19 (here, 5.7.19 is the version of the wamp server, there is some different version but you should go on that folder only).Then again open the bin folder.Then on the upper, on the address section just type CMD and Enter. Go to the c drive. Open the Wamp server name folder. Open the folder named bin, then open folder the MySQL. Now open the folder mysql5.7.19 (here, 5.7.19 is the version of the wamp server, there is some different version but you should go on that folder only). Then again open the bin folder. Then on the upper, on the address section just type CMD and Enter. Then there is command prompt open with the address of the following step you follow. Then type, mysqldump -u root -p harshitdb >harshitbackup.sql Here, the harshitdb mean the harshit is the database name which created and the db means database. after that, it creates the database and that you be to share and that was save from corrupted or from loss. There is following address link to open the cmd (command prompt) C:\wamp\bin\mysql\mysql5.7.19\bin>mysqldump -u root -p harshitdb > harshitbackup.sql Then press enter. mysql SQLmysql SQL Web Technologies SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SQL Trigger | Student Database CTE in SQL How to Update Multiple Columns in Single Update Statement in SQL? SQL | Views SQL Interview Questions Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 23974, "s": 23946, "text": "\n19 Nov, 2019" }, { "code": null, "e": 24344, "s": 23974, "text": "Here, The database creating now a day is very important for daily work. The database creates from the MySQL that can be transferred from one system to another and also make it secure from the destroy. Sometimes the system gets corrupted by some faults, so the created database is clear. So there is an option to create a backup of a database from the MySQL wamp server." }, { "code": null, "e": 24413, "s": 24344, "text": "The following is the step to create the backup from the wamp server:" }, { "code": null, "e": 24768, "s": 24413, "text": "Go to the c drive.Open the Wamp server name folder.Open the folder named bin, then open folder the MySQL.Now open the folder mysql5.7.19 (here, 5.7.19 is the version of the wamp server, there is some different version but you should go on that folder only).Then again open the bin folder.Then on the upper, on the address section just type CMD and Enter." }, { "code": null, "e": 24787, "s": 24768, "text": "Go to the c drive." }, { "code": null, "e": 24821, "s": 24787, "text": "Open the Wamp server name folder." }, { "code": null, "e": 24876, "s": 24821, "text": "Open the folder named bin, then open folder the MySQL." }, { "code": null, "e": 25029, "s": 24876, "text": "Now open the folder mysql5.7.19 (here, 5.7.19 is the version of the wamp server, there is some different version but you should go on that folder only)." }, { "code": null, "e": 25061, "s": 25029, "text": "Then again open the bin folder." }, { "code": null, "e": 25128, "s": 25061, "text": "Then on the upper, on the address section just type CMD and Enter." }, { "code": null, "e": 25224, "s": 25128, "text": "Then there is command prompt open with the address of the following step you follow. Then type," }, { "code": null, "e": 25275, "s": 25224, "text": "mysqldump -u root -p harshitdb >harshitbackup.sql " }, { "code": null, "e": 25482, "s": 25275, "text": "Here, the harshitdb mean the harshit is the database name which created and the db means database. after that, it creates the database and that you be to share and that was save from corrupted or from loss." }, { "code": null, "e": 25547, "s": 25482, "text": "There is following address link to open the cmd (command prompt)" }, { "code": null, "e": 25633, "s": 25547, "text": "C:\\wamp\\bin\\mysql\\mysql5.7.19\\bin>mysqldump -u root -p harshitdb > harshitbackup.sql " }, { "code": null, "e": 25651, "s": 25633, "text": "Then press enter." }, { "code": null, "e": 25657, "s": 25651, "text": "mysql" }, { "code": null, "e": 25666, "s": 25657, "text": "SQLmysql" }, { "code": null, "e": 25670, "s": 25666, "text": "SQL" }, { "code": null, "e": 25687, "s": 25670, "text": "Web Technologies" }, { "code": null, "e": 25691, "s": 25687, "text": "SQL" }, { "code": null, "e": 25789, "s": 25691, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25820, "s": 25789, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 25831, "s": 25820, "text": "CTE in SQL" }, { "code": null, "e": 25897, "s": 25831, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 25909, "s": 25897, "text": "SQL | Views" }, { "code": null, "e": 25933, "s": 25909, "text": "SQL Interview Questions" }, { "code": null, "e": 25975, "s": 25933, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 26008, "s": 25975, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26051, "s": 26008, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 26101, "s": 26051, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to Deploy a FastAPI App on Heroku for Free | by Shinichi Okada | Towards Data Science
Heroku is a cloud Platform As A Service (PaaS) supporting Ruby on Rails, Java, Node.js, Scala, Clojure, Python, PHP, and Go. Heroku’s free version offers 550–1000 dyno hours per month. Your apps sleep after 30 mins if no one is using your app. Your apps will be always free if your monthly dyno hours is within the limit. The Dynos are isolated, virtualized Linux containers on the Heroku platform. In this article, you will learn how easy it is to set up and run your FastAPI project and making it active 24/7 on Heroku. I’m currently hosting this FastAPI website at Heroku as a demo. Table of Contents· Introduction· Git· Setting up Your Heroku Account· How to Create the requirement.txt for FastAPI on Heroku· runtime.txt· Procfile· Environment Variables· How to Upload to Heroku· How to Add a Subdomain· How to Keep Your App Active 24/7 ∘ cron-job.org· How to fix a failed cron-job ∘ Kaffeine· How to Rename Your App· How to ssh to Heroku· Conclusion· Newsletter· References I use Gitstart to automate the Git initialization. From your terminal, it runs git init. Add .gitignore and README file and commit with a message. This creates a new repo in Github, and it will push all the files. $ mkdir my_new_project$ cd my_new_project$ gitstart Personal accounts are given a base of 550 free dyno hours each month. In addition to these base hours, accounts that verify with a credit card [1] will receive an additional 450 hours added to the monthly free dyno quota. [2] You need to add SSH Keys to Heroku.[3]Install the Heroku CLI [4]Then log in to Heroku from your terminal and create a Heroku app: $ heroku login$ heroku create You can add a custom domain to your Heroku app.[5] Heroku requires the requirement.txt to install your Python packages. pipreqs [6] generates it based on imports in your project. $ pip install pipreqs$ cd my_new_project$ pipreqs ./# if you already have the requirement.txt$ pipreqs --force ./ Since pipreqs generates it based on import, you need to add the following to the requirements.txt manually. uvicorn==0.12.3aiofiles==0.6.0python-multipart==0.0.5jinja2==2.11.2 You need the uvicorn to start an ASGI server on Heroku. You need the aiofiles for your static files. If your project has a form, add the python-multipart. If your project uses a template engine, add the jinja2. Heroku uses the default Python version. In order to use a certain Python version, add runtime.txt with your Python version. For example: python-3.8.6 Heroku requires the Procfile.[7] If you have the main.py in the app directory, add the following: web: uvicorn app.main:app --host=0.0.0.0 --port=${PORT:-5000} If you have the main.py in the root directory: web: uvicorn main:app --host=0.0.0.0 --port=${PORT:-5000} Heroku doesn’t use the .env file. Instead, add values in your .env file to Config Vars. You can find it under the Settings tab. Now you are ready to push your project to Heroku: $ git push heroku main$ heroku open The heroku open command opens your project in your browser. I am using Cloudflare and this is what I had to do. Select CNAME for the type. Add your subdomain name for the Name. Add your Heroku domain for the Content. Your Heroku domain name is something like, serene-example-4269.herokuapp.com. The image below shows how to add toolbox.mywebsite.com subdomain. After 30min of inactivity, the Heroku app goes idle. You can find your app process using heroic ps. You can find the “idle” in the last line. This is my other app process status showing “up”. cron-job.org [8] and Kaffeine [9] provide a free service. Both visit your URL at a scheduled time. You can create a cronjob by adding your URL and Execution schedule. For your cronjob, you need to select Every 15 minutes. If you set it Every 30 minutes, it may delay 5 to 15 seconds. You can edit or delete your cronjob at ease. Your cron-job may fail telling “Response data too big” or “Output too large”. The cron-job.org accepts up to 4 kB of response data from your URL/script. To fix it, you can create an endpoint that returns a JSON string rather than an HTML page. Kaffeine pings your Heroku app every 30 minutes so it will never go to sleep. How to remove your app from Kaffeine The link in the website doesn’t work but if you click the link below it worked for me. http://kaffeine.herokuapp.com/#decaf $ heroku apps:rename new_app_name When you rename your app, don’t forget to update your cron job. You may want to ssh to Heroku. heroku ps:exec does that. $ heroku ps:execEstablishing credentials... doneConnecting to web.1 on ⬢ demo-desuyo...~ $ Heroku provides max of 1000 hrs of free hosting for your project which uses under 512MB of RAM usage. You can use your domain name. If you require SSL on custom domains, you need to upgrade to the Hobby tier. cron-job.org and Kaffeine provide a cronjob to visit your URL to avoid sleeping. Get full access to every story on Medium by becoming a member. Account verificationFree Dyno HoursSSH KeysHeroku CLICustom Domain Names for AppspipreqsProcfilecron-job.orgKaffeine Account verification Free Dyno Hours SSH Keys Heroku CLI Custom Domain Names for Apps
[ { "code": null, "e": 493, "s": 171, "text": "Heroku is a cloud Platform As A Service (PaaS) supporting Ruby on Rails, Java, Node.js, Scala, Clojure, Python, PHP, and Go. Heroku’s free version offers 550–1000 dyno hours per month. Your apps sleep after 30 mins if no one is using your app. Your apps will be always free if your monthly dyno hours is within the limit." }, { "code": null, "e": 570, "s": 493, "text": "The Dynos are isolated, virtualized Linux containers on the Heroku platform." }, { "code": null, "e": 693, "s": 570, "text": "In this article, you will learn how easy it is to set up and run your FastAPI project and making it active 24/7 on Heroku." }, { "code": null, "e": 757, "s": 693, "text": "I’m currently hosting this FastAPI website at Heroku as a demo." }, { "code": null, "e": 1152, "s": 757, "text": "Table of Contents· Introduction· Git· Setting up Your Heroku Account· How to Create the requirement.txt for FastAPI on Heroku· runtime.txt· Procfile· Environment Variables· How to Upload to Heroku· How to Add a Subdomain· How to Keep Your App Active 24/7 ∘ cron-job.org· How to fix a failed cron-job ∘ Kaffeine· How to Rename Your App· How to ssh to Heroku· Conclusion· Newsletter· References" }, { "code": null, "e": 1366, "s": 1152, "text": "I use Gitstart to automate the Git initialization. From your terminal, it runs git init. Add .gitignore and README file and commit with a message. This creates a new repo in Github, and it will push all the files." }, { "code": null, "e": 1418, "s": 1366, "text": "$ mkdir my_new_project$ cd my_new_project$ gitstart" }, { "code": null, "e": 1644, "s": 1418, "text": "Personal accounts are given a base of 550 free dyno hours each month. In addition to these base hours, accounts that verify with a credit card [1] will receive an additional 450 hours added to the monthly free dyno quota. [2]" }, { "code": null, "e": 1774, "s": 1644, "text": "You need to add SSH Keys to Heroku.[3]Install the Heroku CLI [4]Then log in to Heroku from your terminal and create a Heroku app:" }, { "code": null, "e": 1804, "s": 1774, "text": "$ heroku login$ heroku create" }, { "code": null, "e": 1855, "s": 1804, "text": "You can add a custom domain to your Heroku app.[5]" }, { "code": null, "e": 1983, "s": 1855, "text": "Heroku requires the requirement.txt to install your Python packages. pipreqs [6] generates it based on imports in your project." }, { "code": null, "e": 2097, "s": 1983, "text": "$ pip install pipreqs$ cd my_new_project$ pipreqs ./# if you already have the requirement.txt$ pipreqs --force ./" }, { "code": null, "e": 2205, "s": 2097, "text": "Since pipreqs generates it based on import, you need to add the following to the requirements.txt manually." }, { "code": null, "e": 2273, "s": 2205, "text": "uvicorn==0.12.3aiofiles==0.6.0python-multipart==0.0.5jinja2==2.11.2" }, { "code": null, "e": 2484, "s": 2273, "text": "You need the uvicorn to start an ASGI server on Heroku. You need the aiofiles for your static files. If your project has a form, add the python-multipart. If your project uses a template engine, add the jinja2." }, { "code": null, "e": 2621, "s": 2484, "text": "Heroku uses the default Python version. In order to use a certain Python version, add runtime.txt with your Python version. For example:" }, { "code": null, "e": 2634, "s": 2621, "text": "python-3.8.6" }, { "code": null, "e": 2667, "s": 2634, "text": "Heroku requires the Procfile.[7]" }, { "code": null, "e": 2732, "s": 2667, "text": "If you have the main.py in the app directory, add the following:" }, { "code": null, "e": 2794, "s": 2732, "text": "web: uvicorn app.main:app --host=0.0.0.0 --port=${PORT:-5000}" }, { "code": null, "e": 2841, "s": 2794, "text": "If you have the main.py in the root directory:" }, { "code": null, "e": 2899, "s": 2841, "text": "web: uvicorn main:app --host=0.0.0.0 --port=${PORT:-5000}" }, { "code": null, "e": 3027, "s": 2899, "text": "Heroku doesn’t use the .env file. Instead, add values in your .env file to Config Vars. You can find it under the Settings tab." }, { "code": null, "e": 3077, "s": 3027, "text": "Now you are ready to push your project to Heroku:" }, { "code": null, "e": 3113, "s": 3077, "text": "$ git push heroku main$ heroku open" }, { "code": null, "e": 3173, "s": 3113, "text": "The heroku open command opens your project in your browser." }, { "code": null, "e": 3225, "s": 3173, "text": "I am using Cloudflare and this is what I had to do." }, { "code": null, "e": 3408, "s": 3225, "text": "Select CNAME for the type. Add your subdomain name for the Name. Add your Heroku domain for the Content. Your Heroku domain name is something like, serene-example-4269.herokuapp.com." }, { "code": null, "e": 3474, "s": 3408, "text": "The image below shows how to add toolbox.mywebsite.com subdomain." }, { "code": null, "e": 3574, "s": 3474, "text": "After 30min of inactivity, the Heroku app goes idle. You can find your app process using heroic ps." }, { "code": null, "e": 3616, "s": 3574, "text": "You can find the “idle” in the last line." }, { "code": null, "e": 3666, "s": 3616, "text": "This is my other app process status showing “up”." }, { "code": null, "e": 3765, "s": 3666, "text": "cron-job.org [8] and Kaffeine [9] provide a free service. Both visit your URL at a scheduled time." }, { "code": null, "e": 3833, "s": 3765, "text": "You can create a cronjob by adding your URL and Execution schedule." }, { "code": null, "e": 3950, "s": 3833, "text": "For your cronjob, you need to select Every 15 minutes. If you set it Every 30 minutes, it may delay 5 to 15 seconds." }, { "code": null, "e": 3995, "s": 3950, "text": "You can edit or delete your cronjob at ease." }, { "code": null, "e": 4073, "s": 3995, "text": "Your cron-job may fail telling “Response data too big” or “Output too large”." }, { "code": null, "e": 4239, "s": 4073, "text": "The cron-job.org accepts up to 4 kB of response data from your URL/script. To fix it, you can create an endpoint that returns a JSON string rather than an HTML page." }, { "code": null, "e": 4317, "s": 4239, "text": "Kaffeine pings your Heroku app every 30 minutes so it will never go to sleep." }, { "code": null, "e": 4354, "s": 4317, "text": "How to remove your app from Kaffeine" }, { "code": null, "e": 4441, "s": 4354, "text": "The link in the website doesn’t work but if you click the link below it worked for me." }, { "code": null, "e": 4478, "s": 4441, "text": "http://kaffeine.herokuapp.com/#decaf" }, { "code": null, "e": 4512, "s": 4478, "text": "$ heroku apps:rename new_app_name" }, { "code": null, "e": 4576, "s": 4512, "text": "When you rename your app, don’t forget to update your cron job." }, { "code": null, "e": 4633, "s": 4576, "text": "You may want to ssh to Heroku. heroku ps:exec does that." }, { "code": null, "e": 4724, "s": 4633, "text": "$ heroku ps:execEstablishing credentials... doneConnecting to web.1 on ⬢ demo-desuyo...~ $" }, { "code": null, "e": 4933, "s": 4724, "text": "Heroku provides max of 1000 hrs of free hosting for your project which uses under 512MB of RAM usage. You can use your domain name. If you require SSL on custom domains, you need to upgrade to the Hobby tier." }, { "code": null, "e": 5014, "s": 4933, "text": "cron-job.org and Kaffeine provide a cronjob to visit your URL to avoid sleeping." }, { "code": null, "e": 5077, "s": 5014, "text": "Get full access to every story on Medium by becoming a member." }, { "code": null, "e": 5194, "s": 5077, "text": "Account verificationFree Dyno HoursSSH KeysHeroku CLICustom Domain Names for AppspipreqsProcfilecron-job.orgKaffeine" }, { "code": null, "e": 5215, "s": 5194, "text": "Account verification" }, { "code": null, "e": 5231, "s": 5215, "text": "Free Dyno Hours" }, { "code": null, "e": 5240, "s": 5231, "text": "SSH Keys" }, { "code": null, "e": 5251, "s": 5240, "text": "Heroku CLI" } ]
JavaScript Remainder(%) Operator - GeeksforGeeks
22 Apr, 2021 Remainder operator is JavaScript is used to get the remaining value when an operand is divided by another operand. In some languages, % is considered as modulo. Modulo and Remainder work differently when the sign of both the operand is different. In JavaScript remainder takes the sign of the dividend and to get modulo ((a % n) + n) % n should be used instead of a % n. Syntax remainder = var1 % var2 Example 1: This example returns the positive remainder in this case both modulo and remainder will be the same as both operands are positive. Javascript <script> // Initializing variables var a =4 var n = 2 // Calculating remainder var rem = a%n // Calculating modulo var mod = ((a%n)+n)%n // Printing result console.log("Remainder is "+rem) console.log("Modulo is "+mod)</script> Output: "Remainder is 0" "Modulo is 0" Example 2: This example returns negative remainder as dividend is negative. Javascript <script> // Initializing variables var a =-4 var n = 2 // Calculating remainder var rem = a%n // Calculating modulo var mod = ((a%n)+n)%n // Printing result console.log(rem) console.log(mod)</script> Output: -0 0 Example 3: Remainder with Infinity and NaN Javascript <script> // Both operands are NaN console.log(NaN%NaN) // Dividend is NaN console.log(NaN%2) // Dividend is Nan and Divisor is Infinity console.log(NaN%Infinity) // Dividend is Infinity and Divisor is NaN console.log(Infinity%NaN) // Both operands are Infinity console.log(Infinity%Infinity) // Dividend is infinity console.log(Infinity%5)</script> Output: > NaN > NaN > NaN > NaN > NaN > NaN arorakashish0911 javascript-operators Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? Remove elements from a JavaScript Array Installation of Node.js on Linux How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26655, "s": 26627, "text": "\n22 Apr, 2021" }, { "code": null, "e": 26902, "s": 26655, "text": "Remainder operator is JavaScript is used to get the remaining value when an operand is divided by another operand. In some languages, % is considered as modulo. Modulo and Remainder work differently when the sign of both the operand is different." }, { "code": null, "e": 27026, "s": 26902, "text": "In JavaScript remainder takes the sign of the dividend and to get modulo ((a % n) + n) % n should be used instead of a % n." }, { "code": null, "e": 27033, "s": 27026, "text": "Syntax" }, { "code": null, "e": 27057, "s": 27033, "text": "remainder = var1 % var2" }, { "code": null, "e": 27199, "s": 27057, "text": "Example 1: This example returns the positive remainder in this case both modulo and remainder will be the same as both operands are positive." }, { "code": null, "e": 27210, "s": 27199, "text": "Javascript" }, { "code": "<script> // Initializing variables var a =4 var n = 2 // Calculating remainder var rem = a%n // Calculating modulo var mod = ((a%n)+n)%n // Printing result console.log(\"Remainder is \"+rem) console.log(\"Modulo is \"+mod)</script>", "e": 27483, "s": 27210, "text": null }, { "code": null, "e": 27491, "s": 27483, "text": "Output:" }, { "code": null, "e": 27522, "s": 27491, "text": "\"Remainder is 0\"\n\"Modulo is 0\"" }, { "code": null, "e": 27598, "s": 27522, "text": "Example 2: This example returns negative remainder as dividend is negative." }, { "code": null, "e": 27609, "s": 27598, "text": "Javascript" }, { "code": "<script> // Initializing variables var a =-4 var n = 2 // Calculating remainder var rem = a%n // Calculating modulo var mod = ((a%n)+n)%n // Printing result console.log(rem) console.log(mod)</script>", "e": 27854, "s": 27609, "text": null }, { "code": null, "e": 27862, "s": 27854, "text": "Output:" }, { "code": null, "e": 27867, "s": 27862, "text": "-0\n0" }, { "code": null, "e": 27910, "s": 27867, "text": "Example 3: Remainder with Infinity and NaN" }, { "code": null, "e": 27921, "s": 27910, "text": "Javascript" }, { "code": "<script> // Both operands are NaN console.log(NaN%NaN) // Dividend is NaN console.log(NaN%2) // Dividend is Nan and Divisor is Infinity console.log(NaN%Infinity) // Dividend is Infinity and Divisor is NaN console.log(Infinity%NaN) // Both operands are Infinity console.log(Infinity%Infinity) // Dividend is infinity console.log(Infinity%5)</script>", "e": 28331, "s": 27921, "text": null }, { "code": null, "e": 28339, "s": 28331, "text": "Output:" }, { "code": null, "e": 28375, "s": 28339, "text": "> NaN\n> NaN\n> NaN\n> NaN\n> NaN\n> NaN" }, { "code": null, "e": 28392, "s": 28375, "text": "arorakashish0911" }, { "code": null, "e": 28413, "s": 28392, "text": "javascript-operators" }, { "code": null, "e": 28420, "s": 28413, "text": "Picked" }, { "code": null, "e": 28431, "s": 28420, "text": "JavaScript" }, { "code": null, "e": 28448, "s": 28431, "text": "Web Technologies" }, { "code": null, "e": 28546, "s": 28448, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28586, "s": 28546, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28647, "s": 28586, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28688, "s": 28647, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 28710, "s": 28688, "text": "JavaScript | Promises" }, { "code": null, "e": 28764, "s": 28710, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 28804, "s": 28764, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28837, "s": 28804, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28880, "s": 28837, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28930, "s": 28880, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Find the maximum value permutation of a graph - GeeksforGeeks
07 Jun, 2021 Given a graph containing N nodes. For any permutation of nodes P1, P2, P3, ..., PN the value of the permutation is defined as the number of indices which have at least 1 node on the left of it that has an edge to it. Find the maximum value across all permutations.Examples: Input: N = 3, edges[] = {{1, 2}, {2, 3}} Output: 2 Consider the permutation 2 1 3 Node 1 has node 2 on the left of it and there is an edge connecting them in the graph. Node 3 has node 2 on the left of it and there is an edge connecting them in the graph.Input: N = 4, edges[] = {{1, 3}, {2, 4}} Output: 2 Consider the permutation 1 2 3 4 Node 3 has node 1 on the left of it and there is an edge connecting them in the graph. Node 4 has node 2 on the left of it and there is an edge connecting them in the graph. Approach: Let’s start with any node at the beginning, we can follow it up with any node adjacent to it and repeat the process. This resembles a dfs traversal in which every node except the first node has a node before it with which it shares an edge. So for every connected component, the maximum value we can get for the permutation of the nodes of this component is Size of component – 1.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the number of nodes// in the current connected componentint dfs(int x, vector<int> adj[], int vis[]){ // Initialise size to 1 int sz = 1; // Mark the node as visited vis[x] = 1; // Start a dfs for every unvisited // adjacent node for (auto ch : adj[x]) if (!vis[ch]) sz += dfs(ch, adj, vis); // Return the number of nodes in // the current connected component return sz;} // Function to return the maximum value// of the required permutationint maxValue(int n, vector<int> adj[]){ int val = 0; int vis[n + 1] = { 0 }; // For each connected component // add the corresponding value for (int i = 1; i <= n; i++) if (!vis[i]) val += dfs(i, adj, vis) - 1; return val;} // Driver codeint main(){ int n = 3; vector<int> adj[n + 1] = { { 1, 2 }, { 2, 3 } }; cout << maxValue(n, adj); return 0;} // Java implementation of the approachimport java.util.*; class GFG{ static int vis[]; // Function to return the number of nodes// in the current connected componentstatic int dfs(int x, Vector<Vector<Integer>> adj){ // Initialise size to 1 int sz = 1; // Mark the node as visited vis[x] = 1; // Start a dfs for every unvisited // adjacent node for (int i = 0; i < adj.get(x).size(); i++) if (vis[adj.get(x).get(i)] == 0) sz += dfs(adj.get(x).get(i), adj); // Return the number of nodes in // the current connected component return sz;} // Function to return the maximum value// of the required permutationstatic int maxValue(int n, Vector<Vector<Integer>> adj){ int val = 0; vis = new int[n + 1]; for (int i = 0; i < n; i++) vis[i] = 0; // For each connected component // add the corresponding value for (int i = 0; i < n; i++) if (vis[i] == 0) val += dfs(i, adj) - 1; return val;} // Driver codepublic static void main(String args[]){ int n = 3; Vector<Vector<Integer>> adj = new Vector<Vector<Integer>>() ; // create the graph Vector<Integer> v = new Vector<Integer>(); v.add(0); v.add(1); Vector<Integer> v1 = new Vector<Integer>(); v1.add(1); v1.add(2); adj.add(v); adj.add(v1); adj.add(new Vector<Integer>()); System.out.println( maxValue(n, adj));}} // This code is contributed by Arnab Kundu # Python3 implementation of the approach # Function to return the number of nodes# in the current connected componentdef dfs(x, adj, vis): # Initialise size to 1 sz = 1 # Mark the node as visited vis[x] = 1 # Start a dfs for every unvisited # adjacent node for ch in adj: if (not vis[ch]): sz += dfs(ch, adj, vis) # Return the number of nodes in # the current connected component return sz # Function to return the maximum value# of the required permutationdef maxValue(n, adj): val = 0 vis = [0] * (n + 1) # For each connected component # add the corresponding value for i in range(1, n + 1): if (not vis[i]): val += dfs(i, adj, vis) - 1 return val # Driver Codeif __name__ == '__main__': n = 3 adj = [1, 2 , 2, 3] print(maxValue(n, adj)) # This code is contributed by# SHUBHAMSINGH10 // C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ static int []vis ; // Function to return the number of nodes// in the current connected componentstatic int dfs(int x, List<List<int>> adj){ // Initialise size to 1 int sz = 1; // Mark the node as visited vis[x] = 1; // Start a dfs for every unvisited // adjacent node for (int i = 0; i < adj[x].Count; i++) if (vis[adj[x][i]] == 0) sz += dfs(adj[x][i], adj); // Return the number of nodes in // the current connected component return sz;} // Function to return the maximum value// of the required permutationstatic int maxValue(int n, List<List<int>> adj){ int val = 0; vis = new int[n + 1]; for (int i = 0; i < n; i++) vis[i] = 0; // For each connected component // add the corresponding value for (int i = 0; i < n; i++) if (vis[i] == 0) val += dfs(i, adj) - 1; return val;} // Driver codepublic static void Main(String []args){ int n = 3; List<List<int>> adj = new List<List<int>>() ; // create the graph List<int> v = new List<int>(); v.Add(0); v.Add(1); List<int> v1 = new List<int>(); v1.Add(1); v1.Add(2); adj.Add(v); adj.Add(v1); adj.Add(new List<int>()); Console.WriteLine( maxValue(n, adj));}} // This code is contributed by Rajput-Ji <script> // Javascript implementation of the approach // Function to return the number of nodes// in the current connected componentfunction dfs(x, adj, vis){ if(x>1) return 1; // Initialise size to 1 var sz = 1; // Mark the node as visited vis[x] = 1; // Start a dfs for every unvisited // adjacent node adj[x].forEach(ch => { if (!vis[ch]) sz += dfs(ch, adj, vis); }); // Return the number of nodes in // the current connected component return sz;} // Function to return the maximum value// of the required permutationfunction maxValue(n, adj){ var val = 0; var vis = Array(n+1).fill(0); // For each connected component // add the corresponding value for (var i = 0; i < n; i++) if (!vis[i]) val += dfs(i, adj, vis) - 1; return val;} // Driver codevar n = 2;var adj = [ [ 0, 1 ], [ 1, 2] ];document.write( maxValue(n, adj)); // This code is contributed by famously.</script> 2 Time Complexity: O(N) andrew1234 SHUBHAMSINGH10 Rajput-Ji famously DFS Algorithms Graph DFS Graph Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments DSA Sheet by Love Babbar Quadratic Probing in Hashing SCAN (Elevator) Disk Scheduling Algorithms K means Clustering - Introduction Difference between Informed and Uninformed Search in AI Breadth First Search or BFS for a Graph Dijkstra's shortest path algorithm | Greedy Algo-7 Depth First Search or DFS for a Graph Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
[ { "code": null, "e": 24666, "s": 24638, "text": "\n07 Jun, 2021" }, { "code": null, "e": 24942, "s": 24666, "text": "Given a graph containing N nodes. For any permutation of nodes P1, P2, P3, ..., PN the value of the permutation is defined as the number of indices which have at least 1 node on the left of it that has an edge to it. Find the maximum value across all permutations.Examples: " }, { "code": null, "e": 25457, "s": 24942, "text": "Input: N = 3, edges[] = {{1, 2}, {2, 3}} Output: 2 Consider the permutation 2 1 3 Node 1 has node 2 on the left of it and there is an edge connecting them in the graph. Node 3 has node 2 on the left of it and there is an edge connecting them in the graph.Input: N = 4, edges[] = {{1, 3}, {2, 4}} Output: 2 Consider the permutation 1 2 3 4 Node 3 has node 1 on the left of it and there is an edge connecting them in the graph. Node 4 has node 2 on the left of it and there is an edge connecting them in the graph. " }, { "code": null, "e": 25902, "s": 25459, "text": "Approach: Let’s start with any node at the beginning, we can follow it up with any node adjacent to it and repeat the process. This resembles a dfs traversal in which every node except the first node has a node before it with which it shares an edge. So for every connected component, the maximum value we can get for the permutation of the nodes of this component is Size of component – 1.Below is the implementation of the above approach: " }, { "code": null, "e": 25906, "s": 25902, "text": "C++" }, { "code": null, "e": 25911, "s": 25906, "text": "Java" }, { "code": null, "e": 25919, "s": 25911, "text": "Python3" }, { "code": null, "e": 25922, "s": 25919, "text": "C#" }, { "code": null, "e": 25933, "s": 25922, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the number of nodes// in the current connected componentint dfs(int x, vector<int> adj[], int vis[]){ // Initialise size to 1 int sz = 1; // Mark the node as visited vis[x] = 1; // Start a dfs for every unvisited // adjacent node for (auto ch : adj[x]) if (!vis[ch]) sz += dfs(ch, adj, vis); // Return the number of nodes in // the current connected component return sz;} // Function to return the maximum value// of the required permutationint maxValue(int n, vector<int> adj[]){ int val = 0; int vis[n + 1] = { 0 }; // For each connected component // add the corresponding value for (int i = 1; i <= n; i++) if (!vis[i]) val += dfs(i, adj, vis) - 1; return val;} // Driver codeint main(){ int n = 3; vector<int> adj[n + 1] = { { 1, 2 }, { 2, 3 } }; cout << maxValue(n, adj); return 0;}", "e": 26926, "s": 25933, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG{ static int vis[]; // Function to return the number of nodes// in the current connected componentstatic int dfs(int x, Vector<Vector<Integer>> adj){ // Initialise size to 1 int sz = 1; // Mark the node as visited vis[x] = 1; // Start a dfs for every unvisited // adjacent node for (int i = 0; i < adj.get(x).size(); i++) if (vis[adj.get(x).get(i)] == 0) sz += dfs(adj.get(x).get(i), adj); // Return the number of nodes in // the current connected component return sz;} // Function to return the maximum value// of the required permutationstatic int maxValue(int n, Vector<Vector<Integer>> adj){ int val = 0; vis = new int[n + 1]; for (int i = 0; i < n; i++) vis[i] = 0; // For each connected component // add the corresponding value for (int i = 0; i < n; i++) if (vis[i] == 0) val += dfs(i, adj) - 1; return val;} // Driver codepublic static void main(String args[]){ int n = 3; Vector<Vector<Integer>> adj = new Vector<Vector<Integer>>() ; // create the graph Vector<Integer> v = new Vector<Integer>(); v.add(0); v.add(1); Vector<Integer> v1 = new Vector<Integer>(); v1.add(1); v1.add(2); adj.add(v); adj.add(v1); adj.add(new Vector<Integer>()); System.out.println( maxValue(n, adj));}} // This code is contributed by Arnab Kundu", "e": 28379, "s": 26926, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the number of nodes# in the current connected componentdef dfs(x, adj, vis): # Initialise size to 1 sz = 1 # Mark the node as visited vis[x] = 1 # Start a dfs for every unvisited # adjacent node for ch in adj: if (not vis[ch]): sz += dfs(ch, adj, vis) # Return the number of nodes in # the current connected component return sz # Function to return the maximum value# of the required permutationdef maxValue(n, adj): val = 0 vis = [0] * (n + 1) # For each connected component # add the corresponding value for i in range(1, n + 1): if (not vis[i]): val += dfs(i, adj, vis) - 1 return val # Driver Codeif __name__ == '__main__': n = 3 adj = [1, 2 , 2, 3] print(maxValue(n, adj)) # This code is contributed by# SHUBHAMSINGH10", "e": 29264, "s": 28379, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ static int []vis ; // Function to return the number of nodes// in the current connected componentstatic int dfs(int x, List<List<int>> adj){ // Initialise size to 1 int sz = 1; // Mark the node as visited vis[x] = 1; // Start a dfs for every unvisited // adjacent node for (int i = 0; i < adj[x].Count; i++) if (vis[adj[x][i]] == 0) sz += dfs(adj[x][i], adj); // Return the number of nodes in // the current connected component return sz;} // Function to return the maximum value// of the required permutationstatic int maxValue(int n, List<List<int>> adj){ int val = 0; vis = new int[n + 1]; for (int i = 0; i < n; i++) vis[i] = 0; // For each connected component // add the corresponding value for (int i = 0; i < n; i++) if (vis[i] == 0) val += dfs(i, adj) - 1; return val;} // Driver codepublic static void Main(String []args){ int n = 3; List<List<int>> adj = new List<List<int>>() ; // create the graph List<int> v = new List<int>(); v.Add(0); v.Add(1); List<int> v1 = new List<int>(); v1.Add(1); v1.Add(2); adj.Add(v); adj.Add(v1); adj.Add(new List<int>()); Console.WriteLine( maxValue(n, adj));}} // This code is contributed by Rajput-Ji", "e": 30661, "s": 29264, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to return the number of nodes// in the current connected componentfunction dfs(x, adj, vis){ if(x>1) return 1; // Initialise size to 1 var sz = 1; // Mark the node as visited vis[x] = 1; // Start a dfs for every unvisited // adjacent node adj[x].forEach(ch => { if (!vis[ch]) sz += dfs(ch, adj, vis); }); // Return the number of nodes in // the current connected component return sz;} // Function to return the maximum value// of the required permutationfunction maxValue(n, adj){ var val = 0; var vis = Array(n+1).fill(0); // For each connected component // add the corresponding value for (var i = 0; i < n; i++) if (!vis[i]) val += dfs(i, adj, vis) - 1; return val;} // Driver codevar n = 2;var adj = [ [ 0, 1 ], [ 1, 2] ];document.write( maxValue(n, adj)); // This code is contributed by famously.</script>", "e": 31657, "s": 30661, "text": null }, { "code": null, "e": 31659, "s": 31657, "text": "2" }, { "code": null, "e": 31684, "s": 31661, "text": "Time Complexity: O(N) " }, { "code": null, "e": 31695, "s": 31684, "text": "andrew1234" }, { "code": null, "e": 31710, "s": 31695, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 31720, "s": 31710, "text": "Rajput-Ji" }, { "code": null, "e": 31729, "s": 31720, "text": "famously" }, { "code": null, "e": 31733, "s": 31729, "text": "DFS" }, { "code": null, "e": 31744, "s": 31733, "text": "Algorithms" }, { "code": null, "e": 31750, "s": 31744, "text": "Graph" }, { "code": null, "e": 31754, "s": 31750, "text": "DFS" }, { "code": null, "e": 31760, "s": 31754, "text": "Graph" }, { "code": null, "e": 31771, "s": 31760, "text": "Algorithms" }, { "code": null, "e": 31869, "s": 31771, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31878, "s": 31869, "text": "Comments" }, { "code": null, "e": 31891, "s": 31878, "text": "Old Comments" }, { "code": null, "e": 31916, "s": 31891, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 31945, "s": 31916, "text": "Quadratic Probing in Hashing" }, { "code": null, "e": 31988, "s": 31945, "text": "SCAN (Elevator) Disk Scheduling Algorithms" }, { "code": null, "e": 32022, "s": 31988, "text": "K means Clustering - Introduction" }, { "code": null, "e": 32078, "s": 32022, "text": "Difference between Informed and Uninformed Search in AI" }, { "code": null, "e": 32118, "s": 32078, "text": "Breadth First Search or BFS for a Graph" }, { "code": null, "e": 32169, "s": 32118, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 32207, "s": 32169, "text": "Depth First Search or DFS for a Graph" }, { "code": null, "e": 32265, "s": 32207, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" } ]
Python PIL | ImageOps.expand() method
16 Sep, 2021 PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. the ImageOps module contains a number of ‘ready-made’ image processing operations. This module is somewhat experimental, and most operators only work on L and RGB images.ImageOps.expand() adds a border to the image upon which this function is called or used. Syntax: PIL.ImageOps.expand(image, border = 0, fill = 0)Parameters: image : The image to size and crop. border : The border to be applied to the image in pixels. fill: This defines the pixel fill value or color value to be applied. The default value is 0 which means the color is black.Returns: An image with the required border. Below is the implementation of ImageOps.expand()Image used: Python3 # Importing Image and ImageOps module from PIL packagefrom PIL import Image, ImageOps # creating a image1 objectim1 = Image.open(r"C:\Users\System-Pc\Desktop\a.jpg") # applying expand method# using border value = 20# using fill = 50 which is brown type colorim2 = ImageOps.expand(im1, border = 20, fill = 50) im2.show() Output: simmytarika5 Python-pil 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 Check if element exists in list in Python Python | os.path.join() method How To Convert Python Dictionary To JSON? Python | Get unique values from a list Defaultdict in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Sep, 2021" }, { "code": null, "e": 393, "s": 28, "text": "PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. the ImageOps module contains a number of ‘ready-made’ image processing operations. This module is somewhat experimental, and most operators only work on L and RGB images.ImageOps.expand() adds a border to the image upon which this function is called or used. " }, { "code": null, "e": 725, "s": 393, "text": "Syntax: PIL.ImageOps.expand(image, border = 0, fill = 0)Parameters: image : The image to size and crop. border : The border to be applied to the image in pixels. fill: This defines the pixel fill value or color value to be applied. The default value is 0 which means the color is black.Returns: An image with the required border. " }, { "code": null, "e": 787, "s": 725, "text": "Below is the implementation of ImageOps.expand()Image used: " }, { "code": null, "e": 797, "s": 789, "text": "Python3" }, { "code": "# Importing Image and ImageOps module from PIL packagefrom PIL import Image, ImageOps # creating a image1 objectim1 = Image.open(r\"C:\\Users\\System-Pc\\Desktop\\a.jpg\") # applying expand method# using border value = 20# using fill = 50 which is brown type colorim2 = ImageOps.expand(im1, border = 20, fill = 50) im2.show()", "e": 1125, "s": 797, "text": null }, { "code": null, "e": 1135, "s": 1125, "text": "Output: " }, { "code": null, "e": 1150, "s": 1137, "text": "simmytarika5" }, { "code": null, "e": 1161, "s": 1150, "text": "Python-pil" }, { "code": null, "e": 1168, "s": 1161, "text": "Python" }, { "code": null, "e": 1266, "s": 1168, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1298, "s": 1266, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1325, "s": 1298, "text": "Python Classes and Objects" }, { "code": null, "e": 1346, "s": 1325, "text": "Python OOPs Concepts" }, { "code": null, "e": 1369, "s": 1346, "text": "Introduction To PYTHON" }, { "code": null, "e": 1425, "s": 1369, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1467, "s": 1425, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1498, "s": 1467, "text": "Python | os.path.join() method" }, { "code": null, "e": 1540, "s": 1498, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1579, "s": 1540, "text": "Python | Get unique values from a list" } ]
Number of pairs with maximum sum
14 Jun, 2022 Given an array arr[], count number of pairs arr[i], arr[j] such that arr[i] + arr[j] is maximum and i < j. Example : Input : arr[] = {1, 1, 1, 2, 2, 2} Output : 3 Explanation: The maximum possible pair sum where i<j is 4, which is given by 3 pairs, so the answer is 3 the pairs are (2, 2), (2, 2) and (2, 2) Input : arr[] = {1, 4, 3, 3, 5, 1} Output : 1 Explanation: The pair 4, 5 yields the maximum sum i.e, 9 which is given by 1 pair only Method 1 (Naive) Traverse a loop i from 0 to n, i.e length of the array and another loop j from i+1 to n to find all possible pairs with i<j. Find the pair with the maximum possible sum, again traverse for all pairs and keep the count of the number of pairs which gives the pair sum equal to maximum C++ Java Python3 C# PHP Javascript // CPP program to count pairs with maximum sum.#include <bits/stdc++.h>using namespace std; // function to find the number of maximum pair sumsint sum(int a[], int n){ // traverse through all the pairs int maxSum = INT_MIN; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) maxSum = max(maxSum, a[i] + a[j]); // traverse through all pairs and keep a count // of the number of maximum pairs int c = 0; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (a[i] + a[j] == maxSum) c++; return c;} // driver program to test the above functionint main(){ int array[] = { 1, 1, 1, 2, 2, 2 }; int n = sizeof(array) / sizeof(array[0]); cout << sum(array, n); return 0;} // Java program to count pairs// with maximum sum.class GFG { // function to find the number of// maximum pair sumsstatic int sum(int a[], int n){ // traverse through all the pairs int maxSum = Integer.MIN_VALUE; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) maxSum = Math.max(maxSum, a[i] + a[j]); // traverse through all pairs and // keep a count of the number of // maximum pairs int c = 0; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (a[i] + a[j] == maxSum) c++; return c;} // driver program to test the above functionpublic static void main(String[] args){ int array[] = { 1, 1, 1, 2, 2, 2 }; int n = array.length; System.out.println(sum(array, n));}} // This code is contributed by Prerna Saini # Python program to count pairs with# maximum sum def _sum( a, n): # traverse through all the pairs maxSum = -9999999 for i in range(n): for j in range(n): maxSum = max(maxSum, a[i] + a[j]) # traverse through all pairs and # keep a count of the number # of maximum pairs c = 0 for i in range(n): for j in range(i+1, n): if a[i] + a[j] == maxSum: c+=1 return c # driver codearray = [ 1, 1, 1, 2, 2, 2 ]n = len(array)print(_sum(array, n)) # This code is contributed by "Abhishek Sharma 44" // C# program to count pairs// with maximum sum.using System; class GFG { // function to find the number of // maximum pair sums static int sum(int []a, int n) { // traverse through all the pairs int maxSum = int.MinValue; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) maxSum = Math.Max(maxSum, a[i] + a[j]); // traverse through all pairs and // keep a count of the number of // maximum pairs int c = 0; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (a[i] + a[j] == maxSum) c++; return c; } // driver program to test the above // function public static void Main() { int []array = { 1, 1, 1, 2, 2, 2 }; int n = array.Length; Console.WriteLine(sum(array, n)); }} // This code is contributed by anuj_67. <?php// PHP program to count pairs// with maximum sum. // function to find the number// of maximum pair sumfunction sum( $a, $n){ // traverse through all // the pairs $maxSum = PHP_INT_MIN; for($i = 0; $i < $n; $i++) for($j = $i + 1; $j < $n; $j++) $maxSum = max($maxSum, $a[$i] + $a[$j]); // traverse through all // pairs and keep a count // of the number of // maximum pairs $c = 0; for($i = 0; $i < $n; $i++) for($j = $i + 1; $j < $n; $j++) if ($a[$i] + $a[$j] == $maxSum) $c++; return $c;} // Driver Code $array = array(1, 1, 1, 2, 2, 2); $n = count($array); echo sum($array, $n); // This code is contributed by anuj_67.?> <script> // JavaScript program to count pairs// with maximum sum. // Function to find the number of// maximum pair sumsfunction sum(a, n){ // traverse through all the pairs let maxSum = Number.MIN_VALUE; for(let i = 0; i < n; i++) for(let j = i + 1; j < n; j++) maxSum = Math.max(maxSum, a[i] + a[j]); // Traverse through all pairs and // keep a count of the number of // maximum pairs let c = 0; for(let i = 0; i < n; i++) for(let j = i + 1; j < n; j++) if (a[i] + a[j] == maxSum) c++; return c;} // Driver Codelet array = [ 1, 1, 1, 2, 2, 2 ];let n = array.length; document.write(sum(array, n)); // This code is contributed by code_hunt </script> Output : 3 Time complexity: O(n2) Auxiliary Space: O(1) Method 2 (Efficient) If we take a closer look, we can notice following facts. Maximum element is always part of solutionIf maximum element appears more than once, then result is maxCount * (maxCount – 1)/2. We basically need to choose 2 elements from maxCount (maxCountC2).If maximum element appears once, then result is equal to count of second maximum element. We can form a pair with every second max and max Maximum element is always part of solution If maximum element appears more than once, then result is maxCount * (maxCount – 1)/2. We basically need to choose 2 elements from maxCount (maxCountC2). If maximum element appears once, then result is equal to count of second maximum element. We can form a pair with every second max and max C++ Java Python3 C# PHP Javascript // CPP program to count pairs with maximum sum.#include <bits/stdc++.h>using namespace std; // function to find the number of maximum pair sumsint sum(int a[], int n){ // Find maximum and second maximum elements. // Also find their counts. int maxVal = a[0], maxCount = 1; int secondMax = INT_MIN, secondMaxCount; for (int i = 1; i < n; i++) { if (a[i] == maxVal) maxCount++; else if (a[i] > maxVal) { secondMax = maxVal; secondMaxCount = maxCount; maxVal = a[i]; maxCount = 1; } else if (a[i] == secondMax) { secondMax = a[i]; secondMaxCount++; } else if (a[i] > secondMax) { secondMax = a[i]; secondMaxCount = 1; } } // If maximum element appears more than once. if (maxCount > 1) return maxCount * (maxCount - 1) / 2; // If maximum element appears only once. return secondMaxCount;} // driver program to test the above functionint main(){ int array[] = { 1, 1, 1, 2, 2, 2, 3 }; int n = sizeof(array) / sizeof(array[0]); cout << sum(array, n); return 0;} // Java program to count pairs// with maximum sum.import java.io.*;class GFG { // function to find the number// of maximum pair sumsstatic int sum(int a[], int n){ // Find maximum and second maximum // elements. Also find their counts. int maxVal = a[0], maxCount = 1; int secondMax = Integer.MIN_VALUE, secondMaxCount = 0; for (int i = 1; i < n; i++) { if (a[i] == maxVal) maxCount++; else if (a[i] > maxVal) { secondMax = maxVal; secondMaxCount = maxCount; maxVal = a[i]; maxCount = 1; } else if (a[i] == secondMax) { secondMax = a[i]; secondMaxCount++; } else if (a[i] > secondMax) { secondMax = a[i]; secondMaxCount = 1; } } // If maximum element appears // more than once. if (maxCount > 1) return maxCount * (maxCount - 1) / 2; // If maximum element appears // only once. return secondMaxCount;} // driver programpublic static void main(String[] args){ int array[] = { 1, 1, 1, 2, 2, 2, 3 }; int n = array.length; System.out.println(sum(array, n));}} // This code is contributed by Prerna Saini # Python 3 program to count# pairs with maximum sum.import sys # Function to find the number# of maximum pair sumsdef sum(a, n): # Find maximum and second maximum elements. # Also find their counts. maxVal = a[0]; maxCount = 1 secondMax = sys.maxsize for i in range(1, n) : if (a[i] == maxVal) : maxCount += 1 elif (a[i] > maxVal) : secondMax = maxVal secondMaxCount = maxCount maxVal = a[i] maxCount = 1 elif (a[i] == secondMax) : secondMax = a[i] secondMaxCount += 1 elif (a[i] > secondMax) : secondMax = a[i] secondMaxCount = 1 # If maximum element appears more than once. if (maxCount > 1): return maxCount * (maxCount - 1) / 2 # If maximum element appears only once. return secondMaxCount # Driver Codearray = [1, 1, 1, 2, 2, 2, 3]n = len(array)print(sum(array, n)) # This code is contributed by Smitha Dinesh Semwal // C# program to count pairs with maximum// sum.using System; class GFG { // function to find the number // of maximum pair sums static int sum(int []a, int n) { // Find maximum and second maximum // elements. Also find their counts. int maxVal = a[0], maxCount = 1; int secondMax = int.MinValue; int secondMaxCount = 0; for (int i = 1; i < n; i++) { if (a[i] == maxVal) maxCount++; else if (a[i] > maxVal) { secondMax = maxVal; secondMaxCount = maxCount; maxVal = a[i]; maxCount = 1; } else if (a[i] == secondMax) { secondMax = a[i]; secondMaxCount++; } else if (a[i] > secondMax) { secondMax = a[i]; secondMaxCount = 1; } } // If maximum element appears // more than once. if (maxCount > 1) return maxCount * (maxCount - 1) / 2; // If maximum element appears // only once. return secondMaxCount; } // driver program public static void Main() { int []array = { 1, 1, 1, 2, 2, 2, 3 }; int n = array.Length; Console.WriteLine(sum(array, n)); }} // This code is contributed by anuj_67. <?php// PHP program to count// pairs with maximum sum. // function to find the number// of maximum pair sumsfunction sum( $a, $n){ // Find maximum and second // maximum elements. Also // find their counts. $maxVal = $a[0]; $maxCount = 1; $secondMax = PHP_INT_MIN; $secondMaxCount; for ( $i = 1; $i < $n; $i++) { if ($a[$i] == $maxVal) $maxCount++; else if ($a[$i] > $maxVal) { $secondMax = $maxVal; $secondMaxCount = $maxCount; $maxVal = $a[$i]; $maxCount = 1; } else if ($a[$i] == $secondMax) { $secondMax = $a[$i]; $secondMaxCount++; } else if ($a[$i] > $secondMax) { $secondMax = $a[$i]; $secondMaxCount = 1; } } // If maximum element appears // more than once. if ($maxCount > 1) return $maxCount * ($maxCount - 1) / 2; // If maximum element // appears only once. return $secondMaxCount;} // Driver Code$array = array(1, 1, 1, 2, 2, 2, 3 );$n = count($array);echo sum($array, $n); // This code is contributed by anuj_67.?> <script> // Javascript program to count pairs with maximum sum. // function to find the number // of maximum pair sums function sum(a, n) { // Find maximum and second maximum // elements. Also find their counts. let maxVal = a[0], maxCount = 1; let secondMax = Number.MIN_VALUE; let secondMaxCount = 0; for (let i = 1; i < n; i++) { if (a[i] == maxVal) maxCount++; else if (a[i] > maxVal) { secondMax = maxVal; secondMaxCount = maxCount; maxVal = a[i]; maxCount = 1; } else if (a[i] == secondMax) { secondMax = a[i]; secondMaxCount++; } else if (a[i] > secondMax) { secondMax = a[i]; secondMaxCount = 1; } } // If maximum element appears // more than once. if (maxCount > 1) return maxCount * parseInt((maxCount - 1) / 2, 10); // If maximum element appears // only once. return secondMaxCount; } let array = [ 1, 1, 1, 2, 2, 2, 3 ]; let n = array.length; document.write(sum(array, n)); // This code is contributed by divyesh072019.</script> Output : 3 Time complexity: O(n) Auxiliary Space: O(1) vt_m code_hunt divyesh072019 _shinchancode Arrays Searching Arrays Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n14 Jun, 2022" }, { "code": null, "e": 159, "s": 52, "text": "Given an array arr[], count number of pairs arr[i], arr[j] such that arr[i] + arr[j] is maximum and i < j." }, { "code": null, "e": 500, "s": 159, "text": "Example :\nInput : arr[] = {1, 1, 1, 2, 2, 2}\nOutput : 3\nExplanation: The maximum possible pair \nsum where i<j is 4, which is given \nby 3 pairs, so the answer is 3\nthe pairs are (2, 2), (2, 2) and (2, 2)\n\nInput : arr[] = {1, 4, 3, 3, 5, 1}\nOutput : 1\nExplanation: The pair 4, 5 yields the \nmaximum sum i.e, 9 which is given by 1 pair only" }, { "code": null, "e": 801, "s": 500, "text": "Method 1 (Naive) Traverse a loop i from 0 to n, i.e length of the array and another loop j from i+1 to n to find all possible pairs with i<j. Find the pair with the maximum possible sum, again traverse for all pairs and keep the count of the number of pairs which gives the pair sum equal to maximum " }, { "code": null, "e": 805, "s": 801, "text": "C++" }, { "code": null, "e": 810, "s": 805, "text": "Java" }, { "code": null, "e": 818, "s": 810, "text": "Python3" }, { "code": null, "e": 821, "s": 818, "text": "C#" }, { "code": null, "e": 825, "s": 821, "text": "PHP" }, { "code": null, "e": 836, "s": 825, "text": "Javascript" }, { "code": "// CPP program to count pairs with maximum sum.#include <bits/stdc++.h>using namespace std; // function to find the number of maximum pair sumsint sum(int a[], int n){ // traverse through all the pairs int maxSum = INT_MIN; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) maxSum = max(maxSum, a[i] + a[j]); // traverse through all pairs and keep a count // of the number of maximum pairs int c = 0; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (a[i] + a[j] == maxSum) c++; return c;} // driver program to test the above functionint main(){ int array[] = { 1, 1, 1, 2, 2, 2 }; int n = sizeof(array) / sizeof(array[0]); cout << sum(array, n); return 0;}", "e": 1606, "s": 836, "text": null }, { "code": "// Java program to count pairs// with maximum sum.class GFG { // function to find the number of// maximum pair sumsstatic int sum(int a[], int n){ // traverse through all the pairs int maxSum = Integer.MIN_VALUE; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) maxSum = Math.max(maxSum, a[i] + a[j]); // traverse through all pairs and // keep a count of the number of // maximum pairs int c = 0; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (a[i] + a[j] == maxSum) c++; return c;} // driver program to test the above functionpublic static void main(String[] args){ int array[] = { 1, 1, 1, 2, 2, 2 }; int n = array.length; System.out.println(sum(array, n));}} // This code is contributed by Prerna Saini", "e": 2463, "s": 1606, "text": null }, { "code": "# Python program to count pairs with# maximum sum def _sum( a, n): # traverse through all the pairs maxSum = -9999999 for i in range(n): for j in range(n): maxSum = max(maxSum, a[i] + a[j]) # traverse through all pairs and # keep a count of the number # of maximum pairs c = 0 for i in range(n): for j in range(i+1, n): if a[i] + a[j] == maxSum: c+=1 return c # driver codearray = [ 1, 1, 1, 2, 2, 2 ]n = len(array)print(_sum(array, n)) # This code is contributed by \"Abhishek Sharma 44\"", "e": 3035, "s": 2463, "text": null }, { "code": "// C# program to count pairs// with maximum sum.using System; class GFG { // function to find the number of // maximum pair sums static int sum(int []a, int n) { // traverse through all the pairs int maxSum = int.MinValue; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) maxSum = Math.Max(maxSum, a[i] + a[j]); // traverse through all pairs and // keep a count of the number of // maximum pairs int c = 0; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (a[i] + a[j] == maxSum) c++; return c; } // driver program to test the above // function public static void Main() { int []array = { 1, 1, 1, 2, 2, 2 }; int n = array.Length; Console.WriteLine(sum(array, n)); }} // This code is contributed by anuj_67.", "e": 4011, "s": 3035, "text": null }, { "code": "<?php// PHP program to count pairs// with maximum sum. // function to find the number// of maximum pair sumfunction sum( $a, $n){ // traverse through all // the pairs $maxSum = PHP_INT_MIN; for($i = 0; $i < $n; $i++) for($j = $i + 1; $j < $n; $j++) $maxSum = max($maxSum, $a[$i] + $a[$j]); // traverse through all // pairs and keep a count // of the number of // maximum pairs $c = 0; for($i = 0; $i < $n; $i++) for($j = $i + 1; $j < $n; $j++) if ($a[$i] + $a[$j] == $maxSum) $c++; return $c;} // Driver Code $array = array(1, 1, 1, 2, 2, 2); $n = count($array); echo sum($array, $n); // This code is contributed by anuj_67.?>", "e": 4745, "s": 4011, "text": null }, { "code": "<script> // JavaScript program to count pairs// with maximum sum. // Function to find the number of// maximum pair sumsfunction sum(a, n){ // traverse through all the pairs let maxSum = Number.MIN_VALUE; for(let i = 0; i < n; i++) for(let j = i + 1; j < n; j++) maxSum = Math.max(maxSum, a[i] + a[j]); // Traverse through all pairs and // keep a count of the number of // maximum pairs let c = 0; for(let i = 0; i < n; i++) for(let j = i + 1; j < n; j++) if (a[i] + a[j] == maxSum) c++; return c;} // Driver Codelet array = [ 1, 1, 1, 2, 2, 2 ];let n = array.length; document.write(sum(array, n)); // This code is contributed by code_hunt </script>", "e": 5511, "s": 4745, "text": null }, { "code": null, "e": 5521, "s": 5511, "text": "Output : " }, { "code": null, "e": 5523, "s": 5521, "text": "3" }, { "code": null, "e": 5546, "s": 5523, "text": "Time complexity: O(n2)" }, { "code": null, "e": 5568, "s": 5546, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 5647, "s": 5568, "text": "Method 2 (Efficient) If we take a closer look, we can notice following facts. " }, { "code": null, "e": 5981, "s": 5647, "text": "Maximum element is always part of solutionIf maximum element appears more than once, then result is maxCount * (maxCount – 1)/2. We basically need to choose 2 elements from maxCount (maxCountC2).If maximum element appears once, then result is equal to count of second maximum element. We can form a pair with every second max and max" }, { "code": null, "e": 6024, "s": 5981, "text": "Maximum element is always part of solution" }, { "code": null, "e": 6178, "s": 6024, "text": "If maximum element appears more than once, then result is maxCount * (maxCount – 1)/2. We basically need to choose 2 elements from maxCount (maxCountC2)." }, { "code": null, "e": 6317, "s": 6178, "text": "If maximum element appears once, then result is equal to count of second maximum element. We can form a pair with every second max and max" }, { "code": null, "e": 6321, "s": 6317, "text": "C++" }, { "code": null, "e": 6326, "s": 6321, "text": "Java" }, { "code": null, "e": 6334, "s": 6326, "text": "Python3" }, { "code": null, "e": 6337, "s": 6334, "text": "C#" }, { "code": null, "e": 6341, "s": 6337, "text": "PHP" }, { "code": null, "e": 6352, "s": 6341, "text": "Javascript" }, { "code": "// CPP program to count pairs with maximum sum.#include <bits/stdc++.h>using namespace std; // function to find the number of maximum pair sumsint sum(int a[], int n){ // Find maximum and second maximum elements. // Also find their counts. int maxVal = a[0], maxCount = 1; int secondMax = INT_MIN, secondMaxCount; for (int i = 1; i < n; i++) { if (a[i] == maxVal) maxCount++; else if (a[i] > maxVal) { secondMax = maxVal; secondMaxCount = maxCount; maxVal = a[i]; maxCount = 1; } else if (a[i] == secondMax) { secondMax = a[i]; secondMaxCount++; } else if (a[i] > secondMax) { secondMax = a[i]; secondMaxCount = 1; } } // If maximum element appears more than once. if (maxCount > 1) return maxCount * (maxCount - 1) / 2; // If maximum element appears only once. return secondMaxCount;} // driver program to test the above functionint main(){ int array[] = { 1, 1, 1, 2, 2, 2, 3 }; int n = sizeof(array) / sizeof(array[0]); cout << sum(array, n); return 0;}", "e": 7508, "s": 6352, "text": null }, { "code": "// Java program to count pairs// with maximum sum.import java.io.*;class GFG { // function to find the number// of maximum pair sumsstatic int sum(int a[], int n){ // Find maximum and second maximum // elements. Also find their counts. int maxVal = a[0], maxCount = 1; int secondMax = Integer.MIN_VALUE, secondMaxCount = 0; for (int i = 1; i < n; i++) { if (a[i] == maxVal) maxCount++; else if (a[i] > maxVal) { secondMax = maxVal; secondMaxCount = maxCount; maxVal = a[i]; maxCount = 1; } else if (a[i] == secondMax) { secondMax = a[i]; secondMaxCount++; } else if (a[i] > secondMax) { secondMax = a[i]; secondMaxCount = 1; } } // If maximum element appears // more than once. if (maxCount > 1) return maxCount * (maxCount - 1) / 2; // If maximum element appears // only once. return secondMaxCount;} // driver programpublic static void main(String[] args){ int array[] = { 1, 1, 1, 2, 2, 2, 3 }; int n = array.length; System.out.println(sum(array, n));}} // This code is contributed by Prerna Saini", "e": 8722, "s": 7508, "text": null }, { "code": "# Python 3 program to count# pairs with maximum sum.import sys # Function to find the number# of maximum pair sumsdef sum(a, n): # Find maximum and second maximum elements. # Also find their counts. maxVal = a[0]; maxCount = 1 secondMax = sys.maxsize for i in range(1, n) : if (a[i] == maxVal) : maxCount += 1 elif (a[i] > maxVal) : secondMax = maxVal secondMaxCount = maxCount maxVal = a[i] maxCount = 1 elif (a[i] == secondMax) : secondMax = a[i] secondMaxCount += 1 elif (a[i] > secondMax) : secondMax = a[i] secondMaxCount = 1 # If maximum element appears more than once. if (maxCount > 1): return maxCount * (maxCount - 1) / 2 # If maximum element appears only once. return secondMaxCount # Driver Codearray = [1, 1, 1, 2, 2, 2, 3]n = len(array)print(sum(array, n)) # This code is contributed by Smitha Dinesh Semwal", "e": 9762, "s": 8722, "text": null }, { "code": "// C# program to count pairs with maximum// sum.using System; class GFG { // function to find the number // of maximum pair sums static int sum(int []a, int n) { // Find maximum and second maximum // elements. Also find their counts. int maxVal = a[0], maxCount = 1; int secondMax = int.MinValue; int secondMaxCount = 0; for (int i = 1; i < n; i++) { if (a[i] == maxVal) maxCount++; else if (a[i] > maxVal) { secondMax = maxVal; secondMaxCount = maxCount; maxVal = a[i]; maxCount = 1; } else if (a[i] == secondMax) { secondMax = a[i]; secondMaxCount++; } else if (a[i] > secondMax) { secondMax = a[i]; secondMaxCount = 1; } } // If maximum element appears // more than once. if (maxCount > 1) return maxCount * (maxCount - 1) / 2; // If maximum element appears // only once. return secondMaxCount; } // driver program public static void Main() { int []array = { 1, 1, 1, 2, 2, 2, 3 }; int n = array.Length; Console.WriteLine(sum(array, n)); }} // This code is contributed by anuj_67.", "e": 11238, "s": 9762, "text": null }, { "code": "<?php// PHP program to count// pairs with maximum sum. // function to find the number// of maximum pair sumsfunction sum( $a, $n){ // Find maximum and second // maximum elements. Also // find their counts. $maxVal = $a[0]; $maxCount = 1; $secondMax = PHP_INT_MIN; $secondMaxCount; for ( $i = 1; $i < $n; $i++) { if ($a[$i] == $maxVal) $maxCount++; else if ($a[$i] > $maxVal) { $secondMax = $maxVal; $secondMaxCount = $maxCount; $maxVal = $a[$i]; $maxCount = 1; } else if ($a[$i] == $secondMax) { $secondMax = $a[$i]; $secondMaxCount++; } else if ($a[$i] > $secondMax) { $secondMax = $a[$i]; $secondMaxCount = 1; } } // If maximum element appears // more than once. if ($maxCount > 1) return $maxCount * ($maxCount - 1) / 2; // If maximum element // appears only once. return $secondMaxCount;} // Driver Code$array = array(1, 1, 1, 2, 2, 2, 3 );$n = count($array);echo sum($array, $n); // This code is contributed by anuj_67.?>", "e": 12416, "s": 11238, "text": null }, { "code": "<script> // Javascript program to count pairs with maximum sum. // function to find the number // of maximum pair sums function sum(a, n) { // Find maximum and second maximum // elements. Also find their counts. let maxVal = a[0], maxCount = 1; let secondMax = Number.MIN_VALUE; let secondMaxCount = 0; for (let i = 1; i < n; i++) { if (a[i] == maxVal) maxCount++; else if (a[i] > maxVal) { secondMax = maxVal; secondMaxCount = maxCount; maxVal = a[i]; maxCount = 1; } else if (a[i] == secondMax) { secondMax = a[i]; secondMaxCount++; } else if (a[i] > secondMax) { secondMax = a[i]; secondMaxCount = 1; } } // If maximum element appears // more than once. if (maxCount > 1) return maxCount * parseInt((maxCount - 1) / 2, 10); // If maximum element appears // only once. return secondMaxCount; } let array = [ 1, 1, 1, 2, 2, 2, 3 ]; let n = array.length; document.write(sum(array, n)); // This code is contributed by divyesh072019.</script>", "e": 13779, "s": 12416, "text": null }, { "code": null, "e": 13790, "s": 13779, "text": "Output : " }, { "code": null, "e": 13792, "s": 13790, "text": "3" }, { "code": null, "e": 13814, "s": 13792, "text": "Time complexity: O(n)" }, { "code": null, "e": 13837, "s": 13814, "text": "Auxiliary Space: O(1) " }, { "code": null, "e": 13842, "s": 13837, "text": "vt_m" }, { "code": null, "e": 13852, "s": 13842, "text": "code_hunt" }, { "code": null, "e": 13866, "s": 13852, "text": "divyesh072019" }, { "code": null, "e": 13880, "s": 13866, "text": "_shinchancode" }, { "code": null, "e": 13887, "s": 13880, "text": "Arrays" }, { "code": null, "e": 13897, "s": 13887, "text": "Searching" }, { "code": null, "e": 13904, "s": 13897, "text": "Arrays" }, { "code": null, "e": 13914, "s": 13904, "text": "Searching" } ]
HTML <label> for Attribute
21 Jun, 2022 The HTML <label> for Attribute is used to specify the type of form element a label is bound to. Syntax: <label for="element_id"> Attribute Values: It contains the value i.e element_id which specify the id of the element that the label is bound to. Example: This Example that illustrates the use of for attribute in <label> element. html <!-- HTML code to illustrates label tag --><!DOCTYPE html><html> <head> <title> HTML | for Attribute </title> <style> body { font-size: 20px; } </style></head> <body style="text-align:center"> <h1 style="color:green"> GeeksforGeeks</h1> <h2> HTML | &lt;label&gt;for Attribute </h2> <form> <!-- Starts label tag from here --> <label for="student"> Student </label> <input type="radio" name="Occupation" id="student" value="student"> <br> <label for="business"> Business </label> <input type="radio" name="Occupation" id="business" value="business"> <br> <label for="other"> Other </label> <!-- Ends label tags here --> <input type="radio" name="Occupation" id="other" value="other"> </form></body> </html> Output: Supported Browsers: The browser supported by HTML | <label>for Attribute are listed below: Google Chrome Edge version 12 and above Internet Explorer Firefox Opera Safari satyamm09 HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? REST API (Introduction) CSS to put icon inside an input element in a form Types of CSS (Cascading Style Sheet) HTTP headers | Content-Type Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Jun, 2022" }, { "code": null, "e": 125, "s": 28, "text": "The HTML <label> for Attribute is used to specify the type of form element a label is bound to. " }, { "code": null, "e": 133, "s": 125, "text": "Syntax:" }, { "code": null, "e": 158, "s": 133, "text": "<label for=\"element_id\">" }, { "code": null, "e": 278, "s": 158, "text": "Attribute Values: It contains the value i.e element_id which specify the id of the element that the label is bound to. " }, { "code": null, "e": 363, "s": 278, "text": "Example: This Example that illustrates the use of for attribute in <label> element. " }, { "code": null, "e": 368, "s": 363, "text": "html" }, { "code": "<!-- HTML code to illustrates label tag --><!DOCTYPE html><html> <head> <title> HTML | for Attribute </title> <style> body { font-size: 20px; } </style></head> <body style=\"text-align:center\"> <h1 style=\"color:green\"> GeeksforGeeks</h1> <h2> HTML | &lt;label&gt;for Attribute </h2> <form> <!-- Starts label tag from here --> <label for=\"student\"> Student </label> <input type=\"radio\" name=\"Occupation\" id=\"student\" value=\"student\"> <br> <label for=\"business\"> Business </label> <input type=\"radio\" name=\"Occupation\" id=\"business\" value=\"business\"> <br> <label for=\"other\"> Other </label> <!-- Ends label tags here --> <input type=\"radio\" name=\"Occupation\" id=\"other\" value=\"other\"> </form></body> </html>", "e": 1395, "s": 368, "text": null }, { "code": null, "e": 1403, "s": 1395, "text": "Output:" }, { "code": null, "e": 1497, "s": 1406, "text": "Supported Browsers: The browser supported by HTML | <label>for Attribute are listed below:" }, { "code": null, "e": 1512, "s": 1497, "text": "Google Chrome " }, { "code": null, "e": 1538, "s": 1512, "text": "Edge version 12 and above" }, { "code": null, "e": 1557, "s": 1538, "text": "Internet Explorer " }, { "code": null, "e": 1565, "s": 1557, "text": "Firefox" }, { "code": null, "e": 1572, "s": 1565, "text": "Opera " }, { "code": null, "e": 1580, "s": 1572, "text": "Safari " }, { "code": null, "e": 1590, "s": 1580, "text": "satyamm09" }, { "code": null, "e": 1606, "s": 1590, "text": "HTML-Attributes" }, { "code": null, "e": 1611, "s": 1606, "text": "HTML" }, { "code": null, "e": 1628, "s": 1611, "text": "Web Technologies" }, { "code": null, "e": 1633, "s": 1628, "text": "HTML" }, { "code": null, "e": 1731, "s": 1633, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1779, "s": 1731, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 1803, "s": 1779, "text": "REST API (Introduction)" }, { "code": null, "e": 1853, "s": 1803, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 1890, "s": 1853, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 1918, "s": 1890, "text": "HTTP headers | Content-Type" }, { "code": null, "e": 1951, "s": 1918, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2012, "s": 1951, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2055, "s": 2012, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 2127, "s": 2055, "text": "Differences between Functional Components and Class Components in React" } ]
Waybackurls – Fetch all the URLs that the Wayback Machine knows about for a domain
23 Aug, 2021 Web crawling in security testing is an important aspect as this is the process of indexing data on web pages by using automated scripts or crawling programs. These scripts pr crawling programs are known as web crawler, spider, spider bot, and a crawler. Waybackurls is also a Golang based script or tool used for crawling domains on stdin, fetch known URLs from Wayback Machines, also known as Archives for *.targetdomain and output them stdout. Note: As Waybackurls is a Golang language-based tool, so you need to have a Golang environment on your system. So check this link to install Golang in your system – How to Install Go Programming Language in Linux Step 1: If you have downloaded Golang in your system, verify the installation by checking the version of Golang, use the following command. go version Step 2: Get the Waybackurls tool through the Go utility, use the following command. sudo go get github.com/tomnomnom/waybackurls Step 3: Check the help menu page for getting a better understanding of the tool, use the following command. waybackurls -h Example 1: Simple Scan waybackurls geeksforgeeks.org Now as below picture we see we have input the command to collect all the possible waybackurls from our target which is geeksforgeeks.org, this tool will collect all the URLs and output them in the terminal itself. Now as below picture we see we were successfully able to collect all the possible Wayback URLs from Our targeted Domain i.e. geekforgeeks.org. Almost every URL is collected by the WaybackURL tool. Example 2 : Using –no-subs Tag echo "geeksforgeeks.org" | waybackurls -no-subs In this example, our target is geeksforgeeks.org and we have provided -no-subs tags, in this tag, URLs will be fetched only through the main domain. No subdomains are considered while crawling the URLs. In the below screenshot, you can see waybackurls tool has fetched some URLs but the interesting thing to look at is that it has fetched the URLs related to only the main domain, no subdomains are considered while crawling. Example 3: Using -dates Tag echo "geeksforgeeks.org" | waybackurls -dates In this example, our target is geeksforgeeks.org and we are using the -dates tag for getting the dates in the first column. It displays the date of the fetch of that particular URL. In the below screenshot, you can see that we have got the dates in the first column which states the exact fetching date of the particular URL in wayback machine. For Example, https://www.geeksforgeeks.org/find-subarray-with-given-sum/ref=leftbar-rightbar , this link was fetched fetch on the date 2020-09-30, along with this time is also mentioned 22:51:11. Example 4 : Using -get-versions Tag echo "geeksforgeeks.org" | waybackurls -get-versions In this example, we are re-fetching the URL which has helped us to get these results or crawled URLs. -get-versions tag is used for getting the URLs. In the below screenshot, you can see that along with the crawled URLs of geeksforgeeks.org, we have got some extra URLs that specify the sources from which the geeksforgeeks.org URLs are crawled. Example. https://www.geeksforgeeks.org/ URL is fetched by the https://web.archive.org/web/20210715090226if_. This can help you to directly go to the source URL can explore more about the crawled URL of geeksforgeeks.org. Kali-Linux Linux-Tools Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Docker - COPY Instruction scp command in Linux with Examples chown command in Linux with Examples SED command in Linux | Set 2 mv command in Linux with examples chmod command in Linux with examples nohup Command in Linux with Examples Introduction to Linux Operating System Array Basics in Shell Scripting | Set 1 Basic Operators in Shell Scripting
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Aug, 2021" }, { "code": null, "e": 475, "s": 28, "text": "Web crawling in security testing is an important aspect as this is the process of indexing data on web pages by using automated scripts or crawling programs. These scripts pr crawling programs are known as web crawler, spider, spider bot, and a crawler. Waybackurls is also a Golang based script or tool used for crawling domains on stdin, fetch known URLs from Wayback Machines, also known as Archives for *.targetdomain and output them stdout." }, { "code": null, "e": 688, "s": 475, "text": "Note: As Waybackurls is a Golang language-based tool, so you need to have a Golang environment on your system. So check this link to install Golang in your system – How to Install Go Programming Language in Linux" }, { "code": null, "e": 828, "s": 688, "text": "Step 1: If you have downloaded Golang in your system, verify the installation by checking the version of Golang, use the following command." }, { "code": null, "e": 839, "s": 828, "text": "go version" }, { "code": null, "e": 923, "s": 839, "text": "Step 2: Get the Waybackurls tool through the Go utility, use the following command." }, { "code": null, "e": 968, "s": 923, "text": "sudo go get github.com/tomnomnom/waybackurls" }, { "code": null, "e": 1076, "s": 968, "text": "Step 3: Check the help menu page for getting a better understanding of the tool, use the following command." }, { "code": null, "e": 1091, "s": 1076, "text": "waybackurls -h" }, { "code": null, "e": 1114, "s": 1091, "text": "Example 1: Simple Scan" }, { "code": null, "e": 1144, "s": 1114, "text": "waybackurls geeksforgeeks.org" }, { "code": null, "e": 1358, "s": 1144, "text": "Now as below picture we see we have input the command to collect all the possible waybackurls from our target which is geeksforgeeks.org, this tool will collect all the URLs and output them in the terminal itself." }, { "code": null, "e": 1555, "s": 1358, "text": "Now as below picture we see we were successfully able to collect all the possible Wayback URLs from Our targeted Domain i.e. geekforgeeks.org. Almost every URL is collected by the WaybackURL tool." }, { "code": null, "e": 1586, "s": 1555, "text": "Example 2 : Using –no-subs Tag" }, { "code": null, "e": 1634, "s": 1586, "text": "echo \"geeksforgeeks.org\" | waybackurls -no-subs" }, { "code": null, "e": 1837, "s": 1634, "text": "In this example, our target is geeksforgeeks.org and we have provided -no-subs tags, in this tag, URLs will be fetched only through the main domain. No subdomains are considered while crawling the URLs." }, { "code": null, "e": 2060, "s": 1837, "text": "In the below screenshot, you can see waybackurls tool has fetched some URLs but the interesting thing to look at is that it has fetched the URLs related to only the main domain, no subdomains are considered while crawling." }, { "code": null, "e": 2088, "s": 2060, "text": "Example 3: Using -dates Tag" }, { "code": null, "e": 2134, "s": 2088, "text": "echo \"geeksforgeeks.org\" | waybackurls -dates" }, { "code": null, "e": 2316, "s": 2134, "text": "In this example, our target is geeksforgeeks.org and we are using the -dates tag for getting the dates in the first column. It displays the date of the fetch of that particular URL." }, { "code": null, "e": 2675, "s": 2316, "text": "In the below screenshot, you can see that we have got the dates in the first column which states the exact fetching date of the particular URL in wayback machine. For Example, https://www.geeksforgeeks.org/find-subarray-with-given-sum/ref=leftbar-rightbar , this link was fetched fetch on the date 2020-09-30, along with this time is also mentioned 22:51:11." }, { "code": null, "e": 2711, "s": 2675, "text": "Example 4 : Using -get-versions Tag" }, { "code": null, "e": 2764, "s": 2711, "text": "echo \"geeksforgeeks.org\" | waybackurls -get-versions" }, { "code": null, "e": 2914, "s": 2764, "text": "In this example, we are re-fetching the URL which has helped us to get these results or crawled URLs. -get-versions tag is used for getting the URLs." }, { "code": null, "e": 3332, "s": 2914, "text": "In the below screenshot, you can see that along with the crawled URLs of geeksforgeeks.org, we have got some extra URLs that specify the sources from which the geeksforgeeks.org URLs are crawled. Example. https://www.geeksforgeeks.org/ URL is fetched by the https://web.archive.org/web/20210715090226if_. This can help you to directly go to the source URL can explore more about the crawled URL of geeksforgeeks.org." }, { "code": null, "e": 3343, "s": 3332, "text": "Kali-Linux" }, { "code": null, "e": 3355, "s": 3343, "text": "Linux-Tools" }, { "code": null, "e": 3366, "s": 3355, "text": "Linux-Unix" }, { "code": null, "e": 3464, "s": 3366, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3490, "s": 3464, "text": "Docker - COPY Instruction" }, { "code": null, "e": 3525, "s": 3490, "text": "scp command in Linux with Examples" }, { "code": null, "e": 3562, "s": 3525, "text": "chown command in Linux with Examples" }, { "code": null, "e": 3591, "s": 3562, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 3625, "s": 3591, "text": "mv command in Linux with examples" }, { "code": null, "e": 3662, "s": 3625, "text": "chmod command in Linux with examples" }, { "code": null, "e": 3699, "s": 3662, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 3738, "s": 3699, "text": "Introduction to Linux Operating System" }, { "code": null, "e": 3778, "s": 3738, "text": "Array Basics in Shell Scripting | Set 1" } ]
How to Automate VPN to change IP location on Ubuntu using Python?
04 Jul, 2021 To Protect Our system from unauthorized users Access you can spoof our system’s IP Address using VPN service provided by different organizations. You can set up a VPN on your system for free. After you set up and log in to the VPN over the Ubuntu system you need to manually connect with different VPN servers after some duration. We can automate it using python so that automatically the IP address of our system keeps changing after some duration so that no one can have track of our system anyhow. It will make our system more protected. Step 1: Open your terminal (Ctrl+Alt+T) and create a file using gedit by typing the following command on the terminal. gedit gfg.py Step 2: import the modules of python into the opened file. Python3 # import required modulesimport osfrom time import sleepimport random Step 3: Create a list of Free VPN server codes provided by Windscribe (VPN). Python3 # list of VPN server codescodeList = ["TR", "US-C", "US", "US-W", "CA", "CA-W", "FR", "DE", "NL", "NO", "RO", "CH", "GB", "HK"] Step 4: Start a try block connect with Windscribe using os module os.system("windscribe connect") And, then start an infinite loop and write some lines under it. Choose a random code from codelist using random module. choiceCode = random.choice(codeList) Create a random sleep for 15 to 20 min after which the IP of the system gets changed using time and random modules. sleep(random.randrange(120,300)) Connect with the randomly chosen VPN code. os.system("windscribe connect "+ choiceCode) Python3 try: # connect to VPN os.system("windscribe connect") while True: # assigning a random VPN server code choiceCode = random.choice(codeList) # changing IP after a particular time period sleep(random.randrange(120, 300)) # connecting to a different VPN server print("!!! Changing the IP Address........") os.system("windscribe connect " + choiceCode) Step 5: Start a catch block and then: Disconnect the VPN, it will run if it gets any error. os.system("windscribe disconnect") Display a disconnection message here. print("sorry, some error has occurred..!!") Python3 except: # disconnect VPN os.system("windscribe disconnect") print("sorry, some error has occurred..!!") Python3 # import required modulesimport osfrom time import sleepimport random # list of VPN server codescodeList = ["TR", "US-C", "US", "US-W", "CA", "CA-W", "FR", "DE", "NL", "NO", "RO", "CH", "GB", "HK"] try: # connect to VPN os.system("windscribe connect") while True: # assigning a random VPN server code choiceCode = random.choice(codeList) # changing IP after a particular time period sleep(random.randrange(120, 300)) # connecting to a different VPN server print("!!! Changing the IP Address........") os.system("windscribe connect " + choiceCode) except: # disconnect VPN os.system("windscribe disconnect") print("sorry, some error has occurred..!!") Output: Step 1: Log in to the Windscribe with which you have setup the VPN over the system with the command given below. windscribe login Step 2: Execute the file you have created in the above steps with the command below. python3 gfg.py NOTE: This will change your system’s IP address randomly. Press Ctrl+c to close the VPN service. Click here to view a small video for a better understanding of the setup and execution of the VPN Automation program. saurabh1990aror python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n04 Jul, 2021" }, { "code": null, "e": 248, "s": 54, "text": "To Protect Our system from unauthorized users Access you can spoof our system’s IP Address using VPN service provided by different organizations. You can set up a VPN on your system for free. " }, { "code": null, "e": 598, "s": 248, "text": "After you set up and log in to the VPN over the Ubuntu system you need to manually connect with different VPN servers after some duration. We can automate it using python so that automatically the IP address of our system keeps changing after some duration so that no one can have track of our system anyhow. It will make our system more protected." }, { "code": null, "e": 717, "s": 598, "text": "Step 1: Open your terminal (Ctrl+Alt+T) and create a file using gedit by typing the following command on the terminal." }, { "code": null, "e": 730, "s": 717, "text": "gedit gfg.py" }, { "code": null, "e": 789, "s": 730, "text": "Step 2: import the modules of python into the opened file." }, { "code": null, "e": 797, "s": 789, "text": "Python3" }, { "code": "# import required modulesimport osfrom time import sleepimport random", "e": 867, "s": 797, "text": null }, { "code": null, "e": 948, "s": 871, "text": "Step 3: Create a list of Free VPN server codes provided by Windscribe (VPN)." }, { "code": null, "e": 958, "s": 950, "text": "Python3" }, { "code": "# list of VPN server codescodeList = [\"TR\", \"US-C\", \"US\", \"US-W\", \"CA\", \"CA-W\", \"FR\", \"DE\", \"NL\", \"NO\", \"RO\", \"CH\", \"GB\", \"HK\"]", "e": 1097, "s": 958, "text": null }, { "code": null, "e": 1167, "s": 1101, "text": "Step 4: Start a try block connect with Windscribe using os module" }, { "code": null, "e": 1201, "s": 1169, "text": "os.system(\"windscribe connect\")" }, { "code": null, "e": 1267, "s": 1203, "text": "And, then start an infinite loop and write some lines under it." }, { "code": null, "e": 1325, "s": 1269, "text": "Choose a random code from codelist using random module." }, { "code": null, "e": 1362, "s": 1325, "text": "choiceCode = random.choice(codeList)" }, { "code": null, "e": 1478, "s": 1362, "text": "Create a random sleep for 15 to 20 min after which the IP of the system gets changed using time and random modules." }, { "code": null, "e": 1511, "s": 1478, "text": "sleep(random.randrange(120,300))" }, { "code": null, "e": 1554, "s": 1511, "text": "Connect with the randomly chosen VPN code." }, { "code": null, "e": 1599, "s": 1554, "text": "os.system(\"windscribe connect \"+ choiceCode)" }, { "code": null, "e": 1609, "s": 1601, "text": "Python3" }, { "code": "try: # connect to VPN os.system(\"windscribe connect\") while True: # assigning a random VPN server code choiceCode = random.choice(codeList) # changing IP after a particular time period sleep(random.randrange(120, 300)) # connecting to a different VPN server print(\"!!! Changing the IP Address........\") os.system(\"windscribe connect \" + choiceCode)", "e": 2020, "s": 1609, "text": null }, { "code": null, "e": 2058, "s": 2020, "text": "Step 5: Start a catch block and then:" }, { "code": null, "e": 2112, "s": 2058, "text": "Disconnect the VPN, it will run if it gets any error." }, { "code": null, "e": 2147, "s": 2112, "text": "os.system(\"windscribe disconnect\")" }, { "code": null, "e": 2185, "s": 2147, "text": "Display a disconnection message here." }, { "code": null, "e": 2229, "s": 2185, "text": "print(\"sorry, some error has occurred..!!\")" }, { "code": null, "e": 2237, "s": 2229, "text": "Python3" }, { "code": "except: # disconnect VPN os.system(\"windscribe disconnect\") print(\"sorry, some error has occurred..!!\")", "e": 2351, "s": 2237, "text": null }, { "code": null, "e": 2359, "s": 2351, "text": "Python3" }, { "code": "# import required modulesimport osfrom time import sleepimport random # list of VPN server codescodeList = [\"TR\", \"US-C\", \"US\", \"US-W\", \"CA\", \"CA-W\", \"FR\", \"DE\", \"NL\", \"NO\", \"RO\", \"CH\", \"GB\", \"HK\"] try: # connect to VPN os.system(\"windscribe connect\") while True: # assigning a random VPN server code choiceCode = random.choice(codeList) # changing IP after a particular time period sleep(random.randrange(120, 300)) # connecting to a different VPN server print(\"!!! Changing the IP Address........\") os.system(\"windscribe connect \" + choiceCode) except: # disconnect VPN os.system(\"windscribe disconnect\") print(\"sorry, some error has occurred..!!\")", "e": 3093, "s": 2359, "text": null }, { "code": null, "e": 3101, "s": 3093, "text": "Output:" }, { "code": null, "e": 3214, "s": 3101, "text": "Step 1: Log in to the Windscribe with which you have setup the VPN over the system with the command given below." }, { "code": null, "e": 3231, "s": 3214, "text": "windscribe login" }, { "code": null, "e": 3316, "s": 3231, "text": "Step 2: Execute the file you have created in the above steps with the command below." }, { "code": null, "e": 3331, "s": 3316, "text": "python3 gfg.py" }, { "code": null, "e": 3428, "s": 3331, "text": "NOTE: This will change your system’s IP address randomly. Press Ctrl+c to close the VPN service." }, { "code": null, "e": 3546, "s": 3428, "text": "Click here to view a small video for a better understanding of the setup and execution of the VPN Automation program." }, { "code": null, "e": 3562, "s": 3546, "text": "saurabh1990aror" }, { "code": null, "e": 3577, "s": 3562, "text": "python-utility" }, { "code": null, "e": 3584, "s": 3577, "text": "Python" } ]
Cyclomatic Complexity
21 Jun, 2021 Cyclomatic complexity of a code section is the quantitative measure of the number of linearly independent paths in it. It is a software metric used to indicate the complexity of a program. It is computed using the Control Flow Graph of the program. The nodes in the graph indicate the smallest group of commands of a program, and a directed edge in it connects the two nodes i.e. if second command might immediately follow the first command. For example, if source code contains no control flow statement then its cyclomatic complexity will be 1 and source code contains a single path in it. Similarly, if the source code contains one if condition then cyclomatic complexity will be 2 because there will be two paths one for true and the other for false. Mathematically, for a structured program, the directed graph inside control flow is the edge joining two basic blocks of the program as control may pass from first to second. So, cyclomatic complexity M would be defined as, M = E – N + 2P where, E = the number of edges in the control flow graph N = the number of nodes in the control flow graph P = the number of connected components Steps that should be followed in calculating cyclomatic complexity and test cases design are: Construction of graph with nodes and edges from code. Identification of independent paths. Cyclomatic Complexity Calculation Design of Test Cases Let a section of code as such: A = 10 IF B > C THEN A = B ELSE A = C ENDIF Print A Print B Print C Control Flow Graph of above code The cyclomatic complexity calculated for above code will be from control flow graph. The graph shows seven shapes(nodes), seven lines(edges), hence cyclomatic complexity is 7-7+2 = 2. Use of Cyclomatic Complexity: Determining the independent path executions thus proven to be very helpful for Developers and Testers. It can make sure that every path have been tested at least once. Thus help to focus more on uncovered paths. Code coverage can be improved. Risk associated with program can be evaluated. These metrics being used earlier in the program helps in reducing the risks. Advantages of Cyclomatic Complexity:. It can be used as a quality metric, gives relative complexity of various designs. It is able to compute faster than the Halstead’s metrics. It is used to measure the minimum effort and best areas of concentration for testing. It is able to guide the testing process. It is easy to apply. Disadvantages of Cyclomatic Complexity: It is the measure of the programs’s control complexity and not the data the data complexity. In this, nested conditional structures are harder to understand than non-nested structures. In case of simple comparisons and decision structures, it may give a misleading figure. Reference: https://en.wikipedia.org/wiki/Cyclomatic_complexity itskawal2000 sumitgumber28 Algorithms-Analysis of Algorithms time complexity Algorithms Analysis Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. What is Hashing | A Complete Tutorial Find if there is a path between two vertices in an undirected graph How to Start Learning DSA? Complete Roadmap To Learn DSA From Scratch Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete Practice Questions on Time Complexity Analysis Time Complexity and Space Complexity Time Complexity of building a heap Analysis of different sorting techniques Time complexities of different data structures
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Jun, 2021" }, { "code": null, "e": 495, "s": 52, "text": "Cyclomatic complexity of a code section is the quantitative measure of the number of linearly independent paths in it. It is a software metric used to indicate the complexity of a program. It is computed using the Control Flow Graph of the program. The nodes in the graph indicate the smallest group of commands of a program, and a directed edge in it connects the two nodes i.e. if second command might immediately follow the first command. " }, { "code": null, "e": 809, "s": 495, "text": "For example, if source code contains no control flow statement then its cyclomatic complexity will be 1 and source code contains a single path in it. Similarly, if the source code contains one if condition then cyclomatic complexity will be 2 because there will be two paths one for true and the other for false. " }, { "code": null, "e": 1034, "s": 809, "text": "Mathematically, for a structured program, the directed graph inside control flow is the edge joining two basic blocks of the program as control may pass from first to second. So, cyclomatic complexity M would be defined as, " }, { "code": null, "e": 1052, "s": 1036, "text": "M = E – N + 2P " }, { "code": null, "e": 1200, "s": 1052, "text": "where, E = the number of edges in the control flow graph N = the number of nodes in the control flow graph P = the number of connected components " }, { "code": null, "e": 1296, "s": 1200, "text": "Steps that should be followed in calculating cyclomatic complexity and test cases design are: " }, { "code": null, "e": 1350, "s": 1296, "text": "Construction of graph with nodes and edges from code." }, { "code": null, "e": 1387, "s": 1350, "text": "Identification of independent paths." }, { "code": null, "e": 1421, "s": 1387, "text": "Cyclomatic Complexity Calculation" }, { "code": null, "e": 1442, "s": 1421, "text": "Design of Test Cases" }, { "code": null, "e": 1475, "s": 1442, "text": "Let a section of code as such: " }, { "code": null, "e": 1564, "s": 1475, "text": "A = 10\n IF B > C THEN\n A = B\n ELSE\n A = C\n ENDIF\nPrint A\nPrint B\nPrint C" }, { "code": null, "e": 1599, "s": 1566, "text": "Control Flow Graph of above code" }, { "code": null, "e": 1786, "s": 1601, "text": "The cyclomatic complexity calculated for above code will be from control flow graph. The graph shows seven shapes(nodes), seven lines(edges), hence cyclomatic complexity is 7-7+2 = 2. " }, { "code": null, "e": 1818, "s": 1786, "text": "Use of Cyclomatic Complexity: " }, { "code": null, "e": 1921, "s": 1818, "text": "Determining the independent path executions thus proven to be very helpful for Developers and Testers." }, { "code": null, "e": 1986, "s": 1921, "text": "It can make sure that every path have been tested at least once." }, { "code": null, "e": 2030, "s": 1986, "text": "Thus help to focus more on uncovered paths." }, { "code": null, "e": 2061, "s": 2030, "text": "Code coverage can be improved." }, { "code": null, "e": 2108, "s": 2061, "text": "Risk associated with program can be evaluated." }, { "code": null, "e": 2185, "s": 2108, "text": "These metrics being used earlier in the program helps in reducing the risks." }, { "code": null, "e": 2223, "s": 2185, "text": "Advantages of Cyclomatic Complexity:." }, { "code": null, "e": 2305, "s": 2223, "text": "It can be used as a quality metric, gives relative complexity of various designs." }, { "code": null, "e": 2363, "s": 2305, "text": "It is able to compute faster than the Halstead’s metrics." }, { "code": null, "e": 2449, "s": 2363, "text": "It is used to measure the minimum effort and best areas of concentration for testing." }, { "code": null, "e": 2490, "s": 2449, "text": "It is able to guide the testing process." }, { "code": null, "e": 2511, "s": 2490, "text": "It is easy to apply." }, { "code": null, "e": 2551, "s": 2511, "text": "Disadvantages of Cyclomatic Complexity:" }, { "code": null, "e": 2644, "s": 2551, "text": "It is the measure of the programs’s control complexity and not the data the data complexity." }, { "code": null, "e": 2736, "s": 2644, "text": "In this, nested conditional structures are harder to understand than non-nested structures." }, { "code": null, "e": 2824, "s": 2736, "text": "In case of simple comparisons and decision structures, it may give a misleading figure." }, { "code": null, "e": 2888, "s": 2824, "text": "Reference: https://en.wikipedia.org/wiki/Cyclomatic_complexity " }, { "code": null, "e": 2901, "s": 2888, "text": "itskawal2000" }, { "code": null, "e": 2915, "s": 2901, "text": "sumitgumber28" }, { "code": null, "e": 2949, "s": 2915, "text": "Algorithms-Analysis of Algorithms" }, { "code": null, "e": 2965, "s": 2949, "text": "time complexity" }, { "code": null, "e": 2976, "s": 2965, "text": "Algorithms" }, { "code": null, "e": 2985, "s": 2976, "text": "Analysis" }, { "code": null, "e": 2996, "s": 2985, "text": "Algorithms" }, { "code": null, "e": 3094, "s": 2996, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3132, "s": 3094, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 3200, "s": 3132, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 3227, "s": 3200, "text": "How to Start Learning DSA?" }, { "code": null, "e": 3270, "s": 3227, "text": "Complete Roadmap To Learn DSA From Scratch" }, { "code": null, "e": 3337, "s": 3270, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" }, { "code": null, "e": 3384, "s": 3337, "text": "Practice Questions on Time Complexity Analysis" }, { "code": null, "e": 3421, "s": 3384, "text": "Time Complexity and Space Complexity" }, { "code": null, "e": 3456, "s": 3421, "text": "Time Complexity of building a heap" }, { "code": null, "e": 3497, "s": 3456, "text": "Analysis of different sorting techniques" } ]
When to use the readAllBytes() method of InputStream in Java 9?
Since Java 9, we can use the readAllBytes() method from InputStream class to read all bytes into a byte array. This method reads all bytes from an InputStream object at once and blocks until all remaining bytes have read and end of a stream is detected, or an exception is thrown. The reallAllBytes() method can't automatically close the InputStream instance. When it can reach the end of a stream, the further invocations of this method can return an empty byte array. We can use this method for simple use cases where it is convenient to read all bytes into a byte array and not intended for reading input streams with a large amount of data. public byte[] readAllBytes() throws IOException In the below example, we have created a "Technology.txt" file in a "C:\Temp" folder with simple data: { "JAVA", "PYTHON", "JAVASCRIPT", "SELENIUM", "SCALA"}. import java.nio.*; import java.nio.file.*; import java.io.*; import java.util.stream.*; import java.nio.charset.StandardCharsets; public class ReadAllBytesMethodTest { public static void main(String args[]) { try(InputStream stream = Files.newInputStream(Paths.get("C://Temp//Technology.txt"))) { // Convert stream to string String contents = new String(stream.readAllBytes(), StandardCharsets.UTF_8); // To print the string content System.out.println(contents); } catch(IOException ioe) { ioe.printStackTrace(); } } } "JAVA", "PYTHON", "JAVASCRIPT", "SELENIUM", "SCALA"
[ { "code": null, "e": 1468, "s": 1187, "text": "Since Java 9, we can use the readAllBytes() method from InputStream class to read all bytes into a byte array. This method reads all bytes from an InputStream object at once and blocks until all remaining bytes have read and end of a stream is detected, or an exception is thrown." }, { "code": null, "e": 1832, "s": 1468, "text": "The reallAllBytes() method can't automatically close the InputStream instance. When it can reach the end of a stream, the further invocations of this method can return an empty byte array. We can use this method for simple use cases where it is convenient to read all bytes into a byte array and not intended for reading input streams with a large amount of data." }, { "code": null, "e": 1880, "s": 1832, "text": "public byte[] readAllBytes() throws IOException" }, { "code": null, "e": 2038, "s": 1880, "text": "In the below example, we have created a \"Technology.txt\" file in a \"C:\\Temp\" folder with simple data: { \"JAVA\", \"PYTHON\", \"JAVASCRIPT\", \"SELENIUM\", \"SCALA\"}." }, { "code": null, "e": 2628, "s": 2038, "text": "import java.nio.*;\nimport java.nio.file.*;\nimport java.io.*;\nimport java.util.stream.*;\nimport java.nio.charset.StandardCharsets;\n\npublic class ReadAllBytesMethodTest {\n public static void main(String args[]) {\n try(InputStream stream = Files.newInputStream(Paths.get(\"C://Temp//Technology.txt\"))) {\n // Convert stream to string\n String contents = new String(stream.readAllBytes(), StandardCharsets.UTF_8);\n\n // To print the string content\n System.out.println(contents);\n } catch(IOException ioe) {\n ioe.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 2680, "s": 2628, "text": "\"JAVA\", \"PYTHON\", \"JAVASCRIPT\", \"SELENIUM\", \"SCALA\"" } ]
Automated Trading using Python
16 Jul, 2020 Using Python speeds up the trading process, and hence it is also called automated trading/ quantitative trading. The use of Python is credited to its highly functional libraries like TA-Lib, Zipline, Scipy, Pyplot, Matplotlib, NumPy, Pandas etc. Exploring the data at hand is called data analysis. Starting with Python. We will first learn to extract data using the Quandl API. Using previous data is going to be our key to backtesting strategy. How a strategy works in a given circumstance can only be understood using historical data. We use historical data because in trends in the stock market tend to repeat itself over time. The easiest way to get started is by installing Anaconda. Anaconda is a distribution of Python, and it offers different IDEs like Spyder, Jupyter, __, ___ etc. Quandl will help us in retrieving the historical data of the stock. To ninstall quandl type the below command in the terminal – pip install quandl Note: The Quandl Python module is free but you must have a Quandl API key in order to download data. To get your own API key, you will need to create a free Quandl account and set your API key. Once Quandl is installed, the next step is to import packages. We will be using Pandas rigorously in this tutorial as backtesting requires a lot of data manipulation. import pandas as pd import quandl as qd After the packages have been imported, we will extract data from Quandl, using the API key. qd.ApiConfig.api_key = "<API key>” Python3 import pandas as pdimport quandl as qd qd.ApiConfig.api_key = "API KEY" msft_data = qd.get("EOD/MSFT", start_date="2010-01-01", end_date="2020-01-01")msft_data.head() Output: The above code will extract the data of MSFT stocks from 1st Jan 2010 to 1st Jan 2020. data.head() will display first 5 rows of the data. Important terminology: One should understand what the data represents and depicts. Open/ Close – The opening and closing price of the stock. High/ Low – The highest and the lowest price the stock has reached during the particular day. Adj_High/ Adj_Close – The impact of present dividend distribution, stock splits, or other corporate action on the historical data. Returns is simply the profit gained or losses incurred by the stock after the trader/ investor has used long or short positions. We simply use the function pct_change() Python3 # Import numpy packageimport numpy as np # assign `Adj Close` to `close_price`close_price = msft_data[['Adj_Close']] # returns as fractional changedaily_return = close_price.pct_change() # replacing NA values with 0daily_return.fillna(0, inplace=True) print(daily_return) Output: Adj_Close Date 2013-09-03 0.000000 2013-09-04 -0.021487 2013-09-05 0.001282 2013-09-06 -0.002657 2013-09-09 0.016147 ... ... 2017-12-21 -0.000234 2017-12-22 0.000117 2017-12-26 -0.001286 2017-12-27 0.003630 2017-12-28 0.000117 [1090 rows x 1 columns] Formula used in daily return = (Price at ‘t’ – Price at 1)/Price at 1 (Price at any given time ‘t’ – opening price)/ opening price The concept of moving averages will lay the foundation for our momentum-based trade strategy. For finance, analysts also need to constantly test statistical measures over a sliding time period which is called moving period calculations. Let’s see how the rolling mean can be calculated over a 50-day window, and slide the window by 1 day. Python3 # assigning adjusted closing prices # to adj_pricesadj_price = msft_data['Adj_Close'] # calculate the moving averagemav = adj_price.rolling(window=50).mean() # print the resultprint(mav[-10:]) Date 2017-12-14 78.769754 2017-12-15 78.987478 2017-12-18 79.195540 2017-12-19 79.387391 2017-12-20 79.573250 2017-12-21 79.756221 2017-12-22 79.925922 2017-12-26 80.086379 2017-12-27 80.249752 2017-12-28 80.414472 Name: Adj_Close, dtype: float64 Moving averages help smooth out any data anomalies or spikes, and provide you with a smoother curve for the company’s results. Plot and see the difference: Python3 # import the matplotlib package # to see the plotimport matplotlib.pyplot as plt adj_price.plot() Output: Observe the difference: Python3 mav.plot() Output: Plotting them together: Python3 # import the matplotlib package # to see the plotimport matplotlib.pyplot as plt adj_price.plot()mav.plot() Output: Python-projects python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Jul, 2020" }, { "code": null, "e": 409, "s": 28, "text": "Using Python speeds up the trading process, and hence it is also called automated trading/ quantitative trading. The use of Python is credited to its highly functional libraries like TA-Lib, Zipline, Scipy, Pyplot, Matplotlib, NumPy, Pandas etc. Exploring the data at hand is called data analysis. Starting with Python. We will first learn to extract data using the Quandl API. " }, { "code": null, "e": 662, "s": 409, "text": "Using previous data is going to be our key to backtesting strategy. How a strategy works in a given circumstance can only be understood using historical data. We use historical data because in trends in the stock market tend to repeat itself over time." }, { "code": null, "e": 822, "s": 662, "text": "The easiest way to get started is by installing Anaconda. Anaconda is a distribution of Python, and it offers different IDEs like Spyder, Jupyter, __, ___ etc." }, { "code": null, "e": 951, "s": 822, "text": "Quandl will help us in retrieving the historical data of the stock. To ninstall quandl type the below command in the terminal – " }, { "code": null, "e": 970, "s": 951, "text": "pip install quandl" }, { "code": null, "e": 1164, "s": 970, "text": "Note: The Quandl Python module is free but you must have a Quandl API key in order to download data. To get your own API key, you will need to create a free Quandl account and set your API key." }, { "code": null, "e": 1331, "s": 1164, "text": "Once Quandl is installed, the next step is to import packages. We will be using Pandas rigorously in this tutorial as backtesting requires a lot of data manipulation." }, { "code": null, "e": 1372, "s": 1331, "text": "import pandas as pd\nimport quandl as qd\n" }, { "code": null, "e": 1464, "s": 1372, "text": "After the packages have been imported, we will extract data from Quandl, using the API key." }, { "code": null, "e": 1500, "s": 1464, "text": "qd.ApiConfig.api_key = \"<API key>”\n" }, { "code": null, "e": 1508, "s": 1500, "text": "Python3" }, { "code": "import pandas as pdimport quandl as qd qd.ApiConfig.api_key = \"API KEY\" msft_data = qd.get(\"EOD/MSFT\", start_date=\"2010-01-01\", end_date=\"2020-01-01\")msft_data.head()", "e": 1713, "s": 1508, "text": null }, { "code": null, "e": 1721, "s": 1713, "text": "Output:" }, { "code": null, "e": 1860, "s": 1721, "text": "The above code will extract the data of MSFT stocks from 1st Jan 2010 to 1st Jan 2020. data.head() will display first 5 rows of the data." }, { "code": null, "e": 1943, "s": 1860, "text": "Important terminology: One should understand what the data represents and depicts." }, { "code": null, "e": 2001, "s": 1943, "text": "Open/ Close – The opening and closing price of the stock." }, { "code": null, "e": 2095, "s": 2001, "text": "High/ Low – The highest and the lowest price the stock has reached during the particular day." }, { "code": null, "e": 2226, "s": 2095, "text": "Adj_High/ Adj_Close – The impact of present dividend distribution, stock splits, or other corporate action on the historical data." }, { "code": null, "e": 2395, "s": 2226, "text": "Returns is simply the profit gained or losses incurred by the stock after the trader/ investor has used long or short positions. We simply use the function pct_change()" }, { "code": null, "e": 2403, "s": 2395, "text": "Python3" }, { "code": "# Import numpy packageimport numpy as np # assign `Adj Close` to `close_price`close_price = msft_data[['Adj_Close']] # returns as fractional changedaily_return = close_price.pct_change() # replacing NA values with 0daily_return.fillna(0, inplace=True) print(daily_return)", "e": 2681, "s": 2403, "text": null }, { "code": null, "e": 2689, "s": 2681, "text": "Output:" }, { "code": null, "e": 3000, "s": 2689, "text": " Adj_Close\nDate \n2013-09-03 0.000000\n2013-09-04 -0.021487\n2013-09-05 0.001282\n2013-09-06 -0.002657\n2013-09-09 0.016147\n... ...\n2017-12-21 -0.000234\n2017-12-22 0.000117\n2017-12-26 -0.001286\n2017-12-27 0.003630\n2017-12-28 0.000117\n\n[1090 rows x 1 columns]" }, { "code": null, "e": 3131, "s": 3000, "text": "Formula used in daily return = (Price at ‘t’ – Price at 1)/Price at 1 (Price at any given time ‘t’ – opening price)/ opening price" }, { "code": null, "e": 3470, "s": 3131, "text": "The concept of moving averages will lay the foundation for our momentum-based trade strategy. For finance, analysts also need to constantly test statistical measures over a sliding time period which is called moving period calculations. Let’s see how the rolling mean can be calculated over a 50-day window, and slide the window by 1 day." }, { "code": null, "e": 3478, "s": 3470, "text": "Python3" }, { "code": "# assigning adjusted closing prices # to adj_pricesadj_price = msft_data['Adj_Close'] # calculate the moving averagemav = adj_price.rolling(window=50).mean() # print the resultprint(mav[-10:])", "e": 3673, "s": 3478, "text": null }, { "code": null, "e": 3951, "s": 3673, "text": "Date\n2017-12-14 78.769754\n2017-12-15 78.987478\n2017-12-18 79.195540\n2017-12-19 79.387391\n2017-12-20 79.573250\n2017-12-21 79.756221\n2017-12-22 79.925922\n2017-12-26 80.086379\n2017-12-27 80.249752\n2017-12-28 80.414472\nName: Adj_Close, dtype: float64\n" }, { "code": null, "e": 4078, "s": 3951, "text": "Moving averages help smooth out any data anomalies or spikes, and provide you with a smoother curve for the company’s results." }, { "code": null, "e": 4107, "s": 4078, "text": "Plot and see the difference:" }, { "code": null, "e": 4115, "s": 4107, "text": "Python3" }, { "code": "# import the matplotlib package # to see the plotimport matplotlib.pyplot as plt adj_price.plot()", "e": 4214, "s": 4115, "text": null }, { "code": null, "e": 4222, "s": 4214, "text": "Output:" }, { "code": null, "e": 4246, "s": 4222, "text": "Observe the difference:" }, { "code": null, "e": 4254, "s": 4246, "text": "Python3" }, { "code": "mav.plot()", "e": 4265, "s": 4254, "text": null }, { "code": null, "e": 4273, "s": 4265, "text": "Output:" }, { "code": null, "e": 4297, "s": 4273, "text": "Plotting them together:" }, { "code": null, "e": 4305, "s": 4297, "text": "Python3" }, { "code": "# import the matplotlib package # to see the plotimport matplotlib.pyplot as plt adj_price.plot()mav.plot()", "e": 4414, "s": 4305, "text": null }, { "code": null, "e": 4422, "s": 4414, "text": "Output:" }, { "code": null, "e": 4438, "s": 4422, "text": "Python-projects" }, { "code": null, "e": 4453, "s": 4438, "text": "python-utility" }, { "code": null, "e": 4460, "s": 4453, "text": "Python" }, { "code": null, "e": 4558, "s": 4460, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4576, "s": 4558, "text": "Python Dictionary" }, { "code": null, "e": 4618, "s": 4576, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 4640, "s": 4618, "text": "Enumerate() in Python" }, { "code": null, "e": 4675, "s": 4640, "text": "Read a file line by line in Python" }, { "code": null, "e": 4701, "s": 4675, "text": "Python String | replace()" }, { "code": null, "e": 4733, "s": 4701, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4762, "s": 4733, "text": "*args and **kwargs in Python" }, { "code": null, "e": 4789, "s": 4762, "text": "Python Classes and Objects" }, { "code": null, "e": 4819, "s": 4789, "text": "Iterate over a list in Python" } ]
Java Program to Handle Unchecked Exception
27 Apr, 2022 Exceptions are the issues arising at the runtime resulting in an abrupt flow of working of the program. Remember exceptions are never thrown at the compile-time rather always at runtime be it of any type. No exception is thrown at compile time. Throwable Is super-class of all exceptions and errors too. Now there is an urgency to deal with them for which a concept is defined in Java language known as ‘Exception Handling Techniques’ There are two types of exceptions defined as follows Checked Exceptions Unchecked Exceptions Real-world Illustration: Exceptions Consider an employee leaving home for office. He is being monitored by the parent to take ID card stuff and all things as they can think of. Though the employee knows out everything but still being monitored. Now employee leaves out the home still somehow was delayed as his vehicle tyre gets punctured because of which result is that he arrived late to office. Now these wanted things that disrupt his daily routine is referred as Exceptions in Java. Parent actions that helped him though he checked those stuffs but if someday somehow missed and the employee gets things correctly at home itself is referred as ‘checked exception’ in Java. The actions over which parental access does not have any control is referred as ‘unchecked exceptions.’ Here, parent or monitoring authority is referred as ‘Compilers’ in programming languages. Exceptions that can be detected by compilers are checked exceptions and those who can not be detected are called unchecked exceptions. Approach: Now, in order to deal with exceptions, the concept proposed out are exception handling techniques. Straight away diving onto the concept for unchecked exceptions. Unchecked Exception These types of Exceptions occur during the runtime of the program. These are the exceptions that are not checked at a compiled time by the compiler. In Java exceptions under Error and Runtime Exception classes are unchecked exceptions, This Exception occurs due to bad programming. Errors class Exceptions like StackOverflow, OutOfMemoryError exception, etc are difficult to handleRuntime Exceptions like IndexoutOfBoundException, Nullpointer Exception, etc can be handled with the help of try-Catch Block Errors class Exceptions like StackOverflow, OutOfMemoryError exception, etc are difficult to handle Runtime Exceptions like IndexoutOfBoundException, Nullpointer Exception, etc can be handled with the help of try-Catch Block There are 2 major Unchecked Exceptions which are faced generally by programmers namely IndexOutOfBoundsExcepetion and NullPointerException. They are discussed below with the help of an example also, we will implement them and discuss how to handle them out. Both the major approaches are proposed as below: IndexOutOfBoundsExceptionNullPointerException IndexOutOfBoundsException NullPointerException Case 1: (Array)IndexoutOfBoundException: This Exception occurs due to accessing the index greater than and equal to the size of the array length. The program will automatically be terminated after this exception. In simpler terms, a memory is being tried to accessed which the current data structure is not holding by itself. Here this exception is defined over data structure namely ‘Arrays‘. Java // Importing Classes/Filesimport java.io.*; class GFG { // Main Driver Function public static void main(String[] args) { // Array containing 4 elements int a[] = { 1, 2, 3, 4 }; // Try to access elements greater than // index size of the array System.out.println(a[5]); }} Output: Handling ArrayIndexoutOfBoundException: Try-catch Block we can handle this exception try statement allows you to define a block of code to be tested for errors and catch block captures the given exception object and perform required operations. The program will not terminate. Java // Importing Classes/Filesimport java.io.*; public class GFG { // Main Driver Method public static void main(String[] args) { // Inserting elements into Array int a[] = { 1, 2, 3, 4, 5 }; // Try block for exceptions try { // Forcefully trying to access and print // element/s beyond indexes of the array System.out.println(a[5]); } // Catch block for catching exceptions catch (ArrayIndexOutOfBoundsException e) { // Printing display message when index not // present in a array is accessed System.out.println( "Out of index please check your code"); } }} Output: Case 2: NullPointerException: This exception occurs when trying to access the object reference that has a null value. Java // Importing Classes/Filesimport java.io.*; public class GFG { // Main Driver Method public static void main(String[] args) { // Instance of string a has null value String a = null; // Comparing null value with the string value // throw exception and Print System.out.println(a.equals("GFG")); }} Output: Handling Technique for NullPointerException Java // Importing Files/Classesimport java.io.*; public class GFG { // Driver Main Method public static void main(String[] args) { // Assigning NULL to string String m = null; // Try-Catch Block try { // Checking the null value with GFG string // and throw exception if (m.equals("GFG")) { // Print String System.out.println("YES"); } } // Try-Catch Block catch (NullPointerException e) { // Handles the exception System.out.println( "Object reference cannot be null"); } }} Output: ankur035 Java-Exception Handling Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Apr, 2022" }, { "code": null, "e": 463, "s": 28, "text": "Exceptions are the issues arising at the runtime resulting in an abrupt flow of working of the program. Remember exceptions are never thrown at the compile-time rather always at runtime be it of any type. No exception is thrown at compile time. Throwable Is super-class of all exceptions and errors too. Now there is an urgency to deal with them for which a concept is defined in Java language known as ‘Exception Handling Techniques’" }, { "code": null, "e": 517, "s": 463, "text": "There are two types of exceptions defined as follows " }, { "code": null, "e": 536, "s": 517, "text": "Checked Exceptions" }, { "code": null, "e": 557, "s": 536, "text": "Unchecked Exceptions" }, { "code": null, "e": 593, "s": 557, "text": "Real-world Illustration: Exceptions" }, { "code": null, "e": 1564, "s": 593, "text": "Consider an employee leaving home for office. He is being monitored by the parent to take ID card stuff and all things as they can think of. Though the employee knows out everything but still being monitored. Now employee leaves out the home still somehow was delayed as his vehicle tyre gets punctured because of which result is that he arrived late to office. Now these wanted things that disrupt his daily routine is referred as Exceptions in Java. Parent actions that helped him though he checked those stuffs but if someday somehow missed and the employee gets things correctly at home itself is referred as ‘checked exception’ in Java. The actions over which parental access does not have any control is referred as ‘unchecked exceptions.’ Here, parent or monitoring authority is referred as ‘Compilers’ in programming languages. Exceptions that can be detected by compilers are checked exceptions and those who can not be detected are called unchecked exceptions." }, { "code": null, "e": 1737, "s": 1564, "text": "Approach: Now, in order to deal with exceptions, the concept proposed out are exception handling techniques. Straight away diving onto the concept for unchecked exceptions." }, { "code": null, "e": 1757, "s": 1737, "text": "Unchecked Exception" }, { "code": null, "e": 2040, "s": 1757, "text": "These types of Exceptions occur during the runtime of the program. These are the exceptions that are not checked at a compiled time by the compiler. In Java exceptions under Error and Runtime Exception classes are unchecked exceptions, This Exception occurs due to bad programming." }, { "code": null, "e": 2265, "s": 2040, "text": "Errors class Exceptions like StackOverflow, OutOfMemoryError exception, etc are difficult to handleRuntime Exceptions like IndexoutOfBoundException, Nullpointer Exception, etc can be handled with the help of try-Catch Block" }, { "code": null, "e": 2366, "s": 2265, "text": "Errors class Exceptions like StackOverflow, OutOfMemoryError exception, etc are difficult to handle" }, { "code": null, "e": 2491, "s": 2366, "text": "Runtime Exceptions like IndexoutOfBoundException, Nullpointer Exception, etc can be handled with the help of try-Catch Block" }, { "code": null, "e": 2798, "s": 2491, "text": "There are 2 major Unchecked Exceptions which are faced generally by programmers namely IndexOutOfBoundsExcepetion and NullPointerException. They are discussed below with the help of an example also, we will implement them and discuss how to handle them out. Both the major approaches are proposed as below:" }, { "code": null, "e": 2844, "s": 2798, "text": "IndexOutOfBoundsExceptionNullPointerException" }, { "code": null, "e": 2870, "s": 2844, "text": "IndexOutOfBoundsException" }, { "code": null, "e": 2891, "s": 2870, "text": "NullPointerException" }, { "code": null, "e": 3285, "s": 2891, "text": "Case 1: (Array)IndexoutOfBoundException: This Exception occurs due to accessing the index greater than and equal to the size of the array length. The program will automatically be terminated after this exception. In simpler terms, a memory is being tried to accessed which the current data structure is not holding by itself. Here this exception is defined over data structure namely ‘Arrays‘." }, { "code": null, "e": 3290, "s": 3285, "text": "Java" }, { "code": "// Importing Classes/Filesimport java.io.*; class GFG { // Main Driver Function public static void main(String[] args) { // Array containing 4 elements int a[] = { 1, 2, 3, 4 }; // Try to access elements greater than // index size of the array System.out.println(a[5]); }}", "e": 3612, "s": 3290, "text": null }, { "code": null, "e": 3620, "s": 3612, "text": "Output:" }, { "code": null, "e": 3897, "s": 3620, "text": "Handling ArrayIndexoutOfBoundException: Try-catch Block we can handle this exception try statement allows you to define a block of code to be tested for errors and catch block captures the given exception object and perform required operations. The program will not terminate." }, { "code": null, "e": 3902, "s": 3897, "text": "Java" }, { "code": "// Importing Classes/Filesimport java.io.*; public class GFG { // Main Driver Method public static void main(String[] args) { // Inserting elements into Array int a[] = { 1, 2, 3, 4, 5 }; // Try block for exceptions try { // Forcefully trying to access and print // element/s beyond indexes of the array System.out.println(a[5]); } // Catch block for catching exceptions catch (ArrayIndexOutOfBoundsException e) { // Printing display message when index not // present in a array is accessed System.out.println( \"Out of index please check your code\"); } }}", "e": 4614, "s": 3902, "text": null }, { "code": null, "e": 4622, "s": 4614, "text": "Output:" }, { "code": null, "e": 4740, "s": 4622, "text": "Case 2: NullPointerException: This exception occurs when trying to access the object reference that has a null value." }, { "code": null, "e": 4745, "s": 4740, "text": "Java" }, { "code": "// Importing Classes/Filesimport java.io.*; public class GFG { // Main Driver Method public static void main(String[] args) { // Instance of string a has null value String a = null; // Comparing null value with the string value // throw exception and Print System.out.println(a.equals(\"GFG\")); }}", "e": 5091, "s": 4745, "text": null }, { "code": null, "e": 5099, "s": 5091, "text": "Output:" }, { "code": null, "e": 5143, "s": 5099, "text": "Handling Technique for NullPointerException" }, { "code": null, "e": 5148, "s": 5143, "text": "Java" }, { "code": "// Importing Files/Classesimport java.io.*; public class GFG { // Driver Main Method public static void main(String[] args) { // Assigning NULL to string String m = null; // Try-Catch Block try { // Checking the null value with GFG string // and throw exception if (m.equals(\"GFG\")) { // Print String System.out.println(\"YES\"); } } // Try-Catch Block catch (NullPointerException e) { // Handles the exception System.out.println( \"Object reference cannot be null\"); } }}", "e": 5812, "s": 5148, "text": null }, { "code": null, "e": 5820, "s": 5812, "text": "Output:" }, { "code": null, "e": 5829, "s": 5820, "text": "ankur035" }, { "code": null, "e": 5853, "s": 5829, "text": "Java-Exception Handling" }, { "code": null, "e": 5877, "s": 5853, "text": "Technical Scripter 2020" }, { "code": null, "e": 5882, "s": 5877, "text": "Java" }, { "code": null, "e": 5896, "s": 5882, "text": "Java Programs" }, { "code": null, "e": 5915, "s": 5896, "text": "Technical Scripter" }, { "code": null, "e": 5920, "s": 5915, "text": "Java" }, { "code": null, "e": 6018, "s": 5920, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6033, "s": 6018, "text": "Stream In Java" }, { "code": null, "e": 6054, "s": 6033, "text": "Introduction to Java" }, { "code": null, "e": 6075, "s": 6054, "text": "Constructors in Java" }, { "code": null, "e": 6094, "s": 6075, "text": "Exceptions in Java" }, { "code": null, "e": 6111, "s": 6094, "text": "Generics in Java" }, { "code": null, "e": 6137, "s": 6111, "text": "Java Programming Examples" }, { "code": null, "e": 6171, "s": 6137, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 6218, "s": 6171, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 6256, "s": 6218, "text": "Factory method design pattern in Java" } ]
Draw Concentric Circles with VIBGYOR Using Turtle in Python
20 Oct, 2020 Turtle is an inbuilt module in Python. It provides drawing using a screen (cardboard) and turtle (pen). To draw something on the screen, we need to move the turtle (pen). To move turtle, there are some functions i.e forward(), backward(), etc. Following steps are used : Importing turtle module Set a screen Make Turtle object Define a method for circle with dynamic radius and colour. Write text by setting turtle object at required position. Below is the implementation : Python3 # import turtle packageimport turtle # Screen objectsc = turtle.Screen() # Screen background colorsc.bgcolor('black') # turtle objectpen = turtle.Turtle() # turtle widthpen.width(4) # function to draw a circle of# rad radius and col colordef circle(col, rad, val): pen.color(col) pen.circle(rad) pen.up() # set position for space pen.setpos(0, val) pen.down() # function to write text# by setting positionsdef text(): pen.color('white') pen.up() pen.setpos(-100, 140) pen.down() pen.write("Concentric VIBGYOR", font = ("Verdana", 15)) pen.up() pen.setpos(-82, -188) pen.down() pen.write("Using Turtle Graphics", font = ("Verdana", 12)) pen.hideturtle() # Driver code if __name__ == "__main__" : # VIBGYOR color list col = ['violet', 'indigo', 'blue', 'green', 'yellow', 'orange', 'red'] # 7 Concentric circles for i in range(7): # function call circle(col[i], -20*(i+1), 20*(i+1)) # function call text() Concentric Vibgyor pulkitagarwal03pulkit Python-turtle Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Oct, 2020" }, { "code": null, "e": 272, "s": 28, "text": "Turtle is an inbuilt module in Python. It provides drawing using a screen (cardboard) and turtle (pen). To draw something on the screen, we need to move the turtle (pen). To move turtle, there are some functions i.e forward(), backward(), etc." }, { "code": null, "e": 299, "s": 272, "text": "Following steps are used :" }, { "code": null, "e": 323, "s": 299, "text": "Importing turtle module" }, { "code": null, "e": 336, "s": 323, "text": "Set a screen" }, { "code": null, "e": 355, "s": 336, "text": "Make Turtle object" }, { "code": null, "e": 414, "s": 355, "text": "Define a method for circle with dynamic radius and colour." }, { "code": null, "e": 472, "s": 414, "text": "Write text by setting turtle object at required position." }, { "code": null, "e": 502, "s": 472, "text": "Below is the implementation :" }, { "code": null, "e": 510, "s": 502, "text": "Python3" }, { "code": "# import turtle packageimport turtle # Screen objectsc = turtle.Screen() # Screen background colorsc.bgcolor('black') # turtle objectpen = turtle.Turtle() # turtle widthpen.width(4) # function to draw a circle of# rad radius and col colordef circle(col, rad, val): pen.color(col) pen.circle(rad) pen.up() # set position for space pen.setpos(0, val) pen.down() # function to write text# by setting positionsdef text(): pen.color('white') pen.up() pen.setpos(-100, 140) pen.down() pen.write(\"Concentric VIBGYOR\", font = (\"Verdana\", 15)) pen.up() pen.setpos(-82, -188) pen.down() pen.write(\"Using Turtle Graphics\", font = (\"Verdana\", 12)) pen.hideturtle() # Driver code if __name__ == \"__main__\" : # VIBGYOR color list col = ['violet', 'indigo', 'blue', 'green', 'yellow', 'orange', 'red'] # 7 Concentric circles for i in range(7): # function call circle(col[i], -20*(i+1), 20*(i+1)) # function call text()", "e": 1546, "s": 510, "text": null }, { "code": null, "e": 1565, "s": 1546, "text": "Concentric Vibgyor" }, { "code": null, "e": 1587, "s": 1565, "text": "pulkitagarwal03pulkit" }, { "code": null, "e": 1601, "s": 1587, "text": "Python-turtle" }, { "code": null, "e": 1608, "s": 1601, "text": "Python" } ]
How to generate a random phone number using Python?
27 Mar, 2021 In this article, we will learn how to generate a random phone number using Python. In general, Indian phone numbers are of 10 digits and start with 9, 8, 7, or 6. Approach: We will use the random library to generate random numbers. The number should contain 10 digits. The first digit should start with 9 or 8 or 7 or 6, we will use randint() method. The remaining 9 digits will also be generated using the randint() method. Examples: The generated random phone numbers would looklike: 9980231467 8726189362 Implementation: Python3 # import moduleimport random as r ph_no = [] # the first number should be in the range of 6 to 9ph_no.append(r.randint(6, 9)) # the for loop is used to append the other 9 numbers.# the other 9 numbers can be in the range of 0 to 9.for i in range(1, 10): ph_no.append(r.randint(0, 9)) # printing the numberfor i in ph_no: print(i, end="") Output: 8349603502 Python-random 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 Python | os.path.join() method 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 Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Mar, 2021" }, { "code": null, "e": 191, "s": 28, "text": "In this article, we will learn how to generate a random phone number using Python. In general, Indian phone numbers are of 10 digits and start with 9, 8, 7, or 6." }, { "code": null, "e": 201, "s": 191, "text": "Approach:" }, { "code": null, "e": 260, "s": 201, "text": "We will use the random library to generate random numbers." }, { "code": null, "e": 297, "s": 260, "text": "The number should contain 10 digits." }, { "code": null, "e": 379, "s": 297, "text": "The first digit should start with 9 or 8 or 7 or 6, we will use randint() method." }, { "code": null, "e": 453, "s": 379, "text": "The remaining 9 digits will also be generated using the randint() method." }, { "code": null, "e": 463, "s": 453, "text": "Examples:" }, { "code": null, "e": 536, "s": 463, "text": "The generated random phone numbers would looklike:\n9980231467\n8726189362" }, { "code": null, "e": 552, "s": 536, "text": "Implementation:" }, { "code": null, "e": 560, "s": 552, "text": "Python3" }, { "code": "# import moduleimport random as r ph_no = [] # the first number should be in the range of 6 to 9ph_no.append(r.randint(6, 9)) # the for loop is used to append the other 9 numbers.# the other 9 numbers can be in the range of 0 to 9.for i in range(1, 10): ph_no.append(r.randint(0, 9)) # printing the numberfor i in ph_no: print(i, end=\"\")", "e": 908, "s": 560, "text": null }, { "code": null, "e": 916, "s": 908, "text": "Output:" }, { "code": null, "e": 927, "s": 916, "text": "8349603502" }, { "code": null, "e": 941, "s": 927, "text": "Python-random" }, { "code": null, "e": 948, "s": 941, "text": "Python" }, { "code": null, "e": 1046, "s": 948, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1078, "s": 1046, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1105, "s": 1078, "text": "Python Classes and Objects" }, { "code": null, "e": 1126, "s": 1105, "text": "Python OOPs Concepts" }, { "code": null, "e": 1149, "s": 1126, "text": "Introduction To PYTHON" }, { "code": null, "e": 1180, "s": 1149, "text": "Python | os.path.join() method" }, { "code": null, "e": 1236, "s": 1180, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1278, "s": 1236, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1320, "s": 1278, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1359, "s": 1320, "text": "Python | Get unique values from a list" } ]
Java - The LinkedHashSet Class
This class extends HashSet, but adds no members of its own. LinkedHashSet maintains a linked list of the entries in the set, in the order in which they were inserted. This allows insertion-order iteration over the set. That is, when cycling through a LinkedHashSet using an iterator, the elements will be returned in the order in which they were inserted. The hash code is then used as the index at which the data associated with the key is stored. The transformation of the key into its hash code is performed automatically. Following is the list of constructors supported by the LinkedHashSet. HashSet( ) This constructor constructs a default HashSet. HashSet(Collection c) This constructor initializes the hash set by using the elements of the collection c. LinkedHashSet(int capacity) This constructor initializes the capacity of the linkedhashset to the given integer value capacity. The capacity grows automatically as elements are added to the HashSet. LinkedHashSet(int capacity, float fillRatio) This constructor initializes both the capacity and the fill ratio (also called load capacity) of the hash set from its arguments. The following program illustrates several of the methods supported by LinkedHashSet − import java.util.*; public class HashSetDemo { public static void main(String args[]) { // create a hash set LinkedHashSet hs = new LinkedHashSet(); // add elements to the hash set hs.add("B"); hs.add("A"); hs.add("D"); hs.add("E"); hs.add("C"); hs.add("F"); System.out.println(hs); } } This will produce the following result − [B, A, D, E, C, F]
[ { "code": null, "e": 2571, "s": 2511, "text": "This class extends HashSet, but adds no members of its own." }, { "code": null, "e": 2730, "s": 2571, "text": "LinkedHashSet maintains a linked list of the entries in the set, in the order in which they were inserted. This allows insertion-order iteration over the set." }, { "code": null, "e": 2867, "s": 2730, "text": "That is, when cycling through a LinkedHashSet using an iterator, the elements will be returned in the order in which they were inserted." }, { "code": null, "e": 3037, "s": 2867, "text": "The hash code is then used as the index at which the data associated with the key is stored. The transformation of the key into its hash code is performed automatically." }, { "code": null, "e": 3107, "s": 3037, "text": "Following is the list of constructors supported by the LinkedHashSet." }, { "code": null, "e": 3118, "s": 3107, "text": "HashSet( )" }, { "code": null, "e": 3165, "s": 3118, "text": "This constructor constructs a default HashSet." }, { "code": null, "e": 3187, "s": 3165, "text": "HashSet(Collection c)" }, { "code": null, "e": 3272, "s": 3187, "text": "This constructor initializes the hash set by using the elements of the collection c." }, { "code": null, "e": 3300, "s": 3272, "text": "LinkedHashSet(int capacity)" }, { "code": null, "e": 3472, "s": 3300, "text": "This constructor initializes the capacity of the linkedhashset to the given integer value capacity. The capacity grows automatically as elements are added to the HashSet." }, { "code": null, "e": 3517, "s": 3472, "text": "LinkedHashSet(int capacity, float fillRatio)" }, { "code": null, "e": 3647, "s": 3517, "text": "This constructor initializes both the capacity and the fill ratio (also called load capacity) of the hash set from its arguments." }, { "code": null, "e": 3733, "s": 3647, "text": "The following program illustrates several of the methods supported by LinkedHashSet −" }, { "code": null, "e": 4094, "s": 3733, "text": "import java.util.*;\npublic class HashSetDemo {\n\n public static void main(String args[]) {\n // create a hash set\n LinkedHashSet hs = new LinkedHashSet();\n \n // add elements to the hash set\n hs.add(\"B\");\n hs.add(\"A\");\n hs.add(\"D\");\n hs.add(\"E\");\n hs.add(\"C\");\n hs.add(\"F\");\n System.out.println(hs);\n }\n}" }, { "code": null, "e": 4135, "s": 4094, "text": "This will produce the following result −" } ]
How to build a Horizontal ListView with RecyclerView in Android?
Before getting into example, we should know what is Recycler view in android. Recycler view is more advanced version of list view and it works based on View holder design pattern. Using recycler view we can show grids and list of items. This example demonstrate about how to build a horizontal list view with Recycler View by creating a beautiful student records app that displays student name with age. 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 − Open build.gradle and add Recycler view & Card view library dependencies. apply plugin: 'com.android.application' android { compileSdkVersion 28 defaultConfig { applicationId "com.example.andy.tutorialspoint" minSdkVersion 19 targetSdkVersion 28 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.android.support:appcompat-v7:28.0.0' implementation 'com.android.support:design:28.0.0' implementation 'com.android.support.constraint:constraint-layout:1.1.3' implementation 'com.android.support:cardview-v7:28.0.0' implementation 'com.android.support:recyclerview-v7:28.0.0' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' } Step 3 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:tools = "http://schemas.android.com/tools" xmlns:app = "http://schemas.android.com/apk/res-auto" android:layout_width = "match_parent" android:layout_height = "match_parent" app:layout_behavior = "@string/appbar_scrolling_view_behavior" tools:showIn = "@layout/activity_main" tools:context = ".MainActivity"> <android.support.v7.widget.RecyclerView android:id = "@+id/recycler_view" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:scrollbars = "horizontal" /> </RelativeLayout> In the above code we have added recycler view to window manger as relative parent layout and assigned Horizontal scroll bars to scroll horizontal way. Step 4 − Add the following code to src/MainActivity.java package com.example.andy.tutorialspoint; import android.annotation.TargetApi; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DividerItemDecoration; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.Toast; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class MainActivity extends AppCompatActivity { private RecyclerView recyclerView; private StudentAdapter studentAdapter; private List studentDataList = new ArrayList<>(); @TargetApi(Build.VERSION_CODES.O) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); recyclerView = findViewById(R.id.recycler_view); studentAdapter = new StudentAdapter(studentDataList,MainActivity.this); RecyclerView.LayoutManager manager = new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL, false); recyclerView.setLayoutManager(manager); recyclerView.setAdapter(studentAdapter); StudentDataPrepare(); } @RequiresApi(api = Build.VERSION_CODES.N) private void StudentDataPrepare() { studentData data = new studentData("sai", 25); studentDataList.add(data); data = new studentData("sai raj", 25); studentDataList.add(data); data = new studentData("raghu", 20); studentDataList.add(data); data = new studentData("raj", 28); studentDataList.add(data); data = new studentData("amar", 15); studentDataList.add(data); data = new studentData("bapu", 19); studentDataList.add(data); data = new studentData("chandra", 52); studentDataList.add(data); data = new studentData("deraj", 30); studentDataList.add(data); data = new studentData("eshanth", 28); studentDataList.add(data); Collections.sort(studentDataList, new Comparator() { @Override public int compare(studentData o1, studentData o2) { return o1.name.compareTo(o2.name); } }); } } In the above code we have added recycler view and studentAdapter. In that student adapter we have passed studentDatalist as arraylist. In Student data list contains name of the student and age. To get the horizontal view we need to add layout prams' as shown below - RecyclerView.LayoutManager manager = new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL, false); recyclerView.setLayoutManager(manager); In the above code we added LinearLayoutManager and scroll position is Horizontal so it going to scroll Horizontal way. Step 5 − Following is the content of the modified file src/ StudentAdapter.java. package com.example.andy.tutorialspoint; import android.graphics.Color; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import java.util.List; import java.util.Random; class StudentAdapter extends RecyclerView.Adapter { List<studentData> studentDataList; public StudentAdapter(List studentDataList) { this.studentDataList = studentDataList; } @NonNull @Override public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View itemView = LayoutInflater.from(viewGroup.getContext()) .inflate(R.layout.student_list_row, viewGroup, false); return new MyViewHolder(itemView); } @Override public void onBindViewHolder(MyViewHolder viewHolder, int i) { studentData data = studentDataList.get(i); Random rnd = new Random(); int currentColor = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256)); viewHolder.parent.setBackgroundColor(currentColor); viewHolder.name.setText(data.name); viewHolder.age.setText(String.valueOf(data.age)); } @Override public int getItemCount() { return studentDataList.size(); } class MyViewHolder extends RecyclerView.ViewHolder { TextView name,age; LinearLayout parent; public MyViewHolder(View itemView) { super(itemView); parent = itemView.findViewById(R.id.parent); name = itemView.findViewById(R.id.name); age = itemView.findViewById(R.id.age); } } } In the adapter class we have four methods as shown below - onCreateViewHolder() :- It is used to create a view holder and it returns a view. onCreateViewHolder() :- It is used to create a view holder and it returns a view. onBindViewHolder() - it going to bind with created view holder. onBindViewHolder() - it going to bind with created view holder. getItemCount() - it contains size of list. getItemCount() - it contains size of list. MyViewHolder class- it is view holder inner class which is extended by RecyclerView.ViewHolder MyViewHolder class- it is view holder inner class which is extended by RecyclerView.ViewHolder To set random background for recycler view items, we have generated random colors using random class(which is predefined class in Android) and added color to parent of view item as shown below - Random rnd = new Random(); int currentColor = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256)); viewHolder.parent.setBackgroundColor(currentColor); Step 6 − Following is the modified content of the xml res/layout/student_list_row.xml. <?xml version = "1.0" encoding = "utf-8"?> <android.support.v7.widget.CardView xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:card_view = "http://schemas.android.com/apk/res-auto" android:layout_width = "match_parent" card_view:cardCornerRadius = "4dp" android:id = "@+id/card_view" android:layout_margin = "10dp" android:layout_height = "200dp"> <LinearLayout android:id = "@+id/parent" android:layout_gravity = "center" android:layout_width = "match_parent" android:orientation = "vertical" android:gravity = "center" android:layout_height = "match_parent"> <TextView android:id = "@+id/name" android:layout_width = "wrap_content" android:gravity = "center" android:textSize = "25sp" android:textColor = "#FFF" android:layout_height = "wrap_content" /> <TextView android:id = "@+id/age" android:layout_width = "wrap_content" android:gravity = "center" android:textSize = "25sp" android:textColor = "#FFF" android:layout_height = "wrap_content" /> </LinearLayout> </android.support.v7.widget.CardView> In the above list item view we have created two text views for name and age inside the cardview. Card view contains pre defined corner radius and shadow property. So we have used corner radius with card view. Step 7 − Following is the content of the modified file src/ studentData.java. package com.example.andy.tutorialspoint; class studentData { String name; int age; public studentData(String name, int age) { this.name = name; this.age = age; } } In the above code informs about student data object. 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 − Now scroll horizontal way to the recyclerview, it will show the result as shown below - Click here to download the project code
[ { "code": null, "e": 1424, "s": 1187, "text": "Before getting into example, we should know what is Recycler view in android. Recycler view is more advanced version of list view and it works based on View holder design pattern. Using recycler view we can show grids and list of items." }, { "code": null, "e": 1591, "s": 1424, "text": "This example demonstrate about how to build a horizontal list view with Recycler View by creating a beautiful student records app that displays student name with age." }, { "code": null, "e": 1720, "s": 1591, "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": 1803, "s": 1720, "text": "Step 2 − Open build.gradle and add Recycler view & Card view library dependencies." }, { "code": null, "e": 2880, "s": 1803, "text": "apply plugin: 'com.android.application'\nandroid {\n compileSdkVersion 28\n defaultConfig {\n applicationId \"com.example.andy.tutorialspoint\"\n minSdkVersion 19\n targetSdkVersion 28\n versionCode 1\n versionName \"1.0\"\n testInstrumentationRunner \"android.support.test.runner.AndroidJUnitRunner\"\n }\n buildTypes {\n release {\n minifyEnabled false\n proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\n }\n }\n}\ndependencies {\n implementation fileTree(dir: 'libs', include: ['*.jar'])\n implementation 'com.android.support:appcompat-v7:28.0.0'\n implementation 'com.android.support:design:28.0.0'\n implementation 'com.android.support.constraint:constraint-layout:1.1.3'\n implementation 'com.android.support:cardview-v7:28.0.0'\n implementation 'com.android.support:recyclerview-v7:28.0.0'\n testImplementation 'junit:junit:4.12'\n androidTestImplementation 'com.android.support.test:runner:1.0.2'\n androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'\n}" }, { "code": null, "e": 2945, "s": 2880, "text": "Step 3 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 3637, "s": 2945, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<RelativeLayout\n xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n app:layout_behavior = \"@string/appbar_scrolling_view_behavior\"\n tools:showIn = \"@layout/activity_main\"\n tools:context = \".MainActivity\">\n <android.support.v7.widget.RecyclerView\n android:id = \"@+id/recycler_view\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:scrollbars = \"horizontal\" />\n</RelativeLayout>" }, { "code": null, "e": 3788, "s": 3637, "text": "In the above code we have added recycler view to window manger as relative parent layout and assigned Horizontal scroll bars to scroll horizontal way." }, { "code": null, "e": 3845, "s": 3788, "text": "Step 4 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 6260, "s": 3845, "text": "package com.example.andy.tutorialspoint;\n\nimport android.annotation.TargetApi;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.support.v7.widget.DividerItemDecoration;\nimport android.support.v7.widget.GridLayoutManager;\nimport android.support.v7.widget.LinearLayoutManager;\nimport android.support.v7.widget.RecyclerView;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.LinearLayout;\nimport android.widget.Toast;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.List;\n\n\npublic class MainActivity extends AppCompatActivity {\n private RecyclerView recyclerView;\n private StudentAdapter studentAdapter;\n private List studentDataList = new ArrayList<>();\n @TargetApi(Build.VERSION_CODES.O)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n recyclerView = findViewById(R.id.recycler_view);\n studentAdapter = new StudentAdapter(studentDataList,MainActivity.this);\n RecyclerView.LayoutManager manager = new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL, false);\n recyclerView.setLayoutManager(manager);\n recyclerView.setAdapter(studentAdapter);\n StudentDataPrepare();\n }\n @RequiresApi(api = Build.VERSION_CODES.N)\n private void StudentDataPrepare() {\n studentData data = new studentData(\"sai\", 25);\n studentDataList.add(data);\n data = new studentData(\"sai raj\", 25);\n studentDataList.add(data);\n data = new studentData(\"raghu\", 20);\n studentDataList.add(data);\n data = new studentData(\"raj\", 28);\n studentDataList.add(data);\n data = new studentData(\"amar\", 15);\n studentDataList.add(data);\n data = new studentData(\"bapu\", 19);\n studentDataList.add(data);\n data = new studentData(\"chandra\", 52);\n studentDataList.add(data);\n data = new studentData(\"deraj\", 30);\n studentDataList.add(data);\n data = new studentData(\"eshanth\", 28);\n studentDataList.add(data);\n Collections.sort(studentDataList, new Comparator() {\n @Override\n public int compare(studentData o1, studentData o2) {\n return o1.name.compareTo(o2.name);\n }\n });\n }\n}" }, { "code": null, "e": 6454, "s": 6260, "text": "In the above code we have added recycler view and studentAdapter. In that student adapter we have passed studentDatalist as arraylist. In Student data list contains name of the student and age." }, { "code": null, "e": 6527, "s": 6454, "text": "To get the horizontal view we need to add layout prams' as shown below -" }, { "code": null, "e": 6673, "s": 6527, "text": "RecyclerView.LayoutManager manager = new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL, false);\nrecyclerView.setLayoutManager(manager);" }, { "code": null, "e": 6792, "s": 6673, "text": "In the above code we added LinearLayoutManager and scroll position is Horizontal so it going to scroll Horizontal way." }, { "code": null, "e": 6873, "s": 6792, "text": "Step 5 − Following is the content of the modified file src/ StudentAdapter.java." }, { "code": null, "e": 8564, "s": 6873, "text": "package com.example.andy.tutorialspoint;\n\nimport android.graphics.Color;\nimport android.support.annotation.NonNull;\nimport android.support.v7.widget.RecyclerView;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.LinearLayout;\nimport android.widget.TextView;\n\nimport java.util.List;\nimport java.util.Random;\n\nclass StudentAdapter extends RecyclerView.Adapter {\n List<studentData> studentDataList;\n public StudentAdapter(List studentDataList) {\n this.studentDataList = studentDataList;\n }\n @NonNull\n @Override\n public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {\n View itemView = LayoutInflater.from(viewGroup.getContext())\n .inflate(R.layout.student_list_row, viewGroup, false);\n return new MyViewHolder(itemView);\n }\n @Override\n public void onBindViewHolder(MyViewHolder viewHolder, int i) {\n studentData data = studentDataList.get(i);\n Random rnd = new Random();\n int currentColor = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));\n viewHolder.parent.setBackgroundColor(currentColor);\n viewHolder.name.setText(data.name);\n viewHolder.age.setText(String.valueOf(data.age));\n }\n @Override\n public int getItemCount() {\n return studentDataList.size();\n }\n class MyViewHolder extends RecyclerView.ViewHolder {\n TextView name,age;\n LinearLayout parent;\n public MyViewHolder(View itemView) {\n super(itemView);\n parent = itemView.findViewById(R.id.parent);\n name = itemView.findViewById(R.id.name);\n age = itemView.findViewById(R.id.age);\n }\n }\n}" }, { "code": null, "e": 8623, "s": 8564, "text": "In the adapter class we have four methods as shown below -" }, { "code": null, "e": 8705, "s": 8623, "text": "onCreateViewHolder() :- It is used to create a view holder and it returns a view." }, { "code": null, "e": 8787, "s": 8705, "text": "onCreateViewHolder() :- It is used to create a view holder and it returns a view." }, { "code": null, "e": 8851, "s": 8787, "text": "onBindViewHolder() - it going to bind with created view holder." }, { "code": null, "e": 8915, "s": 8851, "text": "onBindViewHolder() - it going to bind with created view holder." }, { "code": null, "e": 8958, "s": 8915, "text": "getItemCount() - it contains size of list." }, { "code": null, "e": 9001, "s": 8958, "text": "getItemCount() - it contains size of list." }, { "code": null, "e": 9096, "s": 9001, "text": "MyViewHolder class- it is view holder inner class which is extended by RecyclerView.ViewHolder" }, { "code": null, "e": 9191, "s": 9096, "text": "MyViewHolder class- it is view holder inner class which is extended by RecyclerView.ViewHolder" }, { "code": null, "e": 9386, "s": 9191, "text": "To set random background for recycler view items, we have generated random colors using random class(which is predefined class in Android) and added color to parent of view item as shown below -" }, { "code": null, "e": 9555, "s": 9386, "text": "Random rnd = new Random();\nint currentColor = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));\nviewHolder.parent.setBackgroundColor(currentColor);" }, { "code": null, "e": 9642, "s": 9555, "text": "Step 6 − Following is the modified content of the xml res/layout/student_list_row.xml." }, { "code": null, "e": 10845, "s": 9642, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<android.support.v7.widget.CardView xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:card_view = \"http://schemas.android.com/apk/res-auto\"\n android:layout_width = \"match_parent\"\n card_view:cardCornerRadius = \"4dp\"\n android:id = \"@+id/card_view\"\n android:layout_margin = \"10dp\"\n android:layout_height = \"200dp\">\n <LinearLayout\n android:id = \"@+id/parent\"\n android:layout_gravity = \"center\"\n android:layout_width = \"match_parent\"\n android:orientation = \"vertical\"\n android:gravity = \"center\"\n android:layout_height = \"match_parent\">\n <TextView\n android:id = \"@+id/name\"\n android:layout_width = \"wrap_content\"\n android:gravity = \"center\"\n android:textSize = \"25sp\"\n android:textColor = \"#FFF\"\n android:layout_height = \"wrap_content\" />\n <TextView\n android:id = \"@+id/age\"\n android:layout_width = \"wrap_content\"\n android:gravity = \"center\"\n android:textSize = \"25sp\"\n android:textColor = \"#FFF\"\n android:layout_height = \"wrap_content\" />\n </LinearLayout>\n</android.support.v7.widget.CardView>" }, { "code": null, "e": 11054, "s": 10845, "text": "In the above list item view we have created two text views for name and age inside the cardview. Card view contains pre defined corner radius and shadow property. So we have used corner radius with card view." }, { "code": null, "e": 11173, "s": 11054, "text": "Step 7 − Following is the content of the modified file src/ studentData.java. package com.example.andy.tutorialspoint;" }, { "code": null, "e": 11320, "s": 11173, "text": "class studentData {\n String name;\n int age;\n public studentData(String name, int age) {\n this.name = name;\n this.age = age;\n }\n}" }, { "code": null, "e": 11721, "s": 11320, "text": "In the above code informs about student data object. 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": 11809, "s": 11721, "text": "Now scroll horizontal way to the recyclerview, it will show the result as shown below -" }, { "code": null, "e": 11849, "s": 11809, "text": "Click here to download the project code" } ]
Compute the parity of a number using XOR and table look-up
27 Jun, 2022 Parity of a number refers to whether it contains an odd or even number of 1-bits. The number has “odd parity”, if it contains odd number of 1-bits and is “even parity” if it contains even number of 1-bits. 1 --> parity of the set is odd 0 --> parity of the set is even Examples: Input : 254 Output : Odd Parity Explanation : Binary of 254 is 11111110. There are 7 ones. Thus, parity is odd. Input : 1742346774 Output : Even Method 1 : (Naive approach) We have already discussed this method here. Method 2 : (Efficient) Pre-requisites : Table look up, X-OR magic If we break a number S into two parts S1 and S2 such S = S1S2. If we know parity of S1 and S2, we can compute parity of S using below facts : If S1 and S2 have the same parity, i.e. they both have an even number of bits or an odd number of bits, their union S will have an even number of bits.Therefore parity of S is XOR of parities of S1 and S2 If S1 and S2 have the same parity, i.e. they both have an even number of bits or an odd number of bits, their union S will have an even number of bits. Therefore parity of S is XOR of parities of S1 and S2 The idea is to create a look up table to store parities of all 8 bit numbers. Then compute parity of whole number by dividing it into 8 bit numbers and using above facts. Steps: 1. Create a look-up table for 8-bit numbers ( 0 to 255 ) Parity of 0 is 0. Parity of 1 is 1. . . . Parity of 255 is 0. 2. Break the number into 8-bit chunks while performing XOR operations. 3. Check for the result in the table for the 8-bit number. Since a 32 bit or 64 bit number contains constant number of bytes, the above steps take O(1) time. Example : 1. Take 32-bit number : 1742346774 2. Calculate Binary of the number : 01100111110110100001101000010110 3. Split the 32-bit binary representation into 16-bit chunks : 0110011111011010 | 0001101000010110 4. Compute X-OR : 0110011111011010 ^ 0001101000010110 ___________________ = 0111110111001100 5. Split the 16-bit binary representation into 8-bit chunks : 01111101 | 11001100 6. Again, Compute X-OR : 01111101 ^ 11001100 ___________________ = 10110001 10110001 is 177 in decimal. Check for its parity in look-up table : Even number of 1 = Even parity. Thus, Parity of 1742346774 is even. Below is the implementation that works for both 32 bit and 64 bit numbers. C++ Java Python3 C# PHP Javascript // CPP program to illustrate Compute the parity of a// number using XOR#include <bits/stdc++.h> // Generating the look-up table while pre-processing#define P2(n) n, n ^ 1, n ^ 1, n#define P4(n) P2(n), P2(n ^ 1), P2(n ^ 1), P2(n)#define P6(n) P4(n), P4(n ^ 1), P4(n ^ 1), P4(n)#define LOOK_UP P6(0), P6(1), P6(1), P6(0) // LOOK_UP is the macro expansion to generate the tableunsigned int table[256] = { LOOK_UP }; // Function to find the parityint Parity(int num){ // Number is considered to be of 32 bits int max = 16; // Dividing the number into 8-bit // chunks while performing X-OR while (max >= 8) { num = num ^ (num >> max); max = max / 2; } // Masking the number with 0xff (11111111) // to produce valid 8-bit result return table[num & 0xff];} // Driver codeint main(){ unsigned int num = 1742346774; // Result is 1 for odd parity, 0 for even parity bool result = Parity(num); // Printing the desired result result ? std::cout << "Odd Parity" : std::cout << "Even Parity"; return 0;} // Java program to illustrate Compute the// parity of a number using XOR import java.util.ArrayList; class GFG { // LOOK_UP is the macro expansion to // generate the table static ArrayList<Integer> table = new ArrayList<Integer>(); // Generating the look-up table while // pre-processing static void P2(int n) { table.add(n); table.add(n ^ 1); table.add(n ^ 1); table.add(n); } static void P4(int n) { P2(n); P2(n ^ 1); P2(n ^ 1); P2(n); } static void P6(int n) { P4(n); P4(n ^ 1); P4(n ^ 1); P4(n) ; } static void LOOK_UP() { P6(0); P6(1); P6(1); P6(0); } // Function to find the parity static int Parity(int num) { // Number is considered to be // of 32 bits int max = 16; // Dividing the number o 8-bit // chunks while performing X-OR while (max >= 8) { num = num ^ (num >> max); max = (max / 2); } // Masking the number with 0xff (11111111) // to produce valid 8-bit result return table.get(num & 0xff); } public static void main(String[] args) { // Driver code int num = 1742346774; LOOK_UP(); //Function call int result = Parity(num); // Result is 1 for odd parity, // 0 for even parity if (result != 0) System.out.println("Odd Parity"); else System.out.println("Even Parity"); }} //This code is contributed by phasing17 # Python3 program to illustrate Compute the# parity of a number using XOR # Generating the look-up table while# pre-processingdef P2(n, table): table.extend([n, n ^ 1, n ^ 1, n])def P4(n, table): return (P2(n, table), P2(n ^ 1, table), P2(n ^ 1, table), P2(n, table))def P6(n, table): return (P4(n, table), P4(n ^ 1, table), P4(n ^ 1, table), P4(n, table))def LOOK_UP(table): return (P6(0, table), P6(1, table), P6(1, table), P6(0, table)) # LOOK_UP is the macro expansion to# generate the tabletable = [0] * 256LOOK_UP(table) # Function to find the paritydef Parity(num) : # Number is considered to be # of 32 bits max = 16 # Dividing the number o 8-bit # chunks while performing X-OR while (max >= 8): num = num ^ (num >> max) max = max // 2 # Masking the number with 0xff (11111111) # to produce valid 8-bit result return table[num & 0xff] # Driver codeif __name__ =="__main__": num = 1742346774 # Result is 1 for odd parity, # 0 for even parity result = Parity(num) print("Odd Parity") if result else print("Even Parity") # This code is contributed by# Shubham Singh(SHUBHAMSINGH10) // C# program to illustrate Compute the// parity of a number using XORusing System;using System.Collections.Generic; class GFG { // LOOK_UP is the macro expansion to // generate the table static List<int> table = new List<int>(); // Generating the look-up table while // pre-processing static void P2(int n) { table.Add(n); table.Add(n ^ 1); table.Add(n ^ 1); table.Add(n); } static void P4(int n) { P2(n); P2(n ^ 1); P2(n ^ 1); P2(n); } static void P6(int n) { P4(n); P4(n ^ 1); P4(n ^ 1); P4(n); } static void LOOK_UP() { P6(0); P6(1); P6(1); P6(0); } // Function to find the parity static int Parity(int num) { // Number is considered to be // of 32 bits int max = 16; // Dividing the number o 8-bit // chunks while performing X-OR while (max >= 8) { num = num ^ (num >> max); max = (max / 2); } // Masking the number with 0xff (11111111) // to produce valid 8-bit result return table[num & 0xff]; } public static void Main(string[] args) { // Driver code int num = 1742346774; LOOK_UP(); // Function call int result = Parity(num); // Result is 1 for odd parity, // 0 for even parity if (result != 0) Console.WriteLine("Odd Parity"); else Console.WriteLine("Even Parity"); }} // This code is contributed by phasing17 <?php// PHP program to illustrate// Compute the parity of a// number using XOR /* Generating the look-uptable while pre-processing#define P2(n) n, n ^ 1, n ^ 1, n#define P4(n) P2(n), P2(n ^ 1), P2(n ^ 1), P2(n)#define P6(n) P4(n), P4(n ^ 1), P4(n ^ 1), P4(n)#define LOOK_UP P6(0), P6(1), P6(1), P6(0) LOOK_UP is the macro expansionto generate the table$table = array(LOOK_UP );*/ // Function to find// the parityfunction Parity($num){ global $table; // Number is considered // to be of 32 bits $max = 16; // Dividing the number // into 8-bit chunks // while performing X-OR while ($max >= 8) { $num = $num ^ ($num >> $max); $max = (int)$max / 2; } // Masking the number with // 0xff (11111111) to produce // valid 8-bit result return $table[$num & 0xff];} // Driver code$num = 1742346774; // Result is 1 for odd// parity, 0 for even parity$result = Parity($num); // Printing the desired resultif($result == true) echo "Odd Parity" ; else echo"Even Parity"; // This code is contributed by ajit?> //JavaScript program to illustrate Compute the// parity of a number using XOR // Generating the look-up table while// pre-processingfunction P2(n, table){ table.push(n, n ^ 1, n ^ 1, n);} function P4(n, table){ return (P2(n, table), P2(n ^ 1, table), P2(n ^ 1, table), P2(n, table));} function P6(n, table){ return (P4(n, table), P4(n ^ 1, table), P4(n ^ 1, table), P4(n, table)) ;} function LOOK_UP(table){ return (P6(0, table), P6(1, table), P6(1, table), P6(0, table));} // LOOK_UP is the macro expansion to// generate the tablevar table = new Array(256).fill(0);LOOK_UP(table); // Function to find the parityfunction Parity(num){ // Number is considered to be // of 32 bits var max = 16; // Dividing the number o 8-bit // chunks while performing X-OR while (max >= 8) { num = num ^ (num >> max); max = Math.floor(max / 2); } // Masking the number with 0xff (11111111) // to produce valid 8-bit result return table[num & 0xff] ;} // Driver codevar num = 1742346774; //Function callvar result = Parity(num);// Result is 1 for odd parity,// 0 for even parityconsole.log(result ? "Odd Parity" : "Even Parity"); // This code is contributed by phasing17 Output: Even Parity Time Complexity : O(1). Note that a 32 bit or 64 bit number has fixed number of bytes (4 in case of 32 bits and 8 in case of 64 bits). This article is contributed by Rohit Thapliyal. 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. jit_t SHUBHAMSINGH10 surinderdawra388 phasing17 cryptography Bit Magic Mathematical Mathematical Bit Magic cryptography Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Left Shift and Right Shift Operators in C/C++ Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Count set bits in an integer How to swap two numbers without using a temporary variable? Program to find whether a given number is power of 2 Program for Fibonacci numbers Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays
[ { "code": null, "e": 52, "s": 24, "text": "\n27 Jun, 2022" }, { "code": null, "e": 258, "s": 52, "text": "Parity of a number refers to whether it contains an odd or even number of 1-bits. The number has “odd parity”, if it contains odd number of 1-bits and is “even parity” if it contains even number of 1-bits." }, { "code": null, "e": 321, "s": 258, "text": "1 --> parity of the set is odd\n0 --> parity of the set is even" }, { "code": null, "e": 331, "s": 321, "text": "Examples:" }, { "code": null, "e": 478, "s": 331, "text": "Input : 254\nOutput : Odd Parity\nExplanation : Binary of 254 is 11111110. \nThere are 7 ones. Thus, parity is odd.\n\nInput : 1742346774\nOutput : Even" }, { "code": null, "e": 758, "s": 478, "text": "Method 1 : (Naive approach) We have already discussed this method here. Method 2 : (Efficient) Pre-requisites : Table look up, X-OR magic If we break a number S into two parts S1 and S2 such S = S1S2. If we know parity of S1 and S2, we can compute parity of S using below facts :" }, { "code": null, "e": 963, "s": 758, "text": "If S1 and S2 have the same parity, i.e. they both have an even number of bits or an odd number of bits, their union S will have an even number of bits.Therefore parity of S is XOR of parities of S1 and S2" }, { "code": null, "e": 1115, "s": 963, "text": "If S1 and S2 have the same parity, i.e. they both have an even number of bits or an odd number of bits, their union S will have an even number of bits." }, { "code": null, "e": 1169, "s": 1115, "text": "Therefore parity of S is XOR of parities of S1 and S2" }, { "code": null, "e": 1347, "s": 1169, "text": "The idea is to create a look up table to store parities of all 8 bit numbers. Then compute parity of whole number by dividing it into 8 bit numbers and using above facts. Steps:" }, { "code": null, "e": 1621, "s": 1347, "text": "1. Create a look-up table for 8-bit numbers ( 0 to 255 )\n Parity of 0 is 0.\n Parity of 1 is 1.\n .\n .\n .\n Parity of 255 is 0.\n2. Break the number into 8-bit chunks\n while performing XOR operations.\n3. Check for the result in the table for\n the 8-bit number." }, { "code": null, "e": 1730, "s": 1621, "text": "Since a 32 bit or 64 bit number contains constant number of bytes, the above steps take O(1) time. Example :" }, { "code": null, "e": 2343, "s": 1730, "text": "1. Take 32-bit number : 1742346774\n\n2. Calculate Binary of the number : \n 01100111110110100001101000010110\n\n3. Split the 32-bit binary representation into \n 16-bit chunks :\n0110011111011010 | 0001101000010110 \n\n4. Compute X-OR :\n 0110011111011010\n^ 0001101000010110\n___________________\n= 0111110111001100\n\n5. Split the 16-bit binary representation \n into 8-bit chunks : 01111101 | 11001100\n\n6. Again, Compute X-OR :\n 01111101\n^ 11001100\n___________________\n= 10110001\n10110001 is 177 in decimal. Check\n for its parity in look-up table :\nEven number of 1 = Even parity.\n\nThus, Parity of 1742346774 is even." }, { "code": null, "e": 2419, "s": 2343, "text": "Below is the implementation that works for both 32 bit and 64 bit numbers. " }, { "code": null, "e": 2423, "s": 2419, "text": "C++" }, { "code": null, "e": 2428, "s": 2423, "text": "Java" }, { "code": null, "e": 2436, "s": 2428, "text": "Python3" }, { "code": null, "e": 2439, "s": 2436, "text": "C#" }, { "code": null, "e": 2443, "s": 2439, "text": "PHP" }, { "code": null, "e": 2454, "s": 2443, "text": "Javascript" }, { "code": "// CPP program to illustrate Compute the parity of a// number using XOR#include <bits/stdc++.h> // Generating the look-up table while pre-processing#define P2(n) n, n ^ 1, n ^ 1, n#define P4(n) P2(n), P2(n ^ 1), P2(n ^ 1), P2(n)#define P6(n) P4(n), P4(n ^ 1), P4(n ^ 1), P4(n)#define LOOK_UP P6(0), P6(1), P6(1), P6(0) // LOOK_UP is the macro expansion to generate the tableunsigned int table[256] = { LOOK_UP }; // Function to find the parityint Parity(int num){ // Number is considered to be of 32 bits int max = 16; // Dividing the number into 8-bit // chunks while performing X-OR while (max >= 8) { num = num ^ (num >> max); max = max / 2; } // Masking the number with 0xff (11111111) // to produce valid 8-bit result return table[num & 0xff];} // Driver codeint main(){ unsigned int num = 1742346774; // Result is 1 for odd parity, 0 for even parity bool result = Parity(num); // Printing the desired result result ? std::cout << \"Odd Parity\" : std::cout << \"Even Parity\"; return 0;}", "e": 3520, "s": 2454, "text": null }, { "code": "// Java program to illustrate Compute the// parity of a number using XOR import java.util.ArrayList; class GFG { // LOOK_UP is the macro expansion to // generate the table static ArrayList<Integer> table = new ArrayList<Integer>(); // Generating the look-up table while // pre-processing static void P2(int n) { table.add(n); table.add(n ^ 1); table.add(n ^ 1); table.add(n); } static void P4(int n) { P2(n); P2(n ^ 1); P2(n ^ 1); P2(n); } static void P6(int n) { P4(n); P4(n ^ 1); P4(n ^ 1); P4(n) ; } static void LOOK_UP() { P6(0); P6(1); P6(1); P6(0); } // Function to find the parity static int Parity(int num) { // Number is considered to be // of 32 bits int max = 16; // Dividing the number o 8-bit // chunks while performing X-OR while (max >= 8) { num = num ^ (num >> max); max = (max / 2); } // Masking the number with 0xff (11111111) // to produce valid 8-bit result return table.get(num & 0xff); } public static void main(String[] args) { // Driver code int num = 1742346774; LOOK_UP(); //Function call int result = Parity(num); // Result is 1 for odd parity, // 0 for even parity if (result != 0) System.out.println(\"Odd Parity\"); else System.out.println(\"Even Parity\"); }} //This code is contributed by phasing17", "e": 5203, "s": 3520, "text": null }, { "code": "# Python3 program to illustrate Compute the# parity of a number using XOR # Generating the look-up table while# pre-processingdef P2(n, table): table.extend([n, n ^ 1, n ^ 1, n])def P4(n, table): return (P2(n, table), P2(n ^ 1, table), P2(n ^ 1, table), P2(n, table))def P6(n, table): return (P4(n, table), P4(n ^ 1, table), P4(n ^ 1, table), P4(n, table))def LOOK_UP(table): return (P6(0, table), P6(1, table), P6(1, table), P6(0, table)) # LOOK_UP is the macro expansion to# generate the tabletable = [0] * 256LOOK_UP(table) # Function to find the paritydef Parity(num) : # Number is considered to be # of 32 bits max = 16 # Dividing the number o 8-bit # chunks while performing X-OR while (max >= 8): num = num ^ (num >> max) max = max // 2 # Masking the number with 0xff (11111111) # to produce valid 8-bit result return table[num & 0xff] # Driver codeif __name__ ==\"__main__\": num = 1742346774 # Result is 1 for odd parity, # 0 for even parity result = Parity(num) print(\"Odd Parity\") if result else print(\"Even Parity\") # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)", "e": 6400, "s": 5203, "text": null }, { "code": "// C# program to illustrate Compute the// parity of a number using XORusing System;using System.Collections.Generic; class GFG { // LOOK_UP is the macro expansion to // generate the table static List<int> table = new List<int>(); // Generating the look-up table while // pre-processing static void P2(int n) { table.Add(n); table.Add(n ^ 1); table.Add(n ^ 1); table.Add(n); } static void P4(int n) { P2(n); P2(n ^ 1); P2(n ^ 1); P2(n); } static void P6(int n) { P4(n); P4(n ^ 1); P4(n ^ 1); P4(n); } static void LOOK_UP() { P6(0); P6(1); P6(1); P6(0); } // Function to find the parity static int Parity(int num) { // Number is considered to be // of 32 bits int max = 16; // Dividing the number o 8-bit // chunks while performing X-OR while (max >= 8) { num = num ^ (num >> max); max = (max / 2); } // Masking the number with 0xff (11111111) // to produce valid 8-bit result return table[num & 0xff]; } public static void Main(string[] args) { // Driver code int num = 1742346774; LOOK_UP(); // Function call int result = Parity(num); // Result is 1 for odd parity, // 0 for even parity if (result != 0) Console.WriteLine(\"Odd Parity\"); else Console.WriteLine(\"Even Parity\"); }} // This code is contributed by phasing17", "e": 7996, "s": 6400, "text": null }, { "code": "<?php// PHP program to illustrate// Compute the parity of a// number using XOR /* Generating the look-uptable while pre-processing#define P2(n) n, n ^ 1, n ^ 1, n#define P4(n) P2(n), P2(n ^ 1), P2(n ^ 1), P2(n)#define P6(n) P4(n), P4(n ^ 1), P4(n ^ 1), P4(n)#define LOOK_UP P6(0), P6(1), P6(1), P6(0) LOOK_UP is the macro expansionto generate the table$table = array(LOOK_UP );*/ // Function to find// the parityfunction Parity($num){ global $table; // Number is considered // to be of 32 bits $max = 16; // Dividing the number // into 8-bit chunks // while performing X-OR while ($max >= 8) { $num = $num ^ ($num >> $max); $max = (int)$max / 2; } // Masking the number with // 0xff (11111111) to produce // valid 8-bit result return $table[$num & 0xff];} // Driver code$num = 1742346774; // Result is 1 for odd// parity, 0 for even parity$result = Parity($num); // Printing the desired resultif($result == true) echo \"Odd Parity\" ; else echo\"Even Parity\"; // This code is contributed by ajit?>", "e": 9112, "s": 7996, "text": null }, { "code": "//JavaScript program to illustrate Compute the// parity of a number using XOR // Generating the look-up table while// pre-processingfunction P2(n, table){ table.push(n, n ^ 1, n ^ 1, n);} function P4(n, table){ return (P2(n, table), P2(n ^ 1, table), P2(n ^ 1, table), P2(n, table));} function P6(n, table){ return (P4(n, table), P4(n ^ 1, table), P4(n ^ 1, table), P4(n, table)) ;} function LOOK_UP(table){ return (P6(0, table), P6(1, table), P6(1, table), P6(0, table));} // LOOK_UP is the macro expansion to// generate the tablevar table = new Array(256).fill(0);LOOK_UP(table); // Function to find the parityfunction Parity(num){ // Number is considered to be // of 32 bits var max = 16; // Dividing the number o 8-bit // chunks while performing X-OR while (max >= 8) { num = num ^ (num >> max); max = Math.floor(max / 2); } // Masking the number with 0xff (11111111) // to produce valid 8-bit result return table[num & 0xff] ;} // Driver codevar num = 1742346774; //Function callvar result = Parity(num);// Result is 1 for odd parity,// 0 for even parityconsole.log(result ? \"Odd Parity\" : \"Even Parity\"); // This code is contributed by phasing17", "e": 10364, "s": 9112, "text": null }, { "code": null, "e": 10372, "s": 10364, "text": "Output:" }, { "code": null, "e": 10384, "s": 10372, "text": "Even Parity" }, { "code": null, "e": 10943, "s": 10384, "text": "Time Complexity : O(1). Note that a 32 bit or 64 bit number has fixed number of bytes (4 in case of 32 bits and 8 in case of 64 bits). This article is contributed by Rohit Thapliyal. 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": 10949, "s": 10943, "text": "jit_t" }, { "code": null, "e": 10964, "s": 10949, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 10981, "s": 10964, "text": "surinderdawra388" }, { "code": null, "e": 10991, "s": 10981, "text": "phasing17" }, { "code": null, "e": 11004, "s": 10991, "text": "cryptography" }, { "code": null, "e": 11014, "s": 11004, "text": "Bit Magic" }, { "code": null, "e": 11027, "s": 11014, "text": "Mathematical" }, { "code": null, "e": 11040, "s": 11027, "text": "Mathematical" }, { "code": null, "e": 11050, "s": 11040, "text": "Bit Magic" }, { "code": null, "e": 11063, "s": 11050, "text": "cryptography" }, { "code": null, "e": 11161, "s": 11063, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11207, "s": 11161, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 11275, "s": 11207, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 11304, "s": 11275, "text": "Count set bits in an integer" }, { "code": null, "e": 11364, "s": 11304, "text": "How to swap two numbers without using a temporary variable?" }, { "code": null, "e": 11417, "s": 11364, "text": "Program to find whether a given number is power of 2" }, { "code": null, "e": 11447, "s": 11417, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 11490, "s": 11447, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 11550, "s": 11490, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 11565, "s": 11550, "text": "C++ Data Types" } ]
Java Program to Display Current Hour and Current Minute
06 Jul, 2022 The difference between Date and Calendar is that the Date class operates with a specific instant in time and Calendar operates with a difference between two dates. The Calendar class gives you the possibility for converting between a specific instant in time and a set of calendar fields such as HOUR, YEAR, MONTH, DAY_OF_MONTH. Manipulation over the calendar fields taken for instance getting backdate when the organization was formed or birthdays. Calendar Class It is used to display the date and time and manipulate date and time in java and in addition to this it is also used for formatting date and time class in java across time zone associated data. So in order to import this class from a package called “java.utils”. After importing this class one can create an object of the Date class in order to print the current date and time. Now in order to print the default date and time simply call the print command using toString() method to get the current date and time. java.util.Calendar.get() method is a method of java.util.Calendar class. The Calendar class provides some methods for implementing a concrete calendar system outside the package. Some examples of Calendar fields are : YEAR, DATE, MONTH, DAY_OF_WEEK, DAY_OF_YEAR, WEEK_OF_YEAR, MINUTE, SECOND, HOUR, AM_PM, WEEK_OF_MONTH, DAY_OF_WEEK_IN_MONTH, HOUR_OF_DAY. Syntax : public int get(int field) Here, field represents the given calendar field and the function returns the value of given field.Approaches: Using Calendar class with Format specifiersUsing Calendar class without Format specifier Using Calendar class with Format specifiers Using Calendar class without Format specifier Approach 1: Using Calendar class with Format specifiers java.util.Calendar.get() method is a method of java.util.Calendar class. The Calendar class provides some methods for implementing a concrete calendar system outside the package. Format specifiers begin with a percent character (%) and terminate with a “type character” which indicates the type of data (int, float, etc.) that will be converted in the basic manner in which the data will be represented (decimal, hexadecimal, etc.) Implementation: Below is the implementation of the program using the above format specifiers. Java // Java Program to Display// current hour and minute // Importing java Date class librariesimport java.util.Calendar;import java.util.Formatter; class GFG { // Main driver method public static void main(String args[]) { // Create Formatter class object Formatter format = new Formatter(); // Creating a calendar Calendar gfg_calender = Calendar.getInstance(); // Displaying hour using Format class using format // specifiers // '%tl' for hours and '%tM' for minutes format = new Formatter(); format.format("%tl:%tM", gfg_calender, gfg_calender); // Printing the current hour and minute System.out.println(format); }} 9:04 Approach 2: Using Calendar class without Format specifiers java.util.Calendar.get() method is a method of java.util.Calendar class. The Calendar class provides some methods for implementing a concrete calendar system outside the package. Some examples of Calendar fields are: YEAR, DATE, MONTH, DAY_OF_WEEK, DAY_OF_YEAR, WEEK_OF_YEAR, MINUTE, SECOND, HOUR, AM_PM, WEEK_OF_MONTH, DAY_OF_WEEK_IN_MONTH, HOUR_OF_DAY. Below is a java example to display the current date and time without using format specifiers: Java // Java Program to Display// current hour and minute // Importing java Date class librariesimport java.util.Calendar;import java.util.Formatter; class GFG { // Main driver method public static void main(String args[]) { // Creating a calendar using getInstance method Calendar now = Calendar.getInstance(); // Get the current hour and minute as parameters System.out.println(now.get(Calendar.HOUR_OF_DAY) + ":" + now.get(Calendar.MINUTE)); // Printing the current hour and minute using now }} 9:4 clintra rkbhola5 Java-Date-Time Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Jul, 2022" }, { "code": null, "e": 478, "s": 28, "text": "The difference between Date and Calendar is that the Date class operates with a specific instant in time and Calendar operates with a difference between two dates. The Calendar class gives you the possibility for converting between a specific instant in time and a set of calendar fields such as HOUR, YEAR, MONTH, DAY_OF_MONTH. Manipulation over the calendar fields taken for instance getting backdate when the organization was formed or birthdays." }, { "code": null, "e": 493, "s": 478, "text": "Calendar Class" }, { "code": null, "e": 1007, "s": 493, "text": "It is used to display the date and time and manipulate date and time in java and in addition to this it is also used for formatting date and time class in java across time zone associated data. So in order to import this class from a package called “java.utils”. After importing this class one can create an object of the Date class in order to print the current date and time. Now in order to print the default date and time simply call the print command using toString() method to get the current date and time." }, { "code": null, "e": 1363, "s": 1007, "text": "java.util.Calendar.get() method is a method of java.util.Calendar class. The Calendar class provides some methods for implementing a concrete calendar system outside the package. Some examples of Calendar fields are : YEAR, DATE, MONTH, DAY_OF_WEEK, DAY_OF_YEAR, WEEK_OF_YEAR, MINUTE, SECOND, HOUR, AM_PM, WEEK_OF_MONTH, DAY_OF_WEEK_IN_MONTH, HOUR_OF_DAY." }, { "code": null, "e": 1372, "s": 1363, "text": "Syntax :" }, { "code": null, "e": 1398, "s": 1372, "text": "public int get(int field)" }, { "code": null, "e": 1509, "s": 1398, "text": "Here, field represents the given calendar field and the function returns the value of given field.Approaches: " }, { "code": null, "e": 1598, "s": 1509, "text": "Using Calendar class with Format specifiersUsing Calendar class without Format specifier" }, { "code": null, "e": 1642, "s": 1598, "text": "Using Calendar class with Format specifiers" }, { "code": null, "e": 1688, "s": 1642, "text": "Using Calendar class without Format specifier" }, { "code": null, "e": 1744, "s": 1688, "text": "Approach 1: Using Calendar class with Format specifiers" }, { "code": null, "e": 2176, "s": 1744, "text": "java.util.Calendar.get() method is a method of java.util.Calendar class. The Calendar class provides some methods for implementing a concrete calendar system outside the package. Format specifiers begin with a percent character (%) and terminate with a “type character” which indicates the type of data (int, float, etc.) that will be converted in the basic manner in which the data will be represented (decimal, hexadecimal, etc.)" }, { "code": null, "e": 2270, "s": 2176, "text": "Implementation: Below is the implementation of the program using the above format specifiers." }, { "code": null, "e": 2275, "s": 2270, "text": "Java" }, { "code": "// Java Program to Display// current hour and minute // Importing java Date class librariesimport java.util.Calendar;import java.util.Formatter; class GFG { // Main driver method public static void main(String args[]) { // Create Formatter class object Formatter format = new Formatter(); // Creating a calendar Calendar gfg_calender = Calendar.getInstance(); // Displaying hour using Format class using format // specifiers // '%tl' for hours and '%tM' for minutes format = new Formatter(); format.format(\"%tl:%tM\", gfg_calender, gfg_calender); // Printing the current hour and minute System.out.println(format); }}", "e": 3009, "s": 2275, "text": null }, { "code": null, "e": 3017, "s": 3012, "text": "9:04" }, { "code": null, "e": 3076, "s": 3017, "text": "Approach 2: Using Calendar class without Format specifiers" }, { "code": null, "e": 3433, "s": 3078, "text": "java.util.Calendar.get() method is a method of java.util.Calendar class. The Calendar class provides some methods for implementing a concrete calendar system outside the package. Some examples of Calendar fields are: YEAR, DATE, MONTH, DAY_OF_WEEK, DAY_OF_YEAR, WEEK_OF_YEAR, MINUTE, SECOND, HOUR, AM_PM, WEEK_OF_MONTH, DAY_OF_WEEK_IN_MONTH, HOUR_OF_DAY." }, { "code": null, "e": 3530, "s": 3435, "text": "Below is a java example to display the current date and time without using format specifiers: " }, { "code": null, "e": 3537, "s": 3532, "text": "Java" }, { "code": "// Java Program to Display// current hour and minute // Importing java Date class librariesimport java.util.Calendar;import java.util.Formatter; class GFG { // Main driver method public static void main(String args[]) { // Creating a calendar using getInstance method Calendar now = Calendar.getInstance(); // Get the current hour and minute as parameters System.out.println(now.get(Calendar.HOUR_OF_DAY) + \":\" + now.get(Calendar.MINUTE)); // Printing the current hour and minute using now }}", "e": 4132, "s": 3537, "text": null }, { "code": null, "e": 4139, "s": 4135, "text": "9:4" }, { "code": null, "e": 4151, "s": 4143, "text": "clintra" }, { "code": null, "e": 4160, "s": 4151, "text": "rkbhola5" }, { "code": null, "e": 4175, "s": 4160, "text": "Java-Date-Time" }, { "code": null, "e": 4182, "s": 4175, "text": "Picked" }, { "code": null, "e": 4187, "s": 4182, "text": "Java" }, { "code": null, "e": 4201, "s": 4187, "text": "Java Programs" }, { "code": null, "e": 4206, "s": 4201, "text": "Java" } ]
Loading Images in Tkinter using PIL
04 Dec, 2021 In this article, we will learn how to load images from user system to Tkinter window using PIL module. This program will open a dialogue box to select the required file from any directory and display it in the tkinter window.Install the requirements – Use this command to install Tkinter : pip install python-tk Use this command to install PIL : pip install pillow Importing modules – Python3 from tkinter import * # loading Python Imaging Libraryfrom PIL import ImageTk, Image # To get the dialog box to open when requiredfrom tkinter import filedialog Note: The ImageTk module contains support to create and modify Tkinter BitmapImage and PhotoImage objects from PIL images and filedialog is used for the dialog box to appear when you are opening file from anywhere in your system or saving your file in a particular position or place. Function to create a Tkinder window consisting of a button – Python3 # Create a windowroot = Tk() # Set Title as Image Loaderroot.title("Image Loader") # Set the resolution of windowroot.geometry("550x300 + 300 + 150") # Allow Window to be resizableroot.resizable(width = True, height = True) # Create a button and place it into the window using grid layoutbtn = Button(root, text ='open image', command = open_img).grid( row = 1, columnspan = 4)root.mainloop() The Button object is created with text ‘open image’. On clicking it the open_image function will be invoked. Function to place the image onto the window – Python3 def open_img(): # Select the Imagename from a folder x = openfilename() # opens the image img = Image.open(x) # resize the image and apply a high-quality down sampling filter img = img.resize((250, 250), Image.ANTIALIAS) # PhotoImage class is used to add image to widgets, icons etc img = ImageTk.PhotoImage(img) # create a label panel = Label(root, image = img) # set the image as img panel.image = img panel.grid(row = 2) The openfilename function will return the file name of image. Function to return the file name chosen from a dialog box – Python3 def openfilename(): # open file dialog box to select image # The dialogue box has a title "Open" filename = filedialog.askopenfilename(title ='"pen') return filename To run this code, save it by the extension .py and then open cmd (command prompt) and move to the location of the file saved and then write the following – python "filename".py and press enter and it will run. Or can be run directly by simply double-clicking your .py extension file. Output: https://media.geeksforgeeks.org/wp-content/uploads/20191121233525/Screencast-from-Thursday-21-November-2019-111137-IST2.webm kashishsoda sagar0719kumar varshagumber28 Python-pil Python-tkinter Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Iterate over a list in Python Python Classes and Objects Convert integer to string in Python
[ { "code": null, "e": 52, "s": 24, "text": "\n04 Dec, 2021" }, { "code": null, "e": 343, "s": 52, "text": "In this article, we will learn how to load images from user system to Tkinter window using PIL module. This program will open a dialogue box to select the required file from any directory and display it in the tkinter window.Install the requirements – Use this command to install Tkinter : " }, { "code": null, "e": 365, "s": 343, "text": "pip install python-tk" }, { "code": null, "e": 400, "s": 365, "text": "Use this command to install PIL : " }, { "code": null, "e": 419, "s": 400, "text": "pip install pillow" }, { "code": null, "e": 440, "s": 419, "text": "Importing modules – " }, { "code": null, "e": 448, "s": 440, "text": "Python3" }, { "code": "from tkinter import * # loading Python Imaging Libraryfrom PIL import ImageTk, Image # To get the dialog box to open when requiredfrom tkinter import filedialog", "e": 609, "s": 448, "text": null }, { "code": null, "e": 958, "s": 609, "text": "Note: The ImageTk module contains support to create and modify Tkinter BitmapImage and PhotoImage objects from PIL images and filedialog is used for the dialog box to appear when you are opening file from anywhere in your system or saving your file in a particular position or place. Function to create a Tkinder window consisting of a button – " }, { "code": null, "e": 966, "s": 958, "text": "Python3" }, { "code": "# Create a windowroot = Tk() # Set Title as Image Loaderroot.title(\"Image Loader\") # Set the resolution of windowroot.geometry(\"550x300 + 300 + 150\") # Allow Window to be resizableroot.resizable(width = True, height = True) # Create a button and place it into the window using grid layoutbtn = Button(root, text ='open image', command = open_img).grid( row = 1, columnspan = 4)root.mainloop()", "e": 1398, "s": 966, "text": null }, { "code": null, "e": 1555, "s": 1398, "text": "The Button object is created with text ‘open image’. On clicking it the open_image function will be invoked. Function to place the image onto the window – " }, { "code": null, "e": 1563, "s": 1555, "text": "Python3" }, { "code": "def open_img(): # Select the Imagename from a folder x = openfilename() # opens the image img = Image.open(x) # resize the image and apply a high-quality down sampling filter img = img.resize((250, 250), Image.ANTIALIAS) # PhotoImage class is used to add image to widgets, icons etc img = ImageTk.PhotoImage(img) # create a label panel = Label(root, image = img) # set the image as img panel.image = img panel.grid(row = 2)", "e": 2041, "s": 1563, "text": null }, { "code": null, "e": 2165, "s": 2041, "text": "The openfilename function will return the file name of image. Function to return the file name chosen from a dialog box – " }, { "code": null, "e": 2173, "s": 2165, "text": "Python3" }, { "code": "def openfilename(): # open file dialog box to select image # The dialogue box has a title \"Open\" filename = filedialog.askopenfilename(title ='\"pen') return filename", "e": 2352, "s": 2173, "text": null }, { "code": null, "e": 2510, "s": 2352, "text": "To run this code, save it by the extension .py and then open cmd (command prompt) and move to the location of the file saved and then write the following – " }, { "code": null, "e": 2532, "s": 2510, "text": "python \"filename\".py " }, { "code": null, "e": 2775, "s": 2532, "text": "and press enter and it will run. Or can be run directly by simply double-clicking your .py extension file. Output: https://media.geeksforgeeks.org/wp-content/uploads/20191121233525/Screencast-from-Thursday-21-November-2019-111137-IST2.webm " }, { "code": null, "e": 2787, "s": 2775, "text": "kashishsoda" }, { "code": null, "e": 2802, "s": 2787, "text": "sagar0719kumar" }, { "code": null, "e": 2817, "s": 2802, "text": "varshagumber28" }, { "code": null, "e": 2828, "s": 2817, "text": "Python-pil" }, { "code": null, "e": 2843, "s": 2828, "text": "Python-tkinter" }, { "code": null, "e": 2850, "s": 2843, "text": "Python" }, { "code": null, "e": 2869, "s": 2850, "text": "Technical Scripter" }, { "code": null, "e": 2967, "s": 2869, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2985, "s": 2967, "text": "Python Dictionary" }, { "code": null, "e": 3027, "s": 2985, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3049, "s": 3027, "text": "Enumerate() in Python" }, { "code": null, "e": 3084, "s": 3049, "text": "Read a file line by line in Python" }, { "code": null, "e": 3110, "s": 3084, "text": "Python String | replace()" }, { "code": null, "e": 3142, "s": 3110, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3171, "s": 3142, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3201, "s": 3171, "text": "Iterate over a list in Python" }, { "code": null, "e": 3228, "s": 3201, "text": "Python Classes and Objects" } ]
Python | Add one string to another
22 May, 2019 Concatenation of two strings have been discussed multiple times over various languages. But the task of adding one string to other is quite easy task in Python. Knowledge of performing this task has many application. Let’s discuss certain ways in which this can be performed. Method #1 : Using += operator This operator can be used to perform this particular task of concatenating the string. This is quite simpler than the traditional methods that are employed in other languages, like using a dedicated function to perform this particular task. # Python code to demonstrate# Adding one string to another# Using += operator # initializing string test_string = "GFG" # initializing add_stringadd_string = " is best" # printing original string print("The original string : " + str(test_string)) # printing original add string print("The add string : " + str(add_string)) # Using += operator# adding one string to another test_string += add_string # print resultprint("The concatenated string is : " + test_string) The original string : GFG The add string : is best The concatenated string is : GFG is best Method #2 : Using join() One can also perform this very task of the concatenation of string using the join function. The advantage this method holds over the above method is when we have many strings to concatenate rather than just two. # Python code to demonstrate# Adding one string to another# Using join() # initializing string test_string = "GFG" # initializing add_stringadd_string = " is best" # printing original string print("The original string : " + str(test_string)) # printing original add string print("The add string : " + str(add_string)) # Using join()# adding one string to another res = "".join((test_string, add_string)) # print resultprint("The concatenated string is : " + res) The original string : GFG The add string : is best The concatenated string is : GFG is best Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 53, "s": 25, "text": "\n22 May, 2019" }, { "code": null, "e": 329, "s": 53, "text": "Concatenation of two strings have been discussed multiple times over various languages. But the task of adding one string to other is quite easy task in Python. Knowledge of performing this task has many application. Let’s discuss certain ways in which this can be performed." }, { "code": null, "e": 359, "s": 329, "text": "Method #1 : Using += operator" }, { "code": null, "e": 600, "s": 359, "text": "This operator can be used to perform this particular task of concatenating the string. This is quite simpler than the traditional methods that are employed in other languages, like using a dedicated function to perform this particular task." }, { "code": "# Python code to demonstrate# Adding one string to another# Using += operator # initializing string test_string = \"GFG\" # initializing add_stringadd_string = \" is best\" # printing original string print(\"The original string : \" + str(test_string)) # printing original add string print(\"The add string : \" + str(add_string)) # Using += operator# adding one string to another test_string += add_string # print resultprint(\"The concatenated string is : \" + test_string)", "e": 1072, "s": 600, "text": null }, { "code": null, "e": 1166, "s": 1072, "text": "The original string : GFG\nThe add string : is best\nThe concatenated string is : GFG is best\n" }, { "code": null, "e": 1193, "s": 1168, "text": "Method #2 : Using join()" }, { "code": null, "e": 1405, "s": 1193, "text": "One can also perform this very task of the concatenation of string using the join function. The advantage this method holds over the above method is when we have many strings to concatenate rather than just two." }, { "code": "# Python code to demonstrate# Adding one string to another# Using join() # initializing string test_string = \"GFG\" # initializing add_stringadd_string = \" is best\" # printing original string print(\"The original string : \" + str(test_string)) # printing original add string print(\"The add string : \" + str(add_string)) # Using join()# adding one string to another res = \"\".join((test_string, add_string)) # print resultprint(\"The concatenated string is : \" + res)", "e": 1874, "s": 1405, "text": null }, { "code": null, "e": 1968, "s": 1874, "text": "The original string : GFG\nThe add string : is best\nThe concatenated string is : GFG is best\n" }, { "code": null, "e": 1991, "s": 1968, "text": "Python string-programs" }, { "code": null, "e": 1998, "s": 1991, "text": "Python" }, { "code": null, "e": 2014, "s": 1998, "text": "Python Programs" }, { "code": null, "e": 2112, "s": 2014, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2154, "s": 2112, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2176, "s": 2154, "text": "Enumerate() in Python" }, { "code": null, "e": 2202, "s": 2176, "text": "Python String | replace()" }, { "code": null, "e": 2234, "s": 2202, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2263, "s": 2234, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2285, "s": 2263, "text": "Defaultdict in Python" }, { "code": null, "e": 2324, "s": 2285, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2362, "s": 2324, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2411, "s": 2362, "text": "Python | Convert string dictionary to dictionary" } ]
ReactJS - Props Overview
The main difference between state and props is that props are immutable. This is why the container component should define the state that can be updated and changed, while the child components should only pass data from the state using props. When we need immutable data in our component, we can just add props to reactDOM.render() function in main.js and use it inside our component. import React from 'react'; class App extends React.Component { render() { return ( <div> <h1>{this.props.headerProp}</h1> <h2>{this.props.contentProp}</h2> </div> ); } } export default App; import React from 'react'; import ReactDOM from 'react-dom'; import App from './App.jsx'; ReactDOM.render(<App headerProp = "Header from props..." contentProp = "Content from props..."/>, document.getElementById('app')); export default App; This will produce the following result. You can also set default property values directly on the component constructor instead of adding it to the reactDom.render() element. import React from 'react'; class App extends React.Component { render() { return ( <div> <h1>{this.props.headerProp}</h1> <h2>{this.props.contentProp}</h2> </div> ); } } App.defaultProps = { headerProp: "Header from props...", contentProp:"Content from props..." } export default App; import React from 'react'; import ReactDOM from 'react-dom'; import App from './App.jsx'; ReactDOM.render(<App/>, document.getElementById('app')); Output is the same as before. The following example shows how to combine state and props in your app. We are setting the state in our parent component and passing it down the component tree using props. Inside the render function, we are setting headerProp and contentProp used in child components. import React from 'react'; class App extends React.Component { constructor(props) { super(props); this.state = { header: "Header from props...", content: "Content from props..." } } render() { return ( <div> <Header headerProp = {this.state.header}/> <Content contentProp = {this.state.content}/> </div> ); } } class Header extends React.Component { render() { return ( <div> <h1>{this.props.headerProp}</h1> </div> ); } } class Content extends React.Component { render() { return ( <div> <h2>{this.props.contentProp}</h2> </div> ); } } export default App; import React from 'react'; import ReactDOM from 'react-dom'; import App from './App.jsx'; ReactDOM.render(<App/>, document.getElementById('app')); The result will again be the same as in the previous two examples, the only thing that is different is the source of our data, which is now originally coming from the state. When we want to update it, we just need to update the state, and all child components will be updated. More on this in the Events chapter.
[ { "code": null, "e": 2410, "s": 2167, "text": "The main difference between state and props is that props are immutable. This is why the container component should define the state that can be updated and changed, while the child components should only pass data from the state using props." }, { "code": null, "e": 2552, "s": 2410, "text": "When we need immutable data in our component, we can just add props to reactDOM.render() function in main.js and use it inside our component." }, { "code": null, "e": 2803, "s": 2552, "text": "import React from 'react';\n\nclass App extends React.Component {\n render() {\n return (\n <div>\n <h1>{this.props.headerProp}</h1>\n <h2>{this.props.contentProp}</h2>\n </div>\n );\n }\n}\nexport default App;" }, { "code": null, "e": 3049, "s": 2803, "text": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport App from './App.jsx';\n\nReactDOM.render(<App headerProp = \"Header from props...\" contentProp = \"Content\n from props...\"/>, document.getElementById('app'));\n\nexport default App;" }, { "code": null, "e": 3089, "s": 3049, "text": "This will produce the following result." }, { "code": null, "e": 3223, "s": 3089, "text": "You can also set default property values directly on the component constructor instead of adding it to the reactDom.render() element." }, { "code": null, "e": 3575, "s": 3223, "text": "import React from 'react';\n\nclass App extends React.Component {\n render() {\n return (\n <div>\n <h1>{this.props.headerProp}</h1>\n <h2>{this.props.contentProp}</h2>\n </div>\n );\n }\n}\nApp.defaultProps = {\n headerProp: \"Header from props...\",\n contentProp:\"Content from props...\"\n}\nexport default App;" }, { "code": null, "e": 3723, "s": 3575, "text": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport App from './App.jsx';\n\nReactDOM.render(<App/>, document.getElementById('app'));" }, { "code": null, "e": 3753, "s": 3723, "text": "Output is the same as before." }, { "code": null, "e": 4022, "s": 3753, "text": "The following example shows how to combine state and props in your app. We are setting the state in our parent component and passing it down the component tree using props. Inside the render function, we are setting headerProp and contentProp used in child components." }, { "code": null, "e": 4778, "s": 4022, "text": "import React from 'react';\n\nclass App extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n header: \"Header from props...\",\n content: \"Content from props...\"\n }\n }\n render() {\n return (\n <div>\n <Header headerProp = {this.state.header}/>\n <Content contentProp = {this.state.content}/>\n </div>\n );\n }\n}\nclass Header extends React.Component {\n render() {\n return (\n <div>\n <h1>{this.props.headerProp}</h1>\n </div>\n );\n }\n}\nclass Content extends React.Component {\n render() {\n return (\n <div>\n <h2>{this.props.contentProp}</h2>\n </div>\n );\n }\n}\nexport default App;" }, { "code": null, "e": 4926, "s": 4778, "text": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport App from './App.jsx';\n\nReactDOM.render(<App/>, document.getElementById('app'));" } ]
Sum of all subsequences of an array
02 Feb, 2022 Given an array of n integers. Find the sum of all possible subsequences of an array. Examples : Input : arr[] = { 1, 2 } Output : 6 All possible subsequences are {}, {1}, {2} and { 1, 2 } Input : arr[] = { 1, 2, 3 } Output : 24 We have already discussed two different solutions in below post. Sum of all Subarrays | Set 1 In this post a different solution is discussed. Let us take a closer look at the problem and try to find a pattern Let a[] = { 1, 2, 3 } All subsequences are {}, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3} So sum of subsequences are 0 + 1 + 2 + 3 + 3 + 4 + 5 + 6 = 24 Here we can observe that in sum every elements occurs 4 times. Or in general every element will occur 2^(n-1) times. And we can also observe that sum of array elements is 6. So final result will be 6*4. In general we can find sum of all subsequences by adding all elements of array multiplied by 2(n-1) where n is number of elements in array. C++ Java Python C# PHP Javascript // CPP program to find sum of// all subarrays of array#include <bits/stdc++.h>using namespace std; // To find sum of all subsequencesint findSum(int arr[], int n){ // Sum all array elements int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; // Result is sum * 2^(n-1) return sum * (1 << (n - 1));} // Driver program to test findSum()int main(){ int arr[] = { 1, 2 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findSum(arr, n); return 0;} // Java program to find sum of// all subarrays of array public class Main { // To find sum of all subsequences static int findSum(int arr[], int n) { // Sum all array elements int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; // Result is sum * 2^(n-1) return sum * (1 << (n - 1)); } // Driver program to test findSum() public static void main(String[] args) { int arr[] = { 1, 2 }; int n = arr.length; System.out.print(findSum(arr, n)); }} # Python program to find sum of# all subarrays of array # To find sum of all subsequencesdef findSum(arr, n): # Sum all array elements sum = 0 for i in range(n): sum += arr[i] # Result is sum * 2^(n-1) return sum * (1 << (n - 1)) # Driver program to test findSum()arr = [1, 2]n = len(arr)print findSum(arr, n) # This code is submitted by Sachin Bisht // C# program to find sum of // all subarrays of array using System; class GFG{ // To find sum of all subsequencesstatic int findSum(int []arr, int n) { // Sum all array elements int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; // Result is sum * 2^(n-1) return sum * (1 << (n - 1)); } // Driver Codestatic public void Main (){ int []arr = { 1, 2 }; int n = arr.Length; Console.WriteLine(findSum(arr, n)); } } // This code is contributed by ajit <?php// PHP program to find sum of// all subarrays of array // To find sum of all subsequences function findSum($arr, $n){ // Sum all array elements $sum = 0; for ($i = 0; $i < $n; $i++) $sum += $arr[$i]; // Result is sum * 2^(n-1) return $sum * (1 << ($n - 1));} // Driver Code$arr = array( 1, 2 );$n = sizeof($arr); echo findSum($arr, $n); // This code is contributed by ajit?> <script> // Javascript program to find sum of // all subarrays of array // To find sum of all subsequencesfunction findSum(arr, n) { // Sum all array elements let sum = 0; for(let i = 0; i < n; i++) sum += arr[i]; // Result is sum * 2^(n-1) return sum * (1 << (n - 1)); } // Driver codelet arr = [ 1, 2 ]; let n = arr.length; document.write(findSum(arr, n)); // This code is contributed by rameshtravel07 </script> Output : 6 This article is contributed by nuclode. 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. jit_t rameshtravel07 darshil23sep sachinjourneyoflife subsequence Arrays Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n02 Feb, 2022" }, { "code": null, "e": 140, "s": 54, "text": "Given an array of n integers. Find the sum of all possible subsequences of an array. " }, { "code": null, "e": 152, "s": 140, "text": "Examples : " }, { "code": null, "e": 286, "s": 152, "text": "Input : arr[] = { 1, 2 }\nOutput : 6\nAll possible subsequences are {}, {1}, {2} \nand { 1, 2 }\n\nInput : arr[] = { 1, 2, 3 }\nOutput : 24" }, { "code": null, "e": 380, "s": 286, "text": "We have already discussed two different solutions in below post. Sum of all Subarrays | Set 1" }, { "code": null, "e": 497, "s": 380, "text": "In this post a different solution is discussed. Let us take a closer look at the problem and try to find a pattern " }, { "code": null, "e": 916, "s": 497, "text": "Let a[] = { 1, 2, 3 }\n\nAll subsequences are {}, {1}, {2}, {3}, {1, 2}, \n {1, 3}, {2, 3}, {1, 2, 3}\n\nSo sum of subsequences are 0 + 1 + 2 + 3 + 3 + \n 4 + 5 + 6 = 24\n\nHere we can observe that in sum every elements \noccurs 4 times. Or in general every element \nwill occur 2^(n-1) times. And we can also \nobserve that sum of array elements is 6. So\nfinal result will be 6*4." }, { "code": null, "e": 1056, "s": 916, "text": "In general we can find sum of all subsequences by adding all elements of array multiplied by 2(n-1) where n is number of elements in array." }, { "code": null, "e": 1060, "s": 1056, "text": "C++" }, { "code": null, "e": 1065, "s": 1060, "text": "Java" }, { "code": null, "e": 1072, "s": 1065, "text": "Python" }, { "code": null, "e": 1075, "s": 1072, "text": "C#" }, { "code": null, "e": 1079, "s": 1075, "text": "PHP" }, { "code": null, "e": 1090, "s": 1079, "text": "Javascript" }, { "code": "// CPP program to find sum of// all subarrays of array#include <bits/stdc++.h>using namespace std; // To find sum of all subsequencesint findSum(int arr[], int n){ // Sum all array elements int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; // Result is sum * 2^(n-1) return sum * (1 << (n - 1));} // Driver program to test findSum()int main(){ int arr[] = { 1, 2 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findSum(arr, n); return 0;}", "e": 1574, "s": 1090, "text": null }, { "code": "// Java program to find sum of// all subarrays of array public class Main { // To find sum of all subsequences static int findSum(int arr[], int n) { // Sum all array elements int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; // Result is sum * 2^(n-1) return sum * (1 << (n - 1)); } // Driver program to test findSum() public static void main(String[] args) { int arr[] = { 1, 2 }; int n = arr.length; System.out.print(findSum(arr, n)); }}", "e": 2117, "s": 1574, "text": null }, { "code": "# Python program to find sum of# all subarrays of array # To find sum of all subsequencesdef findSum(arr, n): # Sum all array elements sum = 0 for i in range(n): sum += arr[i] # Result is sum * 2^(n-1) return sum * (1 << (n - 1)) # Driver program to test findSum()arr = [1, 2]n = len(arr)print findSum(arr, n) # This code is submitted by Sachin Bisht", "e": 2503, "s": 2117, "text": null }, { "code": "// C# program to find sum of // all subarrays of array using System; class GFG{ // To find sum of all subsequencesstatic int findSum(int []arr, int n) { // Sum all array elements int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; // Result is sum * 2^(n-1) return sum * (1 << (n - 1)); } // Driver Codestatic public void Main (){ int []arr = { 1, 2 }; int n = arr.Length; Console.WriteLine(findSum(arr, n)); } } // This code is contributed by ajit", "e": 3003, "s": 2503, "text": null }, { "code": "<?php// PHP program to find sum of// all subarrays of array // To find sum of all subsequences function findSum($arr, $n){ // Sum all array elements $sum = 0; for ($i = 0; $i < $n; $i++) $sum += $arr[$i]; // Result is sum * 2^(n-1) return $sum * (1 << ($n - 1));} // Driver Code$arr = array( 1, 2 );$n = sizeof($arr); echo findSum($arr, $n); // This code is contributed by ajit?>", "e": 3412, "s": 3003, "text": null }, { "code": "<script> // Javascript program to find sum of // all subarrays of array // To find sum of all subsequencesfunction findSum(arr, n) { // Sum all array elements let sum = 0; for(let i = 0; i < n; i++) sum += arr[i]; // Result is sum * 2^(n-1) return sum * (1 << (n - 1)); } // Driver codelet arr = [ 1, 2 ]; let n = arr.length; document.write(findSum(arr, n)); // This code is contributed by rameshtravel07 </script>", "e": 3873, "s": 3412, "text": null }, { "code": null, "e": 3883, "s": 3873, "text": "Output : " }, { "code": null, "e": 3885, "s": 3883, "text": "6" }, { "code": null, "e": 4301, "s": 3885, "text": "This article is contributed by nuclode. 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": 4307, "s": 4301, "text": "jit_t" }, { "code": null, "e": 4322, "s": 4307, "text": "rameshtravel07" }, { "code": null, "e": 4335, "s": 4322, "text": "darshil23sep" }, { "code": null, "e": 4355, "s": 4335, "text": "sachinjourneyoflife" }, { "code": null, "e": 4367, "s": 4355, "text": "subsequence" }, { "code": null, "e": 4374, "s": 4367, "text": "Arrays" }, { "code": null, "e": 4381, "s": 4374, "text": "Arrays" } ]
Getting cosine and hyperbolic cosine in Julia – cos(), cosh() and cosd() Methods
26 Mar, 2020 The cos() is an inbuilt function in julia which is used to calculate cosine of the specified radian values. Syntax: cos(x) Parameters: x: Specified radian values. Returns: It returns the calculated cosine of the specified radian values. Example: # Julia program to illustrate # the use of cos() method # Getting cosine of the specified# radian values.println(cos(0))println(cos(30))println(cos(90))println(cos(44)) Output: 1.0 0.15425144988758405 -0.4480736161291702 0.9998433086476912 The cosh() is an inbuilt function in julia which is used to calculate hyperbolic cosine of the specified values. Syntax: cosh(x) Parameters: x: Specified values. Returns: It returns the calculated hyperbolic cosine of the specified values. Example: # Julia program to illustrate # the use of cosh() method # Getting cosine of the specified values.println(cosh(0))println(cosh(30))println(cosh(90))println(cosh(45)) Output: 1.0 5.343237290762231e12 6.102016471589204e38 1.7467135528742547e19 The cosd() is an inbuilt function in julia which is used to calculate cosine of the specified value in degrees. Syntax: cosd(x) Parameters: x: Specified value in degrees. Returns: It returns the calculated cosine of the specified value in degrees. Example: # Julia program to illustrate # the use of cosd() method # Getting cosine of the specified value # in degreeprintln(cosd(0))println(cosd(30))println(cosd(90))println(cosd(45)) Output: 1.0 0.8660254037844386 0.0 0.7071067811865476 Julia Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Exception handling in Julia Get array dimensions and size of a dimension in Julia - size() Method Get number of elements of array in Julia - length() Method Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder) NamedTuple in Julia Find maximum element along with its index in Julia - findmax() Method Searching in Array for a given element in Julia Difference Between MATLAB and Julia Getting the maximum value from a list in Julia - max() Method Join an array of strings into a single string in Julia - join() Method
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Mar, 2020" }, { "code": null, "e": 136, "s": 28, "text": "The cos() is an inbuilt function in julia which is used to calculate cosine of the specified radian values." }, { "code": null, "e": 151, "s": 136, "text": "Syntax: cos(x)" }, { "code": null, "e": 163, "s": 151, "text": "Parameters:" }, { "code": null, "e": 191, "s": 163, "text": "x: Specified radian values." }, { "code": null, "e": 265, "s": 191, "text": "Returns: It returns the calculated cosine of the specified radian values." }, { "code": null, "e": 274, "s": 265, "text": "Example:" }, { "code": "# Julia program to illustrate # the use of cos() method # Getting cosine of the specified# radian values.println(cos(0))println(cos(30))println(cos(90))println(cos(44))", "e": 444, "s": 274, "text": null }, { "code": null, "e": 452, "s": 444, "text": "Output:" }, { "code": null, "e": 515, "s": 452, "text": "1.0\n0.15425144988758405\n-0.4480736161291702\n0.9998433086476912" }, { "code": null, "e": 628, "s": 515, "text": "The cosh() is an inbuilt function in julia which is used to calculate hyperbolic cosine of the specified values." }, { "code": null, "e": 644, "s": 628, "text": "Syntax: cosh(x)" }, { "code": null, "e": 656, "s": 644, "text": "Parameters:" }, { "code": null, "e": 677, "s": 656, "text": "x: Specified values." }, { "code": null, "e": 755, "s": 677, "text": "Returns: It returns the calculated hyperbolic cosine of the specified values." }, { "code": null, "e": 764, "s": 755, "text": "Example:" }, { "code": "# Julia program to illustrate # the use of cosh() method # Getting cosine of the specified values.println(cosh(0))println(cosh(30))println(cosh(90))println(cosh(45))", "e": 931, "s": 764, "text": null }, { "code": null, "e": 939, "s": 931, "text": "Output:" }, { "code": null, "e": 1007, "s": 939, "text": "1.0\n5.343237290762231e12\n6.102016471589204e38\n1.7467135528742547e19" }, { "code": null, "e": 1119, "s": 1007, "text": "The cosd() is an inbuilt function in julia which is used to calculate cosine of the specified value in degrees." }, { "code": null, "e": 1135, "s": 1119, "text": "Syntax: cosd(x)" }, { "code": null, "e": 1147, "s": 1135, "text": "Parameters:" }, { "code": null, "e": 1178, "s": 1147, "text": "x: Specified value in degrees." }, { "code": null, "e": 1255, "s": 1178, "text": "Returns: It returns the calculated cosine of the specified value in degrees." }, { "code": null, "e": 1264, "s": 1255, "text": "Example:" }, { "code": "# Julia program to illustrate # the use of cosd() method # Getting cosine of the specified value # in degreeprintln(cosd(0))println(cosd(30))println(cosd(90))println(cosd(45))", "e": 1441, "s": 1264, "text": null }, { "code": null, "e": 1449, "s": 1441, "text": "Output:" }, { "code": null, "e": 1495, "s": 1449, "text": "1.0\n0.8660254037844386\n0.0\n0.7071067811865476" }, { "code": null, "e": 1501, "s": 1495, "text": "Julia" }, { "code": null, "e": 1599, "s": 1501, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1627, "s": 1599, "text": "Exception handling in Julia" }, { "code": null, "e": 1697, "s": 1627, "text": "Get array dimensions and size of a dimension in Julia - size() Method" }, { "code": null, "e": 1756, "s": 1697, "text": "Get number of elements of array in Julia - length() Method" }, { "code": null, "e": 1829, "s": 1756, "text": "Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)" }, { "code": null, "e": 1849, "s": 1829, "text": "NamedTuple in Julia" }, { "code": null, "e": 1919, "s": 1849, "text": "Find maximum element along with its index in Julia - findmax() Method" }, { "code": null, "e": 1967, "s": 1919, "text": "Searching in Array for a given element in Julia" }, { "code": null, "e": 2003, "s": 1967, "text": "Difference Between MATLAB and Julia" }, { "code": null, "e": 2065, "s": 2003, "text": "Getting the maximum value from a list in Julia - max() Method" } ]
Difference between 2NF and 3NF in DBMS
02 Aug, 2021 1. Second Normal Form (2NF) : A relation is said to be in second normal form when it is already in first normal form and there is no partial functional dependency that is no non-prime attribute should be functionally dependent on prime attribute. It was given by E.F Codd in 1971. If the candidate key comprises of only single attribute and relation is in 1NF then it is already in 2NF. The concept of checking relation for 2NF applies when there is composite candidate key that is candidate key comprises of more than one attribute. Example: Consider a relation R(A, B, C, D) with functional dependencies: {AB–>CD, BC–>D} Closure of (AB)={A, B, C, D} So AB is a candidate key. The relation R is in 1NF as relational DBMS does not allow multi-valued or composite attribute. In AB–>CD (AB is candidate key and C, D is non-prime) In BC–>D (BC is non-prime and D is non-prime which is allowed in 2NF) The relation R is in 2NF as no prime attribute is deriving non prime attribute that is there is no partial functional dependency. The relation R is not in 3NF as non-prime attribute is deriving non-prime attribute. 2. Third Normal Form (3NF) : A relation is said to be in third normal form when it is already in first normal and second normal forms and every non prime attribute is non-transitively dependent on superkey of relation or in simple language there is no transitive functional dependency. It was also given by E.F Codd in 1971. In this form duplication of data is reduced and referential integrity is ensured. A relation R having functional dependency A–>B is in 3NF if either of the conditions given below are true . A is a superkey. B is prime attribute, that is B is the part of candidate key. A is a superkey. B is prime attribute, that is B is the part of candidate key. Example:- Consider a relation R(A, B, C) having functional dependency {AB–>C, C–>A} Closure of (AB)={A, B, C} Closure of (BC)={A, B, C} Candidate keys are-{AB, BC} The relation R is in 1NF as relational DBMS does not allow multi-valued or composite attribute. AB-->C(prime deriving prime) C-->A(prime deriving prime) So the relation R is in 2NF and in 3NF also because there is no prime deriving non-prime and no non-prime deriving non-prime that is there is no partial functional dependency and no transitive functional dependency. Difference between 2NF and 3NF : simmytarika5 Picked DBMS Difference Between GATE CS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. CTE in SQL Difference between Clustered and Non-clustered index Introduction of DBMS (Database Management System) | Set 1 Introduction of B-Tree SQL Trigger | Student Database 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": 52, "s": 24, "text": "\n02 Aug, 2021" }, { "code": null, "e": 587, "s": 52, "text": "1. Second Normal Form (2NF) : A relation is said to be in second normal form when it is already in first normal form and there is no partial functional dependency that is no non-prime attribute should be functionally dependent on prime attribute. It was given by E.F Codd in 1971. If the candidate key comprises of only single attribute and relation is in 1NF then it is already in 2NF. The concept of checking relation for 2NF applies when there is composite candidate key that is candidate key comprises of more than one attribute. " }, { "code": null, "e": 678, "s": 587, "text": "Example: Consider a relation R(A, B, C, D) with functional dependencies: {AB–>CD, BC–>D} " }, { "code": null, "e": 708, "s": 678, "text": "Closure of (AB)={A, B, C, D} " }, { "code": null, "e": 1170, "s": 708, "text": "So AB is a candidate key. The relation R is in 1NF as relational DBMS does not allow multi-valued or composite attribute. In AB–>CD (AB is candidate key and C, D is non-prime) In BC–>D (BC is non-prime and D is non-prime which is allowed in 2NF) The relation R is in 2NF as no prime attribute is deriving non prime attribute that is there is no partial functional dependency. The relation R is not in 3NF as non-prime attribute is deriving non-prime attribute. " }, { "code": null, "e": 1687, "s": 1170, "text": "2. Third Normal Form (3NF) : A relation is said to be in third normal form when it is already in first normal and second normal forms and every non prime attribute is non-transitively dependent on superkey of relation or in simple language there is no transitive functional dependency. It was also given by E.F Codd in 1971. In this form duplication of data is reduced and referential integrity is ensured. A relation R having functional dependency A–>B is in 3NF if either of the conditions given below are true . " }, { "code": null, "e": 1769, "s": 1687, "text": "A is a superkey. B is prime attribute, that is B is the part of candidate key. " }, { "code": null, "e": 1788, "s": 1769, "text": "A is a superkey. " }, { "code": null, "e": 1852, "s": 1788, "text": "B is prime attribute, that is B is the part of candidate key. " }, { "code": null, "e": 1937, "s": 1852, "text": "Example:- Consider a relation R(A, B, C) having functional dependency {AB–>C, C–>A} " }, { "code": null, "e": 2018, "s": 1937, "text": "Closure of (AB)={A, B, C}\nClosure of (BC)={A, B, C}\nCandidate keys are-{AB, BC} " }, { "code": null, "e": 2116, "s": 2018, "text": "The relation R is in 1NF as relational DBMS does not allow multi-valued or composite attribute. " }, { "code": null, "e": 2173, "s": 2116, "text": "AB-->C(prime deriving prime)\nC-->A(prime deriving prime)" }, { "code": null, "e": 2390, "s": 2173, "text": "So the relation R is in 2NF and in 3NF also because there is no prime deriving non-prime and no non-prime deriving non-prime that is there is no partial functional dependency and no transitive functional dependency. " }, { "code": null, "e": 2425, "s": 2390, "text": "Difference between 2NF and 3NF : " }, { "code": null, "e": 2440, "s": 2427, "text": "simmytarika5" }, { "code": null, "e": 2447, "s": 2440, "text": "Picked" }, { "code": null, "e": 2452, "s": 2447, "text": "DBMS" }, { "code": null, "e": 2471, "s": 2452, "text": "Difference Between" }, { "code": null, "e": 2479, "s": 2471, "text": "GATE CS" }, { "code": null, "e": 2484, "s": 2479, "text": "DBMS" }, { "code": null, "e": 2582, "s": 2484, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2593, "s": 2582, "text": "CTE in SQL" }, { "code": null, "e": 2646, "s": 2593, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 2704, "s": 2646, "text": "Introduction of DBMS (Database Management System) | Set 1" }, { "code": null, "e": 2727, "s": 2704, "text": "Introduction of B-Tree" }, { "code": null, "e": 2758, "s": 2727, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 2798, "s": 2758, "text": "Class method vs Static method in Python" }, { "code": null, "e": 2829, "s": 2798, "text": "Difference between BFS and DFS" }, { "code": null, "e": 2890, "s": 2829, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2958, "s": 2890, "text": "Difference Between Method Overloading and Method Overriding in Java" } ]
An Easy Way to Divide Your Dataset Based on Data Types with Pandas | by Byron Dolon | Towards Data Science
Before you can get into pre-processing data for a machine learning model to use, you’ll usually need to separate your numerical and non-numerical columns. In this piece, we’ll go over an easy way to do just that! One way to do it is to manually check which columns contain just numbers and which columns contain text. However, if you’re working with a dataset that has dozens of columns, having to write code like the line below is a little silly and prone to human error. df_numerical = df[['num_1', 'num_2', 'num_3', 'num_4', 'num_5']] Instead, let’s take a look at using a simple Pandas method that will do this without you having to manually type out all your desired columns. If you’d like to follow along, go ahead and download the ‘train’ dataset here. Once you’ve done that, make sure it’s saved to the same directory as your notebook and then run the code below to read it in: import pandas as pddf = pd.read_csv('train.csv') Now let’s get going! A good first step before we split our DataFrame’s columns is to check what columns we’re actually working with, as well as what their respective data types are. To do so, we use the following Pandas method: df.info() Using info gives us a breakdown of all of the columns in our DataFrame, how many non-null values each column contains, and the DataTypes. We verify that there are indeed text columns in this dataset, which in Pandas fall under the “object” data type. As such, before we can actually train a machine learning model on this data set, we will need to somehow convert these text columns into numerical columns. A simple way to do that would be to pick an encoding method and apply it to all categorical columns simultaneously. Therefore, let’s separate our numerical and categorical columns using the select_dtypes method in Pandas. We’ll run the following two lines of code and get the resulting subsets of columns: df_numerical = df.select_dtypes(include='int64') df_categorical = df.select_dtypes(include='object') Wonderful! The select_dtypes method returns a subset of the DataFrame based on the column data types you specify. In this case, we’ve used the include parameter and passed in 'int64' to get the numerical columns and 'object' to get the categorical columns. BUT... I just realized I actually did something wrong. The subset of categorical columns looks correct, as it contains all the columns with text values in our original DataFrame. However, the subset of numerical columns seems to be missing a few columns. This is because we used select_dtypes to only get the 'int64' type columns, when in fact the info method earlier showed us that there are also 'float64' type columns. One way to get around this would be to pass a list into the 'include' parameter, but an alternative to that would be to use the 'exclude' parameter instead: df_numerical = df.select_dtypes(exclude=’object’) Now we have all 7 numerical columns from our original dataset! The exclude parameter returns all the columns except the data type specified, which in our case are the text (object) columns. To actually get the column names and not only the subset DataFrames, we just need to do the following: df_numerical_cols = df_numerical.columns.tolist()df_categorical_cols = df_categorical.columns.tolist() Printing the two resulting lists gives us these two lists of column names: Now that we’ve gotten the numerical and categorical columns separated, we can easily perform different transformations on our data before training a machine learning model. For example, if you wanted to impute (fill in missing data) your numerical and categorical columns with two different methods, you would be able to pass each list of column names to the respective imputation method (depending on what library you’re using). I hope you found this quick run-through of select_dtypes helpful for splitting up your data and getting lists of columns you can pass into your pre-processing functions! Good luck with your data-wrangling adventures! More by me:- Conditional Selection and Assignment With .loc in Pandas- 2 Easy Ways to Get Tables From a Website With Pandas- 5 (and a half) Lines of Code for Understanding Your Data with Pandas- Top 4 Repositories on GitHub to Learn Pandas- Learning to Forecast With Tableau in 5 Minutes Or Less *sidenote- I know the target (column with the value you need to predict if you were to train a machine learning model) is still in the df_numerical list (woops), so if you do use this code be sure to assign the “Survived” column to another variable and then drop it from the DataFrame or list of column names.
[ { "code": null, "e": 385, "s": 172, "text": "Before you can get into pre-processing data for a machine learning model to use, you’ll usually need to separate your numerical and non-numerical columns. In this piece, we’ll go over an easy way to do just that!" }, { "code": null, "e": 645, "s": 385, "text": "One way to do it is to manually check which columns contain just numbers and which columns contain text. However, if you’re working with a dataset that has dozens of columns, having to write code like the line below is a little silly and prone to human error." }, { "code": null, "e": 710, "s": 645, "text": "df_numerical = df[['num_1', 'num_2', 'num_3', 'num_4', 'num_5']]" }, { "code": null, "e": 853, "s": 710, "text": "Instead, let’s take a look at using a simple Pandas method that will do this without you having to manually type out all your desired columns." }, { "code": null, "e": 1058, "s": 853, "text": "If you’d like to follow along, go ahead and download the ‘train’ dataset here. Once you’ve done that, make sure it’s saved to the same directory as your notebook and then run the code below to read it in:" }, { "code": null, "e": 1107, "s": 1058, "text": "import pandas as pddf = pd.read_csv('train.csv')" }, { "code": null, "e": 1128, "s": 1107, "text": "Now let’s get going!" }, { "code": null, "e": 1335, "s": 1128, "text": "A good first step before we split our DataFrame’s columns is to check what columns we’re actually working with, as well as what their respective data types are. To do so, we use the following Pandas method:" }, { "code": null, "e": 1345, "s": 1335, "text": "df.info()" }, { "code": null, "e": 1868, "s": 1345, "text": "Using info gives us a breakdown of all of the columns in our DataFrame, how many non-null values each column contains, and the DataTypes. We verify that there are indeed text columns in this dataset, which in Pandas fall under the “object” data type. As such, before we can actually train a machine learning model on this data set, we will need to somehow convert these text columns into numerical columns. A simple way to do that would be to pick an encoding method and apply it to all categorical columns simultaneously." }, { "code": null, "e": 2058, "s": 1868, "text": "Therefore, let’s separate our numerical and categorical columns using the select_dtypes method in Pandas. We’ll run the following two lines of code and get the resulting subsets of columns:" }, { "code": null, "e": 2107, "s": 2058, "text": "df_numerical = df.select_dtypes(include='int64')" }, { "code": null, "e": 2159, "s": 2107, "text": "df_categorical = df.select_dtypes(include='object')" }, { "code": null, "e": 2170, "s": 2159, "text": "Wonderful!" }, { "code": null, "e": 2416, "s": 2170, "text": "The select_dtypes method returns a subset of the DataFrame based on the column data types you specify. In this case, we’ve used the include parameter and passed in 'int64' to get the numerical columns and 'object' to get the categorical columns." }, { "code": null, "e": 2471, "s": 2416, "text": "BUT... I just realized I actually did something wrong." }, { "code": null, "e": 2995, "s": 2471, "text": "The subset of categorical columns looks correct, as it contains all the columns with text values in our original DataFrame. However, the subset of numerical columns seems to be missing a few columns. This is because we used select_dtypes to only get the 'int64' type columns, when in fact the info method earlier showed us that there are also 'float64' type columns. One way to get around this would be to pass a list into the 'include' parameter, but an alternative to that would be to use the 'exclude' parameter instead:" }, { "code": null, "e": 3045, "s": 2995, "text": "df_numerical = df.select_dtypes(exclude=’object’)" }, { "code": null, "e": 3235, "s": 3045, "text": "Now we have all 7 numerical columns from our original dataset! The exclude parameter returns all the columns except the data type specified, which in our case are the text (object) columns." }, { "code": null, "e": 3338, "s": 3235, "text": "To actually get the column names and not only the subset DataFrames, we just need to do the following:" }, { "code": null, "e": 3441, "s": 3338, "text": "df_numerical_cols = df_numerical.columns.tolist()df_categorical_cols = df_categorical.columns.tolist()" }, { "code": null, "e": 3516, "s": 3441, "text": "Printing the two resulting lists gives us these two lists of column names:" }, { "code": null, "e": 3946, "s": 3516, "text": "Now that we’ve gotten the numerical and categorical columns separated, we can easily perform different transformations on our data before training a machine learning model. For example, if you wanted to impute (fill in missing data) your numerical and categorical columns with two different methods, you would be able to pass each list of column names to the respective imputation method (depending on what library you’re using)." }, { "code": null, "e": 4116, "s": 3946, "text": "I hope you found this quick run-through of select_dtypes helpful for splitting up your data and getting lists of columns you can pass into your pre-processing functions!" }, { "code": null, "e": 4163, "s": 4116, "text": "Good luck with your data-wrangling adventures!" }, { "code": null, "e": 4459, "s": 4163, "text": "More by me:- Conditional Selection and Assignment With .loc in Pandas- 2 Easy Ways to Get Tables From a Website With Pandas- 5 (and a half) Lines of Code for Understanding Your Data with Pandas- Top 4 Repositories on GitHub to Learn Pandas- Learning to Forecast With Tableau in 5 Minutes Or Less" } ]
Count of strings where adjacent characters are of difference one in C++
We are given a num number as input. The goal is to count the number of possible strings of length num such that all adjacent characters have difference between ascii values as 1. If num is 2 then strings will be “ab”, “ba”, “bc”, “cb”, ........”yz”, “zy”. Let us understand with examples Input − num=3 Output − Count of strings where adjacent characters are of difference one are − 98 Explanation − Some sample strings are: “abc”, “aba”, “cde” .....”xyx”, “zyz”, “xyz”. Input − num=2 Output − Count of strings where adjacent characters are of difference one are − 50 Explanation − Some sample strings are: “ab”, “ba”, “cd” .....”xy”, “zy”, “yz”. For length = 2. String starting with a= “ab” Strings starting with b= “ba”, “bc” Strings starting with c= “cd”, “cb”............... For length = n. String starting with a=ways of number of strings of length n-1 starting with b String starting with b=ways of number of strings of length n-1 starting with a or c String starting with c=ways of number of strings of length n-1 starting with b or d We will solve this using dynamic programming. Take an array arr[num+1][27]. Containing a number of strings of length i starting with alphabet number j in arr[i][j]. All arr[1][j] will be 1 for strings “a”, “b”...”z”. Rest for arr[2 to num+1][0 to 25], set arr[i][j]=arr[i-1][j+1] for j=0. Else set arr[i][j] = arr[i-1][j-1] + arr[i-1][j+1]; The result will be the sum of num-th row counts. Take input integer num Take input integer num Function difference_strings(int num) takes the num and returns the count of strings where adjacent characters are of difference one Function difference_strings(int num) takes the num and returns the count of strings where adjacent characters are of difference one Take the initial count as 0. Take the initial count as 0. Initialize arr[num + 1][27] with all 0s. Initialize arr[num + 1][27] with all 0s. Initialize arr[1][0 to 25] with all 1’s. Initialize arr[1][0 to 25] with all 1’s. Traverse 2D array arr[][] using two for loops from row 2nd to last and columns 0 to 25 for all 26 alphabets. Traverse 2D array arr[][] using two for loops from row 2nd to last and columns 0 to 25 for all 26 alphabets. For j=0, the starting character is ‘a’. Set current count as arr[i][j] = arr[i - 1][j + 1]; For j=0, the starting character is ‘a’. Set current count as arr[i][j] = arr[i - 1][j + 1]; Otherwise set arr[i][j] = (arr[i - 1][j - 1] + arr[i - 1][j + 1]) Otherwise set arr[i][j] = (arr[i - 1][j - 1] + arr[i - 1][j + 1]) Now after the end of the above loops, traverse last row and add arr[num][ 0 to 25] to count. Now after the end of the above loops, traverse last row and add arr[num][ 0 to 25] to count. Return count as result. Return count as result. Live Demo #include <bits/stdc++.h> using namespace std; int difference_strings(int num){ long int count = 0; long int arr[num + 1][27]; memset(arr, 0, sizeof(arr)); for (int i = 0; i <= 25; i++){ arr[1][i] = 1; } for (int i = 2; i <= num; i++){ for (int j = 0; j <= 25; j++){ if (j == 0){ arr[i][j] = arr[i - 1][j + 1]; } else{ arr[i][j] = (arr[i - 1][j - 1] + arr[i - 1][j + 1]); } } } for (int i = 0; i <= 25; i++){ count = (count + arr[num][i]); } return count; } int main(){ int num = 2; cout<<"Count of strings where adjacent characters are of difference one are: "<<difference_strings(num); return 0; } If we run the above code it will generate the following output − Count of strings where adjacent characters are of difference one are: 50
[ { "code": null, "e": 1241, "s": 1062, "text": "We are given a num number as input. The goal is to count the number of possible strings of length num such that all adjacent characters have difference between ascii values as 1." }, { "code": null, "e": 1318, "s": 1241, "text": "If num is 2 then strings will be “ab”, “ba”, “bc”, “cb”, ........”yz”, “zy”." }, { "code": null, "e": 1350, "s": 1318, "text": "Let us understand with examples" }, { "code": null, "e": 1364, "s": 1350, "text": "Input − num=3" }, { "code": null, "e": 1447, "s": 1364, "text": "Output − Count of strings where adjacent characters are of difference one are − 98" }, { "code": null, "e": 1532, "s": 1447, "text": "Explanation − Some sample strings are: “abc”, “aba”, “cde” .....”xyx”, “zyz”, “xyz”." }, { "code": null, "e": 1546, "s": 1532, "text": "Input − num=2" }, { "code": null, "e": 1629, "s": 1546, "text": "Output − Count of strings where adjacent characters are of difference one are − 50" }, { "code": null, "e": 1708, "s": 1629, "text": "Explanation − Some sample strings are: “ab”, “ba”, “cd” .....”xy”, “zy”, “yz”." }, { "code": null, "e": 1724, "s": 1708, "text": "For length = 2." }, { "code": null, "e": 1753, "s": 1724, "text": "String starting with a= “ab”" }, { "code": null, "e": 1789, "s": 1753, "text": "Strings starting with b= “ba”, “bc”" }, { "code": null, "e": 1840, "s": 1789, "text": "Strings starting with c= “cd”, “cb”..............." }, { "code": null, "e": 1856, "s": 1840, "text": "For length = n." }, { "code": null, "e": 1935, "s": 1856, "text": "String starting with a=ways of number of strings of length n-1 starting with b" }, { "code": null, "e": 2019, "s": 1935, "text": "String starting with b=ways of number of strings of length n-1 starting with a or c" }, { "code": null, "e": 2103, "s": 2019, "text": "String starting with c=ways of number of strings of length n-1 starting with b or d" }, { "code": null, "e": 2149, "s": 2103, "text": "We will solve this using dynamic programming." }, { "code": null, "e": 2320, "s": 2149, "text": "Take an array arr[num+1][27]. Containing a number of strings of length i starting with alphabet number j in arr[i][j]. All arr[1][j] will be 1 for strings “a”, “b”...”z”." }, { "code": null, "e": 2444, "s": 2320, "text": "Rest for arr[2 to num+1][0 to 25], set arr[i][j]=arr[i-1][j+1] for j=0. Else set arr[i][j] = arr[i-1][j-1] + arr[i-1][j+1];" }, { "code": null, "e": 2493, "s": 2444, "text": "The result will be the sum of num-th row counts." }, { "code": null, "e": 2516, "s": 2493, "text": "Take input integer num" }, { "code": null, "e": 2539, "s": 2516, "text": "Take input integer num" }, { "code": null, "e": 2671, "s": 2539, "text": "Function difference_strings(int num) takes the num and returns the count of strings where adjacent characters are of difference one" }, { "code": null, "e": 2803, "s": 2671, "text": "Function difference_strings(int num) takes the num and returns the count of strings where adjacent characters are of difference one" }, { "code": null, "e": 2832, "s": 2803, "text": "Take the initial count as 0." }, { "code": null, "e": 2861, "s": 2832, "text": "Take the initial count as 0." }, { "code": null, "e": 2902, "s": 2861, "text": "Initialize arr[num + 1][27] with all 0s." }, { "code": null, "e": 2943, "s": 2902, "text": "Initialize arr[num + 1][27] with all 0s." }, { "code": null, "e": 2984, "s": 2943, "text": "Initialize arr[1][0 to 25] with all 1’s." }, { "code": null, "e": 3025, "s": 2984, "text": "Initialize arr[1][0 to 25] with all 1’s." }, { "code": null, "e": 3134, "s": 3025, "text": "Traverse 2D array arr[][] using two for loops from row 2nd to last and columns 0 to 25 for all 26 alphabets." }, { "code": null, "e": 3243, "s": 3134, "text": "Traverse 2D array arr[][] using two for loops from row 2nd to last and columns 0 to 25 for all 26 alphabets." }, { "code": null, "e": 3335, "s": 3243, "text": "For j=0, the starting character is ‘a’. Set current count as arr[i][j] = arr[i - 1][j + 1];" }, { "code": null, "e": 3427, "s": 3335, "text": "For j=0, the starting character is ‘a’. Set current count as arr[i][j] = arr[i - 1][j + 1];" }, { "code": null, "e": 3493, "s": 3427, "text": "Otherwise set arr[i][j] = (arr[i - 1][j - 1] + arr[i - 1][j + 1])" }, { "code": null, "e": 3559, "s": 3493, "text": "Otherwise set arr[i][j] = (arr[i - 1][j - 1] + arr[i - 1][j + 1])" }, { "code": null, "e": 3652, "s": 3559, "text": "Now after the end of the above loops, traverse last row and add arr[num][ 0 to 25] to count." }, { "code": null, "e": 3745, "s": 3652, "text": "Now after the end of the above loops, traverse last row and add arr[num][ 0 to 25] to count." }, { "code": null, "e": 3769, "s": 3745, "text": "Return count as result." }, { "code": null, "e": 3793, "s": 3769, "text": "Return count as result." }, { "code": null, "e": 3804, "s": 3793, "text": " Live Demo" }, { "code": null, "e": 4526, "s": 3804, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint difference_strings(int num){\n long int count = 0;\n long int arr[num + 1][27];\n memset(arr, 0, sizeof(arr));\n for (int i = 0; i <= 25; i++){\n arr[1][i] = 1;\n }\n for (int i = 2; i <= num; i++){\n for (int j = 0; j <= 25; j++){\n if (j == 0){\n arr[i][j] = arr[i - 1][j + 1];\n }\n else{\n arr[i][j] = (arr[i - 1][j - 1] + arr[i - 1][j + 1]);\n }\n }\n }\n for (int i = 0; i <= 25; i++){\n count = (count + arr[num][i]);\n }\n return count;\n}\nint main(){\n int num = 2;\n cout<<\"Count of strings where adjacent characters are of difference one are: \"<<difference_strings(num);\n return 0;\n}" }, { "code": null, "e": 4591, "s": 4526, "text": "If we run the above code it will generate the following output −" }, { "code": null, "e": 4664, "s": 4591, "text": "Count of strings where adjacent characters are of difference one are: 50" } ]
Class getCanonicalName() method in Java with Examples
25 Jan, 2022 The getCanonicalName() method of java.lang.Class class is used to get the canonical name of this class, which is the canonical name as defined by the Java Language Specification. The method returns the canonical name of this class in the form of String. Syntax: public String getCanonicalName() Parameter: This method does not accept any parameter.Return Value: This method returns the canonical name of this class in the form of String. Below programs demonstrate the getCanonicalName() method.Example 1: Java // Java program to demonstrate getCanonicalName() method import java.util.*; public class Test { public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName("Test"); System.out.println("Class represented by myClass: " + myClass.toString()); // Get the canonical name of myClass // using getCanonicalName() method System.out.println("CanonicalName of myClass: " + myClass.getCanonicalName()); }} Output: Class represented by myClass: class Test CanonicalName of myClass: Test Example 2: Java // Java program to demonstrate getCanonicalName() method import java.util.*; class Main { public Object obj; Main() { class Arr { }; obj = new Arr(); } public static void main(String[] args) throws ClassNotFoundException { Main t = new Main(); // returns the Class object Class myClass = t.obj.getClass(); System.out.println("Class represented by myClass: " + myClass.toString()); // Get the canonical name of myClass // using getCanonicalName() method System.out.println("CanonicalName of myClass: " + myClass.getCanonicalName()); }} Output: Class represented by myClass: class Main$1Arr CanonicalName of myClass: null Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getCanonicalName– adnanirshad158 Java-Functions Java-lang package Java.lang.Class Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Jan, 2022" }, { "code": null, "e": 292, "s": 28, "text": "The getCanonicalName() method of java.lang.Class class is used to get the canonical name of this class, which is the canonical name as defined by the Java Language Specification. The method returns the canonical name of this class in the form of String. Syntax: " }, { "code": null, "e": 325, "s": 292, "text": "public String getCanonicalName()" }, { "code": null, "e": 537, "s": 325, "text": "Parameter: This method does not accept any parameter.Return Value: This method returns the canonical name of this class in the form of String. Below programs demonstrate the getCanonicalName() method.Example 1: " }, { "code": null, "e": 542, "s": 537, "text": "Java" }, { "code": "// Java program to demonstrate getCanonicalName() method import java.util.*; public class Test { public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName(\"Test\"); System.out.println(\"Class represented by myClass: \" + myClass.toString()); // Get the canonical name of myClass // using getCanonicalName() method System.out.println(\"CanonicalName of myClass: \" + myClass.getCanonicalName()); }}", "e": 1134, "s": 542, "text": null }, { "code": null, "e": 1144, "s": 1134, "text": "Output: " }, { "code": null, "e": 1216, "s": 1144, "text": "Class represented by myClass: class Test\nCanonicalName of myClass: Test" }, { "code": null, "e": 1228, "s": 1216, "text": "Example 2: " }, { "code": null, "e": 1233, "s": 1228, "text": "Java" }, { "code": "// Java program to demonstrate getCanonicalName() method import java.util.*; class Main { public Object obj; Main() { class Arr { }; obj = new Arr(); } public static void main(String[] args) throws ClassNotFoundException { Main t = new Main(); // returns the Class object Class myClass = t.obj.getClass(); System.out.println(\"Class represented by myClass: \" + myClass.toString()); // Get the canonical name of myClass // using getCanonicalName() method System.out.println(\"CanonicalName of myClass: \" + myClass.getCanonicalName()); }}", "e": 1926, "s": 1233, "text": null }, { "code": null, "e": 1936, "s": 1926, "text": "Output: " }, { "code": null, "e": 2013, "s": 1936, "text": "Class represented by myClass: class Main$1Arr\nCanonicalName of myClass: null" }, { "code": null, "e": 2106, "s": 2013, "text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getCanonicalName– " }, { "code": null, "e": 2121, "s": 2106, "text": "adnanirshad158" }, { "code": null, "e": 2136, "s": 2121, "text": "Java-Functions" }, { "code": null, "e": 2154, "s": 2136, "text": "Java-lang package" }, { "code": null, "e": 2170, "s": 2154, "text": "Java.lang.Class" }, { "code": null, "e": 2175, "s": 2170, "text": "Java" }, { "code": null, "e": 2180, "s": 2175, "text": "Java" } ]
What do these three dots (...) in React do ?
24 Jun, 2021 The three dots (...) notation referred to as the Spread syntax has been part of React for a long time when it could be used via transpilation, although, it has been made a part of JavaScript as part of the ES2015 syntax. The Spread syntax is used to deconstruct an array or object into separate variables where the exact number of elements in the array may not be known or when we wish to keep an attribute or a set of attributes separate from the entire object. The following can be performed using the spread syntax: 1. Passing attributes: An object can directly be passed to a component instead of passing each data value in the object separately. values:{ height: 20, width: 10 } <Image {...values} source="Image_Source"> // This same as the following: <Image height={values.height} width={values.width} source="Image_Source"> 2. Inheriting an Object: When creating a new object that inherits another object we can use the Spread syntax to inherit the parent object. object1:{ a: 10, b: 20 }; object2:{ ...object1, c: 14 }; 3. Concatenate Arrays: We can also concatenate arrays using the Spread syntax as follows. var first =[1, 2, 3]; var second = [2, 3, 4, 5]; var third = [...first, ...second]; 4. Destructuring Arrays: Destructuring an array into separate components can also be performed using the Spread Syntax. var original = [1,2,3,4,5,6,7]; var [first, ...remaining] = original; // Therefore the following will be the values of first and remaining. first = [1] remaining = [2,3,4,5,6,7] Creating React Application And Installing Module: Step 1: Create a React application using the following command:npx create-react-app spread-syntax-demo Step 1: Create a React application using the following command: npx create-react-app spread-syntax-demo Step 2: After creating your project folder, move to it using the following command:cd spread-syntax-demo Step 2: After creating your project folder, move to it using the following command: cd spread-syntax-demo Project Structure: It will look like the following. Example: Here in the App.js file, we are going to create an object create a child object from it, and then pass it as an attribute to a component. App.js import React from 'react';import Image from './Image.jsx'; function App(props) { const originalImage = { src:"https://media.geeksforgeeks.org/wp-content/cdn-uploads/gfg_200x200-min.png", alt:"This is a random image" }; const formattedImage = { ...originalImage, height:300, width: 300 } return ( <div> <Image {...formattedImage}/> </div> );} export default App; In Image.jsx we pass props to HTML img tag using the spread syntax. Image.jsx import React from 'react'; function Image(props) { return ( <div> <img {...props}/> </div> );} export default Image; 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: Picked React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n24 Jun, 2021" }, { "code": null, "e": 275, "s": 54, "text": "The three dots (...) notation referred to as the Spread syntax has been part of React for a long time when it could be used via transpilation, although, it has been made a part of JavaScript as part of the ES2015 syntax." }, { "code": null, "e": 517, "s": 275, "text": "The Spread syntax is used to deconstruct an array or object into separate variables where the exact number of elements in the array may not be known or when we wish to keep an attribute or a set of attributes separate from the entire object." }, { "code": null, "e": 573, "s": 517, "text": "The following can be performed using the spread syntax:" }, { "code": null, "e": 705, "s": 573, "text": "1. Passing attributes: An object can directly be passed to a component instead of passing each data value in the object separately." }, { "code": null, "e": 896, "s": 705, "text": "values:{\n height: 20,\n width: 10\n}\n\n<Image {...values} source=\"Image_Source\">\n\n// This same as the following:\n<Image height={values.height} \nwidth={values.width} source=\"Image_Source\">" }, { "code": null, "e": 1036, "s": 896, "text": "2. Inheriting an Object: When creating a new object that inherits another object we can use the Spread syntax to inherit the parent object." }, { "code": null, "e": 1110, "s": 1036, "text": "object1:{\n a: 10,\n b: 20\n};\n\nobject2:{\n ...object1,\n c: 14\n};" }, { "code": null, "e": 1200, "s": 1110, "text": "3. Concatenate Arrays: We can also concatenate arrays using the Spread syntax as follows." }, { "code": null, "e": 1284, "s": 1200, "text": "var first =[1, 2, 3];\nvar second = [2, 3, 4, 5];\nvar third = [...first, ...second];" }, { "code": null, "e": 1404, "s": 1284, "text": "4. Destructuring Arrays: Destructuring an array into separate components can also be performed using the Spread Syntax." }, { "code": null, "e": 1585, "s": 1404, "text": "var original = [1,2,3,4,5,6,7];\nvar [first, ...remaining] = original;\n\n// Therefore the following will be the values of first and remaining.\nfirst = [1] \nremaining = [2,3,4,5,6,7]" }, { "code": null, "e": 1635, "s": 1585, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 1738, "s": 1635, "text": "Step 1: Create a React application using the following command:npx create-react-app spread-syntax-demo" }, { "code": null, "e": 1802, "s": 1738, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 1842, "s": 1802, "text": "npx create-react-app spread-syntax-demo" }, { "code": null, "e": 1947, "s": 1842, "text": "Step 2: After creating your project folder, move to it using the following command:cd spread-syntax-demo" }, { "code": null, "e": 2031, "s": 1947, "text": "Step 2: After creating your project folder, move to it using the following command:" }, { "code": null, "e": 2053, "s": 2031, "text": "cd spread-syntax-demo" }, { "code": null, "e": 2105, "s": 2053, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 2252, "s": 2105, "text": "Example: Here in the App.js file, we are going to create an object create a child object from it, and then pass it as an attribute to a component." }, { "code": null, "e": 2259, "s": 2252, "text": "App.js" }, { "code": "import React from 'react';import Image from './Image.jsx'; function App(props) { const originalImage = { src:\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/gfg_200x200-min.png\", alt:\"This is a random image\" }; const formattedImage = { ...originalImage, height:300, width: 300 } return ( <div> <Image {...formattedImage}/> </div> );} export default App;", "e": 2654, "s": 2259, "text": null }, { "code": null, "e": 2722, "s": 2654, "text": "In Image.jsx we pass props to HTML img tag using the spread syntax." }, { "code": null, "e": 2732, "s": 2722, "text": "Image.jsx" }, { "code": "import React from 'react'; function Image(props) { return ( <div> <img {...props}/> </div> );} export default Image;", "e": 2882, "s": 2732, "text": null }, { "code": null, "e": 2995, "s": 2882, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 3005, "s": 2995, "text": "npm start" }, { "code": null, "e": 3104, "s": 3005, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 3111, "s": 3104, "text": "Picked" }, { "code": null, "e": 3127, "s": 3111, "text": "React-Questions" }, { "code": null, "e": 3135, "s": 3127, "text": "ReactJS" }, { "code": null, "e": 3152, "s": 3135, "text": "Web Technologies" } ]
URLs in Flutter
14 Jun, 2022 While surfing the net, every user will come across many buttons, text, etc., that would redirect the user to a different webpage in the same tab or in a different tab when clicked. In the same way, when a developer links a URL to a button or text in an app, the app will open the website when clicked in the following ways: In browser(default) In-App In browser(default) In-App When it comes to opening a website in a browser then it involves two apps at work. One of the app that the user is using and the other is the browser. But, when it comes to, in-app opening, it involves only one app. Each of these features can be used by a developer according to the need of the user. In Flutter, everything is a widget and in the same way, Flutter also uses a lot of plugins or dependencies in order to make the app work faster and easier. In this case, the “url_launcher” plugin can be used to launch the URL in a mobile application. Step 1: Open “pubspec.yaml” file from the project folder. pubspec.yaml Step 2: In the pubspec.yaml file, type “url_launcher:” under dependencies. The code looks like this: Dart dependencies: flutter: sdk: flutter url_launcher: Step 3: Now click “Pub Get” button in the top of the application (Android Studio). Step 4: The “Process finished with exit code 0“ in the console shows that the dependency is been added successfully. Step 5: Now import the plugin or package by adding the “import ‘package:url_launcher/url_launcher.dart’;” code to the top of the “main.dart” file. Now, let’s create a function that can be called whenever the user clicks a button that’s linked to a URL, to open it in a browser. Dart _launchURLBrowser() async { var url = Uri.parse("https://www.geeksforgeeks.org/"); if (await canLaunchUrl(url)) { await launchUrl(url); } else { throw 'Could not launch $url'; }} This is what we did in the above function: The function is named here as “_launchURLBrowser” and the function is declared as “async”, so that it returns a promise. The “url” variable is assigned with the required web address, as a string. It is declared as a “const”, so that the variable is not changed at any circumstance. If there is a possibility to launch the URL, only then the url is launched by calling the launch() function with url variable as an attribute. Else, it will throw/print a text with the URLs value, as an error message. Now, let’s create a function that can be called whenever the user clicks a button that’s linked to a URL, to open it in the app. Dart _launchURLApp() async { var url = Uri.parse("https://www.geeksforgeeks.org/"); if (await canLaunchUrl(url)) { await launchUrl(url); } else { throw 'Could not launch $url'; }} This is what we did in the above function: The function is named here as “_launchURLApp” and the function is declared as “async”, so that it returns a promise. The “url” variable is assigned with the required web address, as a string. It is declared as a “const”, so that the variable is not changed at any circumstance. If there is a possibility to launch the URL, only then the url is launched by calling the launch() function with url variable as an attribute. In order to open the URL inside the app, two conditions have to be made true. forceWebView: true — this helps the app to start the web view of the app for the website to open inside the app itself.forceSafariVC: true — in iOS devices, this helps the app to open the website in the Safari View Controller other than the default browser. forceWebView: true — this helps the app to start the web view of the app for the website to open inside the app itself. forceSafariVC: true — in iOS devices, this helps the app to open the website in the Safari View Controller other than the default browser. 5) Else, it will throw/print a text with the url value, as an error message. Note: In browser opening, the forceWebView and forceSafariVC are set to “false” by default. The above functions can be called whenever needed in code, by calling the name of the functions as such. The examples are as follows: Dart ElevatedButton( onPressed: _launchURLBrowser, style: ButtonStyle( padding: MaterialStateProperty.all(const EdgeInsets.all(5.0)), textStyle: MaterialStateProperty.all( const TextStyle(color: Colors.black), ), ), ElevatedButton( onPressed: _launchURLApp, style: ButtonStyle( padding: MaterialStateProperty.all(const EdgeInsets.all(5.0)), textStyle: MaterialStateProperty.all( const TextStyle(color: Colors.black), ), ), In the above code block we did two things: This creates two raised buttons having the text “Open in Browser” and “Open in App” on it, respectively. For the onPressed attribute, we are calling _launchURLBrowser and _launchURLApp respectively so that, when the first button is pressed the URL is opened in a browser and when the second button is pressed the URL is opened in the app itself. This creates two raised buttons having the text “Open in Browser” and “Open in App” on it, respectively. For the onPressed attribute, we are calling _launchURLBrowser and _launchURLApp respectively so that, when the first button is pressed the URL is opened in a browser and when the second button is pressed the URL is opened in the app itself. Dart // importing dependenciesimport 'package:flutter/material.dart';import 'package:url_launcher/url_launcher.dart'; // function to trigger the build processvoid main() => runApp(const MyApp()); _launchURLBrowser() async { var url = Uri.parse("https://www.geeksforgeeks.org/"); if (await canLaunchUrl(url)) { await launchUrl(url); } else { throw 'Could not launch $url'; }} _launchURLApp() async { var url = Uri.parse("https://www.geeksforgeeks.org/"); if (await canLaunchUrl(url)) { await launchUrl(url); } else { throw 'Could not launch $url'; }} class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('Geeks for Geeks'), backgroundColor: Colors.green, ), body: SafeArea( child: Center( child: Column( children: [ Container( height: 250.0, ), const Text( 'Welcome to GFG!', style: TextStyle( fontSize: 30.0, color: Colors.green, fontWeight: FontWeight.bold, ), ), Container( height: 20.0, ), ElevatedButton( onPressed: _launchURLBrowser, style: ButtonStyle( padding: MaterialStateProperty.all(const EdgeInsets.all(5.0)), textStyle: MaterialStateProperty.all( const TextStyle(color: Colors.black), ), ), // textColor: Colors.black, // padding: const EdgeInsets.all(5.0), child: const Text('Open in Browser'), ), Container( height: 20.0, ), ElevatedButton( onPressed: _launchURLApp, style: ButtonStyle( padding: MaterialStateProperty.all(const EdgeInsets.all(5)), textStyle: MaterialStateProperty.all( const TextStyle(color: Colors.black))), // textColor: Colors.black, // padding: const EdgeInsets.all(5.0), child: const Text('Open in App'), ), ], ), ), ), ), ); }} ankit_kumar_ android Android Dart Flutter Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Jun, 2022" }, { "code": null, "e": 352, "s": 28, "text": "While surfing the net, every user will come across many buttons, text, etc., that would redirect the user to a different webpage in the same tab or in a different tab when clicked. In the same way, when a developer links a URL to a button or text in an app, the app will open the website when clicked in the following ways:" }, { "code": null, "e": 380, "s": 352, "text": " In browser(default) In-App" }, { "code": null, "e": 401, "s": 380, "text": " In browser(default)" }, { "code": null, "e": 409, "s": 401, "text": " In-App" }, { "code": null, "e": 710, "s": 409, "text": "When it comes to opening a website in a browser then it involves two apps at work. One of the app that the user is using and the other is the browser. But, when it comes to, in-app opening, it involves only one app. Each of these features can be used by a developer according to the need of the user." }, { "code": null, "e": 961, "s": 710, "text": "In Flutter, everything is a widget and in the same way, Flutter also uses a lot of plugins or dependencies in order to make the app work faster and easier. In this case, the “url_launcher” plugin can be used to launch the URL in a mobile application." }, { "code": null, "e": 1019, "s": 961, "text": "Step 1: Open “pubspec.yaml” file from the project folder." }, { "code": null, "e": 1032, "s": 1019, "text": "pubspec.yaml" }, { "code": null, "e": 1107, "s": 1032, "text": "Step 2: In the pubspec.yaml file, type “url_launcher:” under dependencies." }, { "code": null, "e": 1133, "s": 1107, "text": "The code looks like this:" }, { "code": null, "e": 1138, "s": 1133, "text": "Dart" }, { "code": "dependencies: flutter: sdk: flutter url_launcher:", "e": 1193, "s": 1138, "text": null }, { "code": null, "e": 1276, "s": 1193, "text": "Step 3: Now click “Pub Get” button in the top of the application (Android Studio)." }, { "code": null, "e": 1393, "s": 1276, "text": "Step 4: The “Process finished with exit code 0“ in the console shows that the dependency is been added successfully." }, { "code": null, "e": 1540, "s": 1393, "text": "Step 5: Now import the plugin or package by adding the “import ‘package:url_launcher/url_launcher.dart’;” code to the top of the “main.dart” file." }, { "code": null, "e": 1672, "s": 1540, "text": "Now, let’s create a function that can be called whenever the user clicks a button that’s linked to a URL, to open it in a browser. " }, { "code": null, "e": 1677, "s": 1672, "text": "Dart" }, { "code": "_launchURLBrowser() async { var url = Uri.parse(\"https://www.geeksforgeeks.org/\"); if (await canLaunchUrl(url)) { await launchUrl(url); } else { throw 'Could not launch $url'; }}", "e": 1866, "s": 1677, "text": null }, { "code": null, "e": 1909, "s": 1866, "text": "This is what we did in the above function:" }, { "code": null, "e": 2030, "s": 1909, "text": "The function is named here as “_launchURLBrowser” and the function is declared as “async”, so that it returns a promise." }, { "code": null, "e": 2191, "s": 2030, "text": "The “url” variable is assigned with the required web address, as a string. It is declared as a “const”, so that the variable is not changed at any circumstance." }, { "code": null, "e": 2335, "s": 2191, "text": " If there is a possibility to launch the URL, only then the url is launched by calling the launch() function with url variable as an attribute." }, { "code": null, "e": 2411, "s": 2335, "text": " Else, it will throw/print a text with the URLs value, as an error message." }, { "code": null, "e": 2540, "s": 2411, "text": "Now, let’s create a function that can be called whenever the user clicks a button that’s linked to a URL, to open it in the app." }, { "code": null, "e": 2545, "s": 2540, "text": "Dart" }, { "code": "_launchURLApp() async { var url = Uri.parse(\"https://www.geeksforgeeks.org/\"); if (await canLaunchUrl(url)) { await launchUrl(url); } else { throw 'Could not launch $url'; }}", "e": 2730, "s": 2545, "text": null }, { "code": null, "e": 2773, "s": 2730, "text": "This is what we did in the above function:" }, { "code": null, "e": 2890, "s": 2773, "text": "The function is named here as “_launchURLApp” and the function is declared as “async”, so that it returns a promise." }, { "code": null, "e": 3051, "s": 2890, "text": "The “url” variable is assigned with the required web address, as a string. It is declared as a “const”, so that the variable is not changed at any circumstance." }, { "code": null, "e": 3194, "s": 3051, "text": "If there is a possibility to launch the URL, only then the url is launched by calling the launch() function with url variable as an attribute." }, { "code": null, "e": 3272, "s": 3194, "text": "In order to open the URL inside the app, two conditions have to be made true." }, { "code": null, "e": 3531, "s": 3272, "text": " forceWebView: true — this helps the app to start the web view of the app for the website to open inside the app itself.forceSafariVC: true — in iOS devices, this helps the app to open the website in the Safari View Controller other than the default browser." }, { "code": null, "e": 3652, "s": 3531, "text": " forceWebView: true — this helps the app to start the web view of the app for the website to open inside the app itself." }, { "code": null, "e": 3791, "s": 3652, "text": "forceSafariVC: true — in iOS devices, this helps the app to open the website in the Safari View Controller other than the default browser." }, { "code": null, "e": 3868, "s": 3791, "text": "5) Else, it will throw/print a text with the url value, as an error message." }, { "code": null, "e": 3960, "s": 3868, "text": "Note: In browser opening, the forceWebView and forceSafariVC are set to “false” by default." }, { "code": null, "e": 4094, "s": 3960, "text": "The above functions can be called whenever needed in code, by calling the name of the functions as such. The examples are as follows:" }, { "code": null, "e": 4099, "s": 4094, "text": "Dart" }, { "code": "ElevatedButton( onPressed: _launchURLBrowser, style: ButtonStyle( padding: MaterialStateProperty.all(const EdgeInsets.all(5.0)), textStyle: MaterialStateProperty.all( const TextStyle(color: Colors.black), ), ), ElevatedButton( onPressed: _launchURLApp, style: ButtonStyle( padding: MaterialStateProperty.all(const EdgeInsets.all(5.0)), textStyle: MaterialStateProperty.all( const TextStyle(color: Colors.black), ), ),", "e": 4807, "s": 4099, "text": null }, { "code": null, "e": 4850, "s": 4807, "text": "In the above code block we did two things:" }, { "code": null, "e": 5196, "s": 4850, "text": "This creates two raised buttons having the text “Open in Browser” and “Open in App” on it, respectively. For the onPressed attribute, we are calling _launchURLBrowser and _launchURLApp respectively so that, when the first button is pressed the URL is opened in a browser and when the second button is pressed the URL is opened in the app itself." }, { "code": null, "e": 5301, "s": 5196, "text": "This creates two raised buttons having the text “Open in Browser” and “Open in App” on it, respectively." }, { "code": null, "e": 5543, "s": 5301, "text": " For the onPressed attribute, we are calling _launchURLBrowser and _launchURLApp respectively so that, when the first button is pressed the URL is opened in a browser and when the second button is pressed the URL is opened in the app itself." }, { "code": null, "e": 5548, "s": 5543, "text": "Dart" }, { "code": "// importing dependenciesimport 'package:flutter/material.dart';import 'package:url_launcher/url_launcher.dart'; // function to trigger the build processvoid main() => runApp(const MyApp()); _launchURLBrowser() async { var url = Uri.parse(\"https://www.geeksforgeeks.org/\"); if (await canLaunchUrl(url)) { await launchUrl(url); } else { throw 'Could not launch $url'; }} _launchURLApp() async { var url = Uri.parse(\"https://www.geeksforgeeks.org/\"); if (await canLaunchUrl(url)) { await launchUrl(url); } else { throw 'Could not launch $url'; }} class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('Geeks for Geeks'), backgroundColor: Colors.green, ), body: SafeArea( child: Center( child: Column( children: [ Container( height: 250.0, ), const Text( 'Welcome to GFG!', style: TextStyle( fontSize: 30.0, color: Colors.green, fontWeight: FontWeight.bold, ), ), Container( height: 20.0, ), ElevatedButton( onPressed: _launchURLBrowser, style: ButtonStyle( padding: MaterialStateProperty.all(const EdgeInsets.all(5.0)), textStyle: MaterialStateProperty.all( const TextStyle(color: Colors.black), ), ), // textColor: Colors.black, // padding: const EdgeInsets.all(5.0), child: const Text('Open in Browser'), ), Container( height: 20.0, ), ElevatedButton( onPressed: _launchURLApp, style: ButtonStyle( padding: MaterialStateProperty.all(const EdgeInsets.all(5)), textStyle: MaterialStateProperty.all( const TextStyle(color: Colors.black))), // textColor: Colors.black, // padding: const EdgeInsets.all(5.0), child: const Text('Open in App'), ), ], ), ), ), ), ); }}", "e": 8126, "s": 5548, "text": null }, { "code": null, "e": 8139, "s": 8126, "text": "ankit_kumar_" }, { "code": null, "e": 8147, "s": 8139, "text": "android" }, { "code": null, "e": 8155, "s": 8147, "text": "Android" }, { "code": null, "e": 8160, "s": 8155, "text": "Dart" }, { "code": null, "e": 8168, "s": 8160, "text": "Flutter" }, { "code": null, "e": 8176, "s": 8168, "text": "Android" } ]
Length Of Last Word in a String
09 Jun, 2021 Given a string s consisting of upper/lower-case alphabets and empty space characters ‘ ‘, return the length of the last word in the string. If the last word does not exist, return 0. Examples: Input : str = "Geeks For Geeks" Output : 5 length(Geeks)= 5 Input : str = "Start Coding Here" Output : 4 length(Here) = 4 Input : ** Output : 0 Approach 1: Iterate String from index 0 If we iterate the string from left to right, we would have to be careful about the spaces after the last word. The spaces before the first word can be ignored easily. However, it is difficult to detect the length of the last word if there are spaces at the end of the string. This can be handled by trimming the spaces before or at the end of the string. If modifying the given string is restricted, we need to create a copy of the string and trim spaces from that. C++ Java Python3 C# Javascript // C++ program for implementation of simple// approach to find length of last word#include<bits/stdc++.h>#include <boost/algorithm/string.hpp>using namespace std; int lengthOfLastWord(string a){ int len = 0; /* String a is 'final'-- can not be modified So, create a copy and trim the spaces from both sides */ string str(a); boost::trim_right(str); for (int i = 0; i < str.length(); i++) { if (str.at(i) == ' ') len = 0; else len++; } return len;} // Driver codeint main(){ string input = "Geeks For Geeks "; cout << "The length of last word is " << lengthOfLastWord(input);} // This code is contributed by Rajput-Ji // Java program for implementation of simple// approach to find length of last wordpublic class GFG { public int lengthOfLastWord(final String a) { int len = 0; /* String a is 'final'-- can not be modified So, create a copy and trim the spaces from both sides */ String x = a.trim(); for (int i = 0; i < x.length(); i++) { if (x.charAt(i) == ' ') len = 0; else len++; } return len; } // Driver code public static void main(String[] args) { String input = "Geeks For Geeks "; GFG gfg = new GFG(); System.out.println("The length of last word is " + gfg.lengthOfLastWord(input)); }} # Python3 program for implementation of simple# approach to find length of last worddef lengthOfLastWord(a): l = 0 # String a is 'final'-- can not be modified # So, create a copy and trim the spaces from # both sides x = a.strip() for i in range(len(x)): if x[i] == " ": l = 0 else: l += 1 return l # Driver codeif __name__ == "__main__": inp = "Geeks For Geeks " print("The length of last word is", lengthOfLastWord(inp)) # This code is contributed by# sanjeev2552 // C# program for implementation of simple// approach to find length of last wordusing System; class GFG { public virtual int lengthOfLastWord(string a) { int len = 0; // String a is 'final'-- can // not be modified So, create // a copy and trim the // spaces from both sides string x = a.Trim(); for (int i = 0; i < x.Length; i++) { if (x[i] == ' ') { len = 0; } else { len++; } } return len; } // Driver code public static void Main(string[] args) { string input = "Geeks For Geeks "; GFG gfg = new GFG(); Console.WriteLine("The length of last word is " + gfg.lengthOfLastWord(input)); }} // This code is contributed by shrikanth13 <script> // js program for implementation of simple// approach to find length of last word function lengthOfLastWord(a){ let len = 0; // String a is 'final'-- can // not be modified So, create // a copy and trim the // spaces from both sides x = a.trim(); for (let i = 0; i < x.length; i++) { if (x[i] == ' ') { len = 0; } else { len++; } } return len;} // Driver code input = "Geeks For Geeks ";document.write("The length of last word is "+ lengthOfLastWord(input)); </script> Output: Length of the last word is 5 Approach 2: Iterate the string from the last index. This idea is more efficient since we can easily ignore the spaces from the last. The idea is to start incrementing the count when you encounter the first alphabet from the last and stop when you encounter a space after those alphabets. C++ Java Python3 C# PHP // CPP program for implementation of efficient// approach to find length of last word#include <bits/stdc++.h>#include <iostream>using namespace std; int length(string str){ int count = 0; bool flag = false; for (int i = str.length() - 1; i >= 0; i--) { // Once the first character from last // is encountered, set char_flag to true. if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z')) { flag = true; count++; } // When the first space after the // characters (from the last) is // encountered, return the length // of the last word else { if (flag == true) return count; } } return count;} // Driver codeint main(){ string str = "Geeks for Geeks"; cout << "The length of last word is " << length(str); return 0;} // This code is contributed by rahulkumawat2107 // Java program for implementation of efficient// approach to find length of last wordpublic class GFG { public int lengthOfLastWord(final String a) { boolean char_flag = false; int len = 0; for (int i = a.length() - 1; i >= 0; i--) { if (Character.isLetter(a.charAt(i))) { // Once the first character from last // is encountered, set char_flag to true. char_flag = true; len++; } else { // When the first space after the characters // (from the last) is encountered, return the // length of the last word if (char_flag == true) return len; } } return len; } // Driver code public static void main(String[] args) { String input = "Geeks For Geeks "; GFG gfg = new GFG(); System.out.println("The length of last word is " + gfg.lengthOfLastWord(input)); }} # Python3 program for implementation of efficient# approach to find length of last worddef length(str): count = 0; flag = False; length = len(str)-1; while(length != 0): if(str[length] == ' '): return count; else: count += 1; length -= 1; return count; # Driver codestr = "Geeks for Geeks";print("The length of last word is", length(str)); # This code is contributed by Rajput Ji // C# program for implementation of efficient// approach to find length of last wordusing System; class GFG { public virtual int lengthOfLastWord(string a) { bool char_flag = false; int len = 0; for (int i = a.Length - 1; i >= 0; i--) { if (char.IsLetter(a[i])) { // Once the first character from last // is encountered, set char_flag to true. char_flag = true; len++; } else { // When the first space after the // characters (from the last) is // encountered, return the length // of the last word if (char_flag == true) { return len; } } } return len; } // Driver code public static void Main(string[] args) { string input = "Geeks For Geeks "; GFG gfg = new GFG(); Console.WriteLine("The length of last word is " + gfg.lengthOfLastWord(input)); }} // This code is contributed by Shrikant13 <?php// PHP program for implementation of efficient// approach to find length of last word function length($str){ $count = 0; $flag = false; for($i = strlen($str)-1 ; $i>=0 ; $i--) { // Once the first character from last // is encountered, set char_flag to true. if( ($str[$i] >='a' && $str[$i]<='z') || ($str[$i] >='A' && $str[$i]<='Z')) { $flag = true; $count++; } // When the first space after the // characters (from the last) is // encountered, return the length // of the last word else { if($flag == true) return $count; } } return $count;} // Driver code$str = "Geeks for Geeks";echo "The length of last word is ", length($str); // This code is contributed by ajit.?> Output: Length of the last word is 5 This article is contributed by Saloni Baweja. 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. As all the words in a sentence are separated by spaces. We have to split the sentence by spaces using split(). We split all the words by spaces and store them in a list. Print the length of the last word of the list. Below is the implementation: Python3 Javascript # Python3 program for implementation of efficient# approach to find length of last word def length(str): # Split by space and converting # String to list and lis = list(str.split(" ")) return len(lis[-1]) # Driver codestr = "Geeks for Geeks"print("The length of last word is", length(str)) # This code is contributed by vikkycirus <script> // Javascript program for implementation// of efficient approach to find length// of last wordfunction length(str){ // Split by space and converting // String to list and var lis = str.split(" ") return lis[lis.length - 1].length;} // Driver codevar str = "Geeks for Geeks"document.write("The length of last word is " + length(str)); // This code is contributed by bunnyram19 </script> Output: Length of the last word is 5 shrikanth13 rahulkumawat2107 jit_t shubham_singh sanjeev2552 Rajput-Ji vikkycirus mohit kumar 29 bunnyram19 Java-Strings Strings Java-Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n09 Jun, 2021" }, { "code": null, "e": 235, "s": 52, "text": "Given a string s consisting of upper/lower-case alphabets and empty space characters ‘ ‘, return the length of the last word in the string. If the last word does not exist, return 0." }, { "code": null, "e": 247, "s": 235, "text": "Examples: " }, { "code": null, "e": 396, "s": 247, "text": "Input : str = \"Geeks For Geeks\"\nOutput : 5\nlength(Geeks)= 5\n\nInput : str = \"Start Coding Here\"\nOutput : 4\nlength(Here) = 4\n\nInput : **\nOutput : 0" }, { "code": null, "e": 904, "s": 396, "text": "Approach 1: Iterate String from index 0 If we iterate the string from left to right, we would have to be careful about the spaces after the last word. The spaces before the first word can be ignored easily. However, it is difficult to detect the length of the last word if there are spaces at the end of the string. This can be handled by trimming the spaces before or at the end of the string. If modifying the given string is restricted, we need to create a copy of the string and trim spaces from that. " }, { "code": null, "e": 908, "s": 904, "text": "C++" }, { "code": null, "e": 913, "s": 908, "text": "Java" }, { "code": null, "e": 921, "s": 913, "text": "Python3" }, { "code": null, "e": 924, "s": 921, "text": "C#" }, { "code": null, "e": 935, "s": 924, "text": "Javascript" }, { "code": "// C++ program for implementation of simple// approach to find length of last word#include<bits/stdc++.h>#include <boost/algorithm/string.hpp>using namespace std; int lengthOfLastWord(string a){ int len = 0; /* String a is 'final'-- can not be modified So, create a copy and trim the spaces from both sides */ string str(a); boost::trim_right(str); for (int i = 0; i < str.length(); i++) { if (str.at(i) == ' ') len = 0; else len++; } return len;} // Driver codeint main(){ string input = \"Geeks For Geeks \"; cout << \"The length of last word is \" << lengthOfLastWord(input);} // This code is contributed by Rajput-Ji", "e": 1636, "s": 935, "text": null }, { "code": "// Java program for implementation of simple// approach to find length of last wordpublic class GFG { public int lengthOfLastWord(final String a) { int len = 0; /* String a is 'final'-- can not be modified So, create a copy and trim the spaces from both sides */ String x = a.trim(); for (int i = 0; i < x.length(); i++) { if (x.charAt(i) == ' ') len = 0; else len++; } return len; } // Driver code public static void main(String[] args) { String input = \"Geeks For Geeks \"; GFG gfg = new GFG(); System.out.println(\"The length of last word is \" + gfg.lengthOfLastWord(input)); }}", "e": 2377, "s": 1636, "text": null }, { "code": "# Python3 program for implementation of simple# approach to find length of last worddef lengthOfLastWord(a): l = 0 # String a is 'final'-- can not be modified # So, create a copy and trim the spaces from # both sides x = a.strip() for i in range(len(x)): if x[i] == \" \": l = 0 else: l += 1 return l # Driver codeif __name__ == \"__main__\": inp = \"Geeks For Geeks \" print(\"The length of last word is\", lengthOfLastWord(inp)) # This code is contributed by# sanjeev2552", "e": 2924, "s": 2377, "text": null }, { "code": "// C# program for implementation of simple// approach to find length of last wordusing System; class GFG { public virtual int lengthOfLastWord(string a) { int len = 0; // String a is 'final'-- can // not be modified So, create // a copy and trim the // spaces from both sides string x = a.Trim(); for (int i = 0; i < x.Length; i++) { if (x[i] == ' ') { len = 0; } else { len++; } } return len; } // Driver code public static void Main(string[] args) { string input = \"Geeks For Geeks \"; GFG gfg = new GFG(); Console.WriteLine(\"The length of last word is \" + gfg.lengthOfLastWord(input)); }} // This code is contributed by shrikanth13", "e": 3767, "s": 2924, "text": null }, { "code": "<script> // js program for implementation of simple// approach to find length of last word function lengthOfLastWord(a){ let len = 0; // String a is 'final'-- can // not be modified So, create // a copy and trim the // spaces from both sides x = a.trim(); for (let i = 0; i < x.length; i++) { if (x[i] == ' ') { len = 0; } else { len++; } } return len;} // Driver code input = \"Geeks For Geeks \";document.write(\"The length of last word is \"+ lengthOfLastWord(input)); </script>", "e": 4328, "s": 3767, "text": null }, { "code": null, "e": 4337, "s": 4328, "text": "Output: " }, { "code": null, "e": 4366, "s": 4337, "text": "Length of the last word is 5" }, { "code": null, "e": 4655, "s": 4366, "text": " Approach 2: Iterate the string from the last index. This idea is more efficient since we can easily ignore the spaces from the last. The idea is to start incrementing the count when you encounter the first alphabet from the last and stop when you encounter a space after those alphabets." }, { "code": null, "e": 4659, "s": 4655, "text": "C++" }, { "code": null, "e": 4664, "s": 4659, "text": "Java" }, { "code": null, "e": 4672, "s": 4664, "text": "Python3" }, { "code": null, "e": 4675, "s": 4672, "text": "C#" }, { "code": null, "e": 4679, "s": 4675, "text": "PHP" }, { "code": "// CPP program for implementation of efficient// approach to find length of last word#include <bits/stdc++.h>#include <iostream>using namespace std; int length(string str){ int count = 0; bool flag = false; for (int i = str.length() - 1; i >= 0; i--) { // Once the first character from last // is encountered, set char_flag to true. if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z')) { flag = true; count++; } // When the first space after the // characters (from the last) is // encountered, return the length // of the last word else { if (flag == true) return count; } } return count;} // Driver codeint main(){ string str = \"Geeks for Geeks\"; cout << \"The length of last word is \" << length(str); return 0;} // This code is contributed by rahulkumawat2107", "e": 5604, "s": 4679, "text": null }, { "code": "// Java program for implementation of efficient// approach to find length of last wordpublic class GFG { public int lengthOfLastWord(final String a) { boolean char_flag = false; int len = 0; for (int i = a.length() - 1; i >= 0; i--) { if (Character.isLetter(a.charAt(i))) { // Once the first character from last // is encountered, set char_flag to true. char_flag = true; len++; } else { // When the first space after the characters // (from the last) is encountered, return the // length of the last word if (char_flag == true) return len; } } return len; } // Driver code public static void main(String[] args) { String input = \"Geeks For Geeks \"; GFG gfg = new GFG(); System.out.println(\"The length of last word is \" + gfg.lengthOfLastWord(input)); }}", "e": 6621, "s": 5604, "text": null }, { "code": "# Python3 program for implementation of efficient# approach to find length of last worddef length(str): count = 0; flag = False; length = len(str)-1; while(length != 0): if(str[length] == ' '): return count; else: count += 1; length -= 1; return count; # Driver codestr = \"Geeks for Geeks\";print(\"The length of last word is\", length(str)); # This code is contributed by Rajput Ji", "e": 7081, "s": 6621, "text": null }, { "code": "// C# program for implementation of efficient// approach to find length of last wordusing System; class GFG { public virtual int lengthOfLastWord(string a) { bool char_flag = false; int len = 0; for (int i = a.Length - 1; i >= 0; i--) { if (char.IsLetter(a[i])) { // Once the first character from last // is encountered, set char_flag to true. char_flag = true; len++; } else { // When the first space after the // characters (from the last) is // encountered, return the length // of the last word if (char_flag == true) { return len; } } } return len; } // Driver code public static void Main(string[] args) { string input = \"Geeks For Geeks \"; GFG gfg = new GFG(); Console.WriteLine(\"The length of last word is \" + gfg.lengthOfLastWord(input)); }} // This code is contributed by Shrikant13", "e": 8166, "s": 7081, "text": null }, { "code": "<?php// PHP program for implementation of efficient// approach to find length of last word function length($str){ $count = 0; $flag = false; for($i = strlen($str)-1 ; $i>=0 ; $i--) { // Once the first character from last // is encountered, set char_flag to true. if( ($str[$i] >='a' && $str[$i]<='z') || ($str[$i] >='A' && $str[$i]<='Z')) { $flag = true; $count++; } // When the first space after the // characters (from the last) is // encountered, return the length // of the last word else { if($flag == true) return $count; } } return $count;} // Driver code$str = \"Geeks for Geeks\";echo \"The length of last word is \", length($str); // This code is contributed by ajit.?>", "e": 9021, "s": 8166, "text": null }, { "code": null, "e": 9031, "s": 9021, "text": "Output: " }, { "code": null, "e": 9060, "s": 9031, "text": "Length of the last word is 5" }, { "code": null, "e": 9481, "s": 9060, "text": "This article is contributed by Saloni Baweja. 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": 9537, "s": 9481, "text": "As all the words in a sentence are separated by spaces." }, { "code": null, "e": 9592, "s": 9537, "text": "We have to split the sentence by spaces using split()." }, { "code": null, "e": 9651, "s": 9592, "text": "We split all the words by spaces and store them in a list." }, { "code": null, "e": 9698, "s": 9651, "text": "Print the length of the last word of the list." }, { "code": null, "e": 9727, "s": 9698, "text": "Below is the implementation:" }, { "code": null, "e": 9735, "s": 9727, "text": "Python3" }, { "code": null, "e": 9746, "s": 9735, "text": "Javascript" }, { "code": "# Python3 program for implementation of efficient# approach to find length of last word def length(str): # Split by space and converting # String to list and lis = list(str.split(\" \")) return len(lis[-1]) # Driver codestr = \"Geeks for Geeks\"print(\"The length of last word is\", length(str)) # This code is contributed by vikkycirus", "e": 10094, "s": 9746, "text": null }, { "code": "<script> // Javascript program for implementation// of efficient approach to find length// of last wordfunction length(str){ // Split by space and converting // String to list and var lis = str.split(\" \") return lis[lis.length - 1].length;} // Driver codevar str = \"Geeks for Geeks\"document.write(\"The length of last word is \" + length(str)); // This code is contributed by bunnyram19 </script>", "e": 10520, "s": 10094, "text": null }, { "code": null, "e": 10528, "s": 10520, "text": "Output:" }, { "code": null, "e": 10557, "s": 10528, "text": "Length of the last word is 5" }, { "code": null, "e": 10569, "s": 10557, "text": "shrikanth13" }, { "code": null, "e": 10586, "s": 10569, "text": "rahulkumawat2107" }, { "code": null, "e": 10592, "s": 10586, "text": "jit_t" }, { "code": null, "e": 10606, "s": 10592, "text": "shubham_singh" }, { "code": null, "e": 10618, "s": 10606, "text": "sanjeev2552" }, { "code": null, "e": 10628, "s": 10618, "text": "Rajput-Ji" }, { "code": null, "e": 10639, "s": 10628, "text": "vikkycirus" }, { "code": null, "e": 10654, "s": 10639, "text": "mohit kumar 29" }, { "code": null, "e": 10665, "s": 10654, "text": "bunnyram19" }, { "code": null, "e": 10678, "s": 10665, "text": "Java-Strings" }, { "code": null, "e": 10686, "s": 10678, "text": "Strings" }, { "code": null, "e": 10699, "s": 10686, "text": "Java-Strings" }, { "code": null, "e": 10707, "s": 10699, "text": "Strings" } ]
Try, Except, else and Finally in Python
04 Jul, 2022 An Exception is an Event, which occurs during the execution of the program. It is also known as a run time error. When that error occurs, Python generates an exception during the execution and that can be handled, which avoids your program to interrupt. Example: Python3 a = 5b = 0print(a/b) Output: Traceback (most recent call last): File "/home/8a10be6ca075391a8b174e0987a3e7f5.py", line 3, in <module> print(a/b) ZeroDivisionError: division by zero In this code, The system can not divide the number with zero so an exception is raised. Try: This block will test the excepted error to occur Except: Here you can handle the error Else: If there is no exception then this block will be executed Finally: Finally block always gets executed either exception is generated or not Syntax: try: # Some Code.... except: # optional block # Handling of exception (if required) else: # execute if no exception finally: # Some code .....(always executed) Let’s first understand how the try and except works – First try clause is executed i.e. the code between try and except clause. If there is no exception, then only try clause will run, except clause will not get executed. If any exception occurs, the try clause will be skipped and except clause will run. If any exception occurs, but the except clause within the code doesn’t handle it, it is passed on to the outer try statements. If the exception is left unhandled, then the execution stops. A try statement can have more than one except clause. Example: Let us try to take user integer input and throw the exception in except block. Python3 # Python code to illustrate# working of try() def divide(x, y): try: # Floor Division : Gives only Fractional # Part as Answer result = x // y print("Yeah ! Your answer is :", result) except ZeroDivisionError: print("Sorry ! You are dividing by zero ") # Look at parameters and note the working of Programdivide(3, 2)divide(3, 0) Output: Yeah ! Your answer is : 1 Sorry ! You are dividing by zero The code enters the else block only if the try clause does not raise an exception. Example: Else block will execute only when no exception occurs. Python3 # Python code to illustrate# working of try() def divide(x, y): try: # Floor Division : Gives only Fractional # Part as Answer result = x // y except ZeroDivisionError: print("Sorry ! You are dividing by zero ") else: print("Yeah ! Your answer is :", result) # Look at parameters and note the working of Programdivide(3, 2)divide(3, 0) Output: Yeah ! Your answer is : 1 Sorry ! You are dividing by zero Python provides a keyword finally, which is always executed after try and except blocks. The finally block always executes after normal termination of try block or after try block terminates due to some exception. Even if you return in the except block still the finally block will execute Example: Let’s try to throw the exception in except block and Finally will execute either exception will generate or not Python3 # Python code to illustrate# working of try() def divide(x, y): try: # Floor Division : Gives only Fractional # Part as Answer result = x // y except ZeroDivisionError: print("Sorry ! You are dividing by zero ") else: print("Yeah ! Your answer is :", result) finally: # this block is always executed # regardless of exception generation. print('This is always executed') # Look at parameters and note the working of Programdivide(3, 2)divide(3, 0) Output: Yeah ! Your answer is : 1 This is always executed Sorry ! You are dividing by zero This is always executed brownmetalheaddev akshay vijay jain Python-exceptions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n04 Jul, 2022" }, { "code": null, "e": 308, "s": 54, "text": "An Exception is an Event, which occurs during the execution of the program. It is also known as a run time error. When that error occurs, Python generates an exception during the execution and that can be handled, which avoids your program to interrupt." }, { "code": null, "e": 317, "s": 308, "text": "Example:" }, { "code": null, "e": 325, "s": 317, "text": "Python3" }, { "code": "a = 5b = 0print(a/b)", "e": 346, "s": 325, "text": null }, { "code": null, "e": 354, "s": 346, "text": "Output:" }, { "code": null, "e": 512, "s": 354, "text": "Traceback (most recent call last):\n File \"/home/8a10be6ca075391a8b174e0987a3e7f5.py\", line 3, in <module>\n print(a/b)\nZeroDivisionError: division by zero" }, { "code": null, "e": 601, "s": 512, "text": "In this code, The system can not divide the number with zero so an exception is raised. " }, { "code": null, "e": 655, "s": 601, "text": "Try: This block will test the excepted error to occur" }, { "code": null, "e": 694, "s": 655, "text": "Except: Here you can handle the error" }, { "code": null, "e": 758, "s": 694, "text": "Else: If there is no exception then this block will be executed" }, { "code": null, "e": 839, "s": 758, "text": "Finally: Finally block always gets executed either exception is generated or not" }, { "code": null, "e": 847, "s": 839, "text": "Syntax:" }, { "code": null, "e": 1045, "s": 847, "text": "try:\n # Some Code.... \n\nexcept:\n # optional block\n # Handling of exception (if required)\n\nelse:\n # execute if no exception\n\nfinally:\n # Some code .....(always executed)" }, { "code": null, "e": 1099, "s": 1045, "text": "Let’s first understand how the try and except works –" }, { "code": null, "e": 1173, "s": 1099, "text": "First try clause is executed i.e. the code between try and except clause." }, { "code": null, "e": 1267, "s": 1173, "text": "If there is no exception, then only try clause will run, except clause will not get executed." }, { "code": null, "e": 1351, "s": 1267, "text": "If any exception occurs, the try clause will be skipped and except clause will run." }, { "code": null, "e": 1540, "s": 1351, "text": "If any exception occurs, but the except clause within the code doesn’t handle it, it is passed on to the outer try statements. If the exception is left unhandled, then the execution stops." }, { "code": null, "e": 1594, "s": 1540, "text": "A try statement can have more than one except clause." }, { "code": null, "e": 1682, "s": 1594, "text": "Example: Let us try to take user integer input and throw the exception in except block." }, { "code": null, "e": 1690, "s": 1682, "text": "Python3" }, { "code": "# Python code to illustrate# working of try() def divide(x, y): try: # Floor Division : Gives only Fractional # Part as Answer result = x // y print(\"Yeah ! Your answer is :\", result) except ZeroDivisionError: print(\"Sorry ! You are dividing by zero \") # Look at parameters and note the working of Programdivide(3, 2)divide(3, 0)", "e": 2063, "s": 1690, "text": null }, { "code": null, "e": 2071, "s": 2063, "text": "Output:" }, { "code": null, "e": 2131, "s": 2071, "text": "Yeah ! Your answer is : 1\nSorry ! You are dividing by zero " }, { "code": null, "e": 2214, "s": 2131, "text": "The code enters the else block only if the try clause does not raise an exception." }, { "code": null, "e": 2278, "s": 2214, "text": "Example: Else block will execute only when no exception occurs." }, { "code": null, "e": 2286, "s": 2278, "text": "Python3" }, { "code": "# Python code to illustrate# working of try() def divide(x, y): try: # Floor Division : Gives only Fractional # Part as Answer result = x // y except ZeroDivisionError: print(\"Sorry ! You are dividing by zero \") else: print(\"Yeah ! Your answer is :\", result) # Look at parameters and note the working of Programdivide(3, 2)divide(3, 0)", "e": 2668, "s": 2286, "text": null }, { "code": null, "e": 2676, "s": 2668, "text": "Output:" }, { "code": null, "e": 2736, "s": 2676, "text": "Yeah ! Your answer is : 1\nSorry ! You are dividing by zero " }, { "code": null, "e": 3026, "s": 2736, "text": "Python provides a keyword finally, which is always executed after try and except blocks. The finally block always executes after normal termination of try block or after try block terminates due to some exception. Even if you return in the except block still the finally block will execute" }, { "code": null, "e": 3147, "s": 3026, "text": "Example: Let’s try to throw the exception in except block and Finally will execute either exception will generate or not" }, { "code": null, "e": 3155, "s": 3147, "text": "Python3" }, { "code": "# Python code to illustrate# working of try() def divide(x, y): try: # Floor Division : Gives only Fractional # Part as Answer result = x // y except ZeroDivisionError: print(\"Sorry ! You are dividing by zero \") else: print(\"Yeah ! Your answer is :\", result) finally: # this block is always executed # regardless of exception generation. print('This is always executed') # Look at parameters and note the working of Programdivide(3, 2)divide(3, 0)", "e": 3677, "s": 3155, "text": null }, { "code": null, "e": 3685, "s": 3677, "text": "Output:" }, { "code": null, "e": 3793, "s": 3685, "text": "Yeah ! Your answer is : 1\nThis is always executed\nSorry ! You are dividing by zero \nThis is always executed" }, { "code": null, "e": 3811, "s": 3793, "text": "brownmetalheaddev" }, { "code": null, "e": 3829, "s": 3811, "text": "akshay vijay jain" }, { "code": null, "e": 3847, "s": 3829, "text": "Python-exceptions" }, { "code": null, "e": 3854, "s": 3847, "text": "Python" } ]
How to Resize a SVG image ?
02 Mar, 2021 Resizing an SVG image cannot be done by simply using CSS height and width property to the img tag. To resize the SVG image, follow these steps: Method1: The SVG image will be taking 100% of all the width and height available to it. To make the image of the desired size set the CSS height and width property of the image Example 1: CSS <!DOCTYPE html> <html> <style> svg{ height: 200px; } </style> <body> <svg xmlns="http://www.w3.org/2000/svg"> <image href= "https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png" /> </svg> </body> </html> Output: Method 2: Directly modify the .svg file and set the width and height to the desired value. Below is how the XML file will look, if an SVG image is present <svg height="40px" width="60px" . . . . . . ></svg> Example 2: HTML <!DOCTYPE html><html> <body> <h1>My first SVG</h1> <svg width="40" height="60"> <rect width="40" height="60" style="fill: rgb(0, 0, 255); stroke-width: 10; stroke: rgb(0, 0, 0);" /> </svg> </body></html> Output: HTML-SVG Picked HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Mar, 2021" }, { "code": null, "e": 172, "s": 28, "text": "Resizing an SVG image cannot be done by simply using CSS height and width property to the img tag. To resize the SVG image, follow these steps:" }, { "code": null, "e": 349, "s": 172, "text": "Method1: The SVG image will be taking 100% of all the width and height available to it. To make the image of the desired size set the CSS height and width property of the image" }, { "code": null, "e": 360, "s": 349, "text": "Example 1:" }, { "code": null, "e": 364, "s": 360, "text": "CSS" }, { "code": "<!DOCTYPE html> <html> <style> svg{ height: 200px; } </style> <body> <svg xmlns=\"http://www.w3.org/2000/svg\"> <image href= \"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png\" /> </svg> </body> </html>", "e": 639, "s": 364, "text": null }, { "code": null, "e": 647, "s": 639, "text": "Output:" }, { "code": null, "e": 802, "s": 647, "text": "Method 2: Directly modify the .svg file and set the width and height to the desired value. Below is how the XML file will look, if an SVG image is present" }, { "code": null, "e": 854, "s": 802, "text": "<svg height=\"40px\" width=\"60px\" . . . . . . ></svg>" }, { "code": null, "e": 865, "s": 854, "text": "Example 2:" }, { "code": null, "e": 870, "s": 865, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <h1>My first SVG</h1> <svg width=\"40\" height=\"60\"> <rect width=\"40\" height=\"60\" style=\"fill: rgb(0, 0, 255); stroke-width: 10; stroke: rgb(0, 0, 0);\" /> </svg> </body></html>", "e": 1150, "s": 870, "text": null }, { "code": null, "e": 1158, "s": 1150, "text": "Output:" }, { "code": null, "e": 1167, "s": 1158, "text": "HTML-SVG" }, { "code": null, "e": 1174, "s": 1167, "text": "Picked" }, { "code": null, "e": 1179, "s": 1174, "text": "HTML" }, { "code": null, "e": 1196, "s": 1179, "text": "Web Technologies" }, { "code": null, "e": 1201, "s": 1196, "text": "HTML" } ]
Difference between sums of odd level and even level nodes of a Binary Tree
05 Jul, 2022 Given a Binary Tree, find the difference between the sum of nodes at odd level and the sum of nodes at even level. Consider root as level 1, left and right children of root as level 2 and so on. For example, in the following tree, sum of nodes at odd level is (5 + 1 + 4 + 8) which is 18. And sum of nodes at even level is (2 + 6 + 3 + 7 + 9) which is 27. The output for following tree should be 18 – 27 which is -9. 5 / \ 2 6 / \ \ 1 4 8 / / \ 3 7 9 A straightforward method is to use level order traversal. In the traversal, check level of current node, if it is odd, increment odd sum by data of current node, otherwise increment even sum. Finally return difference between odd sum and even sum. See following for implementation of this approach. C implementation of level order traversal based approach to find the difference. This approach is provided by Mandeep Singh. For Iterative approach, simply traverse the tree level by level (level order traversal), store sum of node values in even no. level in evenSum and rest in variable oddSum and finally return the difference. Below is the simple implementation of the approach. 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. C++ Java Python3 C# Javascript // CPP program to find// difference between// sums of odd level// and even level nodes// of binary tree#include <bits/stdc++.h>using namespace std; // tree nodestruct Node{ int data; Node *left, *right;}; // returns a new// tree NodeNode* newNode(int data){ Node* temp = new Node(); temp->data = data; temp->left = temp->right = NULL; return temp;} // return difference of// sums of odd level// and even levelint evenOddLevelDifference(Node* root){ if (!root) return 0; // create a queue for // level order traversal queue<Node*> q; q.push(root); int level = 0; int evenSum = 0, oddSum = 0; // traverse until the // queue is empty while (!q.empty()) { int size = q.size(); level += 1; // traverse for // complete level while(size > 0) { Node* temp = q.front(); q.pop(); // check if level no. // is even or odd and // accordingly update // the evenSum or oddSum if(level % 2 == 0) evenSum += temp->data; else oddSum += temp->data; // check for left child if (temp->left) { q.push(temp->left); } // check for right child if (temp->right) { q.push(temp->right); } size -= 1; } } return (oddSum - evenSum);} // driver programint main(){ // construct a tree Node* root = newNode(5); root->left = newNode(2); root->right = newNode(6); root->left->left = newNode(1); root->left->right = newNode(4); root->left->right->left = newNode(3); root->right->right = newNode(8); root->right->right->right = newNode(9); root->right->right->left = newNode(7); int result = evenOddLevelDifference(root); cout << "difference between sums is :: "; cout << result << endl; return 0;} // This article is contributed by Mandeep Singh. // Java program to find // difference between // sums of odd level // and even level nodes // of binary treeimport java.io.*;import java.util.*;// User defined node classclass Node { int data; Node left, right; // Constructor to create a new tree node Node(int key) { data = key; left = right = null; }}class GFG { // return difference of // sums of odd level and even level static int evenOddLevelDifference(Node root) { if (root == null) return 0; // create a queue for // level order traversal Queue<Node> q = new LinkedList<>(); q.add(root); int level = 0; int evenSum = 0, oddSum = 0; // traverse until the // queue is empty while (q.size() != 0) { int size = q.size(); level++; // traverse for complete level while (size > 0) { Node temp = q.remove(); // check if level no. // is even or odd and // accordingly update // the evenSum or oddSum if (level % 2 == 0) evenSum += temp.data; else oddSum += temp.data; // check for left child if (temp.left != null) q.add(temp.left); // check for right child if (temp.right != null) q.add(temp.right); size--; } } return (oddSum - evenSum); } // Driver code public static void main(String args[]) { // construct a tree Node root = new Node(5); root.left = new Node(2); root.right = new Node(6); root.left.left = new Node(1); root.left.right = new Node(4); root.left.right.left = new Node(3); root.right.right = new Node(8); root.right.right.right = new Node(9); root.right.right.left = new Node(7); System.out.println("difference between sums is " + evenOddLevelDifference(root)); }}// This code is contributed by rachana soma # Python3 program to find maximum product# of a level in Binary Tree # Helper function that allocates a new# node with the given data and None# left and right pointers. class newNode: # Construct to create a new node def __init__(self, key): self.data = key self.left = None self.right = None # return difference of sums of odd# level and even leveldef evenOddLevelDifference(root): if (not root): return 0 # create a queue for # level order traversal q = [] q.append(root) level = 0 evenSum = 0 oddSum = 0 # traverse until the queue is empty while (len(q)): size = len(q) level += 1 # traverse for complete level while(size > 0): temp = q[0] #.front() q.pop(0) # check if level no. is even or # odd and accordingly update # the evenSum or oddSum if(level % 2 == 0): evenSum += temp.data else: oddSum += temp.data # check for left child if (temp.left) : q.append(temp.left) # check for right child if (temp.right): q.append(temp.right) size -= 1 return (oddSum - evenSum) # Driver Codeif __name__ == '__main__': """ Let us create Binary Tree shown in above example """ root = newNode(5) root.left = newNode(2) root.right = newNode(6) root.left.left = newNode(1) root.left.right = newNode(4) root.left.right.left = newNode(3) root.right.right = newNode(8) root.right.right.right = newNode(9) root.right.right.left = newNode(7) result = evenOddLevelDifference(root) print("Difference between sums is", result) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10) // C# program to find// difference between// sums of odd level// and even level nodes// of binary treeusing System;using System.Collections.Generic; // User defined node classpublic class Node{ public int data; public Node left, right; // Constructor to create a new tree node public Node(int key) { data = key; left = right = null; }} public class GFG{ // return difference of // sums of odd level and even level static int evenOddLevelDifference(Node root) { if (root == null) return 0; // create a queue for // level order traversal Queue<Node> q = new Queue<Node>(); q.Enqueue(root); int level = 0; int evenSum = 0, oddSum = 0; // traverse until the // queue is empty while (q.Count != 0) { int size = q.Count; level++; // traverse for complete level while (size > 0) { Node temp = q.Dequeue(); // check if level no. // is even or odd and // accordingly update // the evenSum or oddSum if (level % 2 == 0) evenSum += temp.data; else oddSum += temp.data; // check for left child if (temp.left != null) q.Enqueue(temp.left); // check for right child if (temp.right != null) q.Enqueue(temp.right); size--; } } return (oddSum - evenSum); } // Driver code public static void Main(String []args) { // construct a tree Node root = new Node(5); root.left = new Node(2); root.right = new Node(6); root.left.left = new Node(1); root.left.right = new Node(4); root.left.right.left = new Node(3); root.right.right = new Node(8); root.right.right.right = new Node(9); root.right.right.left = new Node(7); Console.WriteLine("difference between sums is " + evenOddLevelDifference(root)); }} // This code is contributed by 29AjayKumar <script>// Javascript program to find // difference between // sums of odd level // and even level nodes // of binary tree // User defined node classclass Node{ constructor(key) { this.data = key; this.left = this.right = null; }} // return difference of // sums of odd level and even levelfunction evenOddLevelDifference(root){ if (root == null) return 0; // create a queue for // level order traversal let q = []; q.push(root); let level = 0; let evenSum = 0, oddSum = 0; // traverse until the // queue is empty while (q.length != 0) { let size = q.length; level++; // traverse for complete level while (size > 0) { let temp = q.shift(); // check if level no. // is even or odd and // accordingly update // the evenSum or oddSum if (level % 2 == 0) evenSum += temp.data; else oddSum += temp.data; // check for left child if (temp.left != null) q.push(temp.left); // check for right child if (temp.right != null) q.push(temp.right); size--; } } return (oddSum - evenSum); } // Driver codelet root = new Node(5); root.left = new Node(2); root.right = new Node(6); root.left.left = new Node(1); root.left.right = new Node(4); root.left.right.left = new Node(3); root.right.right = new Node(8); root.right.right.right = new Node(9); root.right.right.left = new Node(7); document.write("difference between sums is " + evenOddLevelDifference(root)+"<br>"); // This code is contributed by rag2127</script> difference between sums is :: -9 The problem can also be solved using simple recursive traversal. We can recursively calculate the required difference as, value of root’s data subtracted by the difference for subtree under left child and the difference for subtree under right child. Below is the implementation of this approach. C++ C Java Python3 C# Javascript // A recursive program to find difference// between sum of nodes at odd level// and sum at even level#include <bits/stdc++.h>using namespace std; // Binary Tree nodeclass node{ public: int data; node* left, *right;}; // A utility function to allocate// a new tree node with given datanode* newNode(int data){ node* Node = new node(); Node->data = data; Node->left = Node->right = NULL; return (Node);} // The main function that return// difference between odd and even// level nodesint getLevelDiff(node *root){// Base caseif (root == NULL) return 0; // Difference for root is root's data - difference for// left subtree - difference for right subtreereturn root->data - getLevelDiff(root->left) - getLevelDiff(root->right);} // Driver codeint main(){ node *root = newNode(5); root->left = newNode(2); root->right = newNode(6); root->left->left = newNode(1); root->left->right = newNode(4); root->left->right->left = newNode(3); root->right->right = newNode(8); root->right->right->right = newNode(9); root->right->right->left = newNode(7); cout<<getLevelDiff(root)<<" is the required difference\n"; return 0;} // This code is contributed by rathbhupendra // A recursive program to find difference between sum of nodes at// odd level and sum at even level#include <stdio.h>#include <stdlib.h> // Binary Tree nodestruct node{ int data; struct node* left, *right;}; // A utility function to allocate a new tree node with given datastruct node* newNode(int data){ struct node* node = (struct node*)malloc(sizeof(struct node)); node->data = data; node->left = node->right = NULL; return (node);} // The main function that return difference between odd and even level// nodesint getLevelDiff(struct node *root){ // Base case if (root == NULL) return 0; // Difference for root is root's data - difference for // left subtree - difference for right subtree return root->data - getLevelDiff(root->left) - getLevelDiff(root->right);} // Driver program to test above functionsint main(){ struct node *root = newNode(5); root->left = newNode(2); root->right = newNode(6); root->left->left = newNode(1); root->left->right = newNode(4); root->left->right->left = newNode(3); root->right->right = newNode(8); root->right->right->right = newNode(9); root->right->right->left = newNode(7); printf("%d is the required difference\n", getLevelDiff(root)); getchar(); return 0;} // A recursive java program to find difference between sum of nodes at// odd level and sum at even level // A binary tree nodeclass Node{ int data; Node left, right; Node(int item) { data = item; left = right; }} class BinaryTree{ // The main function that return difference between odd and even level // nodes Node root; int getLevelDiff(Node node) { // Base case if (node == null) return 0; // Difference for root is root's data - difference for // left subtree - difference for right subtree return node.data - getLevelDiff(node.left) - getLevelDiff(node.right); } // Driver program to test above functions public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(5); tree.root.left = new Node(2); tree.root.right = new Node(6); tree.root.left.left = new Node(1); tree.root.left.right = new Node(4); tree.root.left.right.left = new Node(3); tree.root.right.right = new Node(8); tree.root.right.right.right = new Node(9); tree.root.right.right.left = new Node(7); System.out.println(tree.getLevelDiff(tree.root) + " is the required difference"); }} // This code has been contributed by Mayank Jaiswal # A recursive program to find difference between sum of nodes# at odd level and sum at even level # A Binary Tree nodeclass Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # The main function that returns difference between odd and# even level nodesdef getLevelDiff(root): # Base Case if root is None: return 0 # Difference for root is root's data - difference for # left subtree - difference for right subtree return (root.data - getLevelDiff(root.left)- getLevelDiff(root.right)) # Driver program to test above functionroot = Node(5)root.left = Node(2)root.right = Node(6)root.left.left = Node(1)root.left.right = Node(4)root.left.right.left = Node(3)root.right.right = Node(8)root.right.right.right = Node(9)root.right.right.left = Node(7)print ("%d is the required difference" %(getLevelDiff(root))) # This code is contributed by Nikhil Kumar Singh(nickzuck_007) using System; // A recursive C# program to find// difference between sum of nodes at// odd level and sum at even level // A binary tree nodepublic class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right; }} public class BinaryTree{ // The main function that return difference // between odd and even level nodes public Node root; public virtual int getLevelDiff(Node node) { // Base case if (node == null) { return 0; } // Difference for root is root's // data - difference for left subtree // - difference for right subtree return node.data - getLevelDiff(node.left) - getLevelDiff(node.right); } // Driver program to test above functions public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(5); tree.root.left = new Node(2); tree.root.right = new Node(6); tree.root.left.left = new Node(1); tree.root.left.right = new Node(4); tree.root.left.right.left = new Node(3); tree.root.right.right = new Node(8); tree.root.right.right.right = new Node(9); tree.root.right.right.left = new Node(7); Console.WriteLine(tree.getLevelDiff(tree.root) + " is the required difference"); }} // This code is contributed by Shrikant13 <script>// A recursive javascript program to find difference between sum of nodes at// odd level and sum at even level // A binary tree nodeclass Node{ constructor(item) { this.data = item; this.left = this.right = null; }} // The main function that return difference between odd and even level // nodeslet root; function getLevelDiff(node){ // Base case if (node == null) return 0; // Difference for root is root's data - difference for // left subtree - difference for right subtree return node.data - getLevelDiff(node.left) - getLevelDiff(node.right);} // Driver program to test above functionsroot = new Node(5);root.left = new Node(2);root.right = new Node(6);root.left.left = new Node(1);root.left.right = new Node(4);root.left.right.left = new Node(3);root.right.right = new Node(8);root.right.right.right = new Node(9);root.right.right.left = new Node(7);document.write(getLevelDiff(root) + " is the required difference"); // This code is contributed by avanitrachhadiya2155</script> -9 is the required difference Time complexity of both methods is O(n), but the second method is simple and easy to implement. shrikanth13 rachana soma SHUBHAMSINGH10 29AjayKumar rathbhupendra rag2127 avanitrachhadiya2155 anikakapoor sweetyty amartyaghoshgfg simmytarika5 hardikkoriintern Amazon Tree Amazon Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Introduction to Tree Data Structure Inorder Tree Traversal without Recursion What is Data Structure: Types, Classifications and Applications Binary Tree | Set 3 (Types of Binary Tree) A program to check if a binary tree is BST or not Binary Tree | Set 2 (Properties) Diameter of a Binary Tree Diagonal Traversal of Binary Tree Lowest Common Ancestor in a Binary Tree | Set 1
[ { "code": null, "e": 52, "s": 24, "text": "\n05 Jul, 2022" }, { "code": null, "e": 470, "s": 52, "text": "Given a Binary Tree, find the difference between the sum of nodes at odd level and the sum of nodes at even level. Consider root as level 1, left and right children of root as level 2 and so on. For example, in the following tree, sum of nodes at odd level is (5 + 1 + 4 + 8) which is 18. And sum of nodes at even level is (2 + 6 + 3 + 7 + 9) which is 27. The output for following tree should be 18 – 27 which is -9. " }, { "code": null, "e": 558, "s": 470, "text": " 5\n / \\\n 2 6\n / \\ \\ \n1 4 8\n / / \\ \n 3 7 9 " }, { "code": null, "e": 857, "s": 558, "text": "A straightforward method is to use level order traversal. In the traversal, check level of current node, if it is odd, increment odd sum by data of current node, otherwise increment even sum. Finally return difference between odd sum and even sum. See following for implementation of this approach." }, { "code": null, "e": 938, "s": 857, "text": "C implementation of level order traversal based approach to find the difference." }, { "code": null, "e": 1188, "s": 938, "text": "This approach is provided by Mandeep Singh. For Iterative approach, simply traverse the tree level by level (level order traversal), store sum of node values in even no. level in evenSum and rest in variable oddSum and finally return the difference." }, { "code": null, "e": 1241, "s": 1188, "text": "Below is the simple implementation of the approach. " }, { "code": null, "e": 1250, "s": 1241, "text": "Chapters" }, { "code": null, "e": 1277, "s": 1250, "text": "descriptions off, selected" }, { "code": null, "e": 1327, "s": 1277, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 1350, "s": 1327, "text": "captions off, selected" }, { "code": null, "e": 1358, "s": 1350, "text": "English" }, { "code": null, "e": 1382, "s": 1358, "text": "This is a modal window." }, { "code": null, "e": 1451, "s": 1382, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 1473, "s": 1451, "text": "End of dialog window." }, { "code": null, "e": 1477, "s": 1473, "text": "C++" }, { "code": null, "e": 1482, "s": 1477, "text": "Java" }, { "code": null, "e": 1490, "s": 1482, "text": "Python3" }, { "code": null, "e": 1493, "s": 1490, "text": "C#" }, { "code": null, "e": 1504, "s": 1493, "text": "Javascript" }, { "code": "// CPP program to find// difference between// sums of odd level// and even level nodes// of binary tree#include <bits/stdc++.h>using namespace std; // tree nodestruct Node{ int data; Node *left, *right;}; // returns a new// tree NodeNode* newNode(int data){ Node* temp = new Node(); temp->data = data; temp->left = temp->right = NULL; return temp;} // return difference of// sums of odd level// and even levelint evenOddLevelDifference(Node* root){ if (!root) return 0; // create a queue for // level order traversal queue<Node*> q; q.push(root); int level = 0; int evenSum = 0, oddSum = 0; // traverse until the // queue is empty while (!q.empty()) { int size = q.size(); level += 1; // traverse for // complete level while(size > 0) { Node* temp = q.front(); q.pop(); // check if level no. // is even or odd and // accordingly update // the evenSum or oddSum if(level % 2 == 0) evenSum += temp->data; else oddSum += temp->data; // check for left child if (temp->left) { q.push(temp->left); } // check for right child if (temp->right) { q.push(temp->right); } size -= 1; } } return (oddSum - evenSum);} // driver programint main(){ // construct a tree Node* root = newNode(5); root->left = newNode(2); root->right = newNode(6); root->left->left = newNode(1); root->left->right = newNode(4); root->left->right->left = newNode(3); root->right->right = newNode(8); root->right->right->right = newNode(9); root->right->right->left = newNode(7); int result = evenOddLevelDifference(root); cout << \"difference between sums is :: \"; cout << result << endl; return 0;} // This article is contributed by Mandeep Singh.", "e": 3550, "s": 1504, "text": null }, { "code": "// Java program to find // difference between // sums of odd level // and even level nodes // of binary treeimport java.io.*;import java.util.*;// User defined node classclass Node { int data; Node left, right; // Constructor to create a new tree node Node(int key) { data = key; left = right = null; }}class GFG { // return difference of // sums of odd level and even level static int evenOddLevelDifference(Node root) { if (root == null) return 0; // create a queue for // level order traversal Queue<Node> q = new LinkedList<>(); q.add(root); int level = 0; int evenSum = 0, oddSum = 0; // traverse until the // queue is empty while (q.size() != 0) { int size = q.size(); level++; // traverse for complete level while (size > 0) { Node temp = q.remove(); // check if level no. // is even or odd and // accordingly update // the evenSum or oddSum if (level % 2 == 0) evenSum += temp.data; else oddSum += temp.data; // check for left child if (temp.left != null) q.add(temp.left); // check for right child if (temp.right != null) q.add(temp.right); size--; } } return (oddSum - evenSum); } // Driver code public static void main(String args[]) { // construct a tree Node root = new Node(5); root.left = new Node(2); root.right = new Node(6); root.left.left = new Node(1); root.left.right = new Node(4); root.left.right.left = new Node(3); root.right.right = new Node(8); root.right.right.right = new Node(9); root.right.right.left = new Node(7); System.out.println(\"difference between sums is \" + evenOddLevelDifference(root)); }}// This code is contributed by rachana soma", "e": 6115, "s": 3550, "text": null }, { "code": "# Python3 program to find maximum product# of a level in Binary Tree # Helper function that allocates a new# node with the given data and None# left and right pointers. class newNode: # Construct to create a new node def __init__(self, key): self.data = key self.left = None self.right = None # return difference of sums of odd# level and even leveldef evenOddLevelDifference(root): if (not root): return 0 # create a queue for # level order traversal q = [] q.append(root) level = 0 evenSum = 0 oddSum = 0 # traverse until the queue is empty while (len(q)): size = len(q) level += 1 # traverse for complete level while(size > 0): temp = q[0] #.front() q.pop(0) # check if level no. is even or # odd and accordingly update # the evenSum or oddSum if(level % 2 == 0): evenSum += temp.data else: oddSum += temp.data # check for left child if (temp.left) : q.append(temp.left) # check for right child if (temp.right): q.append(temp.right) size -= 1 return (oddSum - evenSum) # Driver Codeif __name__ == '__main__': \"\"\" Let us create Binary Tree shown in above example \"\"\" root = newNode(5) root.left = newNode(2) root.right = newNode(6) root.left.left = newNode(1) root.left.right = newNode(4) root.left.right.left = newNode(3) root.right.right = newNode(8) root.right.right.right = newNode(9) root.right.right.left = newNode(7) result = evenOddLevelDifference(root) print(\"Difference between sums is\", result) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)", "e": 8045, "s": 6115, "text": null }, { "code": "// C# program to find// difference between// sums of odd level// and even level nodes// of binary treeusing System;using System.Collections.Generic; // User defined node classpublic class Node{ public int data; public Node left, right; // Constructor to create a new tree node public Node(int key) { data = key; left = right = null; }} public class GFG{ // return difference of // sums of odd level and even level static int evenOddLevelDifference(Node root) { if (root == null) return 0; // create a queue for // level order traversal Queue<Node> q = new Queue<Node>(); q.Enqueue(root); int level = 0; int evenSum = 0, oddSum = 0; // traverse until the // queue is empty while (q.Count != 0) { int size = q.Count; level++; // traverse for complete level while (size > 0) { Node temp = q.Dequeue(); // check if level no. // is even or odd and // accordingly update // the evenSum or oddSum if (level % 2 == 0) evenSum += temp.data; else oddSum += temp.data; // check for left child if (temp.left != null) q.Enqueue(temp.left); // check for right child if (temp.right != null) q.Enqueue(temp.right); size--; } } return (oddSum - evenSum); } // Driver code public static void Main(String []args) { // construct a tree Node root = new Node(5); root.left = new Node(2); root.right = new Node(6); root.left.left = new Node(1); root.left.right = new Node(4); root.left.right.left = new Node(3); root.right.right = new Node(8); root.right.right.right = new Node(9); root.right.right.left = new Node(7); Console.WriteLine(\"difference between sums is \" + evenOddLevelDifference(root)); }} // This code is contributed by 29AjayKumar", "e": 10577, "s": 8045, "text": null }, { "code": "<script>// Javascript program to find // difference between // sums of odd level // and even level nodes // of binary tree // User defined node classclass Node{ constructor(key) { this.data = key; this.left = this.right = null; }} // return difference of // sums of odd level and even levelfunction evenOddLevelDifference(root){ if (root == null) return 0; // create a queue for // level order traversal let q = []; q.push(root); let level = 0; let evenSum = 0, oddSum = 0; // traverse until the // queue is empty while (q.length != 0) { let size = q.length; level++; // traverse for complete level while (size > 0) { let temp = q.shift(); // check if level no. // is even or odd and // accordingly update // the evenSum or oddSum if (level % 2 == 0) evenSum += temp.data; else oddSum += temp.data; // check for left child if (temp.left != null) q.push(temp.left); // check for right child if (temp.right != null) q.push(temp.right); size--; } } return (oddSum - evenSum); } // Driver codelet root = new Node(5); root.left = new Node(2); root.right = new Node(6); root.left.left = new Node(1); root.left.right = new Node(4); root.left.right.left = new Node(3); root.right.right = new Node(8); root.right.right.right = new Node(9); root.right.right.left = new Node(7); document.write(\"difference between sums is \" + evenOddLevelDifference(root)+\"<br>\"); // This code is contributed by rag2127</script>", "e": 12876, "s": 10577, "text": null }, { "code": null, "e": 12909, "s": 12876, "text": "difference between sums is :: -9" }, { "code": null, "e": 13207, "s": 12909, "text": "The problem can also be solved using simple recursive traversal. We can recursively calculate the required difference as, value of root’s data subtracted by the difference for subtree under left child and the difference for subtree under right child. Below is the implementation of this approach. " }, { "code": null, "e": 13211, "s": 13207, "text": "C++" }, { "code": null, "e": 13213, "s": 13211, "text": "C" }, { "code": null, "e": 13218, "s": 13213, "text": "Java" }, { "code": null, "e": 13226, "s": 13218, "text": "Python3" }, { "code": null, "e": 13229, "s": 13226, "text": "C#" }, { "code": null, "e": 13240, "s": 13229, "text": "Javascript" }, { "code": "// A recursive program to find difference// between sum of nodes at odd level// and sum at even level#include <bits/stdc++.h>using namespace std; // Binary Tree nodeclass node{ public: int data; node* left, *right;}; // A utility function to allocate// a new tree node with given datanode* newNode(int data){ node* Node = new node(); Node->data = data; Node->left = Node->right = NULL; return (Node);} // The main function that return// difference between odd and even// level nodesint getLevelDiff(node *root){// Base caseif (root == NULL) return 0; // Difference for root is root's data - difference for// left subtree - difference for right subtreereturn root->data - getLevelDiff(root->left) - getLevelDiff(root->right);} // Driver codeint main(){ node *root = newNode(5); root->left = newNode(2); root->right = newNode(6); root->left->left = newNode(1); root->left->right = newNode(4); root->left->right->left = newNode(3); root->right->right = newNode(8); root->right->right->right = newNode(9); root->right->right->left = newNode(7); cout<<getLevelDiff(root)<<\" is the required difference\\n\"; return 0;} // This code is contributed by rathbhupendra", "e": 14476, "s": 13240, "text": null }, { "code": "// A recursive program to find difference between sum of nodes at// odd level and sum at even level#include <stdio.h>#include <stdlib.h> // Binary Tree nodestruct node{ int data; struct node* left, *right;}; // A utility function to allocate a new tree node with given datastruct node* newNode(int data){ struct node* node = (struct node*)malloc(sizeof(struct node)); node->data = data; node->left = node->right = NULL; return (node);} // The main function that return difference between odd and even level// nodesint getLevelDiff(struct node *root){ // Base case if (root == NULL) return 0; // Difference for root is root's data - difference for // left subtree - difference for right subtree return root->data - getLevelDiff(root->left) - getLevelDiff(root->right);} // Driver program to test above functionsint main(){ struct node *root = newNode(5); root->left = newNode(2); root->right = newNode(6); root->left->left = newNode(1); root->left->right = newNode(4); root->left->right->left = newNode(3); root->right->right = newNode(8); root->right->right->right = newNode(9); root->right->right->left = newNode(7); printf(\"%d is the required difference\\n\", getLevelDiff(root)); getchar(); return 0;}", "e": 15794, "s": 14476, "text": null }, { "code": "// A recursive java program to find difference between sum of nodes at// odd level and sum at even level // A binary tree nodeclass Node{ int data; Node left, right; Node(int item) { data = item; left = right; }} class BinaryTree{ // The main function that return difference between odd and even level // nodes Node root; int getLevelDiff(Node node) { // Base case if (node == null) return 0; // Difference for root is root's data - difference for // left subtree - difference for right subtree return node.data - getLevelDiff(node.left) - getLevelDiff(node.right); } // Driver program to test above functions public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(5); tree.root.left = new Node(2); tree.root.right = new Node(6); tree.root.left.left = new Node(1); tree.root.left.right = new Node(4); tree.root.left.right.left = new Node(3); tree.root.right.right = new Node(8); tree.root.right.right.right = new Node(9); tree.root.right.right.left = new Node(7); System.out.println(tree.getLevelDiff(tree.root) + \" is the required difference\"); }} // This code has been contributed by Mayank Jaiswal", "e": 17222, "s": 15794, "text": null }, { "code": "# A recursive program to find difference between sum of nodes# at odd level and sum at even level # A Binary Tree nodeclass Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # The main function that returns difference between odd and# even level nodesdef getLevelDiff(root): # Base Case if root is None: return 0 # Difference for root is root's data - difference for # left subtree - difference for right subtree return (root.data - getLevelDiff(root.left)- getLevelDiff(root.right)) # Driver program to test above functionroot = Node(5)root.left = Node(2)root.right = Node(6)root.left.left = Node(1)root.left.right = Node(4)root.left.right.left = Node(3)root.right.right = Node(8)root.right.right.right = Node(9)root.right.right.left = Node(7)print (\"%d is the required difference\" %(getLevelDiff(root))) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)", "e": 18219, "s": 17222, "text": null }, { "code": "using System; // A recursive C# program to find// difference between sum of nodes at// odd level and sum at even level // A binary tree nodepublic class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right; }} public class BinaryTree{ // The main function that return difference // between odd and even level nodes public Node root; public virtual int getLevelDiff(Node node) { // Base case if (node == null) { return 0; } // Difference for root is root's // data - difference for left subtree // - difference for right subtree return node.data - getLevelDiff(node.left) - getLevelDiff(node.right); } // Driver program to test above functions public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(5); tree.root.left = new Node(2); tree.root.right = new Node(6); tree.root.left.left = new Node(1); tree.root.left.right = new Node(4); tree.root.left.right.left = new Node(3); tree.root.right.right = new Node(8); tree.root.right.right.right = new Node(9); tree.root.right.right.left = new Node(7); Console.WriteLine(tree.getLevelDiff(tree.root) + \" is the required difference\"); }} // This code is contributed by Shrikant13", "e": 19685, "s": 18219, "text": null }, { "code": "<script>// A recursive javascript program to find difference between sum of nodes at// odd level and sum at even level // A binary tree nodeclass Node{ constructor(item) { this.data = item; this.left = this.right = null; }} // The main function that return difference between odd and even level // nodeslet root; function getLevelDiff(node){ // Base case if (node == null) return 0; // Difference for root is root's data - difference for // left subtree - difference for right subtree return node.data - getLevelDiff(node.left) - getLevelDiff(node.right);} // Driver program to test above functionsroot = new Node(5);root.left = new Node(2);root.right = new Node(6);root.left.left = new Node(1);root.left.right = new Node(4);root.left.right.left = new Node(3);root.right.right = new Node(8);root.right.right.right = new Node(9);root.right.right.left = new Node(7);document.write(getLevelDiff(root) + \" is the required difference\"); // This code is contributed by avanitrachhadiya2155</script>", "e": 20814, "s": 19685, "text": null }, { "code": null, "e": 20844, "s": 20814, "text": "-9 is the required difference" }, { "code": null, "e": 20940, "s": 20844, "text": "Time complexity of both methods is O(n), but the second method is simple and easy to implement." }, { "code": null, "e": 20952, "s": 20940, "text": "shrikanth13" }, { "code": null, "e": 20965, "s": 20952, "text": "rachana soma" }, { "code": null, "e": 20980, "s": 20965, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 20992, "s": 20980, "text": "29AjayKumar" }, { "code": null, "e": 21006, "s": 20992, "text": "rathbhupendra" }, { "code": null, "e": 21014, "s": 21006, "text": "rag2127" }, { "code": null, "e": 21035, "s": 21014, "text": "avanitrachhadiya2155" }, { "code": null, "e": 21047, "s": 21035, "text": "anikakapoor" }, { "code": null, "e": 21056, "s": 21047, "text": "sweetyty" }, { "code": null, "e": 21072, "s": 21056, "text": "amartyaghoshgfg" }, { "code": null, "e": 21085, "s": 21072, "text": "simmytarika5" }, { "code": null, "e": 21102, "s": 21085, "text": "hardikkoriintern" }, { "code": null, "e": 21109, "s": 21102, "text": "Amazon" }, { "code": null, "e": 21114, "s": 21109, "text": "Tree" }, { "code": null, "e": 21121, "s": 21114, "text": "Amazon" }, { "code": null, "e": 21126, "s": 21121, "text": "Tree" }, { "code": null, "e": 21224, "s": 21126, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 21256, "s": 21224, "text": "Introduction to Data Structures" }, { "code": null, "e": 21292, "s": 21256, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 21333, "s": 21292, "text": "Inorder Tree Traversal without Recursion" }, { "code": null, "e": 21397, "s": 21333, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 21440, "s": 21397, "text": "Binary Tree | Set 3 (Types of Binary Tree)" }, { "code": null, "e": 21490, "s": 21440, "text": "A program to check if a binary tree is BST or not" }, { "code": null, "e": 21523, "s": 21490, "text": "Binary Tree | Set 2 (Properties)" }, { "code": null, "e": 21549, "s": 21523, "text": "Diameter of a Binary Tree" }, { "code": null, "e": 21583, "s": 21549, "text": "Diagonal Traversal of Binary Tree" } ]
WordPress Introduction
24 Dec, 2021 WordPress is a free and open source Content Management System(CMS) framework. It is the most widely used CMS framework of recent time. Let us now have a brief discussion on what is CMS and what is wordpress! What is Content Management System? A content management system (CMS) is an application used to create and manage digital content. Content is what makes any organization stand out from the crowd, content must be regular and well organized in order to maintain any branding possible thus rather than doing it manually CMSes are used for enterprise content management (ECM) and web content management (WCM). An ECM is used for the collaboration in any workplace by integrating document management, digital asset management and records retention functionalities, and providing end users with role-based access to the organization’s digital assets. While WCM facilitates collaborative authoring for websites. It is easy to say that WCM is a more public content management tool whereas the ECM is totally built for more confidential contents to be kept secured within the organization. What is WordPress? WordPress is a content management system (WCM) i.e. it is a tool that organizes the whole process of creating, storing and showcasing web-content in an optimal way. WordPress started its journey as an improvement tool to enhance the regular typography of day to day writing. But it was taken as a blogging tool and as we reach the last quarter of this year WordPress stands strong as the most used WCM system used and that also not only in the blogging community.WordPress is completely an open source tool and is still being updated very frequently.You may find the repository here. Like any other open source software, WordPress relies on its community. How does WordPress work? WordPress, like any other WCM system, is dynamically driven through the use of a database with multiple tables storing all the content information and the information required to specify the website structure. You must have the ability to create and utilize a database to use WordPress. The internal structure and database structure are one of the more advanced topics and will be resumed in later articles. After learning about the WordPress the first thing that comes to our mind is that where to use it? What kind of website can I create using WordPress? So let’s move on to the section straight away. When launched, WordPress was nothing but a typographic improvement, but as time passed and the community got stronger and WordPress was developed by contributors from all over the world, now WordPress is a robust system that can be used to create and manage any kind of website to keep it short. To showcase some examples lets look into the various implementations of WordPress already developed. E-commerce Websites: WordPress is really great for E-Commerce websites because of its robust structure and ability to categorize contents. With the proper theme chosen to create an E-commerce website is considered to be one of the best options available.Visit this link to find one of the biggest clients. Educational/Library Websites: One of the most important feature of WordPress is to manage and categorize documents or other assets, though not self-sustaining WordPress is good enough to create and run a Library Website. Using DMS implementation as well as WordPress one can surely develop Library Websites.Such as this. Personal Websites: Whether it’s a small website containing your portfolio or a daily blog. WordPress is undoubtedly one of the best platforms to showcase your talent as it has dedicated sections for the contents and overall easy experience. This will be all to explain and introduce you to the concept of WordPress. The subsequent articles will be various structural elements as How WordPress Works, The Structure of the Database, Plugins, and Lastly more advanced topics such as creating a theme or a plugin for WordPress. Related Articles: Installing WordPress | Part 1 Installing WordPress | Part 2 This article is contributed by Pronab Mukherjee. 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. PHP-Questions Wordpress PHP Web Technologies Web technologies Questions PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n24 Dec, 2021" }, { "code": null, "e": 261, "s": 53, "text": "WordPress is a free and open source Content Management System(CMS) framework. It is the most widely used CMS framework of recent time. Let us now have a brief discussion on what is CMS and what is wordpress!" }, { "code": null, "e": 296, "s": 261, "text": "What is Content Management System?" }, { "code": null, "e": 666, "s": 296, "text": "A content management system (CMS) is an application used to create and manage digital content. Content is what makes any organization stand out from the crowd, content must be regular and well organized in order to maintain any branding possible thus rather than doing it manually CMSes are used for enterprise content management (ECM) and web content management (WCM)." }, { "code": null, "e": 1141, "s": 666, "text": "An ECM is used for the collaboration in any workplace by integrating document management, digital asset management and records retention functionalities, and providing end users with role-based access to the organization’s digital assets. While WCM facilitates collaborative authoring for websites. It is easy to say that WCM is a more public content management tool whereas the ECM is totally built for more confidential contents to be kept secured within the organization." }, { "code": null, "e": 1160, "s": 1141, "text": "What is WordPress?" }, { "code": null, "e": 1816, "s": 1160, "text": "WordPress is a content management system (WCM) i.e. it is a tool that organizes the whole process of creating, storing and showcasing web-content in an optimal way. WordPress started its journey as an improvement tool to enhance the regular typography of day to day writing. But it was taken as a blogging tool and as we reach the last quarter of this year WordPress stands strong as the most used WCM system used and that also not only in the blogging community.WordPress is completely an open source tool and is still being updated very frequently.You may find the repository here. Like any other open source software, WordPress relies on its community." }, { "code": null, "e": 1841, "s": 1816, "text": "How does WordPress work?" }, { "code": null, "e": 2249, "s": 1841, "text": "WordPress, like any other WCM system, is dynamically driven through the use of a database with multiple tables storing all the content information and the information required to specify the website structure. You must have the ability to create and utilize a database to use WordPress. The internal structure and database structure are one of the more advanced topics and will be resumed in later articles." }, { "code": null, "e": 2446, "s": 2249, "text": "After learning about the WordPress the first thing that comes to our mind is that where to use it? What kind of website can I create using WordPress? So let’s move on to the section straight away." }, { "code": null, "e": 2843, "s": 2446, "text": "When launched, WordPress was nothing but a typographic improvement, but as time passed and the community got stronger and WordPress was developed by contributors from all over the world, now WordPress is a robust system that can be used to create and manage any kind of website to keep it short. To showcase some examples lets look into the various implementations of WordPress already developed." }, { "code": null, "e": 3149, "s": 2843, "text": "E-commerce Websites: WordPress is really great for E-Commerce websites because of its robust structure and ability to categorize contents. With the proper theme chosen to create an E-commerce website is considered to be one of the best options available.Visit this link to find one of the biggest clients." }, { "code": null, "e": 3470, "s": 3149, "text": "Educational/Library Websites: One of the most important feature of WordPress is to manage and categorize documents or other assets, though not self-sustaining WordPress is good enough to create and run a Library Website. Using DMS implementation as well as WordPress one can surely develop Library Websites.Such as this." }, { "code": null, "e": 3711, "s": 3470, "text": "Personal Websites: Whether it’s a small website containing your portfolio or a daily blog. WordPress is undoubtedly one of the best platforms to showcase your talent as it has dedicated sections for the contents and overall easy experience." }, { "code": null, "e": 3994, "s": 3711, "text": "This will be all to explain and introduce you to the concept of WordPress. The subsequent articles will be various structural elements as How WordPress Works, The Structure of the Database, Plugins, and Lastly more advanced topics such as creating a theme or a plugin for WordPress." }, { "code": null, "e": 4012, "s": 3994, "text": "Related Articles:" }, { "code": null, "e": 4042, "s": 4012, "text": "Installing WordPress | Part 1" }, { "code": null, "e": 4072, "s": 4042, "text": "Installing WordPress | Part 2" }, { "code": null, "e": 4372, "s": 4072, "text": "This article is contributed by Pronab Mukherjee. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 4497, "s": 4372, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 4511, "s": 4497, "text": "PHP-Questions" }, { "code": null, "e": 4521, "s": 4511, "text": "Wordpress" }, { "code": null, "e": 4525, "s": 4521, "text": "PHP" }, { "code": null, "e": 4542, "s": 4525, "text": "Web Technologies" }, { "code": null, "e": 4569, "s": 4542, "text": "Web technologies Questions" }, { "code": null, "e": 4573, "s": 4569, "text": "PHP" } ]
p5.js | createSlider() Function
09 Jul, 2019 The createSlider() function in p5.js is used to create a slider (input) element in the DOM (Document Object Model). This function includes the p5.dom library. Add the following syntax in the head section. <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.11/addons/p5.dom.min.js"></script> Syntax: createSlider( min, max, value, step ) Parameters: This function accepts four parameters as mentioned above and described below: min: It holds the minimum value of the slider. max: It holds the maximum value of the slider. value: It holds the default value of the slider. step: It holds the step size of the slider. Below programs illustrates the createSlider() function in p5.js: Example: This example uses createSlider() function to change the r value of the background-color (in rgb format) using a slider. // Create a variable for the slider objectvar color_slider; function setup() { // Create a canvas of given size createCanvas(600, 300); // Create the slider color_slider = createSlider(0, 255, 125); // Set the position of slider on the canvas color_slider.position(150, 200);} function draw() { // Get the value of the slider // using .value() function col = color_slider.value(); // Set the value of the background-color background(col, 200, 100);} Output: Reference: https://p5js.org/reference/#/p5/createSlider JavaScript-p5.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Jul, 2019" }, { "code": null, "e": 233, "s": 28, "text": "The createSlider() function in p5.js is used to create a slider (input) element in the DOM (Document Object Model). This function includes the p5.dom library. Add the following syntax in the head section." }, { "code": "<script src=\"https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.11/addons/p5.dom.min.js\"></script>", "e": 330, "s": 233, "text": null }, { "code": null, "e": 338, "s": 330, "text": "Syntax:" }, { "code": null, "e": 376, "s": 338, "text": "createSlider( min, max, value, step )" }, { "code": null, "e": 466, "s": 376, "text": "Parameters: This function accepts four parameters as mentioned above and described below:" }, { "code": null, "e": 513, "s": 466, "text": "min: It holds the minimum value of the slider." }, { "code": null, "e": 560, "s": 513, "text": "max: It holds the maximum value of the slider." }, { "code": null, "e": 609, "s": 560, "text": "value: It holds the default value of the slider." }, { "code": null, "e": 653, "s": 609, "text": "step: It holds the step size of the slider." }, { "code": null, "e": 718, "s": 653, "text": "Below programs illustrates the createSlider() function in p5.js:" }, { "code": null, "e": 847, "s": 718, "text": "Example: This example uses createSlider() function to change the r value of the background-color (in rgb format) using a slider." }, { "code": "// Create a variable for the slider objectvar color_slider; function setup() { // Create a canvas of given size createCanvas(600, 300); // Create the slider color_slider = createSlider(0, 255, 125); // Set the position of slider on the canvas color_slider.position(150, 200);} function draw() { // Get the value of the slider // using .value() function col = color_slider.value(); // Set the value of the background-color background(col, 200, 100);} ", "e": 1378, "s": 847, "text": null }, { "code": null, "e": 1386, "s": 1378, "text": "Output:" }, { "code": null, "e": 1442, "s": 1386, "text": "Reference: https://p5js.org/reference/#/p5/createSlider" }, { "code": null, "e": 1459, "s": 1442, "text": "JavaScript-p5.js" }, { "code": null, "e": 1470, "s": 1459, "text": "JavaScript" }, { "code": null, "e": 1487, "s": 1470, "text": "Web Technologies" } ]
How to copy elements of an Array in a Vector in C++ - GeeksforGeeks
27 Jan, 2022 An Array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Following are the different ways to copy elements from an array to a vector: Method 1: Naive SolutionTraverse the complete array and insert each element into the newly assigned vector using the push_back() function. Below is the implementation of the above approach: C++ // C++ program of the above approach#include <bits/stdc++.h>using namespace std; // Driver codeint main(){ // Initialise an array int arr[] = { 1, 2, 3, 4, 5 }; int N = sizeof(arr) / sizeof(arr[0]); // Initialize an empty vector vector<int> v; // Traverse the array and for (int i = 0; i < N; i++) v.push_back(arr[i]); // Print all elements of vector for (auto ele : v) { cout << ele << " "; } return 0;} 1 2 3 4 5 Method 2: Range-based Assignment during InitializationIn C++, the Vector class provides a constructor which accepts a range, so to create a vector from array elements, pass the pointer to the first and last position of the range as the argument during the vector initialization that needs to be copied to the vector i.e, (arr, arr+N). Below is the implementation of the above approach: C++ // C++ program of the above approach#include <bits/stdc++.h>using namespace std; // Driver codeint main(){ // Initialise an array int arr[] = { 1, 2, 3, 4, 5 }; int N = sizeof(arr) / sizeof(arr[0]); // Initialize a vector by passing the // pointer to the first and last element // of the range as arguments vector<int> v(arr, arr + N); // Print all elements of vector for (auto ele : v) { cout << ele << " "; } return 0;} 1 2 3 4 5 Note that Iterators used to point at the memory addresses of STL containers can also be used. std::begin(arr)- Iterator to the first element of an array. std::end(arr)- Iterator to the one after the last element of an array. vector<int> v(begin(arr), end(arr)); Method 3: Using Inbuilt Function Insert(position, first_iterator, last_iterator): The insert() is a built-in function in C++ STL that inserts new elements before the element at the specified position, effectively increasing the container size by the number of elements inserted. Instead of a single value, a range can also be passed as arguments. Below is the implementation of the above approach: C++ // C++ program of the above approach#include <bits/stdc++.h>using namespace std; // Driver codeint main(){ // Initialise an array int arr[] = { 1, 2, 3, 4, 5 }; int N = sizeof(arr) / sizeof(arr[0]); // Initialize an empty vector vector<int> v; // Add array elements in the required // range into a vector from beginning v.insert(v.begin(), arr, arr + N); // Print all elements of vector for (auto ele : v) { cout << ele << " "; } return 0;} 1 2 3 4 5 Method 4: Using Inbuilt Function Copy(first_iterator, last_iterator, back_inserter()): This is another way to copy array elements into a vector is to use the inbuilt copy function. This function takes 3 arguments, an iterator to the first element of the array, an iterator to the last element of the array, and the back_inserter function to insert values from the back. Below is the implementation of the above approach: C++ // C++ program of the above approach#include <bits/stdc++.h>using namespace std; // Driver codeint main(){ // Initialise an array int arr[] = { 1, 2, 3, 4, 5 }; int N = sizeof(arr) / sizeof(arr[0]); // Initialize an empty vector vector<int> v; // Copy array elements in the required // range into vector v using copy function copy(begin(arr), end(arr), back_inserter(v)); // Print all elements of vector for (auto ele : v) { cout << ele << " "; } return 0;} 1 2 3 4 5 Method 5: Using Inbuilt Function Assign( first_iterator, last_iterator ): The vector::assign() function can be used to assign values to a new vector or an already existing vector. It can also modify the size of the vector if necessary. It takes the iterator to the first and last position as arguments. Below is the implementation of the above approach: C++ // C++ program of the above approach#include <bits/stdc++.h>using namespace std; // Driver codeint main(){ // Initialise an array int arr[] = { 1, 2, 3, 4, 5 }; int N = sizeof(arr) / sizeof(arr[0]); // Initialize an empty vector vector<int> v; // Assign the elements of the array // into the vector v v.assign(arr, arr + N); // Print all elements of vector for (auto ele : v) { cout << ele << " "; } return 0;} 1 2 3 4 5 Method 6: Using Inbuilt Function Transform(first_iterator, last_iterator, back_insert(), function): The std::transform() function takes 4 arguments, an iterator to the first element of the array, an iterator to the last element of the array, the back_inserter function to insert values from the back and a user-defined function which can be used to modify all the elements of the array i.e, perform a unary operation, convert lower case characters to upper case, etc. Below is the implementation of the above approach: C++14 // C++ program of the above approach#include <bits/stdc++.h>using namespace std; // Function to increment the value by 1int increment(int x){ return x + 1;} // Driver codeint main(){ // Initialise an array int arr[] = { 1, 2, 3, 4, 5 }; int N = sizeof(arr) / sizeof(arr[0]); // Initialize an empty vector vector<int> v; // Copy the elements of the array into // vector v and increment each value transform(arr, arr + N, back_inserter(v), increment); // Print all elements of vector for (auto ele : v) { cout << ele << " "; } return 0;} 2 3 4 5 6 Arrays Blogathon-2021 cpp-vector Blogathon C++ Arrays CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Import JSON Data into SQL Server? How to Install Tkinter in Windows? SQL - Multiple Column Ordering How to pass data into table from a form using React Components How to Create a Table With Multiple Foreign Keys in SQL? Vector in C++ STL Arrays in C/C++ Initialize a vector in C++ (6 different ways) Map in C++ Standard Template Library (STL) std::sort() in C++ STL
[ { "code": null, "e": 24445, "s": 24417, "text": "\n27 Jan, 2022" }, { "code": null, "e": 24581, "s": 24445, "text": "An Array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together." }, { "code": null, "e": 24777, "s": 24581, "text": "Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container." }, { "code": null, "e": 24854, "s": 24777, "text": "Following are the different ways to copy elements from an array to a vector:" }, { "code": null, "e": 25044, "s": 24854, "text": "Method 1: Naive SolutionTraverse the complete array and insert each element into the newly assigned vector using the push_back() function. Below is the implementation of the above approach:" }, { "code": null, "e": 25048, "s": 25044, "text": "C++" }, { "code": "// C++ program of the above approach#include <bits/stdc++.h>using namespace std; // Driver codeint main(){ // Initialise an array int arr[] = { 1, 2, 3, 4, 5 }; int N = sizeof(arr) / sizeof(arr[0]); // Initialize an empty vector vector<int> v; // Traverse the array and for (int i = 0; i < N; i++) v.push_back(arr[i]); // Print all elements of vector for (auto ele : v) { cout << ele << \" \"; } return 0;}", "e": 25509, "s": 25048, "text": null }, { "code": null, "e": 25520, "s": 25509, "text": "1 2 3 4 5 " }, { "code": null, "e": 25855, "s": 25520, "text": "Method 2: Range-based Assignment during InitializationIn C++, the Vector class provides a constructor which accepts a range, so to create a vector from array elements, pass the pointer to the first and last position of the range as the argument during the vector initialization that needs to be copied to the vector i.e, (arr, arr+N)." }, { "code": null, "e": 25906, "s": 25855, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 25910, "s": 25906, "text": "C++" }, { "code": "// C++ program of the above approach#include <bits/stdc++.h>using namespace std; // Driver codeint main(){ // Initialise an array int arr[] = { 1, 2, 3, 4, 5 }; int N = sizeof(arr) / sizeof(arr[0]); // Initialize a vector by passing the // pointer to the first and last element // of the range as arguments vector<int> v(arr, arr + N); // Print all elements of vector for (auto ele : v) { cout << ele << \" \"; } return 0;}", "e": 26379, "s": 25910, "text": null }, { "code": null, "e": 26390, "s": 26379, "text": "1 2 3 4 5 " }, { "code": null, "e": 26484, "s": 26390, "text": "Note that Iterators used to point at the memory addresses of STL containers can also be used." }, { "code": null, "e": 26544, "s": 26484, "text": "std::begin(arr)- Iterator to the first element of an array." }, { "code": null, "e": 26615, "s": 26544, "text": "std::end(arr)- Iterator to the one after the last element of an array." }, { "code": null, "e": 26652, "s": 26615, "text": "vector<int> v(begin(arr), end(arr));" }, { "code": null, "e": 26999, "s": 26652, "text": "Method 3: Using Inbuilt Function Insert(position, first_iterator, last_iterator): The insert() is a built-in function in C++ STL that inserts new elements before the element at the specified position, effectively increasing the container size by the number of elements inserted. Instead of a single value, a range can also be passed as arguments." }, { "code": null, "e": 27050, "s": 26999, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27054, "s": 27050, "text": "C++" }, { "code": "// C++ program of the above approach#include <bits/stdc++.h>using namespace std; // Driver codeint main(){ // Initialise an array int arr[] = { 1, 2, 3, 4, 5 }; int N = sizeof(arr) / sizeof(arr[0]); // Initialize an empty vector vector<int> v; // Add array elements in the required // range into a vector from beginning v.insert(v.begin(), arr, arr + N); // Print all elements of vector for (auto ele : v) { cout << ele << \" \"; } return 0;}", "e": 27547, "s": 27054, "text": null }, { "code": null, "e": 27558, "s": 27547, "text": "1 2 3 4 5 " }, { "code": null, "e": 27928, "s": 27558, "text": "Method 4: Using Inbuilt Function Copy(first_iterator, last_iterator, back_inserter()): This is another way to copy array elements into a vector is to use the inbuilt copy function. This function takes 3 arguments, an iterator to the first element of the array, an iterator to the last element of the array, and the back_inserter function to insert values from the back." }, { "code": null, "e": 27979, "s": 27928, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27983, "s": 27979, "text": "C++" }, { "code": "// C++ program of the above approach#include <bits/stdc++.h>using namespace std; // Driver codeint main(){ // Initialise an array int arr[] = { 1, 2, 3, 4, 5 }; int N = sizeof(arr) / sizeof(arr[0]); // Initialize an empty vector vector<int> v; // Copy array elements in the required // range into vector v using copy function copy(begin(arr), end(arr), back_inserter(v)); // Print all elements of vector for (auto ele : v) { cout << ele << \" \"; } return 0;}", "e": 28493, "s": 27983, "text": null }, { "code": null, "e": 28504, "s": 28493, "text": "1 2 3 4 5 " }, { "code": null, "e": 28807, "s": 28504, "text": "Method 5: Using Inbuilt Function Assign( first_iterator, last_iterator ): The vector::assign() function can be used to assign values to a new vector or an already existing vector. It can also modify the size of the vector if necessary. It takes the iterator to the first and last position as arguments." }, { "code": null, "e": 28858, "s": 28807, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 28862, "s": 28858, "text": "C++" }, { "code": "// C++ program of the above approach#include <bits/stdc++.h>using namespace std; // Driver codeint main(){ // Initialise an array int arr[] = { 1, 2, 3, 4, 5 }; int N = sizeof(arr) / sizeof(arr[0]); // Initialize an empty vector vector<int> v; // Assign the elements of the array // into the vector v v.assign(arr, arr + N); // Print all elements of vector for (auto ele : v) { cout << ele << \" \"; } return 0;}", "e": 29325, "s": 28862, "text": null }, { "code": null, "e": 29336, "s": 29325, "text": "1 2 3 4 5 " }, { "code": null, "e": 29804, "s": 29336, "text": "Method 6: Using Inbuilt Function Transform(first_iterator, last_iterator, back_insert(), function): The std::transform() function takes 4 arguments, an iterator to the first element of the array, an iterator to the last element of the array, the back_inserter function to insert values from the back and a user-defined function which can be used to modify all the elements of the array i.e, perform a unary operation, convert lower case characters to upper case, etc." }, { "code": null, "e": 29855, "s": 29804, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 29861, "s": 29855, "text": "C++14" }, { "code": "// C++ program of the above approach#include <bits/stdc++.h>using namespace std; // Function to increment the value by 1int increment(int x){ return x + 1;} // Driver codeint main(){ // Initialise an array int arr[] = { 1, 2, 3, 4, 5 }; int N = sizeof(arr) / sizeof(arr[0]); // Initialize an empty vector vector<int> v; // Copy the elements of the array into // vector v and increment each value transform(arr, arr + N, back_inserter(v), increment); // Print all elements of vector for (auto ele : v) { cout << ele << \" \"; } return 0;}", "e": 30453, "s": 29861, "text": null }, { "code": null, "e": 30464, "s": 30453, "text": "2 3 4 5 6 " }, { "code": null, "e": 30471, "s": 30464, "text": "Arrays" }, { "code": null, "e": 30486, "s": 30471, "text": "Blogathon-2021" }, { "code": null, "e": 30497, "s": 30486, "text": "cpp-vector" }, { "code": null, "e": 30507, "s": 30497, "text": "Blogathon" }, { "code": null, "e": 30511, "s": 30507, "text": "C++" }, { "code": null, "e": 30518, "s": 30511, "text": "Arrays" }, { "code": null, "e": 30522, "s": 30518, "text": "CPP" }, { "code": null, "e": 30620, "s": 30522, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30629, "s": 30620, "text": "Comments" }, { "code": null, "e": 30642, "s": 30629, "text": "Old Comments" }, { "code": null, "e": 30683, "s": 30642, "text": "How to Import JSON Data into SQL Server?" }, { "code": null, "e": 30718, "s": 30683, "text": "How to Install Tkinter in Windows?" }, { "code": null, "e": 30749, "s": 30718, "text": "SQL - Multiple Column Ordering" }, { "code": null, "e": 30812, "s": 30749, "text": "How to pass data into table from a form using React Components" }, { "code": null, "e": 30869, "s": 30812, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 30887, "s": 30869, "text": "Vector in C++ STL" }, { "code": null, "e": 30903, "s": 30887, "text": "Arrays in C/C++" }, { "code": null, "e": 30949, "s": 30903, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 30992, "s": 30949, "text": "Map in C++ Standard Template Library (STL)" } ]
Customizing Filters in Django REST Framework - GeeksforGeeks
05 Jul, 2021 Prerequisite: Adding Filtering in APIs – Django REST Framework [lin needed article on published yet] Django filters facilitate filtering the queryset to retrieve the relevant results based on the values assigned to the filter fields. But, what if the user wants to retrieve details within a given range. Say, for example, the user needs to fetch detail of robots based on price range. Here comes the necessity of customizing the filters. Let’s create and apply a customized filter to the Robot model so that the user can retrieve robot details by providing robot category name, manufacturer name, currency, manufacturing date range, and/or price range. We will create a new class named RobotFilter class, which is a subclass of django_filters.FilterSet class. Let’s declare the imports Python3 from django_filters import FilterSet, AllValuesFilterfrom django_filters import DateTimeFilter, NumberFilter Now, you can add the below code before the RobotList class. Python3 class RobotFilter(FilterSet): from_manufacturing_date = DateTimeFilter(field_name='manufacturing_date', lookup_expr='gte') to_manufacturing_date = DateTimeFilter(field_name='manufacturing_date', lookup_expr='lte') min_price = NumberFilter(field_name='price', lookup_expr='gte') max_price = NumberFilter(field_name='price', lookup_expr='lte') robotcategory_name = AllValuesFilter(field_name='robot_category__name') manufacturer_name = AllValuesFilter(field_name='manufacturer__name') class Meta: model = Robot fields = ( 'name', 'currency', 'from_manufacturing_date', 'to_manufacturing_date', 'min_price', 'max_price', 'robotcategory_name', 'manufacturer_name', ) Let’s look at the attributes declared in the RobotFilter class. from_manufacturing_date to_manufacturing_date min_price max_price robotcategory_name manufacturer_name from_manufacturing_date: It is a django_filters.DateTimeFilter instance attribute that filters the robots whose manufacturing_date value is greater than or equal to the specified DateTime value. Here in the DateTimeFilter, there are two parameters named field_name and lookup_expr. The field_name has the manufacturing_date (for filtering), and ‘gte’ (greater than or equal to) is applied to the lookup_expr. to_manufacturing_date: It is a django_filters.DateTimeFilter instance attribute that filters the robots whose manufacturing_date value is less than or equal to the specified DateTime value. Here in the DateTimeFilter, there are two parameters named field_name and lookup_expr. In the field_name, we mentioned the manufacturing_date, and ‘lte’ (less than or equal to) is applied to the lookup_expr. min_price: It is a django_filters.NumberFilter instance attribute that filters the robots whose price value is greater than or equal to the specified price value. max_price: It is a django_filters.NumberFilter instance attribute that filters the robots whose price value is less than or equal to the specified price value. robotcategory_name: It is a django_filters.AllValuesFilter instance attribute that filters the robots whose robot category name matches with the specified string value. You can notice that there is a double underscore (__) in the value provided to the field_name, between robot_category and name. The field_name uses the Django double underscore to read it as the name field for the RobotCategory model. This helps to retrieve the robot’s detail based on the robot category name rather than its pk id. manufacturer_name: It is a django_filters.AllValuesFilter instance attribute that filters the robots whose manufacturer name matches with the specified string value. The field_name uses the Django double underscore to read the value ‘manufacturer__name’ as the name field for the Manufacturer model. This helps to retrieve the robot’s detail based on the manufacturer name rather than its pk id. The RobotFilter class also defines a Meta inner class. This class has two attributes model and fields. The model attribute specifies the model (Robot) to filter. And, the fields attribute holds field names and filter names (as a tuple of strings) to include in the filters for the mentioned model (Robot). Let’s use the RobotFilter class in our RobotList class. The code as follows Python3 class RobotList(generics.ListCreateAPIView): queryset = Robot.objects.all() serializer_class = RobotSerializer name = 'robot-list' # customized filter class filter_class = RobotFilter search_fields = ( '^name', ) ordering_fields = ( 'price', ) Let’s filter the robots within a manufacturing date. The HTTPie command is http “:8000/robot/?from_manufacturing_date=2019-10-01&to_manufacturing_date=2020-03-01” Output: Let’s filter the robots based on the robot category name and manufacturer name. The HTTPie command as follows http “:8000/robot/?robotcategory_name=Articulated Robots&manufacturer_name=Fanuc” Output: Let’s filter the robots based on price range. The HTTPie command is http “:8000/robot/?min_price=10000&max_price=20000¤cy=USD” Output: Let’s filter the robots using the browsable API feature. You can browse the below URL and click the filter button. http://127.0.0.1:8000/robot/ You can populate the values to filter against robots. Sharing the screenshot below On clicking the submit button, you will get filtered results. Sharing the screenshot below Django-REST Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe Python OOPs Concepts Python | Get unique values from a list Check if element exists in list in Python Python Classes and Objects Python | os.path.join() method How To Convert Python Dictionary To JSON? Python | Pandas dataframe.groupby() Create a directory in Python
[ { "code": null, "e": 24212, "s": 24184, "text": "\n05 Jul, 2021" }, { "code": null, "e": 24313, "s": 24212, "text": "Prerequisite: Adding Filtering in APIs – Django REST Framework [lin needed article on published yet]" }, { "code": null, "e": 24867, "s": 24313, "text": "Django filters facilitate filtering the queryset to retrieve the relevant results based on the values assigned to the filter fields. But, what if the user wants to retrieve details within a given range. Say, for example, the user needs to fetch detail of robots based on price range. Here comes the necessity of customizing the filters. Let’s create and apply a customized filter to the Robot model so that the user can retrieve robot details by providing robot category name, manufacturer name, currency, manufacturing date range, and/or price range. " }, { "code": null, "e": 25001, "s": 24867, "text": "We will create a new class named RobotFilter class, which is a subclass of django_filters.FilterSet class. Let’s declare the imports" }, { "code": null, "e": 25009, "s": 25001, "text": "Python3" }, { "code": "from django_filters import FilterSet, AllValuesFilterfrom django_filters import DateTimeFilter, NumberFilter", "e": 25118, "s": 25009, "text": null }, { "code": null, "e": 25178, "s": 25118, "text": "Now, you can add the below code before the RobotList class." }, { "code": null, "e": 25186, "s": 25178, "text": "Python3" }, { "code": "class RobotFilter(FilterSet): from_manufacturing_date = DateTimeFilter(field_name='manufacturing_date', lookup_expr='gte') to_manufacturing_date = DateTimeFilter(field_name='manufacturing_date', lookup_expr='lte') min_price = NumberFilter(field_name='price', lookup_expr='gte') max_price = NumberFilter(field_name='price', lookup_expr='lte') robotcategory_name = AllValuesFilter(field_name='robot_category__name') manufacturer_name = AllValuesFilter(field_name='manufacturer__name') class Meta: model = Robot fields = ( 'name', 'currency', 'from_manufacturing_date', 'to_manufacturing_date', 'min_price', 'max_price', 'robotcategory_name', 'manufacturer_name', )", "e": 26071, "s": 25186, "text": null }, { "code": null, "e": 26135, "s": 26071, "text": "Let’s look at the attributes declared in the RobotFilter class." }, { "code": null, "e": 26159, "s": 26135, "text": "from_manufacturing_date" }, { "code": null, "e": 26181, "s": 26159, "text": "to_manufacturing_date" }, { "code": null, "e": 26191, "s": 26181, "text": "min_price" }, { "code": null, "e": 26201, "s": 26191, "text": "max_price" }, { "code": null, "e": 26220, "s": 26201, "text": "robotcategory_name" }, { "code": null, "e": 26238, "s": 26220, "text": "manufacturer_name" }, { "code": null, "e": 26647, "s": 26238, "text": "from_manufacturing_date: It is a django_filters.DateTimeFilter instance attribute that filters the robots whose manufacturing_date value is greater than or equal to the specified DateTime value. Here in the DateTimeFilter, there are two parameters named field_name and lookup_expr. The field_name has the manufacturing_date (for filtering), and ‘gte’ (greater than or equal to) is applied to the lookup_expr." }, { "code": null, "e": 27045, "s": 26647, "text": "to_manufacturing_date: It is a django_filters.DateTimeFilter instance attribute that filters the robots whose manufacturing_date value is less than or equal to the specified DateTime value. Here in the DateTimeFilter, there are two parameters named field_name and lookup_expr. In the field_name, we mentioned the manufacturing_date, and ‘lte’ (less than or equal to) is applied to the lookup_expr." }, { "code": null, "e": 27208, "s": 27045, "text": "min_price: It is a django_filters.NumberFilter instance attribute that filters the robots whose price value is greater than or equal to the specified price value." }, { "code": null, "e": 27368, "s": 27208, "text": "max_price: It is a django_filters.NumberFilter instance attribute that filters the robots whose price value is less than or equal to the specified price value." }, { "code": null, "e": 27870, "s": 27368, "text": "robotcategory_name: It is a django_filters.AllValuesFilter instance attribute that filters the robots whose robot category name matches with the specified string value. You can notice that there is a double underscore (__) in the value provided to the field_name, between robot_category and name. The field_name uses the Django double underscore to read it as the name field for the RobotCategory model. This helps to retrieve the robot’s detail based on the robot category name rather than its pk id." }, { "code": null, "e": 28266, "s": 27870, "text": "manufacturer_name: It is a django_filters.AllValuesFilter instance attribute that filters the robots whose manufacturer name matches with the specified string value. The field_name uses the Django double underscore to read the value ‘manufacturer__name’ as the name field for the Manufacturer model. This helps to retrieve the robot’s detail based on the manufacturer name rather than its pk id." }, { "code": null, "e": 28573, "s": 28266, "text": "The RobotFilter class also defines a Meta inner class. This class has two attributes model and fields. The model attribute specifies the model (Robot) to filter. And, the fields attribute holds field names and filter names (as a tuple of strings) to include in the filters for the mentioned model (Robot). " }, { "code": null, "e": 28649, "s": 28573, "text": "Let’s use the RobotFilter class in our RobotList class. The code as follows" }, { "code": null, "e": 28657, "s": 28649, "text": "Python3" }, { "code": "class RobotList(generics.ListCreateAPIView): queryset = Robot.objects.all() serializer_class = RobotSerializer name = 'robot-list' # customized filter class filter_class = RobotFilter search_fields = ( '^name', ) ordering_fields = ( 'price', )", "e": 28942, "s": 28657, "text": null }, { "code": null, "e": 29017, "s": 28942, "text": "Let’s filter the robots within a manufacturing date. The HTTPie command is" }, { "code": null, "e": 29105, "s": 29017, "text": "http “:8000/robot/?from_manufacturing_date=2019-10-01&to_manufacturing_date=2020-03-01”" }, { "code": null, "e": 29113, "s": 29105, "text": "Output:" }, { "code": null, "e": 29223, "s": 29113, "text": "Let’s filter the robots based on the robot category name and manufacturer name. The HTTPie command as follows" }, { "code": null, "e": 29305, "s": 29223, "text": "http “:8000/robot/?robotcategory_name=Articulated Robots&manufacturer_name=Fanuc”" }, { "code": null, "e": 29313, "s": 29305, "text": "Output:" }, { "code": null, "e": 29381, "s": 29313, "text": "Let’s filter the robots based on price range. The HTTPie command is" }, { "code": null, "e": 29440, "s": 29381, "text": "http “:8000/robot/?min_price=10000&max_price=20000¤cy=USD”" }, { "code": null, "e": 29448, "s": 29440, "text": "Output:" }, { "code": null, "e": 29563, "s": 29448, "text": "Let’s filter the robots using the browsable API feature. You can browse the below URL and click the filter button." }, { "code": null, "e": 29592, "s": 29563, "text": "http://127.0.0.1:8000/robot/" }, { "code": null, "e": 29675, "s": 29592, "text": "You can populate the values to filter against robots. Sharing the screenshot below" }, { "code": null, "e": 29766, "s": 29675, "text": "On clicking the submit button, you will get filtered results. Sharing the screenshot below" }, { "code": null, "e": 29778, "s": 29766, "text": "Django-REST" }, { "code": null, "e": 29792, "s": 29778, "text": "Python Django" }, { "code": null, "e": 29799, "s": 29792, "text": "Python" }, { "code": null, "e": 29897, "s": 29799, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29906, "s": 29897, "text": "Comments" }, { "code": null, "e": 29919, "s": 29906, "text": "Old Comments" }, { "code": null, "e": 29951, "s": 29919, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30007, "s": 29951, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 30028, "s": 30007, "text": "Python OOPs Concepts" }, { "code": null, "e": 30067, "s": 30028, "text": "Python | Get unique values from a list" }, { "code": null, "e": 30109, "s": 30067, "text": "Check if element exists in list in Python" }, { "code": null, "e": 30136, "s": 30109, "text": "Python Classes and Objects" }, { "code": null, "e": 30167, "s": 30136, "text": "Python | os.path.join() method" }, { "code": null, "e": 30209, "s": 30167, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 30245, "s": 30209, "text": "Python | Pandas dataframe.groupby()" } ]
How to specify an index while creating a Series in Pandas?
Pandas series is 1-Dimensional ndarray with labeled data, which means every value present in a series is having a label representation which is nothing but each data have thor on index values. The index can be label names (object data) or it can be values. By default, it will assign an index value from 0 - n-1 (n is the length of series values). And it has the ability to define index values. Pandas Series function has an index keyword for specifying index values, and it takes input as an array with any kind of data in it. The data can be integers, floating-point numbers, text data, DateTime, and more. Let’s see how we can specify index values at the time of Series creation. import pandas as pd Countries = ['Australia', 'Iceland', 'India', 'United Kingdom', 'United States'] Capitals = ['Canberra', 'Reykjavik', 'New Delhi', 'London', 'Washington D.C'] # create series s = pd.Series(Capitals, index=Countries) print(s) The expected result of this above code is a pandas Series with labeled index and text data. Here the index values are the list of names of some countries and data is respected capital cities for those countries. We have created a two-python list for holding country names and capital city names. And sent those two lists pandas Series Contractor (pd.Series() function). Capital city names are Series data and country names are indexes. Specifying index names can be achieved by assigning a python list (countries list) to the index keyword of the pandas Series function. One thing we should remember here is the length of index data must be the same as the length of series data. Otherwise, it will raise ValueError. Australia Canberra Iceland Reykjavik India New Delhi United Kingdom London United States Washington D.C dtype: object Both indexes and values present in this above output block are object data types. In the above example, we have specified index labels separately at the time of Series creation. # importing pandas packages import pandas as pd dictionary = {'a':'A','c':"C",'d':'D','e':'E'} #creating a series with null data s_obj = pd.Series(dictionary) print(s_obj) If we use the python dictionary as data to the pandas Series constructor then it will take keys of the dictionary as indexes and values as elements of the series object. a A c C d D e E dtype: object We can specify the indexes of a series object by using the keys of the python dictionary.
[ { "code": null, "e": 1255, "s": 1062, "text": "Pandas series is 1-Dimensional ndarray with labeled data, which means every value present in a series is having a label representation which is nothing but each data have thor on index values." }, { "code": null, "e": 1457, "s": 1255, "text": "The index can be label names (object data) or it can be values. By default, it will assign an index value from 0 - n-1 (n is the length of series values). And it has the ability to define index values." }, { "code": null, "e": 1671, "s": 1457, "text": "Pandas Series function has an index keyword for specifying index values, and it takes input as an array with any kind of data in it. The data can be integers, floating-point numbers, text data, DateTime, and more." }, { "code": null, "e": 1745, "s": 1671, "text": "Let’s see how we can specify index values at the time of Series creation." }, { "code": null, "e": 1993, "s": 1745, "text": "import pandas as pd\n\nCountries = ['Australia', 'Iceland', 'India', 'United Kingdom', 'United States']\nCapitals = ['Canberra', 'Reykjavik', 'New Delhi', 'London', 'Washington D.C']\n\n# create series\ns = pd.Series(Capitals, index=Countries)\n\nprint(s)" }, { "code": null, "e": 2205, "s": 1993, "text": "The expected result of this above code is a pandas Series with labeled index and text data. Here the index values are the list of names of some countries and data is respected capital cities for those countries." }, { "code": null, "e": 2429, "s": 2205, "text": "We have created a two-python list for holding country names and capital city names. And sent those two lists pandas Series Contractor (pd.Series() function). Capital city names are Series data and country names are indexes." }, { "code": null, "e": 2710, "s": 2429, "text": "Specifying index names can be achieved by assigning a python list (countries list) to the index keyword of the pandas Series function. One thing we should remember here is the length of index data must be the same as the length of series data. Otherwise, it will raise ValueError." }, { "code": null, "e": 2884, "s": 2710, "text": "Australia Canberra\nIceland Reykjavik\nIndia New Delhi\nUnited Kingdom London\nUnited States Washington D.C\ndtype: object" }, { "code": null, "e": 3062, "s": 2884, "text": "Both indexes and values present in this above output block are object data types. In the above example, we have specified index labels separately at the time of Series creation." }, { "code": null, "e": 3237, "s": 3062, "text": "# importing pandas packages\nimport pandas as pd\n\ndictionary = {'a':'A','c':\"C\",'d':'D','e':'E'}\n\n#creating a series with null data\ns_obj = pd.Series(dictionary)\n\nprint(s_obj)" }, { "code": null, "e": 3407, "s": 3237, "text": "If we use the python dictionary as data to the pandas Series constructor then it will take keys of the dictionary as indexes and values as elements of the series object." }, { "code": null, "e": 3445, "s": 3407, "text": "a A\nc C\nd D\ne E\ndtype: object" }, { "code": null, "e": 3535, "s": 3445, "text": "We can specify the indexes of a series object by using the keys of the python dictionary." } ]
C Program to check whether the triangle is equilateral, isosceles or scalene
Triangle consists of three sides and three angles. Based on the three sides, there are three types of triangle − Equilateral triangle: All three sides are equal. Isosceles triangle: All two sides are equal. Scalene triangle: No sides are equal. Follow the algorithm given below for writing the respective program. Step 1: Declare three sides of triangle. Step 2: Enter three sides at run time. Step 3: If side1 == side2 && side2 == side3 Go to step 6 Step 4: If side1 == side2 || side2 == side3 || side3 == side1 Go to Step 7 Step 5: Else Go to step 8 Step 6: Print the triangle is equilateral. Step 7: Print the triangle is isosceles. Step 8: Print the triangle is scalene. Following is the C program to check whether the triangle is equilateral, isosceles or scalene − Live Demo #include<stdio.h> int main(){ int side1, side2, side3; printf("Enter sides of triangle:"); scanf("%d%d%d",&side1,&side2,&side3); if(side1 == side2 && side2 == side3) printf("The Given Triangle is equilateral\n"); else if(side1 == side2 || side2 == side3 || side3 == side1) printf("The given Triangle is isosceles\n"); else printf("The given Triangle is scalene\n"); return 0; } Let us compile and run the above program that will produce the following result − Run1: Enter sides of triangle:3 4 6 The given Triangle is scalene Run2 : Enter sides of triangle:2 2 5 The given Triangle is isosceles Run 3: Enter sides of triangle:5 5 5 The Given Triangle is equilateral
[ { "code": null, "e": 1175, "s": 1062, "text": "Triangle consists of three sides and three angles. Based on the three sides, there are three types of triangle −" }, { "code": null, "e": 1224, "s": 1175, "text": "Equilateral triangle: All three sides are equal." }, { "code": null, "e": 1269, "s": 1224, "text": "Isosceles triangle: All two sides are equal." }, { "code": null, "e": 1307, "s": 1269, "text": "Scalene triangle: No sides are equal." }, { "code": null, "e": 1376, "s": 1307, "text": "Follow the algorithm given below for writing the respective program." }, { "code": null, "e": 1737, "s": 1376, "text": "Step 1: Declare three sides of triangle.\nStep 2: Enter three sides at run time.\nStep 3: If side1 == side2 && side2 == side3\nGo to step 6\nStep 4: If side1 == side2 || side2 == side3 || side3 == side1\nGo to Step 7\nStep 5: Else\nGo to step 8\nStep 6: Print the triangle is equilateral.\nStep 7: Print the triangle is isosceles.\nStep 8: Print the triangle is scalene." }, { "code": null, "e": 1833, "s": 1737, "text": "Following is the C program to check whether the triangle is equilateral, isosceles or scalene −" }, { "code": null, "e": 1844, "s": 1833, "text": " Live Demo" }, { "code": null, "e": 2261, "s": 1844, "text": "#include<stdio.h>\nint main(){\n int side1, side2, side3;\n printf(\"Enter sides of triangle:\");\n scanf(\"%d%d%d\",&side1,&side2,&side3);\n if(side1 == side2 && side2 == side3)\n printf(\"The Given Triangle is equilateral\\n\");\n else if(side1 == side2 || side2 == side3 || side3 == side1)\n printf(\"The given Triangle is isosceles\\n\");\n else\n printf(\"The given Triangle is scalene\\n\");\n return 0;\n}" }, { "code": null, "e": 2343, "s": 2261, "text": "Let us compile and run the above program that will produce the following result −" }, { "code": null, "e": 2549, "s": 2343, "text": "Run1:\nEnter sides of triangle:3 4 6\nThe given Triangle is scalene\nRun2 :\nEnter sides of triangle:2 2 5\nThe given Triangle is isosceles\nRun 3:\nEnter sides of triangle:5 5 5\nThe Given Triangle is equilateral" } ]
Transmission Impairment in Data Communication - GeeksforGeeks
06 Oct, 2020 In communication system, analog signals travel through transmission media, which tends to deteriorate the quality of analog signal, which means that the signal at the beginning of the medium is not the same as the signal at the end of the medium. The imperfection causes signal impairment. Below are the causes of the impairment. Causes of impairment – Attenuation – It means loss of energy. The strength of signal decreases with increasing distance which causes loss of energy in overcoming resistance of medium. This is also known as attenuated signal. Amplifiers are used to amplify the attenuated signal which gives the original signal back and compensate for this loss. Image Source – aviationchief Attenuation is measured in decibels(dB). It measures the relative strengths of two signals or one signal at two different point. Attenuation is measured in decibels(dB). It measures the relative strengths of two signals or one signal at two different point. Attenuation(dB) = 10log10(P2/P1) P1 is the power at sending end and P2 is the power at receiving end. Some where the decibel is also define in terms of voltage instead of power.In this case because power is proportional to the square of the voltage the formula is Attenuation(dB) = 20log10(V2/V1) V1 is the voltage at sending end and V2 is the voltage at receiving end. Distortion – It means changes in the form or shape of the signal. This is generally seen in composite signals made up with different frequencies. Each frequency component has its own propagation speed travelling through a medium. And thats why it delay in arriving at the final destination Every component arrive at different time which leads to distortion. Therefore, they have different phases at receiver end from what they had at senders end. Noise – The random or unwanted signal that mixes up with the original signal is called noise. There are several types of noise such as induced noise, crosstalk noise, thermal noise and impulse noise which may corrupt the signal. Induced noise comes from sources such as motors and appliances. These devices act as sending antenna and transmission medium act as receiving antenna. Thermal noise is movement of electrons in wire which creates an extra signal. Crosstalk noise is when one wire affects the other wire. Impulse noise is a signal with high energy that comes from lightning or power lines Induced noise comes from sources such as motors and appliances. These devices act as sending antenna and transmission medium act as receiving antenna. Thermal noise is movement of electrons in wire which creates an extra signal. Crosstalk noise is when one wire affects the other wire. Impulse noise is a signal with high energy that comes from lightning or power lines To find the theoretical bit rate limit, we need to know the ration .The signal-to-noise ratio is defined as SNR = AVG SIGNAL POWER / AVG NOISE POWER References – Data Communication and Networking Fourth edition by Forouzan Data Communication – Slideshare pulkitagarwal03pulkit Digital Electronics & Logic Design Misc Technical Scripter Misc Misc Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. IEEE Standard 754 Floating Point Numbers Shift Registers in Digital Logic 4-bit binary Adder-Subtractor Flip-flop types, their Conversion and Applications Counters in Digital Logic vector::push_back() and vector::pop_back() in C++ STL Top 10 algorithms in Interview Questions Overview of Data Structures | Set 1 (Linear Data Structures) How to write Regular Expressions? Minimax Algorithm in Game Theory | Set 3 (Tic-Tac-Toe AI - Finding optimal move)
[ { "code": null, "e": 25723, "s": 25695, "text": "\n06 Oct, 2020" }, { "code": null, "e": 26054, "s": 25723, "text": "In communication system, analog signals travel through transmission media, which tends to deteriorate the quality of analog signal, which means that the signal at the beginning of the medium is not the same as the signal at the end of the medium. The imperfection causes signal impairment. Below are the causes of the impairment." }, { "code": null, "e": 26078, "s": 26054, "text": "Causes of impairment – " }, { "code": null, "e": 26405, "s": 26082, "text": "Attenuation – It means loss of energy. The strength of signal decreases with increasing distance which causes loss of energy in overcoming resistance of medium. This is also known as attenuated signal. Amplifiers are used to amplify the attenuated signal which gives the original signal back and compensate for this loss. " }, { "code": null, "e": 26567, "s": 26407, "text": "Image Source – aviationchief Attenuation is measured in decibels(dB). It measures the relative strengths of two signals or one signal at two different point. " }, { "code": null, "e": 26698, "s": 26567, "text": "Attenuation is measured in decibels(dB). It measures the relative strengths of two signals or one signal at two different point. " }, { "code": null, "e": 26731, "s": 26698, "text": "Attenuation(dB) = 10log10(P2/P1)" }, { "code": null, "e": 26801, "s": 26731, "text": "P1 is the power at sending end and P2 is the power at receiving end." }, { "code": null, "e": 26965, "s": 26801, "text": "Some where the decibel is also define in terms of voltage instead of power.In this case because power is proportional to the square of the voltage the formula is " }, { "code": null, "e": 26998, "s": 26965, "text": "Attenuation(dB) = 20log10(V2/V1)" }, { "code": null, "e": 27071, "s": 26998, "text": "V1 is the voltage at sending end and V2 is the voltage at receiving end." }, { "code": null, "e": 27520, "s": 27071, "text": "Distortion – It means changes in the form or shape of the signal. This is generally seen in composite signals made up with different frequencies. Each frequency component has its own propagation speed travelling through a medium. And thats why it delay in arriving at the final destination Every component arrive at different time which leads to distortion. Therefore, they have different phases at receiver end from what they had at senders end. " }, { "code": null, "e": 28123, "s": 27522, "text": "Noise – The random or unwanted signal that mixes up with the original signal is called noise. There are several types of noise such as induced noise, crosstalk noise, thermal noise and impulse noise which may corrupt the signal. Induced noise comes from sources such as motors and appliances. These devices act as sending antenna and transmission medium act as receiving antenna. Thermal noise is movement of electrons in wire which creates an extra signal. Crosstalk noise is when one wire affects the other wire. Impulse noise is a signal with high energy that comes from lightning or power lines " }, { "code": null, "e": 28495, "s": 28123, "text": "Induced noise comes from sources such as motors and appliances. These devices act as sending antenna and transmission medium act as receiving antenna. Thermal noise is movement of electrons in wire which creates an extra signal. Crosstalk noise is when one wire affects the other wire. Impulse noise is a signal with high energy that comes from lightning or power lines " }, { "code": null, "e": 28604, "s": 28495, "text": "To find the theoretical bit rate limit, we need to know the ration .The signal-to-noise ratio is defined as " }, { "code": null, "e": 28652, "s": 28604, "text": " SNR = AVG SIGNAL POWER / AVG NOISE POWER \n\n\n" }, { "code": null, "e": 28759, "s": 28652, "text": "References – Data Communication and Networking Fourth edition by Forouzan Data Communication – Slideshare " }, { "code": null, "e": 28781, "s": 28759, "text": "pulkitagarwal03pulkit" }, { "code": null, "e": 28816, "s": 28781, "text": "Digital Electronics & Logic Design" }, { "code": null, "e": 28821, "s": 28816, "text": "Misc" }, { "code": null, "e": 28840, "s": 28821, "text": "Technical Scripter" }, { "code": null, "e": 28845, "s": 28840, "text": "Misc" }, { "code": null, "e": 28850, "s": 28845, "text": "Misc" }, { "code": null, "e": 28948, "s": 28850, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28989, "s": 28948, "text": "IEEE Standard 754 Floating Point Numbers" }, { "code": null, "e": 29022, "s": 28989, "text": "Shift Registers in Digital Logic" }, { "code": null, "e": 29052, "s": 29022, "text": "4-bit binary Adder-Subtractor" }, { "code": null, "e": 29103, "s": 29052, "text": "Flip-flop types, their Conversion and Applications" }, { "code": null, "e": 29129, "s": 29103, "text": "Counters in Digital Logic" }, { "code": null, "e": 29183, "s": 29129, "text": "vector::push_back() and vector::pop_back() in C++ STL" }, { "code": null, "e": 29224, "s": 29183, "text": "Top 10 algorithms in Interview Questions" }, { "code": null, "e": 29285, "s": 29224, "text": "Overview of Data Structures | Set 1 (Linear Data Structures)" }, { "code": null, "e": 29319, "s": 29285, "text": "How to write Regular Expressions?" } ]
Robot Class in Java AWT - GeeksforGeeks
12 May, 2022 The Robot class in the Java AWT package is used to generate native system input events for the purposes of test automation, self-running demos, and other applications where control of the mouse and keyboard is needed. The primary purpose of Robot is to facilitate automated testing of Java platform implementations. In simple terms, the class provides control over the mouse and keyboard devices. Here is an example of how the Robot class takes control of the keyboard and types out into a blank Notepad document. Notepad is called using Process and Runtime, as discussed in this article. Java // Java program to demonstrate working of Robot// class. This program is for Windows. It opens// notepad and types a message.import java.awt.AWTException;import java.awt.Robot;import java.awt.event.KeyEvent;import java.io.*; public class robo{ public static void main(String[] args) throws IOException, AWTException, InterruptedException { String command = "notepad.exe"; Runtime run = Runtime.getRuntime(); run.exec(command); try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Create an instance of Robot class Robot robot = new Robot(); // Press keys using robot. A gap of // of 500 milli seconds is added after // every key press robot.keyPress(KeyEvent.VK_H); Thread.sleep(500); robot.keyPress(KeyEvent.VK_E); Thread.sleep(500); robot.keyPress(KeyEvent.VK_L); Thread.sleep(500); robot.keyPress(KeyEvent.VK_L); Thread.sleep(500); robot.keyPress(KeyEvent.VK_O); Thread.sleep(500); robot.keyPress(KeyEvent.VK_SPACE); Thread.sleep(500); robot.keyPress(KeyEvent.VK_F); Thread.sleep(500); robot.keyPress(KeyEvent.VK_R); Thread.sleep(500); robot.keyPress(KeyEvent.VK_O); Thread.sleep(500); robot.keyPress(KeyEvent.VK_M); Thread.sleep(500); robot.keyPress(KeyEvent.VK_SPACE); Thread.sleep(500); robot.keyPress(KeyEvent.VK_G); Thread.sleep(500); robot.keyPress(KeyEvent.VK_E); Thread.sleep(500); robot.keyPress(KeyEvent.VK_E); Thread.sleep(500); robot.keyPress(KeyEvent.VK_K); Thread.sleep(500); robot.keyPress(KeyEvent.VK_S); Thread.sleep(500); robot.keyPress(KeyEvent.VK_F); Thread.sleep(500); robot.keyPress(KeyEvent.VK_O); Thread.sleep(500); robot.keyPress(KeyEvent.VK_R); Thread.sleep(500); robot.keyPress(KeyEvent.VK_G); Thread.sleep(500); robot.keyPress(KeyEvent.VK_E); Thread.sleep(500); robot.keyPress(KeyEvent.VK_E); Thread.sleep(500); robot.keyPress(KeyEvent.VK_K); Thread.sleep(500); robot.keyPress(KeyEvent.VK_S); }} Output: The code opens a blank Notepad file and types "hello from geeksforgeeks" onto it with a delay of 500 ms before typing out each character. You might have already found out that the code has become really lengthy for writing a small string. In that case we can store the message in a string and iterate it and display. To press the capital letters we have to press down the shift key, press the key and then release the shift key. The same can be done for symbols too. Java import java.awt.*;import java.awt.event.KeyEvent; class Robo { // Our custom sleep method public static void sleep(long ms) { try {Thread.sleep(ms);} catch (Exception ignored) {} } public static void main(String[] args) throws Exception { // Open Notepad Runtime.getRuntime().exec("notepad.exe"); // Wait for 2 seconds sleep(2000); // Create instance of Robot class Robot robot = new Robot(); // The String to type String str = "Hello from GeeksforGeeks"; // Press keys using robot // A gap of 200ms is added between each key press for (int i = 0; i < str.length(); i++) { // Check if the current character is a capital letter if (Character.isUpperCase(str.charAt(i))) { // Press shift key robot.keyPress(KeyEvent.VK_SHIFT); // Press the current character robot.keyPress(Character.toUpperCase(str.charAt(i))); // Release shift key robot.keyRelease(KeyEvent.VK_SHIFT); } // else display the character as it is else robot.keyPress(Character.toUpperCase(str.charAt(i))); // wait for 200ms sleep(200); } }} This opens the Notepad and types the same thing with a 200ms gap between characters. This approach is better when working with larger items. This article is contributed by Anannya Uberoi. 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. simranarora5sos ruthvikas2431 Java-Library Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Interfaces in Java Initialize an ArrayList in Java ArrayList in Java Stack Class in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java Multithreading in Java Initializing a List in Java
[ { "code": null, "e": 25779, "s": 25751, "text": "\n12 May, 2022" }, { "code": null, "e": 26176, "s": 25779, "text": "The Robot class in the Java AWT package is used to generate native system input events for the purposes of test automation, self-running demos, and other applications where control of the mouse and keyboard is needed. The primary purpose of Robot is to facilitate automated testing of Java platform implementations. In simple terms, the class provides control over the mouse and keyboard devices." }, { "code": null, "e": 26368, "s": 26176, "text": "Here is an example of how the Robot class takes control of the keyboard and types out into a blank Notepad document. Notepad is called using Process and Runtime, as discussed in this article." }, { "code": null, "e": 26373, "s": 26368, "text": "Java" }, { "code": "// Java program to demonstrate working of Robot// class. This program is for Windows. It opens// notepad and types a message.import java.awt.AWTException;import java.awt.Robot;import java.awt.event.KeyEvent;import java.io.*; public class robo{ public static void main(String[] args) throws IOException, AWTException, InterruptedException { String command = \"notepad.exe\"; Runtime run = Runtime.getRuntime(); run.exec(command); try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Create an instance of Robot class Robot robot = new Robot(); // Press keys using robot. A gap of // of 500 milli seconds is added after // every key press robot.keyPress(KeyEvent.VK_H); Thread.sleep(500); robot.keyPress(KeyEvent.VK_E); Thread.sleep(500); robot.keyPress(KeyEvent.VK_L); Thread.sleep(500); robot.keyPress(KeyEvent.VK_L); Thread.sleep(500); robot.keyPress(KeyEvent.VK_O); Thread.sleep(500); robot.keyPress(KeyEvent.VK_SPACE); Thread.sleep(500); robot.keyPress(KeyEvent.VK_F); Thread.sleep(500); robot.keyPress(KeyEvent.VK_R); Thread.sleep(500); robot.keyPress(KeyEvent.VK_O); Thread.sleep(500); robot.keyPress(KeyEvent.VK_M); Thread.sleep(500); robot.keyPress(KeyEvent.VK_SPACE); Thread.sleep(500); robot.keyPress(KeyEvent.VK_G); Thread.sleep(500); robot.keyPress(KeyEvent.VK_E); Thread.sleep(500); robot.keyPress(KeyEvent.VK_E); Thread.sleep(500); robot.keyPress(KeyEvent.VK_K); Thread.sleep(500); robot.keyPress(KeyEvent.VK_S); Thread.sleep(500); robot.keyPress(KeyEvent.VK_F); Thread.sleep(500); robot.keyPress(KeyEvent.VK_O); Thread.sleep(500); robot.keyPress(KeyEvent.VK_R); Thread.sleep(500); robot.keyPress(KeyEvent.VK_G); Thread.sleep(500); robot.keyPress(KeyEvent.VK_E); Thread.sleep(500); robot.keyPress(KeyEvent.VK_E); Thread.sleep(500); robot.keyPress(KeyEvent.VK_K); Thread.sleep(500); robot.keyPress(KeyEvent.VK_S); }}", "e": 28759, "s": 26373, "text": null }, { "code": null, "e": 28768, "s": 28759, "text": "Output: " }, { "code": null, "e": 28909, "s": 28768, "text": "The code opens a blank Notepad file and types \n\"hello from geeksforgeeks\" onto it with a delay\nof 500 ms before typing out each character.\n " }, { "code": null, "e": 29238, "s": 28909, "text": "You might have already found out that the code has become really lengthy for writing a small string. In that case we can store the message in a string and iterate it and display. To press the capital letters we have to press down the shift key, press the key and then release the shift key. The same can be done for symbols too." }, { "code": null, "e": 29243, "s": 29238, "text": "Java" }, { "code": "import java.awt.*;import java.awt.event.KeyEvent; class Robo { // Our custom sleep method public static void sleep(long ms) { try {Thread.sleep(ms);} catch (Exception ignored) {} } public static void main(String[] args) throws Exception { // Open Notepad Runtime.getRuntime().exec(\"notepad.exe\"); // Wait for 2 seconds sleep(2000); // Create instance of Robot class Robot robot = new Robot(); // The String to type String str = \"Hello from GeeksforGeeks\"; // Press keys using robot // A gap of 200ms is added between each key press for (int i = 0; i < str.length(); i++) { // Check if the current character is a capital letter if (Character.isUpperCase(str.charAt(i))) { // Press shift key robot.keyPress(KeyEvent.VK_SHIFT); // Press the current character robot.keyPress(Character.toUpperCase(str.charAt(i))); // Release shift key robot.keyRelease(KeyEvent.VK_SHIFT); } // else display the character as it is else robot.keyPress(Character.toUpperCase(str.charAt(i))); // wait for 200ms sleep(200); } }}", "e": 30520, "s": 29243, "text": null }, { "code": null, "e": 30661, "s": 30520, "text": "This opens the Notepad and types the same thing with a 200ms gap between characters. This approach is better when working with larger items." }, { "code": null, "e": 30959, "s": 30661, "text": "This article is contributed by Anannya Uberoi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 31084, "s": 30959, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 31100, "s": 31084, "text": "simranarora5sos" }, { "code": null, "e": 31114, "s": 31100, "text": "ruthvikas2431" }, { "code": null, "e": 31127, "s": 31114, "text": "Java-Library" }, { "code": null, "e": 31132, "s": 31127, "text": "Java" }, { "code": null, "e": 31137, "s": 31132, "text": "Java" }, { "code": null, "e": 31235, "s": 31137, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31250, "s": 31235, "text": "Stream In Java" }, { "code": null, "e": 31269, "s": 31250, "text": "Interfaces in Java" }, { "code": null, "e": 31301, "s": 31269, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 31319, "s": 31301, "text": "ArrayList in Java" }, { "code": null, "e": 31339, "s": 31319, "text": "Stack Class in Java" }, { "code": null, "e": 31363, "s": 31339, "text": "Singleton Class in Java" }, { "code": null, "e": 31395, "s": 31363, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 31407, "s": 31395, "text": "Set in Java" }, { "code": null, "e": 31430, "s": 31407, "text": "Multithreading in Java" } ]
Sorting Algorithms Visualization | Selection Sort - GeeksforGeeks
09 Sep, 2019 Pre-requisite: Selection Sort The human brain can easily process visuals in spite of long codes to understand the algorithms. In this article, Selection Sort visualization has been implemented using graphics.h library. As we all know selection sort first finds the minimum element from the unsorted array and swaps it with the first element of the unsorted array in each pass. It becomes difficult to analyze the data manually between two algorithms or vice versa, but plotting graphically it is much easier to understand. Approach: The white line is used to represent the length of number (9 being represented by 9 pixels vertically upwards) while its position represents its index in the array. Graphical representation of randomly distributed numbers is shown below. Graphically sorting can be shown by first coloring the minimum element from unsorted array as green color. Now swap it with the first element of unsorted array and also swap the color for those two number as shown in code by swap_colors() function. Here delay() can be increased to see the transition in the graph. Examples: Pre-defined Functions Used: setcurrentwindow(): A function which is used to set the size of current window. setcolor(n): A function which is used to change the color of cursor by changing the value of n. delay(n): A function which is used to delay the program by n milliseconds. It is being used for slowing down the transitions speed line(x1, y1, x2, y2): A function which is used to draw an line from point (x1, y1) to point (x2, y2). (0, 0) being the left top corner of the screen and bottom right be (n1, n2) where n1, n2 are the width and height of the current window. There are other graphics which can be applied to this line using setcolor(). Below is the program to visualize the Selection Sort algorithm: // C++ program for visualization// of bubble sort #include "graphics.h"#include <bits/stdc++.h> using namespace std; // Initialize the size// with the total numbers to sorted// and the gap to be maintained in graphvector<int> numbers;int size = 200;int gap = 4; // Function for swapping the lines graphicallyvoid swap_colors(int i, int j, int x, int y){ // y is the minimum element, // first make this number green // Now, swapping it by making black again // and then draw the pixels // for white colour with x value. setcolor(GREEN); line(j, size, j, size - y); delay(500); setcolor(BLACK); line(j, size, j, size - y); setcolor(WHITE); line(j, size, j, size - x); // X is the element to be swapped, // first make this number black // Now, highlight y with green // representing the minimum element // and then draw the pixels // for white colour with y value. setcolor(BLACK); line(i, size, i, size - x); setcolor(GREEN); line(i, size, i, size - y); delay(500); setcolor(WHITE); line(i, size, i, size - y);} // Function for swapping two numbersvoid swap(int* xp, int* yp){ int temp = *xp; *xp = *yp; *yp = temp;} // Selection sort functionvoid selsort(){ for (int i = 0; i < size - 1; i++) { // Find the minimum element // in unsorted array int min_idx = i; for (int j = i + 1; j < size; j++) { if (numbers[j] < numbers[min_idx]) { min_idx = j; } } // Swap the found minimum element // with the first element // delay(500); swap(&numbers[min_idx], &numbers[i]); // Function to show transition in swapping swap_colors(gap * i + 1, gap * (min_idx) + 1, numbers[min_idx], numbers[i]); }} // Driver programint main(){ // auto detection of screen size int gd = DETECT, gm; int wid1; // Graph initialization initgraph(&gd, &gm, NULL); // setting up window size (gap*size) * (size) wid1 = initwindow(gap * size + 1, size + 1); setcurrentwindow(wid1); // Initializing the array for (int i = 1; i <= size; i++) numbers.push_back(i); // Find a seed and shuffle the array // to make it random. // Here different type of array // can be taken to results // such as nearly sorted, already sorted, // reverse sorted to visualize the result unsigned seed = chrono::system_clock::now() .time_since_epoch() .count(); shuffle(numbers.begin(), numbers.end(), default_random_engine(seed)); // Initial plot of numbers in graph taking // the vector position as x-axis and its // corresponding value will be the height of line. for (int i = 1; i <= gap * size; i += gap) { line(i, size, i, (size - numbers[i / gap])); } // Delay the code delay(200); // Call sort selSort(); for (int i = 0; i < size; i++) { cout << numbers[i] << " "; } cout << endl; // Wait for sometime . delay(5000); // Close the graph closegraph(); return 0;} 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 3031 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 5758 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 8485 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188189 190 191 192 193 194 195 196 197 198 199 200 Visualization: Input Visualization:Unsorted Array Unsorted Array Output Visualization:Sorting the array using Selection Sort Sorting the array using Selection Sort selection-sort Algorithms Data Structures Sorting Data Structures Sorting Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar How to Start Learning DSA? Difference between Algorithm, Pseudocode and Program K means Clustering - Introduction Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete DSA Sheet by Love Babbar Doubly Linked List | Set 1 (Introduction and Insertion) How to Start Learning DSA? Implementing a Linked List in Java using Class Abstract Data Types
[ { "code": null, "e": 25917, "s": 25889, "text": "\n09 Sep, 2019" }, { "code": null, "e": 25947, "s": 25917, "text": "Pre-requisite: Selection Sort" }, { "code": null, "e": 26440, "s": 25947, "text": "The human brain can easily process visuals in spite of long codes to understand the algorithms. In this article, Selection Sort visualization has been implemented using graphics.h library. As we all know selection sort first finds the minimum element from the unsorted array and swaps it with the first element of the unsorted array in each pass. It becomes difficult to analyze the data manually between two algorithms or vice versa, but plotting graphically it is much easier to understand." }, { "code": null, "e": 26450, "s": 26440, "text": "Approach:" }, { "code": null, "e": 26614, "s": 26450, "text": "The white line is used to represent the length of number (9 being represented by 9 pixels vertically upwards) while its position represents its index in the array." }, { "code": null, "e": 26687, "s": 26614, "text": "Graphical representation of randomly distributed numbers is shown below." }, { "code": null, "e": 26794, "s": 26687, "text": "Graphically sorting can be shown by first coloring the minimum element from unsorted array as green color." }, { "code": null, "e": 26936, "s": 26794, "text": "Now swap it with the first element of unsorted array and also swap the color for those two number as shown in code by swap_colors() function." }, { "code": null, "e": 27002, "s": 26936, "text": "Here delay() can be increased to see the transition in the graph." }, { "code": null, "e": 27012, "s": 27002, "text": "Examples:" }, { "code": null, "e": 27040, "s": 27012, "text": "Pre-defined Functions Used:" }, { "code": null, "e": 27120, "s": 27040, "text": "setcurrentwindow(): A function which is used to set the size of current window." }, { "code": null, "e": 27216, "s": 27120, "text": "setcolor(n): A function which is used to change the color of cursor by changing the value of n." }, { "code": null, "e": 27347, "s": 27216, "text": "delay(n): A function which is used to delay the program by n milliseconds. It is being used for slowing down the transitions speed" }, { "code": null, "e": 27663, "s": 27347, "text": "line(x1, y1, x2, y2): A function which is used to draw an line from point (x1, y1) to point (x2, y2). (0, 0) being the left top corner of the screen and bottom right be (n1, n2) where n1, n2 are the width and height of the current window. There are other graphics which can be applied to this line using setcolor()." }, { "code": null, "e": 27727, "s": 27663, "text": "Below is the program to visualize the Selection Sort algorithm:" }, { "code": "// C++ program for visualization// of bubble sort #include \"graphics.h\"#include <bits/stdc++.h> using namespace std; // Initialize the size// with the total numbers to sorted// and the gap to be maintained in graphvector<int> numbers;int size = 200;int gap = 4; // Function for swapping the lines graphicallyvoid swap_colors(int i, int j, int x, int y){ // y is the minimum element, // first make this number green // Now, swapping it by making black again // and then draw the pixels // for white colour with x value. setcolor(GREEN); line(j, size, j, size - y); delay(500); setcolor(BLACK); line(j, size, j, size - y); setcolor(WHITE); line(j, size, j, size - x); // X is the element to be swapped, // first make this number black // Now, highlight y with green // representing the minimum element // and then draw the pixels // for white colour with y value. setcolor(BLACK); line(i, size, i, size - x); setcolor(GREEN); line(i, size, i, size - y); delay(500); setcolor(WHITE); line(i, size, i, size - y);} // Function for swapping two numbersvoid swap(int* xp, int* yp){ int temp = *xp; *xp = *yp; *yp = temp;} // Selection sort functionvoid selsort(){ for (int i = 0; i < size - 1; i++) { // Find the minimum element // in unsorted array int min_idx = i; for (int j = i + 1; j < size; j++) { if (numbers[j] < numbers[min_idx]) { min_idx = j; } } // Swap the found minimum element // with the first element // delay(500); swap(&numbers[min_idx], &numbers[i]); // Function to show transition in swapping swap_colors(gap * i + 1, gap * (min_idx) + 1, numbers[min_idx], numbers[i]); }} // Driver programint main(){ // auto detection of screen size int gd = DETECT, gm; int wid1; // Graph initialization initgraph(&gd, &gm, NULL); // setting up window size (gap*size) * (size) wid1 = initwindow(gap * size + 1, size + 1); setcurrentwindow(wid1); // Initializing the array for (int i = 1; i <= size; i++) numbers.push_back(i); // Find a seed and shuffle the array // to make it random. // Here different type of array // can be taken to results // such as nearly sorted, already sorted, // reverse sorted to visualize the result unsigned seed = chrono::system_clock::now() .time_since_epoch() .count(); shuffle(numbers.begin(), numbers.end(), default_random_engine(seed)); // Initial plot of numbers in graph taking // the vector position as x-axis and its // corresponding value will be the height of line. for (int i = 1; i <= gap * size; i += gap) { line(i, size, i, (size - numbers[i / gap])); } // Delay the code delay(200); // Call sort selSort(); for (int i = 0; i < size; i++) { cout << numbers[i] << \" \"; } cout << endl; // Wait for sometime . delay(5000); // Close the graph closegraph(); return 0;}", "e": 30948, "s": 27727, "text": null }, { "code": null, "e": 31632, "s": 30948, "text": "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 3031 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 5758 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 8485 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188189 190 191 192 193 194 195 196 197 198 199 200" }, { "code": null, "e": 31647, "s": 31632, "text": "Visualization:" }, { "code": null, "e": 31682, "s": 31647, "text": "Input Visualization:Unsorted Array" }, { "code": null, "e": 31697, "s": 31682, "text": "Unsorted Array" }, { "code": null, "e": 31757, "s": 31697, "text": "Output Visualization:Sorting the array using Selection Sort" }, { "code": null, "e": 31796, "s": 31757, "text": "Sorting the array using Selection Sort" }, { "code": null, "e": 31811, "s": 31796, "text": "selection-sort" }, { "code": null, "e": 31822, "s": 31811, "text": "Algorithms" }, { "code": null, "e": 31838, "s": 31822, "text": "Data Structures" }, { "code": null, "e": 31846, "s": 31838, "text": "Sorting" }, { "code": null, "e": 31862, "s": 31846, "text": "Data Structures" }, { "code": null, "e": 31870, "s": 31862, "text": "Sorting" }, { "code": null, "e": 31881, "s": 31870, "text": "Algorithms" }, { "code": null, "e": 31979, "s": 31881, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32004, "s": 31979, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 32031, "s": 32004, "text": "How to Start Learning DSA?" }, { "code": null, "e": 32084, "s": 32031, "text": "Difference between Algorithm, Pseudocode and Program" }, { "code": null, "e": 32118, "s": 32084, "text": "K means Clustering - Introduction" }, { "code": null, "e": 32185, "s": 32118, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" }, { "code": null, "e": 32210, "s": 32185, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 32266, "s": 32210, "text": "Doubly Linked List | Set 1 (Introduction and Insertion)" }, { "code": null, "e": 32293, "s": 32266, "text": "How to Start Learning DSA?" }, { "code": null, "e": 32340, "s": 32293, "text": "Implementing a Linked List in Java using Class" } ]
GATE | GATE CS 2020 | Question 27 - GeeksforGeeks
26 May, 2021 Let R be the set of all binary relations on the set {1, 2, 3}. Suppose a relation is chosen from R at random. The probability that the chosen relation is reflexive (round off to 3 decimal places) is ________ . Note – This question was Numerical Type.(A) 0.125(B) 0.25(C) 0.50(D) 0.625Answer: (A)Explanation: The probability that the chosen relation is reflexive on a set with n elements: = (number of reflexive relations) / (total number of relations) = (2n2-n) / (2n2) Given, size (number of elements) of set is 3 (i.e., {1, 2, 3}). Therefore, = (232-3) / (232) = (26) / (29) = 1 / (23) = 1 / 8 = 0.125 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. GATE | Gate IT 2007 | Question 25 GATE | GATE-CS-2001 | Question 39 GATE | GATE-CS-2000 | Question 41 GATE | GATE-CS-2005 | Question 6 GATE | GATE MOCK 2017 | Question 21 GATE | GATE-CS-2006 | Question 47 GATE | GATE MOCK 2017 | Question 24 GATE | Gate IT 2008 | Question 43 GATE | GATE-CS-2009 | Question 38 GATE | GATE-CS-2003 | Question 90
[ { "code": null, "e": 25743, "s": 25715, "text": "\n26 May, 2021" }, { "code": null, "e": 25953, "s": 25743, "text": "Let R be the set of all binary relations on the set {1, 2, 3}. Suppose a relation is chosen from R at random. The probability that the chosen relation is reflexive (round off to 3 decimal places) is ________ ." }, { "code": null, "e": 26131, "s": 25953, "text": "Note – This question was Numerical Type.(A) 0.125(B) 0.25(C) 0.50(D) 0.625Answer: (A)Explanation: The probability that the chosen relation is reflexive on a set with n elements:" }, { "code": null, "e": 26214, "s": 26131, "text": "= (number of reflexive relations) / (total number of relations)\n= (2n2-n) / (2n2) " }, { "code": null, "e": 26289, "s": 26214, "text": "Given, size (number of elements) of set is 3 (i.e., {1, 2, 3}). Therefore," }, { "code": null, "e": 26350, "s": 26289, "text": "= (232-3) / (232) \n= (26) / (29)\n= 1 / (23)\n= 1 / 8\n= 0.125 " }, { "code": null, "e": 26394, "s": 26350, "text": "Option (A) is correct.Quiz of this Question" }, { "code": null, "e": 26399, "s": 26394, "text": "GATE" }, { "code": null, "e": 26497, "s": 26399, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26531, "s": 26497, "text": "GATE | Gate IT 2007 | Question 25" }, { "code": null, "e": 26565, "s": 26531, "text": "GATE | GATE-CS-2001 | Question 39" }, { "code": null, "e": 26599, "s": 26565, "text": "GATE | GATE-CS-2000 | Question 41" }, { "code": null, "e": 26632, "s": 26599, "text": "GATE | GATE-CS-2005 | Question 6" }, { "code": null, "e": 26668, "s": 26632, "text": "GATE | GATE MOCK 2017 | Question 21" }, { "code": null, "e": 26702, "s": 26668, "text": "GATE | GATE-CS-2006 | Question 47" }, { "code": null, "e": 26738, "s": 26702, "text": "GATE | GATE MOCK 2017 | Question 24" }, { "code": null, "e": 26772, "s": 26738, "text": "GATE | Gate IT 2008 | Question 43" }, { "code": null, "e": 26806, "s": 26772, "text": "GATE | GATE-CS-2009 | Question 38" } ]
Flutter - Slidable - GeeksforGeeks
15 Feb, 2021 Slidable in an application can be used to perform a wide range of tasks with just a simple swipe to either right or left on the tile. It not only makes the UI very user-friendly but also saves a lot of time in doing trivial tasks which if done in other ways can be hectic and redundant to design. In this article, we will look into the process of designing a slidable for your application. Here we will build a simple application with tiles that when swiped left to right archives the tile and when swiped right to left deletes the tile. To do so follow the below steps: Add the flutter_slidable dependency to the pubspec.yaml file. Import the dependency to the main.dart file Create a StatelessWidget to give the app a structure Use a StateFulWidget to add a Homepage to the application Use SlidableCntroller to set up the slide actions Use FloatingActionButton to assign actions to the buttons generated while sliding the tile Use the WidgetBuilder to build the tiles on the homepage Let’s discuss the steps in detail. You can import the flutter_slidable dependency in the pubspec.yaml file as shown below: To import the dependency in the main.dart file use the following: import 'package:flutter_slidable/flutter_slidable.dart'; Use a StatelessWidget to give the application a simple structure as shown below: Dart class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Slidable ', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'GeeksForGeeks'), ); }} Use a StatefulWidget to set up the homepage for the application that would in the future hold the tiles that can be swiped in either direction to perform tasks assigned to them as shown below: Dart class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> { SlidableController slidableController; final List<_HomeItem> items = List.generate( 20, (i) => _HomeItem( i, 'Slide Bar $i', _getSubtitle(i), _getAvatarColor(i), ), ); Use the SlidableController to setup the slides for the application. It can be done by the use of either Slidable Constructor or Slidable.builder Constructor. The app we are building has 4 essential components : Slide ActionsA slide Action panel widgetAn extent ratio between a slide action extent and the item extent.A child Slide Actions A slide Action panel widget An extent ratio between a slide action extent and the item extent. A child To design the slidable use the following: Dart Slidable( actionPane: SlidableDrawerActionPane(), actionExtentRatio: 0.25, child: Container( color: Colors.white, child: ListTile( leading: CircleAvatar( backgroundColor: Colors.indigoAccent, child: Text('$3'), foregroundColor: Colors.white, ), title: Text('Tile $3'), subtitle: Text('SlidableDrawerDelegate'), ), ), actions: <Widget>[ IconSlideAction( caption: 'Archive', color: Colors.blue, icon: Icons.archive, onTap: () => _showSnackBar('Archive'), ), IconSlideAction( caption: 'Share', color: Colors.indigo, icon: Icons.share, onTap: () => _showSnackBar('Share'), ), ], secondaryActions: <Widget>[ IconSlideAction( caption: 'More', color: Colors.black45, icon: Icons.more_horiz, onTap: () => _showSnackBar('More'), ), IconSlideAction( caption: 'Delete', color: Colors.red, icon: Icons.delete, onTap: () => _showSnackBar('Delete'), ), ],); As the slides are swiped a FloatingActionButton will appear depending upon the direction of the slide. In both the case two actions will be assigned to each swipe as following: For left to right slide: Archive tileShare tile Archive tile Share tile For the right to left slide: Delete tileMore Delete tile More For the sake of simplicity, we will only assign actions to the Archive tile button and delete the tile button which will archive and delete the tile respectively. To do so use the following: Dart @protectedvoid initState() { slidableController = SlidableController( onSlideAnimationChanged: handleSlideAnimationChanged, onSlideIsOpenChanged: handleSlideIsOpenChanged, ); super.initState();} Animation<double> _rotationAnimation;Color _fabColor = Colors.blue; void handleSlideAnimationChanged(Animation<double> slideAnimation) { setState(() { _rotationAnimation = slideAnimation; });} void handleSlideIsOpenChanged(bool isOpen) { setState(() { _fabColor = isOpen ? Colors.green : Colors.blue; });} @overrideWidget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), backgroundColor: Colors.green, ), body: Center( child: OrientationBuilder( builder: (context, orientation) => _buildList( context, orientation == Orientation.portrait ? Axis.vertical : Axis.horizontal), ), ), floatingActionButton: FloatingActionButton( backgroundColor: _fabColor, onPressed: null, child: _rotationAnimation == null ? Icon(Icons.add) : RotationTransition( turns: _rotationAnimation, child: Icon(Icons.add), ), ), );} Widget _buildList(BuildContext context, Axis direction) { return ListView.builder( scrollDirection: direction, itemBuilder: (context, index) { final Axis slidableDirection = direction == Axis.horizontal ? Axis.vertical : Axis.horizontal; var item = items[index]; if (item.index < 8) { return _getSlidableWithLists(context, index, slidableDirection); } else { return _getSlidableWithDelegates(context, index, slidableDirection); } }, itemCount: items.length, );} Widget _getSlidableWithLists( BuildContext context, int index, Axis direction) { final _HomeItem item = items[index]; return Slidable( key: Key(item.title), controller: slidableController, direction: direction, dismissal: SlidableDismissal( child: SlidableDrawerDismissal(), onDismissed: (actionType) { _showSnackBar( context, actionType == SlideActionType.primary ? 'Dismiss Archive' : 'Dismiss Delete'); setState(() { items.removeAt(index); }); }, ), actionPane: _getActionPane(item.index), actionExtentRatio: 0.25, child: direction == Axis.horizontal ? VerticalListItem(items[index]) : HorizontalListItem(items[index]), actions: <Widget>[ IconSlideAction( caption: 'Archive', color: Colors.blue, icon: Icons.archive, onTap: () => _showSnackBar(context, 'Archive'), ), IconSlideAction( caption: 'Share', color: Colors.indigo, icon: Icons.share, onTap: () => _showSnackBar(context, 'Share'), ), ], secondaryActions: <Widget>[ Container( height: 800, color: Colors.green, child: Text('a'), ), IconSlideAction( caption: 'More', color: Colors.grey.shade200, icon: Icons.more_horiz, onTap: () => _showSnackBar(context, 'More'), closeOnTap: false, ), IconSlideAction( caption: 'Delete', color: Colors.red, icon: Icons.delete, onTap: () => _showSnackBar(context, 'Delete'), ), ], );} Complete Source Code: Dart import 'package:flutter/material.dart';import 'package:flutter_slidable/flutter_slidable.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Slidable ', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'GeeksForGeeks'), ); }} class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> { SlidableController slidableController; final List<_HomeItem> items = List.generate( 20, (i) => _HomeItem( i, 'Slide Bar $i', _getSubtitle(i), _getAvatarColor(i), ), ); @protected void initState() { slidableController = SlidableController( onSlideAnimationChanged: handleSlideAnimationChanged, onSlideIsOpenChanged: handleSlideIsOpenChanged, ); super.initState(); } Animation<double> _rotationAnimation; Color _fabColor = Colors.blue; void handleSlideAnimationChanged(Animation<double> slideAnimation) { setState(() { _rotationAnimation = slideAnimation; }); } void handleSlideIsOpenChanged(bool isOpen) { setState(() { _fabColor = isOpen ? Colors.green : Colors.blue; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), backgroundColor: Colors.green, ), body: Center( child: OrientationBuilder( builder: (context, orientation) => _buildList( context, orientation == Orientation.portrait ? Axis.vertical : Axis.horizontal), ), ), floatingActionButton: FloatingActionButton( backgroundColor: _fabColor, onPressed: null, child: _rotationAnimation == null ? Icon(Icons.add) : RotationTransition( turns: _rotationAnimation, child: Icon(Icons.add), ), ), ); } Widget _buildList(BuildContext context, Axis direction) { return ListView.builder( scrollDirection: direction, itemBuilder: (context, index) { final Axis slidableDirection = direction == Axis.horizontal ? Axis.vertical : Axis.horizontal; var item = items[index]; if (item.index < 8) { return _getSlidableWithLists(context, index, slidableDirection); } else { return _getSlidableWithDelegates(context, index, slidableDirection); } }, itemCount: items.length, ); } Widget _getSlidableWithLists( BuildContext context, int index, Axis direction) { final _HomeItem item = items[index]; //final int t = index; return Slidable( key: Key(item.title), controller: slidableController, direction: direction, dismissal: SlidableDismissal( child: SlidableDrawerDismissal(), onDismissed: (actionType) { _showSnackBar( context, actionType == SlideActionType.primary ? 'Dismiss Archive' : 'Dismiss Delete'); setState(() { items.removeAt(index); }); }, ), actionPane: _getActionPane(item.index), actionExtentRatio: 0.25, child: direction == Axis.horizontal ? VerticalListItem(items[index]) : HorizontalListItem(items[index]), actions: <Widget>[ IconSlideAction( caption: 'Archive', color: Colors.blue, icon: Icons.archive, onTap: () => _showSnackBar(context, 'Archive'), ), IconSlideAction( caption: 'Share', color: Colors.indigo, icon: Icons.share, onTap: () => _showSnackBar(context, 'Share'), ), ], secondaryActions: <Widget>[ Container( height: 800, color: Colors.green, child: Text('a'), ), IconSlideAction( caption: 'More', color: Colors.grey.shade200, icon: Icons.more_horiz, onTap: () => _showSnackBar(context, 'More'), closeOnTap: false, ), IconSlideAction( caption: 'Delete', color: Colors.red, icon: Icons.delete, onTap: () => _showSnackBar(context, 'Delete'), ), ], ); } Widget _getSlidableWithDelegates( BuildContext context, int index, Axis direction) { final _HomeItem item = items[index]; return Slidable.builder( key: Key(item.title), controller: slidableController, direction: direction, dismissal: SlidableDismissal( child: SlidableDrawerDismissal(), closeOnCanceled: true, onWillDismiss: (item.index != 10) ? null : (actionType) { return showDialog<bool>( context: context, builder: (context) { return AlertDialog( title: Text('Delete'), content: Text('Item will be deleted'), actions: <Widget>[ FlatButton( child: Text('Cancel'), onPressed: () => Navigator.of(context).pop(false), ), FlatButton( child: Text('Ok'), onPressed: () => Navigator.of(context).pop(true), ), ], ); }, ); }, onDismissed: (actionType) { _showSnackBar( context, actionType == SlideActionType.primary ? 'Dismiss Archive' : 'Dismiss Delete'); setState(() { items.removeAt(index); }); }, ), actionPane: _getActionPane(item.index), actionExtentRatio: 0.25, child: direction == Axis.horizontal ? VerticalListItem(items[index]) : HorizontalListItem(items[index]), actionDelegate: SlideActionBuilderDelegate( actionCount: 2, builder: (context, index, animation, renderingMode) { if (index == 0) { return IconSlideAction( caption: 'Archive', color: renderingMode == SlidableRenderingMode.slide ? Colors.blue.withOpacity(animation.value) : (renderingMode == SlidableRenderingMode.dismiss ? Colors.blue : Colors.green), icon: Icons.archive, onTap: () async { var state = Slidable.of(context); var dismiss = await showDialog<bool>( context: context, builder: (context) { return AlertDialog( title: Text('Delete'), content: Text('Item will be deleted'), actions: <Widget>[ FlatButton( child: Text('Cancel'), onPressed: () => Navigator.of(context).pop(false), ), FlatButton( child: Text('Ok'), onPressed: () => Navigator.of(context).pop(true), ), ], ); }, ); if (dismiss) { state.dismiss(); } }, ); } else { return IconSlideAction( caption: 'Share', color: renderingMode == SlidableRenderingMode.slide ? Colors.indigo.withOpacity(animation.value) : Colors.indigo, icon: Icons.share, onTap: () => _showSnackBar(context, 'Share'), ); } }), secondaryActionDelegate: SlideActionBuilderDelegate( actionCount: 2, builder: (context, index, animation, renderingMode) { if (index == 0) { return IconSlideAction( caption: 'More', color: renderingMode == SlidableRenderingMode.slide ? Colors.grey.shade200.withOpacity(animation.value) : Colors.grey.shade200, icon: Icons.more_horiz, onTap: () => _showSnackBar(context, 'More'), closeOnTap: false, ); } else { return IconSlideAction( caption: 'Delete', color: renderingMode == SlidableRenderingMode.slide ? Colors.red.withOpacity(animation.value) : Colors.red, icon: Icons.delete, onTap: () => _showSnackBar(context, 'Delete'), ); } }), ); } static Widget _getActionPane(int index) { switch (index % 4) { case 0: return SlidableBehindActionPane(); case 1: return SlidableStrechActionPane(); case 2: return SlidableScrollActionPane(); case 3: return SlidableDrawerActionPane(); default: return null; } } static Color _getAvatarColor(int index) { switch (index % 4) { case 0: return Colors.red; case 1: return Colors.green; case 2: return Colors.blue; case 3: return Colors.indigoAccent; default: return null; } } static String _getSubtitle(int index) { switch (index % 4) { case 0: return ' '; case 1: return ' '; case 2: return ' '; case 3: return ' '; default: return null; } } void _showSnackBar(BuildContext context, String text) { Scaffold.of(context).showSnackBar(SnackBar(content: Text(text))); }} class HorizontalListItem extends StatelessWidget { HorizontalListItem(this.item); final _HomeItem item; @override Widget build(BuildContext context) { return Container( color: Colors.white, width: 160.0, child: Column( mainAxisSize: MainAxisSize.max, children: <Widget>[ Expanded( child: CircleAvatar( backgroundColor: item.color, child: Text('${item.index}'), foregroundColor: Colors.white, ), ), Expanded( child: Center( child: Text( item.subtitle, ), ), ), ], ), ); }} class VerticalListItem extends StatelessWidget { VerticalListItem(this.item); final _HomeItem item; @override Widget build(BuildContext context) { return GestureDetector( onTap: () => Slidable.of(context)?.renderingMode == SlidableRenderingMode.none ? Slidable.of(context)?.open() : Slidable.of(context)?.close(), child: Container( color: Colors.white, child: ListTile( leading: CircleAvatar( backgroundColor: item.color, child: Text('${item.index}'), foregroundColor: Colors.white, ), title: Text(item.title), subtitle: Text(item.subtitle), ), ), ); }} class _HomeItem { const _HomeItem( this.index, this.title, this.subtitle, this.color, ); final int index; final String title; final String subtitle; final Color color;} Output: android Flutter Flutter UI-components Dart Flutter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - Custom Bottom Navigation Bar ListView Class in Flutter Flutter - Flexible Widget Flutter - Stack Widget Flutter - Positioned Widget Flutter - Custom Bottom Navigation Bar Flutter Tutorial Flutter - Flexible Widget Flutter - Stack Widget Flutter - Positioned Widget
[ { "code": null, "e": 25285, "s": 25257, "text": "\n15 Feb, 2021" }, { "code": null, "e": 25675, "s": 25285, "text": "Slidable in an application can be used to perform a wide range of tasks with just a simple swipe to either right or left on the tile. It not only makes the UI very user-friendly but also saves a lot of time in doing trivial tasks which if done in other ways can be hectic and redundant to design. In this article, we will look into the process of designing a slidable for your application." }, { "code": null, "e": 25856, "s": 25675, "text": "Here we will build a simple application with tiles that when swiped left to right archives the tile and when swiped right to left deletes the tile. To do so follow the below steps:" }, { "code": null, "e": 25918, "s": 25856, "text": "Add the flutter_slidable dependency to the pubspec.yaml file." }, { "code": null, "e": 25962, "s": 25918, "text": "Import the dependency to the main.dart file" }, { "code": null, "e": 26015, "s": 25962, "text": "Create a StatelessWidget to give the app a structure" }, { "code": null, "e": 26073, "s": 26015, "text": "Use a StateFulWidget to add a Homepage to the application" }, { "code": null, "e": 26123, "s": 26073, "text": "Use SlidableCntroller to set up the slide actions" }, { "code": null, "e": 26214, "s": 26123, "text": "Use FloatingActionButton to assign actions to the buttons generated while sliding the tile" }, { "code": null, "e": 26271, "s": 26214, "text": "Use the WidgetBuilder to build the tiles on the homepage" }, { "code": null, "e": 26306, "s": 26271, "text": "Let’s discuss the steps in detail." }, { "code": null, "e": 26394, "s": 26306, "text": "You can import the flutter_slidable dependency in the pubspec.yaml file as shown below:" }, { "code": null, "e": 26460, "s": 26394, "text": "To import the dependency in the main.dart file use the following:" }, { "code": null, "e": 26517, "s": 26460, "text": "import 'package:flutter_slidable/flutter_slidable.dart';" }, { "code": null, "e": 26598, "s": 26517, "text": "Use a StatelessWidget to give the application a simple structure as shown below:" }, { "code": null, "e": 26603, "s": 26598, "text": "Dart" }, { "code": "class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Slidable ', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'GeeksForGeeks'), ); }}", "e": 26871, "s": 26603, "text": null }, { "code": null, "e": 27064, "s": 26871, "text": "Use a StatefulWidget to set up the homepage for the application that would in the future hold the tiles that can be swiped in either direction to perform tasks assigned to them as shown below:" }, { "code": null, "e": 27069, "s": 27064, "text": "Dart" }, { "code": "class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> { SlidableController slidableController; final List<_HomeItem> items = List.generate( 20, (i) => _HomeItem( i, 'Slide Bar $i', _getSubtitle(i), _getAvatarColor(i), ), );", "e": 27513, "s": 27069, "text": null }, { "code": null, "e": 27724, "s": 27513, "text": "Use the SlidableController to setup the slides for the application. It can be done by the use of either Slidable Constructor or Slidable.builder Constructor. The app we are building has 4 essential components :" }, { "code": null, "e": 27838, "s": 27724, "text": "Slide ActionsA slide Action panel widgetAn extent ratio between a slide action extent and the item extent.A child" }, { "code": null, "e": 27852, "s": 27838, "text": "Slide Actions" }, { "code": null, "e": 27880, "s": 27852, "text": "A slide Action panel widget" }, { "code": null, "e": 27947, "s": 27880, "text": "An extent ratio between a slide action extent and the item extent." }, { "code": null, "e": 27955, "s": 27947, "text": "A child" }, { "code": null, "e": 27997, "s": 27955, "text": "To design the slidable use the following:" }, { "code": null, "e": 28002, "s": 27997, "text": "Dart" }, { "code": "Slidable( actionPane: SlidableDrawerActionPane(), actionExtentRatio: 0.25, child: Container( color: Colors.white, child: ListTile( leading: CircleAvatar( backgroundColor: Colors.indigoAccent, child: Text('$3'), foregroundColor: Colors.white, ), title: Text('Tile $3'), subtitle: Text('SlidableDrawerDelegate'), ), ), actions: <Widget>[ IconSlideAction( caption: 'Archive', color: Colors.blue, icon: Icons.archive, onTap: () => _showSnackBar('Archive'), ), IconSlideAction( caption: 'Share', color: Colors.indigo, icon: Icons.share, onTap: () => _showSnackBar('Share'), ), ], secondaryActions: <Widget>[ IconSlideAction( caption: 'More', color: Colors.black45, icon: Icons.more_horiz, onTap: () => _showSnackBar('More'), ), IconSlideAction( caption: 'Delete', color: Colors.red, icon: Icons.delete, onTap: () => _showSnackBar('Delete'), ), ],);", "e": 29008, "s": 28002, "text": null }, { "code": null, "e": 29186, "s": 29008, "text": "As the slides are swiped a FloatingActionButton will appear depending upon the direction of the slide. In both the case two actions will be assigned to each swipe as following:" }, { "code": null, "e": 29211, "s": 29186, "text": "For left to right slide:" }, { "code": null, "e": 29234, "s": 29211, "text": "Archive tileShare tile" }, { "code": null, "e": 29247, "s": 29234, "text": "Archive tile" }, { "code": null, "e": 29258, "s": 29247, "text": "Share tile" }, { "code": null, "e": 29287, "s": 29258, "text": "For the right to left slide:" }, { "code": null, "e": 29303, "s": 29287, "text": "Delete tileMore" }, { "code": null, "e": 29315, "s": 29303, "text": "Delete tile" }, { "code": null, "e": 29320, "s": 29315, "text": "More" }, { "code": null, "e": 29511, "s": 29320, "text": "For the sake of simplicity, we will only assign actions to the Archive tile button and delete the tile button which will archive and delete the tile respectively. To do so use the following:" }, { "code": null, "e": 29516, "s": 29511, "text": "Dart" }, { "code": "@protectedvoid initState() { slidableController = SlidableController( onSlideAnimationChanged: handleSlideAnimationChanged, onSlideIsOpenChanged: handleSlideIsOpenChanged, ); super.initState();} Animation<double> _rotationAnimation;Color _fabColor = Colors.blue; void handleSlideAnimationChanged(Animation<double> slideAnimation) { setState(() { _rotationAnimation = slideAnimation; });} void handleSlideIsOpenChanged(bool isOpen) { setState(() { _fabColor = isOpen ? Colors.green : Colors.blue; });} @overrideWidget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), backgroundColor: Colors.green, ), body: Center( child: OrientationBuilder( builder: (context, orientation) => _buildList( context, orientation == Orientation.portrait ? Axis.vertical : Axis.horizontal), ), ), floatingActionButton: FloatingActionButton( backgroundColor: _fabColor, onPressed: null, child: _rotationAnimation == null ? Icon(Icons.add) : RotationTransition( turns: _rotationAnimation, child: Icon(Icons.add), ), ), );} Widget _buildList(BuildContext context, Axis direction) { return ListView.builder( scrollDirection: direction, itemBuilder: (context, index) { final Axis slidableDirection = direction == Axis.horizontal ? Axis.vertical : Axis.horizontal; var item = items[index]; if (item.index < 8) { return _getSlidableWithLists(context, index, slidableDirection); } else { return _getSlidableWithDelegates(context, index, slidableDirection); } }, itemCount: items.length, );} Widget _getSlidableWithLists( BuildContext context, int index, Axis direction) { final _HomeItem item = items[index]; return Slidable( key: Key(item.title), controller: slidableController, direction: direction, dismissal: SlidableDismissal( child: SlidableDrawerDismissal(), onDismissed: (actionType) { _showSnackBar( context, actionType == SlideActionType.primary ? 'Dismiss Archive' : 'Dismiss Delete'); setState(() { items.removeAt(index); }); }, ), actionPane: _getActionPane(item.index), actionExtentRatio: 0.25, child: direction == Axis.horizontal ? VerticalListItem(items[index]) : HorizontalListItem(items[index]), actions: <Widget>[ IconSlideAction( caption: 'Archive', color: Colors.blue, icon: Icons.archive, onTap: () => _showSnackBar(context, 'Archive'), ), IconSlideAction( caption: 'Share', color: Colors.indigo, icon: Icons.share, onTap: () => _showSnackBar(context, 'Share'), ), ], secondaryActions: <Widget>[ Container( height: 800, color: Colors.green, child: Text('a'), ), IconSlideAction( caption: 'More', color: Colors.grey.shade200, icon: Icons.more_horiz, onTap: () => _showSnackBar(context, 'More'), closeOnTap: false, ), IconSlideAction( caption: 'Delete', color: Colors.red, icon: Icons.delete, onTap: () => _showSnackBar(context, 'Delete'), ), ], );}", "e": 32868, "s": 29516, "text": null }, { "code": null, "e": 32890, "s": 32868, "text": "Complete Source Code:" }, { "code": null, "e": 32895, "s": 32890, "text": "Dart" }, { "code": "import 'package:flutter/material.dart';import 'package:flutter_slidable/flutter_slidable.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Slidable ', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'GeeksForGeeks'), ); }} class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> { SlidableController slidableController; final List<_HomeItem> items = List.generate( 20, (i) => _HomeItem( i, 'Slide Bar $i', _getSubtitle(i), _getAvatarColor(i), ), ); @protected void initState() { slidableController = SlidableController( onSlideAnimationChanged: handleSlideAnimationChanged, onSlideIsOpenChanged: handleSlideIsOpenChanged, ); super.initState(); } Animation<double> _rotationAnimation; Color _fabColor = Colors.blue; void handleSlideAnimationChanged(Animation<double> slideAnimation) { setState(() { _rotationAnimation = slideAnimation; }); } void handleSlideIsOpenChanged(bool isOpen) { setState(() { _fabColor = isOpen ? Colors.green : Colors.blue; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), backgroundColor: Colors.green, ), body: Center( child: OrientationBuilder( builder: (context, orientation) => _buildList( context, orientation == Orientation.portrait ? Axis.vertical : Axis.horizontal), ), ), floatingActionButton: FloatingActionButton( backgroundColor: _fabColor, onPressed: null, child: _rotationAnimation == null ? Icon(Icons.add) : RotationTransition( turns: _rotationAnimation, child: Icon(Icons.add), ), ), ); } Widget _buildList(BuildContext context, Axis direction) { return ListView.builder( scrollDirection: direction, itemBuilder: (context, index) { final Axis slidableDirection = direction == Axis.horizontal ? Axis.vertical : Axis.horizontal; var item = items[index]; if (item.index < 8) { return _getSlidableWithLists(context, index, slidableDirection); } else { return _getSlidableWithDelegates(context, index, slidableDirection); } }, itemCount: items.length, ); } Widget _getSlidableWithLists( BuildContext context, int index, Axis direction) { final _HomeItem item = items[index]; //final int t = index; return Slidable( key: Key(item.title), controller: slidableController, direction: direction, dismissal: SlidableDismissal( child: SlidableDrawerDismissal(), onDismissed: (actionType) { _showSnackBar( context, actionType == SlideActionType.primary ? 'Dismiss Archive' : 'Dismiss Delete'); setState(() { items.removeAt(index); }); }, ), actionPane: _getActionPane(item.index), actionExtentRatio: 0.25, child: direction == Axis.horizontal ? VerticalListItem(items[index]) : HorizontalListItem(items[index]), actions: <Widget>[ IconSlideAction( caption: 'Archive', color: Colors.blue, icon: Icons.archive, onTap: () => _showSnackBar(context, 'Archive'), ), IconSlideAction( caption: 'Share', color: Colors.indigo, icon: Icons.share, onTap: () => _showSnackBar(context, 'Share'), ), ], secondaryActions: <Widget>[ Container( height: 800, color: Colors.green, child: Text('a'), ), IconSlideAction( caption: 'More', color: Colors.grey.shade200, icon: Icons.more_horiz, onTap: () => _showSnackBar(context, 'More'), closeOnTap: false, ), IconSlideAction( caption: 'Delete', color: Colors.red, icon: Icons.delete, onTap: () => _showSnackBar(context, 'Delete'), ), ], ); } Widget _getSlidableWithDelegates( BuildContext context, int index, Axis direction) { final _HomeItem item = items[index]; return Slidable.builder( key: Key(item.title), controller: slidableController, direction: direction, dismissal: SlidableDismissal( child: SlidableDrawerDismissal(), closeOnCanceled: true, onWillDismiss: (item.index != 10) ? null : (actionType) { return showDialog<bool>( context: context, builder: (context) { return AlertDialog( title: Text('Delete'), content: Text('Item will be deleted'), actions: <Widget>[ FlatButton( child: Text('Cancel'), onPressed: () => Navigator.of(context).pop(false), ), FlatButton( child: Text('Ok'), onPressed: () => Navigator.of(context).pop(true), ), ], ); }, ); }, onDismissed: (actionType) { _showSnackBar( context, actionType == SlideActionType.primary ? 'Dismiss Archive' : 'Dismiss Delete'); setState(() { items.removeAt(index); }); }, ), actionPane: _getActionPane(item.index), actionExtentRatio: 0.25, child: direction == Axis.horizontal ? VerticalListItem(items[index]) : HorizontalListItem(items[index]), actionDelegate: SlideActionBuilderDelegate( actionCount: 2, builder: (context, index, animation, renderingMode) { if (index == 0) { return IconSlideAction( caption: 'Archive', color: renderingMode == SlidableRenderingMode.slide ? Colors.blue.withOpacity(animation.value) : (renderingMode == SlidableRenderingMode.dismiss ? Colors.blue : Colors.green), icon: Icons.archive, onTap: () async { var state = Slidable.of(context); var dismiss = await showDialog<bool>( context: context, builder: (context) { return AlertDialog( title: Text('Delete'), content: Text('Item will be deleted'), actions: <Widget>[ FlatButton( child: Text('Cancel'), onPressed: () => Navigator.of(context).pop(false), ), FlatButton( child: Text('Ok'), onPressed: () => Navigator.of(context).pop(true), ), ], ); }, ); if (dismiss) { state.dismiss(); } }, ); } else { return IconSlideAction( caption: 'Share', color: renderingMode == SlidableRenderingMode.slide ? Colors.indigo.withOpacity(animation.value) : Colors.indigo, icon: Icons.share, onTap: () => _showSnackBar(context, 'Share'), ); } }), secondaryActionDelegate: SlideActionBuilderDelegate( actionCount: 2, builder: (context, index, animation, renderingMode) { if (index == 0) { return IconSlideAction( caption: 'More', color: renderingMode == SlidableRenderingMode.slide ? Colors.grey.shade200.withOpacity(animation.value) : Colors.grey.shade200, icon: Icons.more_horiz, onTap: () => _showSnackBar(context, 'More'), closeOnTap: false, ); } else { return IconSlideAction( caption: 'Delete', color: renderingMode == SlidableRenderingMode.slide ? Colors.red.withOpacity(animation.value) : Colors.red, icon: Icons.delete, onTap: () => _showSnackBar(context, 'Delete'), ); } }), ); } static Widget _getActionPane(int index) { switch (index % 4) { case 0: return SlidableBehindActionPane(); case 1: return SlidableStrechActionPane(); case 2: return SlidableScrollActionPane(); case 3: return SlidableDrawerActionPane(); default: return null; } } static Color _getAvatarColor(int index) { switch (index % 4) { case 0: return Colors.red; case 1: return Colors.green; case 2: return Colors.blue; case 3: return Colors.indigoAccent; default: return null; } } static String _getSubtitle(int index) { switch (index % 4) { case 0: return ' '; case 1: return ' '; case 2: return ' '; case 3: return ' '; default: return null; } } void _showSnackBar(BuildContext context, String text) { Scaffold.of(context).showSnackBar(SnackBar(content: Text(text))); }} class HorizontalListItem extends StatelessWidget { HorizontalListItem(this.item); final _HomeItem item; @override Widget build(BuildContext context) { return Container( color: Colors.white, width: 160.0, child: Column( mainAxisSize: MainAxisSize.max, children: <Widget>[ Expanded( child: CircleAvatar( backgroundColor: item.color, child: Text('${item.index}'), foregroundColor: Colors.white, ), ), Expanded( child: Center( child: Text( item.subtitle, ), ), ), ], ), ); }} class VerticalListItem extends StatelessWidget { VerticalListItem(this.item); final _HomeItem item; @override Widget build(BuildContext context) { return GestureDetector( onTap: () => Slidable.of(context)?.renderingMode == SlidableRenderingMode.none ? Slidable.of(context)?.open() : Slidable.of(context)?.close(), child: Container( color: Colors.white, child: ListTile( leading: CircleAvatar( backgroundColor: item.color, child: Text('${item.index}'), foregroundColor: Colors.white, ), title: Text(item.title), subtitle: Text(item.subtitle), ), ), ); }} class _HomeItem { const _HomeItem( this.index, this.title, this.subtitle, this.color, ); final int index; final String title; final String subtitle; final Color color;}", "e": 44433, "s": 32895, "text": null }, { "code": null, "e": 44441, "s": 44433, "text": "Output:" }, { "code": null, "e": 44449, "s": 44441, "text": "android" }, { "code": null, "e": 44457, "s": 44449, "text": "Flutter" }, { "code": null, "e": 44479, "s": 44457, "text": "Flutter UI-components" }, { "code": null, "e": 44484, "s": 44479, "text": "Dart" }, { "code": null, "e": 44492, "s": 44484, "text": "Flutter" }, { "code": null, "e": 44590, "s": 44492, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 44629, "s": 44590, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 44655, "s": 44629, "text": "ListView Class in Flutter" }, { "code": null, "e": 44681, "s": 44655, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 44704, "s": 44681, "text": "Flutter - Stack Widget" }, { "code": null, "e": 44732, "s": 44704, "text": "Flutter - Positioned Widget" }, { "code": null, "e": 44771, "s": 44732, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 44788, "s": 44771, "text": "Flutter Tutorial" }, { "code": null, "e": 44814, "s": 44788, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 44837, "s": 44814, "text": "Flutter - Stack Widget" } ]
Mongoose | insertMany() Function - GeeksforGeeks
20 May, 2020 The insertMany() function is used to insert multiple documents into a collection. It accepts an array of documents to insert into the collection. Installation of mongoose module: You can visit the link Install mongoose module. You can install this package by using this command.npm install mongooseAfter installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongooseAfter that, you can just create a folder and add a file for example index.js, To run this file you need to run the following command.node index.js You can visit the link Install mongoose module. You can install this package by using this command.npm install mongoose npm install mongoose After installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongoose npm version mongoose After that, you can just create a folder and add a file for example index.js, To run this file you need to run the following command.node index.js node index.js Filename: index.js const mongoose = require('mongoose'); // Database connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true}); // User modelconst User = mongoose.model('User', { name: { type: String }, age: { type: Number }}); // Function callUser.insertMany([ { name: 'Gourav', age: 20}, { name: 'Kartik', age: 20}, { name: 'Niharika', age: 20}]).then(function(){ console.log("Data inserted") // Success}).catch(function(error){ console.log(error) // Failure}); Steps to run the program: The project structure will look like this:Make sure you have install mongoose module using following command:npm install mongooseRun index.js file using below command:node index.jsAfter running above command, your can see the data is inserted into the database. You can use any GUI tool or terminal to see the database, like I have used Robo3T GUI tool as shown below: The project structure will look like this: Make sure you have install mongoose module using following command:npm install mongoose npm install mongoose Run index.js file using below command:node index.js node index.js After running above command, your can see the data is inserted into the database. You can use any GUI tool or terminal to see the database, like I have used Robo3T GUI tool as shown below: So this is how you can use mongoose insertMany() function to insert multiple documents into the collection in MongoDB and Node.js. Mongoose MongoDB Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Spring Boot JpaRepository with Example Aggregation in MongoDB Mongoose Populate() Method MongoDB - Check the existence of the fields in the specified collection How to build a basic CRUD app with Node.js and ReactJS ? Installation of Node.js on Linux How to update Node.js and NPM to next version ? Node.js fs.readFileSync() Method Node.js fs.writeFile() Method Node.js fs.readFile() Method
[ { "code": null, "e": 25377, "s": 25349, "text": "\n20 May, 2020" }, { "code": null, "e": 25523, "s": 25377, "text": "The insertMany() function is used to insert multiple documents into a collection. It accepts an array of documents to insert into the collection." }, { "code": null, "e": 25556, "s": 25523, "text": "Installation of mongoose module:" }, { "code": null, "e": 25948, "s": 25556, "text": "You can visit the link Install mongoose module. You can install this package by using this command.npm install mongooseAfter installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongooseAfter that, you can just create a folder and add a file for example index.js, To run this file you need to run the following command.node index.js" }, { "code": null, "e": 26068, "s": 25948, "text": "You can visit the link Install mongoose module. You can install this package by using this command.npm install mongoose" }, { "code": null, "e": 26089, "s": 26068, "text": "npm install mongoose" }, { "code": null, "e": 26216, "s": 26089, "text": "After installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongoose" }, { "code": null, "e": 26237, "s": 26216, "text": "npm version mongoose" }, { "code": null, "e": 26384, "s": 26237, "text": "After that, you can just create a folder and add a file for example index.js, To run this file you need to run the following command.node index.js" }, { "code": null, "e": 26398, "s": 26384, "text": "node index.js" }, { "code": null, "e": 26417, "s": 26398, "text": "Filename: index.js" }, { "code": "const mongoose = require('mongoose'); // Database connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true}); // User modelconst User = mongoose.model('User', { name: { type: String }, age: { type: Number }}); // Function callUser.insertMany([ { name: 'Gourav', age: 20}, { name: 'Kartik', age: 20}, { name: 'Niharika', age: 20}]).then(function(){ console.log(\"Data inserted\") // Success}).catch(function(error){ console.log(error) // Failure});", "e": 26987, "s": 26417, "text": null }, { "code": null, "e": 27013, "s": 26987, "text": "Steps to run the program:" }, { "code": null, "e": 27382, "s": 27013, "text": "The project structure will look like this:Make sure you have install mongoose module using following command:npm install mongooseRun index.js file using below command:node index.jsAfter running above command, your can see the data is inserted into the database. You can use any GUI tool or terminal to see the database, like I have used Robo3T GUI tool as shown below:" }, { "code": null, "e": 27425, "s": 27382, "text": "The project structure will look like this:" }, { "code": null, "e": 27513, "s": 27425, "text": "Make sure you have install mongoose module using following command:npm install mongoose" }, { "code": null, "e": 27534, "s": 27513, "text": "npm install mongoose" }, { "code": null, "e": 27586, "s": 27534, "text": "Run index.js file using below command:node index.js" }, { "code": null, "e": 27600, "s": 27586, "text": "node index.js" }, { "code": null, "e": 27789, "s": 27600, "text": "After running above command, your can see the data is inserted into the database. You can use any GUI tool or terminal to see the database, like I have used Robo3T GUI tool as shown below:" }, { "code": null, "e": 27920, "s": 27789, "text": "So this is how you can use mongoose insertMany() function to insert multiple documents into the collection in MongoDB and Node.js." }, { "code": null, "e": 27929, "s": 27920, "text": "Mongoose" }, { "code": null, "e": 27937, "s": 27929, "text": "MongoDB" }, { "code": null, "e": 27945, "s": 27937, "text": "Node.js" }, { "code": null, "e": 27962, "s": 27945, "text": "Web Technologies" }, { "code": null, "e": 28060, "s": 27962, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28099, "s": 28060, "text": "Spring Boot JpaRepository with Example" }, { "code": null, "e": 28122, "s": 28099, "text": "Aggregation in MongoDB" }, { "code": null, "e": 28149, "s": 28122, "text": "Mongoose Populate() Method" }, { "code": null, "e": 28221, "s": 28149, "text": "MongoDB - Check the existence of the fields in the specified collection" }, { "code": null, "e": 28278, "s": 28221, "text": "How to build a basic CRUD app with Node.js and ReactJS ?" }, { "code": null, "e": 28311, "s": 28278, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28359, "s": 28311, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 28392, "s": 28359, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 28422, "s": 28392, "text": "Node.js fs.writeFile() Method" } ]
ZigZag Tree Traversal - GeeksforGeeks
04 Mar, 2022 Write a function to print ZigZag order traversal of a binary tree. For the below binary tree the zigzag order traversal will be 1 3 2 7 6 5 4. This problem can be solved using two stacks. Assume the two stacks are current: currentlevel and nextlevel. We would also need a variable to keep track of the current level order(whether it is left to right or right to left). We pop from the currentlevel stack and print the nodes value. Whenever the current level order is from left to right, push the nodes left child, then its right child to the stack nextlevel. Since a stack is a LIFO(Last-In-First_out) structure, next time when nodes are popped off nextlevel, it will be in the reverse order. On the other hand, when the current level order is from right to left, we would push the nodes right child first, then its left child. Finally, do-not forget to swap those two stacks at the end of each level(i.e., when current level is empty) Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of a O(n) time method for// Zigzag order traversal#include <iostream>#include <stack>using namespace std; // Binary Tree nodestruct Node { int data; struct Node *left, *right;}; // function to print the zigzag traversalvoid zizagtraversal(struct Node* root){ // if null then return if (!root) return; // declare two stacks stack<struct Node*> currentlevel; stack<struct Node*> nextlevel; // push the root currentlevel.push(root); // check if stack is empty bool lefttoright = true; while (!currentlevel.empty()) { // pop out of stack struct Node* temp = currentlevel.top(); currentlevel.pop(); // if not null if (temp) { // print the data in it cout << temp->data << " "; // store data according to current // order. if (lefttoright) { if (temp->left) nextlevel.push(temp->left); if (temp->right) nextlevel.push(temp->right); } else { if (temp->right) nextlevel.push(temp->right); if (temp->left) nextlevel.push(temp->left); } } if (currentlevel.empty()) { lefttoright = !lefttoright; swap(currentlevel, nextlevel); } }} // A utility function to create a new nodestruct Node* newNode(int data){ struct Node* node = new struct Node; node->data = data; node->left = node->right = NULL; return (node);} // driver program to test the above functionint main(){ // create tree struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(7); root->left->right = newNode(6); root->right->left = newNode(5); root->right->right = newNode(4); cout << "ZigZag Order traversal of binary tree is \n"; zizagtraversal(root); return 0;} // Java implementation of a O(n) time// method for Zigzag order traversalimport java.util.*; // Binary Tree nodeclass Node{int data;Node leftChild;Node rightChild;Node(int data){ this.data = data;}} class BinaryTree {Node rootNode; // function to print the// zigzag traversalvoid printZigZagTraversal() { // if null then return if (rootNode == null) { return; } // declare two stacks Stack<Node> currentLevel = new Stack<>(); Stack<Node> nextLevel = new Stack<>(); // push the root currentLevel.push(rootNode); boolean leftToRight = true; // check if stack is empty while (!currentLevel.isEmpty()) { // pop out of stack Node node = currentLevel.pop(); // print the data in it System.out.print(node.data + " "); // store data according to current // order. if (leftToRight) { if (node.leftChild != null) { nextLevel.push(node.leftChild); } if (node.rightChild != null) { nextLevel.push(node.rightChild); } } else { if (node.rightChild != null) { nextLevel.push(node.rightChild); } if (node.leftChild != null) { nextLevel.push(node.leftChild); } } if (currentLevel.isEmpty()) { leftToRight = !leftToRight; Stack<Node> temp = currentLevel; currentLevel = nextLevel; nextLevel = temp; } }}} public class zigZagTreeTraversal { // driver program to test the above functionpublic static void main(String[] args){ BinaryTree tree = new BinaryTree(); tree.rootNode = new Node(1); tree.rootNode.leftChild = new Node(2); tree.rootNode.rightChild = new Node(3); tree.rootNode.leftChild.leftChild = new Node(7); tree.rootNode.leftChild.rightChild = new Node(6); tree.rootNode.rightChild.leftChild = new Node(5); tree.rootNode.rightChild.rightChild = new Node(4); System.out.println("ZigZag Order traversal of binary tree is"); tree.printZigZagTraversal();}} // This Code is contributed by Harikrishnan Rajan. # Python Program to print zigzag traversal# of binary tree # Binary tree nodeclass Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = self.right = None # function to print zigzag traversal of# binary treedef zizagtraversal(root): # Base Case if root is None: return # Create two stacks to store current # and next level currentLevel = [] nextLevel = [] # if ltr is true push nodes from # left to right otherwise from # right to left ltr = True # append root to currentlevel stack currentLevel.append(root) # Check if stack is empty while len(currentLevel) > 0: # pop from stack temp = currentLevel.pop(-1) # print the data print(temp.data, " ", end="") if ltr: # if ltr is true push left # before right if temp.left: nextLevel.append(temp.left) if temp.right: nextLevel.append(temp.right) else: # else push right before left if temp.right: nextLevel.append(temp.right) if temp.left: nextLevel.append(temp.left) if len(currentLevel) == 0: # reverse ltr to push node in # opposite order ltr = not ltr # swapping of stacks currentLevel, nextLevel = nextLevel, currentLevel # Driver program to check above functionroot = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(7)root.left.right = Node(6)root.right.left = Node(5)root.right.right = Node(4)print("Zigzag Order traversal of binary tree is")zizagtraversal(root) # This code is contributed by Shweta Singh // C# implementation of a O(n) time// method for Zigzag order traversalusing System;using System.Collections.Generic; // Binary Tree nodepublic class Node{ public int data; public Node leftChild; public Node rightChild; public Node(int data) { this.data = data; }} class GFG{ public Node rootNode; // function to print the // zigzag traversal public virtual void printZigZagTraversal() { // if null then return if (rootNode == null) { return; } // declare two stacks Stack<Node> currentLevel = new Stack<Node>(); Stack<Node> nextLevel = new Stack<Node>(); // push the root currentLevel.Push(rootNode); bool leftToRight = true; // check if stack is empty while (currentLevel.Count > 0) { // pop out of stack Node node = currentLevel.Pop(); // print the data in it Console.Write(node.data + " "); // store data according to current // order. if (leftToRight) { if (node.leftChild != null) { nextLevel.Push(node.leftChild); } if (node.rightChild != null) { nextLevel.Push(node.rightChild); } } else { if (node.rightChild != null) { nextLevel.Push(node.rightChild); } if (node.leftChild != null) { nextLevel.Push(node.leftChild); } } if (currentLevel.Count == 0) { leftToRight = !leftToRight; Stack<Node> temp = currentLevel; currentLevel = nextLevel; nextLevel = temp; } } }} public class zigZagTreeTraversal{ // Driver Codepublic static void Main(string[] args){ GFG tree = new GFG(); tree.rootNode = new Node(1); tree.rootNode.leftChild = new Node(2); tree.rootNode.rightChild = new Node(3); tree.rootNode.leftChild.leftChild = new Node(7); tree.rootNode.leftChild.rightChild = new Node(6); tree.rootNode.rightChild.leftChild = new Node(5); tree.rootNode.rightChild.rightChild = new Node(4); Console.WriteLine("ZigZag Order traversal " + "of binary tree is"); tree.printZigZagTraversal();}} // This code is contributed by Shrikant13 <script> // JavaScript implementation of a O(n) time // method for Zigzag order traversal class Node { constructor(data) { this.leftChild = null; this.rightChild = null; this.data = data; } } let rootNode; // function to print the // zigzag traversal function printZigZagTraversal() { // if null then return if (rootNode == null) { return; } // declare two stacks let currentLevel = []; let nextLevel = []; // push the root currentLevel.push(rootNode); let leftToRight = true; // check if stack is empty while (currentLevel.length > 0) { // pop out of stack let node = currentLevel.pop(); // print the data in it document.write(node.data + " "); // store data according to current // order. if (leftToRight) { if (node.leftChild != null) { nextLevel.push(node.leftChild); } if (node.rightChild != null) { nextLevel.push(node.rightChild); } } else { if (node.rightChild != null) { nextLevel.push(node.rightChild); } if (node.leftChild != null) { nextLevel.push(node.leftChild); } } if (currentLevel.length == 0) { leftToRight = !leftToRight; let temp = currentLevel; currentLevel = nextLevel; nextLevel = temp; } } } rootNode = new Node(1); rootNode.leftChild = new Node(2); rootNode.rightChild = new Node(3); rootNode.leftChild.leftChild = new Node(7); rootNode.leftChild.rightChild = new Node(6); rootNode.rightChild.leftChild = new Node(5); rootNode.rightChild.rightChild = new Node(4); document.write("ZigZag Order traversal of binary tree is" + "</br>"); printZigZagTraversal(); </script> ZigZag Order traversal of binary tree is 1 3 2 7 6 5 4 Time Complexity: O(n) Space Complexity: O(n)+(n)=O(n) Recursive Approach: The approach used here is the observable similarity to the level order traversal. Here we need to include an extra parameter to keep a track of printing each level in left-right or right-left way. C++ //Initial Template for C++#include <bits/stdc++.h>using namespace std; struct Node { int data; Node *left; Node *right; Node(int val) { data = val; left = right = NULL; }}; // Function to Build TreeNode* buildTree(string str){ // Corner Case if(str.length() == 0 || str[0] == 'N') return NULL; // Creating vector of strings from input // string after splitting by space vector<string> ip; istringstream iss(str); for(string str; iss >> str; ) ip.push_back(str); // Create the root of the tree Node* root = new Node(stoi(ip[0])); // Push the root to the queue queue<Node*> queue; queue.push(root); // Starting from the second element int i = 1; while(!queue.empty() && i < ip.size()) { // Get and remove the front of the queue Node* currNode = queue.front(); queue.pop(); // Get the current node's value from the string string currVal = ip[i]; // If the left child is not null if(currVal != "N") { // Create the left child for the current node currNode->left = new Node(stoi(currVal)); // Push it to the queue queue.push(currNode->left); } // For the right child i++; if(i >= ip.size()) break; currVal = ip[i]; // If the right child is not null if(currVal != "N") { // Create the right child for the current node currNode->right = new Node(stoi(currVal)); // Push it to the queue queue.push(currNode->right); } i++; } return root;} // Function to calculate height of treeint treeHeight(Node *root){ if(!root) return 0; int lHeight = treeHeight(root->left); int rHeight = treeHeight(root->right); return max(lHeight, rHeight) + 1;} // Helper Function to store the zig zag order traversal// of tree in a list recursivelyvoid zigZagTraversalRecursion(Node* root, int height, bool lor, vector<int> &ans){ // Height = 1 means the tree now has only one node if(height <= 1){ if(root) ans.push_back(root->data); } // When Height > 1 else{ if(lor){ if(root->left) zigZagTraversalRecursion(root->left, height - 1, lor, ans); if(root->right) zigZagTraversalRecursion(root->right, height - 1, lor, ans); } else{ if(root->right) zigZagTraversalRecursion(root->right, height - 1, lor, ans); if(root->left) zigZagTraversalRecursion(root->left, height - 1, lor, ans); } }} // Function to traverse tree in zig zag ordervector <int> zigZagTraversal(Node* root){ vector<int> ans; bool leftOrRight = true; int height = treeHeight(root); for(int i = 1; i <= height; i++){ zigZagTraversalRecursion(root, i, leftOrRight, ans); leftOrRight = !leftOrRight; } return ans;} int main(){ // Tree: // 1 // / \ // / \ // / \ // 2 3 // / \ / \ // 4 5 6 7 // / \ / \ / \ / \ //8 9 10 11 12 13 14 15 string s = "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15"; Node* root = buildTree(s); vector <int> res = zigZagTraversal(root); cout<<"ZigZag traversal of binary tree is:"<<endl; for (int i = 0; i < res.size (); i++) cout << res[i] << " "; cout<<endl; return 0;}// Code By Angshuman Sengupta ZigZag traversal of binary tree is: 1 3 2 4 5 6 7 15 14 13 12 11 10 9 8 Output: ZigZag traversal of binary tree is: 1 3 2 4 5 6 7 15 14 13 12 11 10 9 8 Another Approach:In this approach, use a deque to solve the problem. Push and pop in different ways depending on if the level is odd or level is even. Below is the implementation of the above approach: C++ Java Python3 // C++ implementation of a O(n) time method for// Zigzag order traversal#include <bits/stdc++.h>#include <iostream>using namespace std; // Binary Tree nodeclass Node {public: int data; Node *left, *right;}; // Function to print the zigzag traversalvector<int> zigZagTraversal(Node* root){ deque<Node*> q; vector<int> v; q.push_back(root); v.push_back(root->data); Node* temp; // set initial level as 1, because root is // already been taken care of. int l = 1; while (!q.empty()) { int n = q.size(); for (int i = 0; i < n; i++) { // popping mechanism if (l % 2 == 0) { temp = q.back(); q.pop_back(); } else { temp = q.front(); q.pop_front(); } // pushing mechanism if (l % 2 != 0) { if (temp->right) { q.push_back(temp->right); v.push_back(temp->right->data); } if (temp->left) { q.push_back(temp->left); v.push_back(temp->left->data); } } else if (l % 2 == 0) { if (temp->left) { q.push_front(temp->left); v.push_back(temp->left->data); } if (temp->right) { q.push_front(temp->right); v.push_back(temp->right->data); } } } l++; // level plus one } return v;} // A utility function to create a new nodestruct Node* newNode(int data){ struct Node* node = new struct Node; node->data = data; node->left = node->right = NULL; return (node);} // Driver program to test// the above functionint main(){ // vector to store the traversal order. vector<int> v; // create tree struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(7); root->left->right = newNode(6); root->right->left = newNode(5); root->right->right = newNode(4); cout << "ZigZag Order traversal of binary tree is \n"; v = zigZagTraversal(root); for (int i = 0; i < v.size(); i++) { // to print the order cout << v[i] << " "; } return 0;}// This code is contributed by Ritvik Mahajan // Java implementation of a O(n) time method for// Zigzag order traversalimport java.util.*;public class Main{ // Class containing left and // right child of current // node and key value static class Node { public int data; public Node left, right; public Node(int data) { this.data = data; left = right = null; } } // A utility function to create a new node static Node newNode(int data) { Node node = new Node(data); return node; } // Function to print the zigzag traversal static Vector<Integer> zigZagTraversal(Node root) { Deque<Node> q = new LinkedList<Node>(); Vector<Integer> v = new Vector<Integer>(); q.add(root); v.add(root.data); Node temp; // set initial level as 1, because root is // already been taken care of. int l = 1; while (q.size() > 0) { int n = q.size(); for (int i = 0; i < n; i++) { // popping mechanism if (l % 2 == 0) { temp = q.peekLast(); q.pollLast(); } else { temp = q.peekFirst(); q.pollFirst(); } // pushing mechanism if (l % 2 != 0) { if (temp.right != null) { q.add(temp.right); v.add(temp.right.data); } if (temp.left != null) { q.add(temp.left); v.add(temp.left.data); } } else if (l % 2 == 0) { if (temp.left != null) { q.offerFirst(temp.left); v.add(temp.left.data); } if (temp.right != null) { q.offerFirst(temp.right); v.add(temp.right.data); } } } l++; // level plus one } return v; } public static void main(String[] args) { // vector to store the traversal order. Vector<Integer> v; // create tree Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(7); root.left.right = newNode(6); root.right.left = newNode(5); root.right.right = newNode(4); System.out.println("ZigZag Order traversal of binary tree is"); v = zigZagTraversal(root); for (int i = 0; i < v.size(); i++) { // to print the order System.out.print(v.get(i) + " "); } }} // This code is contributed by divyesh072019. # Python3 implementation of a O(n) time method for# Zigzag order traversalfrom collections import deque # Binary Tree nodeclass Node: def __init__(self, data): self.data = data self.left = None self.right = None # Function to print the zigzag traversaldef zigZagTraversal(root): q = deque([]) v = [] q.append(root) v.append(root.data) # set initial level as 1, because root is # already been taken care of. l = 1 while len(q) > 0: n = len(q) for i in range(n): # popping mechanism if (l % 2 == 0): temp = q[-1] q.pop() else: temp = q[0] q.popleft() # pushing mechanism if (l % 2 != 0): if (temp.right): q.append(temp.right) v.append(temp.right.data) if (temp.left): q.append(temp.left) v.append(temp.left.data) elif (l % 2 == 0): if (temp.left): q.appendleft(temp.left) v.append(temp.left.data) if (temp.right): q.appendleft(temp.right) v.append(temp.right.data) l+=1 # level plus one return v # vector to store the traversal order.v = [] # create treeroot = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(7)root.left.right = Node(6)root.right.left = Node(5)root.right.right = Node(4)print("ZigZag Order traversal of binary tree is") v = zigZagTraversal(root) for i in range(len(v)): print(v[i], end = " ") # This code is contributed by suresh07. ZigZag Order traversal of binary tree is 1 3 2 7 6 5 4 Time Complexity: O(N) Auxiliary Space: O(N) for deque data structure Another Approach: We can use a queue just like we used in Level Order Traversal. But in this case, we can also maintain a flag variable which keeps track of alternate level to reverse the order of the corresponding level traversal.flag==true implies we have to insert from left to right and flag==false means we have to insert element from right to left our answer arraylist. C++ Java // C++ implementation of a O(n) time method for// Zigzag order traversal#include <bits/stdc++.h>#include <iostream>using namespace std; // Binary Tree nodeclass Node {public: int data; Node *left, *right;}; // Function to print the zigzag traversalvector<int> zigZagTraversal(Node* root) { if(root == NULL){return { } ; } vector<int > ans ; queue<Node*> q ; q.push(root) ; bool flag = false ; while(!q.empty()){ int size = q.size() ; vector<int> level ; for(int i=0 ; i < size ; i++){ Node* node = q.front() ; q.pop() ; level.push_back(node->data) ; if(node->left != NULL) {q.push(node->left) ;} if(node->right != NULL) {q.push(node->right) ;} } flag = !flag ; if(flag == false){ reverse(level.begin() , level.end()) ; } for(int i = 0 ; i < level.size() ; i++){ ans.push_back(level[i]) ; } } return ans ;} // A utility function to create a new nodestruct Node* newNode(int data){ struct Node* node = new struct Node; node->data = data; node->left = node->right = NULL; return (node);} // Driver program to test// the above functionint main(){ // vector to store the traversal order. vector<int> v; // create tree struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(7); root->left->right = newNode(6); root->right->left = newNode(5); root->right->right = newNode(4); cout << "ZigZag Order traversal of binary tree is \n"; v = zigZagTraversal(root); for (int i = 0; i < v.size(); i++) { // to print the order cout << v[i] << " "; } return 0;} // Java implementation of a O(n) time method for// Zigzag order traversalimport java.util.*;public class Main { // Class containing left and // right child of current // node and key value static class Node { public int data; public Node left, right; public Node(int data) { this.data = data; left = right = null; } } // A utility function to create a new node static Node newNode(int data) { Node node = new Node(data); return node; } // Function to print the zigzag traversal static ArrayList<Integer> zigZagTraversal(Node root) { ArrayList<Integer> ans = new ArrayList<Integer>(); // if there is no element in the tree,return empty // arraylist if (root == null) return ans; Queue<Node> q = new LinkedList<Node>(); q.add(root); // this variable helps to check if elements are to // be added from left to right or right to left boolean leftToRight = true; while (q.size() > 0) { int size = q.size(); // this arraylist is used to store element at // current level ArrayList<Integer> temp = new ArrayList<>(); for (int i = 0; i < size; i++) { Node curr = q.poll(); if (curr.left != null) q.add(curr.left); if (curr.right != null) q.add(curr.right); temp.add(curr.data); } if (leftToRight) // at current level,add element // fom left to right to our // answer { // do nothing } // we have to add element from to right to left // and this can be done by reversing our temp // arraylist else { Collections.reverse(temp); } // add element form temp arraylist to our ans // arraylist for (int i = 0; i < temp.size(); i++) { ans.add(temp.get(i)); } // change the value of leftToRight from true to // false or false to true for next iteration. leftToRight = !(leftToRight); } // return our ans arraylist return ans; } public static void main(String[] args) { // Arraylist to store the traversal order. ArrayList<Integer> ans; // create tree Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(7); root.left.right = newNode(6); root.right.left = newNode(5); root.right.right = newNode(4); System.out.println( "ZigZag Order traversal of binary tree is"); ans = zigZagTraversal(root); for (int i = 0; i < ans.size(); i++) { // to print the order System.out.print(ans.get(i) + " "); } }}// this is contributed by akshita29320 ZigZag Order traversal of binary tree is 1 3 2 7 6 5 4 Time Complexity: O(N) Auxiliary Space: O(N) for queue data structure Below is a simple implementation of this problem. (video)Level order traversal in spiral form shweta44 shrikanth13 innovativeprasen ritvikmahajan2001 coderangshu gabaa406 mukesh07 suresh07 divyesh072019 prasanna1995 akshita29320 saurabh1990aror Amazon cpp-queue cpp-stack FactSet Traversal Queue Stack Tree Amazon FactSet Stack Traversal Queue Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Queue - Linked List Implementation Circular Queue | Set 1 (Introduction and Array Implementation) Sliding Window Maximum (Maximum of all subarrays of size k) Implement Stack using Queues Array implementation of queue (Simple) Stack Data Structure (Introduction and Program) Stack Class in Java Stack in Python Check for Balanced Brackets in an expression (well-formedness) using Stack Stack | Set 2 (Infix to Postfix)
[ { "code": null, "e": 26361, "s": 26333, "text": "\n04 Mar, 2022" }, { "code": null, "e": 26504, "s": 26361, "text": "Write a function to print ZigZag order traversal of a binary tree. For the below binary tree the zigzag order traversal will be 1 3 2 7 6 5 4." }, { "code": null, "e": 27352, "s": 26506, "text": "This problem can be solved using two stacks. Assume the two stacks are current: currentlevel and nextlevel. We would also need a variable to keep track of the current level order(whether it is left to right or right to left). We pop from the currentlevel stack and print the nodes value. Whenever the current level order is from left to right, push the nodes left child, then its right child to the stack nextlevel. Since a stack is a LIFO(Last-In-First_out) structure, next time when nodes are popped off nextlevel, it will be in the reverse order. On the other hand, when the current level order is from right to left, we would push the nodes right child first, then its left child. Finally, do-not forget to swap those two stacks at the end of each level(i.e., when current level is empty) Below is the implementation of the above approach: " }, { "code": null, "e": 27356, "s": 27352, "text": "C++" }, { "code": null, "e": 27361, "s": 27356, "text": "Java" }, { "code": null, "e": 27369, "s": 27361, "text": "Python3" }, { "code": null, "e": 27372, "s": 27369, "text": "C#" }, { "code": null, "e": 27383, "s": 27372, "text": "Javascript" }, { "code": "// C++ implementation of a O(n) time method for// Zigzag order traversal#include <iostream>#include <stack>using namespace std; // Binary Tree nodestruct Node { int data; struct Node *left, *right;}; // function to print the zigzag traversalvoid zizagtraversal(struct Node* root){ // if null then return if (!root) return; // declare two stacks stack<struct Node*> currentlevel; stack<struct Node*> nextlevel; // push the root currentlevel.push(root); // check if stack is empty bool lefttoright = true; while (!currentlevel.empty()) { // pop out of stack struct Node* temp = currentlevel.top(); currentlevel.pop(); // if not null if (temp) { // print the data in it cout << temp->data << \" \"; // store data according to current // order. if (lefttoright) { if (temp->left) nextlevel.push(temp->left); if (temp->right) nextlevel.push(temp->right); } else { if (temp->right) nextlevel.push(temp->right); if (temp->left) nextlevel.push(temp->left); } } if (currentlevel.empty()) { lefttoright = !lefttoright; swap(currentlevel, nextlevel); } }} // A utility function to create a new nodestruct Node* newNode(int data){ struct Node* node = new struct Node; node->data = data; node->left = node->right = NULL; return (node);} // driver program to test the above functionint main(){ // create tree struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(7); root->left->right = newNode(6); root->right->left = newNode(5); root->right->right = newNode(4); cout << \"ZigZag Order traversal of binary tree is \\n\"; zizagtraversal(root); return 0;}", "e": 29380, "s": 27383, "text": null }, { "code": "// Java implementation of a O(n) time// method for Zigzag order traversalimport java.util.*; // Binary Tree nodeclass Node{int data;Node leftChild;Node rightChild;Node(int data){ this.data = data;}} class BinaryTree {Node rootNode; // function to print the// zigzag traversalvoid printZigZagTraversal() { // if null then return if (rootNode == null) { return; } // declare two stacks Stack<Node> currentLevel = new Stack<>(); Stack<Node> nextLevel = new Stack<>(); // push the root currentLevel.push(rootNode); boolean leftToRight = true; // check if stack is empty while (!currentLevel.isEmpty()) { // pop out of stack Node node = currentLevel.pop(); // print the data in it System.out.print(node.data + \" \"); // store data according to current // order. if (leftToRight) { if (node.leftChild != null) { nextLevel.push(node.leftChild); } if (node.rightChild != null) { nextLevel.push(node.rightChild); } } else { if (node.rightChild != null) { nextLevel.push(node.rightChild); } if (node.leftChild != null) { nextLevel.push(node.leftChild); } } if (currentLevel.isEmpty()) { leftToRight = !leftToRight; Stack<Node> temp = currentLevel; currentLevel = nextLevel; nextLevel = temp; } }}} public class zigZagTreeTraversal { // driver program to test the above functionpublic static void main(String[] args){ BinaryTree tree = new BinaryTree(); tree.rootNode = new Node(1); tree.rootNode.leftChild = new Node(2); tree.rootNode.rightChild = new Node(3); tree.rootNode.leftChild.leftChild = new Node(7); tree.rootNode.leftChild.rightChild = new Node(6); tree.rootNode.rightChild.leftChild = new Node(5); tree.rootNode.rightChild.rightChild = new Node(4); System.out.println(\"ZigZag Order traversal of binary tree is\"); tree.printZigZagTraversal();}} // This Code is contributed by Harikrishnan Rajan.", "e": 31431, "s": 29380, "text": null }, { "code": "# Python Program to print zigzag traversal# of binary tree # Binary tree nodeclass Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = self.right = None # function to print zigzag traversal of# binary treedef zizagtraversal(root): # Base Case if root is None: return # Create two stacks to store current # and next level currentLevel = [] nextLevel = [] # if ltr is true push nodes from # left to right otherwise from # right to left ltr = True # append root to currentlevel stack currentLevel.append(root) # Check if stack is empty while len(currentLevel) > 0: # pop from stack temp = currentLevel.pop(-1) # print the data print(temp.data, \" \", end=\"\") if ltr: # if ltr is true push left # before right if temp.left: nextLevel.append(temp.left) if temp.right: nextLevel.append(temp.right) else: # else push right before left if temp.right: nextLevel.append(temp.right) if temp.left: nextLevel.append(temp.left) if len(currentLevel) == 0: # reverse ltr to push node in # opposite order ltr = not ltr # swapping of stacks currentLevel, nextLevel = nextLevel, currentLevel # Driver program to check above functionroot = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(7)root.left.right = Node(6)root.right.left = Node(5)root.right.right = Node(4)print(\"Zigzag Order traversal of binary tree is\")zizagtraversal(root) # This code is contributed by Shweta Singh", "e": 33171, "s": 31431, "text": null }, { "code": "// C# implementation of a O(n) time// method for Zigzag order traversalusing System;using System.Collections.Generic; // Binary Tree nodepublic class Node{ public int data; public Node leftChild; public Node rightChild; public Node(int data) { this.data = data; }} class GFG{ public Node rootNode; // function to print the // zigzag traversal public virtual void printZigZagTraversal() { // if null then return if (rootNode == null) { return; } // declare two stacks Stack<Node> currentLevel = new Stack<Node>(); Stack<Node> nextLevel = new Stack<Node>(); // push the root currentLevel.Push(rootNode); bool leftToRight = true; // check if stack is empty while (currentLevel.Count > 0) { // pop out of stack Node node = currentLevel.Pop(); // print the data in it Console.Write(node.data + \" \"); // store data according to current // order. if (leftToRight) { if (node.leftChild != null) { nextLevel.Push(node.leftChild); } if (node.rightChild != null) { nextLevel.Push(node.rightChild); } } else { if (node.rightChild != null) { nextLevel.Push(node.rightChild); } if (node.leftChild != null) { nextLevel.Push(node.leftChild); } } if (currentLevel.Count == 0) { leftToRight = !leftToRight; Stack<Node> temp = currentLevel; currentLevel = nextLevel; nextLevel = temp; } } }} public class zigZagTreeTraversal{ // Driver Codepublic static void Main(string[] args){ GFG tree = new GFG(); tree.rootNode = new Node(1); tree.rootNode.leftChild = new Node(2); tree.rootNode.rightChild = new Node(3); tree.rootNode.leftChild.leftChild = new Node(7); tree.rootNode.leftChild.rightChild = new Node(6); tree.rootNode.rightChild.leftChild = new Node(5); tree.rootNode.rightChild.rightChild = new Node(4); Console.WriteLine(\"ZigZag Order traversal \" + \"of binary tree is\"); tree.printZigZagTraversal();}} // This code is contributed by Shrikant13", "e": 35609, "s": 33171, "text": null }, { "code": "<script> // JavaScript implementation of a O(n) time // method for Zigzag order traversal class Node { constructor(data) { this.leftChild = null; this.rightChild = null; this.data = data; } } let rootNode; // function to print the // zigzag traversal function printZigZagTraversal() { // if null then return if (rootNode == null) { return; } // declare two stacks let currentLevel = []; let nextLevel = []; // push the root currentLevel.push(rootNode); let leftToRight = true; // check if stack is empty while (currentLevel.length > 0) { // pop out of stack let node = currentLevel.pop(); // print the data in it document.write(node.data + \" \"); // store data according to current // order. if (leftToRight) { if (node.leftChild != null) { nextLevel.push(node.leftChild); } if (node.rightChild != null) { nextLevel.push(node.rightChild); } } else { if (node.rightChild != null) { nextLevel.push(node.rightChild); } if (node.leftChild != null) { nextLevel.push(node.leftChild); } } if (currentLevel.length == 0) { leftToRight = !leftToRight; let temp = currentLevel; currentLevel = nextLevel; nextLevel = temp; } } } rootNode = new Node(1); rootNode.leftChild = new Node(2); rootNode.rightChild = new Node(3); rootNode.leftChild.leftChild = new Node(7); rootNode.leftChild.rightChild = new Node(6); rootNode.rightChild.leftChild = new Node(5); rootNode.rightChild.rightChild = new Node(4); document.write(\"ZigZag Order traversal of binary tree is\" + \"</br>\"); printZigZagTraversal(); </script>", "e": 37818, "s": 35609, "text": null }, { "code": null, "e": 37875, "s": 37818, "text": "ZigZag Order traversal of binary tree is \n1 3 2 7 6 5 4 " }, { "code": null, "e": 37929, "s": 37875, "text": "Time Complexity: O(n) Space Complexity: O(n)+(n)=O(n)" }, { "code": null, "e": 37949, "s": 37929, "text": "Recursive Approach:" }, { "code": null, "e": 38146, "s": 37949, "text": "The approach used here is the observable similarity to the level order traversal. Here we need to include an extra parameter to keep a track of printing each level in left-right or right-left way." }, { "code": null, "e": 38150, "s": 38146, "text": "C++" }, { "code": "//Initial Template for C++#include <bits/stdc++.h>using namespace std; struct Node { int data; Node *left; Node *right; Node(int val) { data = val; left = right = NULL; }}; // Function to Build TreeNode* buildTree(string str){ // Corner Case if(str.length() == 0 || str[0] == 'N') return NULL; // Creating vector of strings from input // string after splitting by space vector<string> ip; istringstream iss(str); for(string str; iss >> str; ) ip.push_back(str); // Create the root of the tree Node* root = new Node(stoi(ip[0])); // Push the root to the queue queue<Node*> queue; queue.push(root); // Starting from the second element int i = 1; while(!queue.empty() && i < ip.size()) { // Get and remove the front of the queue Node* currNode = queue.front(); queue.pop(); // Get the current node's value from the string string currVal = ip[i]; // If the left child is not null if(currVal != \"N\") { // Create the left child for the current node currNode->left = new Node(stoi(currVal)); // Push it to the queue queue.push(currNode->left); } // For the right child i++; if(i >= ip.size()) break; currVal = ip[i]; // If the right child is not null if(currVal != \"N\") { // Create the right child for the current node currNode->right = new Node(stoi(currVal)); // Push it to the queue queue.push(currNode->right); } i++; } return root;} // Function to calculate height of treeint treeHeight(Node *root){ if(!root) return 0; int lHeight = treeHeight(root->left); int rHeight = treeHeight(root->right); return max(lHeight, rHeight) + 1;} // Helper Function to store the zig zag order traversal// of tree in a list recursivelyvoid zigZagTraversalRecursion(Node* root, int height, bool lor, vector<int> &ans){ // Height = 1 means the tree now has only one node if(height <= 1){ if(root) ans.push_back(root->data); } // When Height > 1 else{ if(lor){ if(root->left) zigZagTraversalRecursion(root->left, height - 1, lor, ans); if(root->right) zigZagTraversalRecursion(root->right, height - 1, lor, ans); } else{ if(root->right) zigZagTraversalRecursion(root->right, height - 1, lor, ans); if(root->left) zigZagTraversalRecursion(root->left, height - 1, lor, ans); } }} // Function to traverse tree in zig zag ordervector <int> zigZagTraversal(Node* root){ vector<int> ans; bool leftOrRight = true; int height = treeHeight(root); for(int i = 1; i <= height; i++){ zigZagTraversalRecursion(root, i, leftOrRight, ans); leftOrRight = !leftOrRight; } return ans;} int main(){ // Tree: // 1 // / \\ // / \\ // / \\ // 2 3 // / \\ / \\ // 4 5 6 7 // / \\ / \\ / \\ / \\ //8 9 10 11 12 13 14 15 string s = \"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15\"; Node* root = buildTree(s); vector <int> res = zigZagTraversal(root); cout<<\"ZigZag traversal of binary tree is:\"<<endl; for (int i = 0; i < res.size (); i++) cout << res[i] << \" \"; cout<<endl; return 0;}// Code By Angshuman Sengupta", "e": 41773, "s": 38150, "text": null }, { "code": null, "e": 41846, "s": 41773, "text": "ZigZag traversal of binary tree is:\n1 3 2 4 5 6 7 15 14 13 12 11 10 9 8 " }, { "code": null, "e": 41854, "s": 41846, "text": "Output:" }, { "code": null, "e": 41890, "s": 41854, "text": "ZigZag traversal of binary tree is:" }, { "code": null, "e": 41926, "s": 41890, "text": "1 3 2 4 5 6 7 15 14 13 12 11 10 9 8" }, { "code": null, "e": 42077, "s": 41926, "text": "Another Approach:In this approach, use a deque to solve the problem. Push and pop in different ways depending on if the level is odd or level is even." }, { "code": null, "e": 42128, "s": 42077, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 42132, "s": 42128, "text": "C++" }, { "code": null, "e": 42137, "s": 42132, "text": "Java" }, { "code": null, "e": 42145, "s": 42137, "text": "Python3" }, { "code": "// C++ implementation of a O(n) time method for// Zigzag order traversal#include <bits/stdc++.h>#include <iostream>using namespace std; // Binary Tree nodeclass Node {public: int data; Node *left, *right;}; // Function to print the zigzag traversalvector<int> zigZagTraversal(Node* root){ deque<Node*> q; vector<int> v; q.push_back(root); v.push_back(root->data); Node* temp; // set initial level as 1, because root is // already been taken care of. int l = 1; while (!q.empty()) { int n = q.size(); for (int i = 0; i < n; i++) { // popping mechanism if (l % 2 == 0) { temp = q.back(); q.pop_back(); } else { temp = q.front(); q.pop_front(); } // pushing mechanism if (l % 2 != 0) { if (temp->right) { q.push_back(temp->right); v.push_back(temp->right->data); } if (temp->left) { q.push_back(temp->left); v.push_back(temp->left->data); } } else if (l % 2 == 0) { if (temp->left) { q.push_front(temp->left); v.push_back(temp->left->data); } if (temp->right) { q.push_front(temp->right); v.push_back(temp->right->data); } } } l++; // level plus one } return v;} // A utility function to create a new nodestruct Node* newNode(int data){ struct Node* node = new struct Node; node->data = data; node->left = node->right = NULL; return (node);} // Driver program to test// the above functionint main(){ // vector to store the traversal order. vector<int> v; // create tree struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(7); root->left->right = newNode(6); root->right->left = newNode(5); root->right->right = newNode(4); cout << \"ZigZag Order traversal of binary tree is \\n\"; v = zigZagTraversal(root); for (int i = 0; i < v.size(); i++) { // to print the order cout << v[i] << \" \"; } return 0;}// This code is contributed by Ritvik Mahajan", "e": 44557, "s": 42145, "text": null }, { "code": "// Java implementation of a O(n) time method for// Zigzag order traversalimport java.util.*;public class Main{ // Class containing left and // right child of current // node and key value static class Node { public int data; public Node left, right; public Node(int data) { this.data = data; left = right = null; } } // A utility function to create a new node static Node newNode(int data) { Node node = new Node(data); return node; } // Function to print the zigzag traversal static Vector<Integer> zigZagTraversal(Node root) { Deque<Node> q = new LinkedList<Node>(); Vector<Integer> v = new Vector<Integer>(); q.add(root); v.add(root.data); Node temp; // set initial level as 1, because root is // already been taken care of. int l = 1; while (q.size() > 0) { int n = q.size(); for (int i = 0; i < n; i++) { // popping mechanism if (l % 2 == 0) { temp = q.peekLast(); q.pollLast(); } else { temp = q.peekFirst(); q.pollFirst(); } // pushing mechanism if (l % 2 != 0) { if (temp.right != null) { q.add(temp.right); v.add(temp.right.data); } if (temp.left != null) { q.add(temp.left); v.add(temp.left.data); } } else if (l % 2 == 0) { if (temp.left != null) { q.offerFirst(temp.left); v.add(temp.left.data); } if (temp.right != null) { q.offerFirst(temp.right); v.add(temp.right.data); } } } l++; // level plus one } return v; } public static void main(String[] args) { // vector to store the traversal order. Vector<Integer> v; // create tree Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(7); root.left.right = newNode(6); root.right.left = newNode(5); root.right.right = newNode(4); System.out.println(\"ZigZag Order traversal of binary tree is\"); v = zigZagTraversal(root); for (int i = 0; i < v.size(); i++) { // to print the order System.out.print(v.get(i) + \" \"); } }} // This code is contributed by divyesh072019.", "e": 47463, "s": 44557, "text": null }, { "code": "# Python3 implementation of a O(n) time method for# Zigzag order traversalfrom collections import deque # Binary Tree nodeclass Node: def __init__(self, data): self.data = data self.left = None self.right = None # Function to print the zigzag traversaldef zigZagTraversal(root): q = deque([]) v = [] q.append(root) v.append(root.data) # set initial level as 1, because root is # already been taken care of. l = 1 while len(q) > 0: n = len(q) for i in range(n): # popping mechanism if (l % 2 == 0): temp = q[-1] q.pop() else: temp = q[0] q.popleft() # pushing mechanism if (l % 2 != 0): if (temp.right): q.append(temp.right) v.append(temp.right.data) if (temp.left): q.append(temp.left) v.append(temp.left.data) elif (l % 2 == 0): if (temp.left): q.appendleft(temp.left) v.append(temp.left.data) if (temp.right): q.appendleft(temp.right) v.append(temp.right.data) l+=1 # level plus one return v # vector to store the traversal order.v = [] # create treeroot = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(7)root.left.right = Node(6)root.right.left = Node(5)root.right.right = Node(4)print(\"ZigZag Order traversal of binary tree is\") v = zigZagTraversal(root) for i in range(len(v)): print(v[i], end = \" \") # This code is contributed by suresh07.", "e": 49175, "s": 47463, "text": null }, { "code": null, "e": 49232, "s": 49175, "text": "ZigZag Order traversal of binary tree is \n1 3 2 7 6 5 4 " }, { "code": null, "e": 49254, "s": 49232, "text": "Time Complexity: O(N)" }, { "code": null, "e": 49301, "s": 49254, "text": "Auxiliary Space: O(N) for deque data structure" }, { "code": null, "e": 49319, "s": 49301, "text": "Another Approach:" }, { "code": null, "e": 49677, "s": 49319, "text": "We can use a queue just like we used in Level Order Traversal. But in this case, we can also maintain a flag variable which keeps track of alternate level to reverse the order of the corresponding level traversal.flag==true implies we have to insert from left to right and flag==false means we have to insert element from right to left our answer arraylist." }, { "code": null, "e": 49681, "s": 49677, "text": "C++" }, { "code": null, "e": 49686, "s": 49681, "text": "Java" }, { "code": "// C++ implementation of a O(n) time method for// Zigzag order traversal#include <bits/stdc++.h>#include <iostream>using namespace std; // Binary Tree nodeclass Node {public: int data; Node *left, *right;}; // Function to print the zigzag traversalvector<int> zigZagTraversal(Node* root) { if(root == NULL){return { } ; } vector<int > ans ; queue<Node*> q ; q.push(root) ; bool flag = false ; while(!q.empty()){ int size = q.size() ; vector<int> level ; for(int i=0 ; i < size ; i++){ Node* node = q.front() ; q.pop() ; level.push_back(node->data) ; if(node->left != NULL) {q.push(node->left) ;} if(node->right != NULL) {q.push(node->right) ;} } flag = !flag ; if(flag == false){ reverse(level.begin() , level.end()) ; } for(int i = 0 ; i < level.size() ; i++){ ans.push_back(level[i]) ; } } return ans ;} // A utility function to create a new nodestruct Node* newNode(int data){ struct Node* node = new struct Node; node->data = data; node->left = node->right = NULL; return (node);} // Driver program to test// the above functionint main(){ // vector to store the traversal order. vector<int> v; // create tree struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(7); root->left->right = newNode(6); root->right->left = newNode(5); root->right->right = newNode(4); cout << \"ZigZag Order traversal of binary tree is \\n\"; v = zigZagTraversal(root); for (int i = 0; i < v.size(); i++) { // to print the order cout << v[i] << \" \"; } return 0;}", "e": 51464, "s": 49686, "text": null }, { "code": "// Java implementation of a O(n) time method for// Zigzag order traversalimport java.util.*;public class Main { // Class containing left and // right child of current // node and key value static class Node { public int data; public Node left, right; public Node(int data) { this.data = data; left = right = null; } } // A utility function to create a new node static Node newNode(int data) { Node node = new Node(data); return node; } // Function to print the zigzag traversal static ArrayList<Integer> zigZagTraversal(Node root) { ArrayList<Integer> ans = new ArrayList<Integer>(); // if there is no element in the tree,return empty // arraylist if (root == null) return ans; Queue<Node> q = new LinkedList<Node>(); q.add(root); // this variable helps to check if elements are to // be added from left to right or right to left boolean leftToRight = true; while (q.size() > 0) { int size = q.size(); // this arraylist is used to store element at // current level ArrayList<Integer> temp = new ArrayList<>(); for (int i = 0; i < size; i++) { Node curr = q.poll(); if (curr.left != null) q.add(curr.left); if (curr.right != null) q.add(curr.right); temp.add(curr.data); } if (leftToRight) // at current level,add element // fom left to right to our // answer { // do nothing } // we have to add element from to right to left // and this can be done by reversing our temp // arraylist else { Collections.reverse(temp); } // add element form temp arraylist to our ans // arraylist for (int i = 0; i < temp.size(); i++) { ans.add(temp.get(i)); } // change the value of leftToRight from true to // false or false to true for next iteration. leftToRight = !(leftToRight); } // return our ans arraylist return ans; } public static void main(String[] args) { // Arraylist to store the traversal order. ArrayList<Integer> ans; // create tree Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(7); root.left.right = newNode(6); root.right.left = newNode(5); root.right.right = newNode(4); System.out.println( \"ZigZag Order traversal of binary tree is\"); ans = zigZagTraversal(root); for (int i = 0; i < ans.size(); i++) { // to print the order System.out.print(ans.get(i) + \" \"); } }}// this is contributed by akshita29320", "e": 54518, "s": 51464, "text": null }, { "code": null, "e": 54575, "s": 54518, "text": "ZigZag Order traversal of binary tree is \n1 3 2 7 6 5 4 " }, { "code": null, "e": 54597, "s": 54575, "text": "Time Complexity: O(N)" }, { "code": null, "e": 54644, "s": 54597, "text": "Auxiliary Space: O(N) for queue data structure" }, { "code": null, "e": 54738, "s": 54644, "text": "Below is a simple implementation of this problem. (video)Level order traversal in spiral form" }, { "code": null, "e": 54747, "s": 54738, "text": "shweta44" }, { "code": null, "e": 54759, "s": 54747, "text": "shrikanth13" }, { "code": null, "e": 54776, "s": 54759, "text": "innovativeprasen" }, { "code": null, "e": 54794, "s": 54776, "text": "ritvikmahajan2001" }, { "code": null, "e": 54806, "s": 54794, "text": "coderangshu" }, { "code": null, "e": 54815, "s": 54806, "text": "gabaa406" }, { "code": null, "e": 54824, "s": 54815, "text": "mukesh07" }, { "code": null, "e": 54833, "s": 54824, "text": "suresh07" }, { "code": null, "e": 54847, "s": 54833, "text": "divyesh072019" }, { "code": null, "e": 54860, "s": 54847, "text": "prasanna1995" }, { "code": null, "e": 54873, "s": 54860, "text": "akshita29320" }, { "code": null, "e": 54889, "s": 54873, "text": "saurabh1990aror" }, { "code": null, "e": 54896, "s": 54889, "text": "Amazon" }, { "code": null, "e": 54906, "s": 54896, "text": "cpp-queue" }, { "code": null, "e": 54916, "s": 54906, "text": "cpp-stack" }, { "code": null, "e": 54924, "s": 54916, "text": "FactSet" }, { "code": null, "e": 54934, "s": 54924, "text": "Traversal" }, { "code": null, "e": 54940, "s": 54934, "text": "Queue" }, { "code": null, "e": 54946, "s": 54940, "text": "Stack" }, { "code": null, "e": 54951, "s": 54946, "text": "Tree" }, { "code": null, "e": 54958, "s": 54951, "text": "Amazon" }, { "code": null, "e": 54966, "s": 54958, "text": "FactSet" }, { "code": null, "e": 54972, "s": 54966, "text": "Stack" }, { "code": null, "e": 54982, "s": 54972, "text": "Traversal" }, { "code": null, "e": 54988, "s": 54982, "text": "Queue" }, { "code": null, "e": 54993, "s": 54988, "text": "Tree" }, { "code": null, "e": 55091, "s": 54993, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 55126, "s": 55091, "text": "Queue - Linked List Implementation" }, { "code": null, "e": 55189, "s": 55126, "text": "Circular Queue | Set 1 (Introduction and Array Implementation)" }, { "code": null, "e": 55249, "s": 55189, "text": "Sliding Window Maximum (Maximum of all subarrays of size k)" }, { "code": null, "e": 55278, "s": 55249, "text": "Implement Stack using Queues" }, { "code": null, "e": 55317, "s": 55278, "text": "Array implementation of queue (Simple)" }, { "code": null, "e": 55365, "s": 55317, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 55385, "s": 55365, "text": "Stack Class in Java" }, { "code": null, "e": 55401, "s": 55385, "text": "Stack in Python" }, { "code": null, "e": 55476, "s": 55401, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" } ]
How to remove n elements from the end of a given array in JavaScript ? - GeeksforGeeks
01 Apr, 2021 In this article, we will learn how to remove the last n elements from the end of the given array in JavaScript. This can be achieved using two approaches: The splice() method in JavaScript is used to modify an array by adding or removing elements from it. This method accepts the index from which the modification has to be made and the number of elements to delete. The index from which the deletion has to start can be found out by subtracting the number of elements from the length of the array. Syntax: array.splice(start, deleteCount); Example: HTML <html> <body> <h1 style="color: green;"> GeeksforGeeks </h1> <b> How to remove n elements from the end of a given array in JavaScript? </b> <script> // Define the array let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]; console.log("Original Array:", arr); // Define the number of elements to remove let elemsToDelete = 3; // Using the splice() method to remove from // the last nth index for n elements arr.splice(arr.length - elemsToDelete, elemsToDelete); console.log("Modified Array:", arr); </script> </body></html> Output: Original Array: [1, 2, 3, 4, 5, 6, 7, 8, 9] Modified Array: [1, 2, 3, 4, 5, 6] The pop() method in JavaScript is used to remove the last element from the array. This can be repeated in a loop of n iterations to remove the last n elements of the array using the while loop. Syntax: array.pop(); Example: HTML <html> <body> <h1 style="color: green;"> GeeksforGeeks </h1> <b> How to remove n elements from the end of a given array in JavaScript? </b> <script> // Define the array let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]; console.log("Original Array:", arr); // Define the number of elements to remove let elemsToDelete = 5; // Loop for the number of elements // to delete while (elemsToDelete--) // Pop the last element from the // end of the array arr.pop(); console.log("Modified Array:", arr); </script> </body></html> Output: Original Array: [1, 2, 3, 4, 5, 6, 7, 8, 9] Modified Array: [1, 2, 3, 4] javascript-array JavaScript-Methods JavaScript-Questions JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? Remove elements from a JavaScript Array Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26545, "s": 26517, "text": "\n01 Apr, 2021" }, { "code": null, "e": 26700, "s": 26545, "text": "In this article, we will learn how to remove the last n elements from the end of the given array in JavaScript. This can be achieved using two approaches:" }, { "code": null, "e": 27045, "s": 26700, "text": "The splice() method in JavaScript is used to modify an array by adding or removing elements from it. This method accepts the index from which the modification has to be made and the number of elements to delete. The index from which the deletion has to start can be found out by subtracting the number of elements from the length of the array. " }, { "code": null, "e": 27053, "s": 27045, "text": "Syntax:" }, { "code": null, "e": 27087, "s": 27053, "text": "array.splice(start, deleteCount);" }, { "code": null, "e": 27096, "s": 27087, "text": "Example:" }, { "code": null, "e": 27101, "s": 27096, "text": "HTML" }, { "code": "<html> <body> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <b> How to remove n elements from the end of a given array in JavaScript? </b> <script> // Define the array let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]; console.log(\"Original Array:\", arr); // Define the number of elements to remove let elemsToDelete = 3; // Using the splice() method to remove from // the last nth index for n elements arr.splice(arr.length - elemsToDelete, elemsToDelete); console.log(\"Modified Array:\", arr); </script> </body></html>", "e": 27716, "s": 27101, "text": null }, { "code": null, "e": 27724, "s": 27716, "text": "Output:" }, { "code": null, "e": 27803, "s": 27724, "text": "Original Array: [1, 2, 3, 4, 5, 6, 7, 8, 9]\nModified Array: [1, 2, 3, 4, 5, 6]" }, { "code": null, "e": 27997, "s": 27803, "text": "The pop() method in JavaScript is used to remove the last element from the array. This can be repeated in a loop of n iterations to remove the last n elements of the array using the while loop." }, { "code": null, "e": 28005, "s": 27997, "text": "Syntax:" }, { "code": null, "e": 28018, "s": 28005, "text": "array.pop();" }, { "code": null, "e": 28027, "s": 28018, "text": "Example:" }, { "code": null, "e": 28032, "s": 28027, "text": "HTML" }, { "code": "<html> <body> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <b> How to remove n elements from the end of a given array in JavaScript? </b> <script> // Define the array let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]; console.log(\"Original Array:\", arr); // Define the number of elements to remove let elemsToDelete = 5; // Loop for the number of elements // to delete while (elemsToDelete--) // Pop the last element from the // end of the array arr.pop(); console.log(\"Modified Array:\", arr); </script> </body></html>", "e": 28654, "s": 28032, "text": null }, { "code": null, "e": 28662, "s": 28654, "text": "Output:" }, { "code": null, "e": 28735, "s": 28662, "text": "Original Array: [1, 2, 3, 4, 5, 6, 7, 8, 9]\nModified Array: [1, 2, 3, 4]" }, { "code": null, "e": 28752, "s": 28735, "text": "javascript-array" }, { "code": null, "e": 28771, "s": 28752, "text": "JavaScript-Methods" }, { "code": null, "e": 28792, "s": 28771, "text": "JavaScript-Questions" }, { "code": null, "e": 28803, "s": 28792, "text": "JavaScript" }, { "code": null, "e": 28820, "s": 28803, "text": "Web Technologies" }, { "code": null, "e": 28847, "s": 28820, "text": "Web technologies Questions" }, { "code": null, "e": 28945, "s": 28847, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28985, "s": 28945, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29046, "s": 28985, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29087, "s": 29046, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 29109, "s": 29087, "text": "JavaScript | Promises" }, { "code": null, "e": 29163, "s": 29109, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 29203, "s": 29163, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29236, "s": 29203, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29279, "s": 29236, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29341, "s": 29279, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Program to Iterate over a Stream with Indices in Java 8 - GeeksforGeeks
11 Dec, 2018 Given a Stream in Java, the task is to iterate over it with the help of indices. Examples: Input: Stream = [G, e, e, k, s]Output: [0 -> G, 1 -> e, 2 -> e, 3 -> k, 4 -> s] Input: Stream = [G, e, e, k, s, F, o, r, G, e, e, k, s]Output: [0 -> G, 1 -> e, 2 -> e, 3 -> k, 4 -> s, 5 -> F, 6 -> o, 7 -> r, 8 -> G, 9 -> e, 10 -> e, 11 -> k, 12 -> s] Method 1: Using IntStream.Get the Stream from the array using range() method.Map each elements of the stream with an index associated with it using mapToObj() methodPrint the elements with indices// Java program to iterate over Stream with Indices import java.util.stream.IntStream; class GFG { public static void main(String[] args) { String[] array = { "G", "e", "e", "k", "s" }; // Iterate over the Stream with indices IntStream // Get the Stream from the array .range(0, array.length) // Map each elements of the stream // with an index associated with it .mapToObj(index -> String.format("%d -> %s", index, array[index])) // Print the elements with indices .forEach(System.out::println); }}Output:0 -> G 1 -> e 2 -> e 3 -> k 4 -> s Get the Stream from the array using range() method.Map each elements of the stream with an index associated with it using mapToObj() methodPrint the elements with indices Get the Stream from the array using range() method. Map each elements of the stream with an index associated with it using mapToObj() method Print the elements with indices // Java program to iterate over Stream with Indices import java.util.stream.IntStream; class GFG { public static void main(String[] args) { String[] array = { "G", "e", "e", "k", "s" }; // Iterate over the Stream with indices IntStream // Get the Stream from the array .range(0, array.length) // Map each elements of the stream // with an index associated with it .mapToObj(index -> String.format("%d -> %s", index, array[index])) // Print the elements with indices .forEach(System.out::println); }} 0 -> G 1 -> e 2 -> e 3 -> k 4 -> s Method 2: Using AtomicInteger.Create an AtomicInteger for index.Get the Stream from the array using Arrays.stream() method.Map each elements of the stream with an index associated with it using map() method where the index is fetched from the AtomicInteger by auto-incrementing index everytime with the help of getAndIncrement() method.Print the elements with indices.// Java program to iterate over Stream with Indices import java.util.stream.IntStream;import java.util.*;import java.util.concurrent.atomic.AtomicInteger; class GFG { public static void main(String[] args) { String[] array = { "G", "e", "e", "k", "s" }; // Create an AtomicInteger for index AtomicInteger index = new AtomicInteger(); // Iterate over the Stream with indices Arrays // Get the Stream from the array .stream(array) // Map each elements of the stream // with an index associated with it .map(str -> index.getAndIncrement() + " -> " + str) // Print the elements with indices .forEach(System.out::println); }}Output:0 -> G 1 -> e 2 -> e 3 -> k 4 -> s Create an AtomicInteger for index.Get the Stream from the array using Arrays.stream() method.Map each elements of the stream with an index associated with it using map() method where the index is fetched from the AtomicInteger by auto-incrementing index everytime with the help of getAndIncrement() method.Print the elements with indices. Create an AtomicInteger for index. Get the Stream from the array using Arrays.stream() method. Map each elements of the stream with an index associated with it using map() method where the index is fetched from the AtomicInteger by auto-incrementing index everytime with the help of getAndIncrement() method. Print the elements with indices. // Java program to iterate over Stream with Indices import java.util.stream.IntStream;import java.util.*;import java.util.concurrent.atomic.AtomicInteger; class GFG { public static void main(String[] args) { String[] array = { "G", "e", "e", "k", "s" }; // Create an AtomicInteger for index AtomicInteger index = new AtomicInteger(); // Iterate over the Stream with indices Arrays // Get the Stream from the array .stream(array) // Map each elements of the stream // with an index associated with it .map(str -> index.getAndIncrement() + " -> " + str) // Print the elements with indices .forEach(System.out::println); }} 0 -> G 1 -> e 2 -> e 3 -> k 4 -> s Java 8 java-basics java-stream Java-Stream-programs Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java How to iterate any Map in Java ArrayList in Java Initializing a List in Java Convert a String to Character Array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 25519, "s": 25491, "text": "\n11 Dec, 2018" }, { "code": null, "e": 25600, "s": 25519, "text": "Given a Stream in Java, the task is to iterate over it with the help of indices." }, { "code": null, "e": 25610, "s": 25600, "text": "Examples:" }, { "code": null, "e": 25690, "s": 25610, "text": "Input: Stream = [G, e, e, k, s]Output: [0 -> G, 1 -> e, 2 -> e, 3 -> k, 4 -> s]" }, { "code": null, "e": 25861, "s": 25690, "text": "Input: Stream = [G, e, e, k, s, F, o, r, G, e, e, k, s]Output: [0 -> G, 1 -> e, 2 -> e, 3 -> k, 4 -> s, 5 -> F, 6 -> o, 7 -> r, 8 -> G, 9 -> e, 10 -> e, 11 -> k, 12 -> s]" }, { "code": null, "e": 26757, "s": 25861, "text": "Method 1: Using IntStream.Get the Stream from the array using range() method.Map each elements of the stream with an index associated with it using mapToObj() methodPrint the elements with indices// Java program to iterate over Stream with Indices import java.util.stream.IntStream; class GFG { public static void main(String[] args) { String[] array = { \"G\", \"e\", \"e\", \"k\", \"s\" }; // Iterate over the Stream with indices IntStream // Get the Stream from the array .range(0, array.length) // Map each elements of the stream // with an index associated with it .mapToObj(index -> String.format(\"%d -> %s\", index, array[index])) // Print the elements with indices .forEach(System.out::println); }}Output:0 -> G\n1 -> e\n2 -> e\n3 -> k\n4 -> s\n" }, { "code": null, "e": 26928, "s": 26757, "text": "Get the Stream from the array using range() method.Map each elements of the stream with an index associated with it using mapToObj() methodPrint the elements with indices" }, { "code": null, "e": 26980, "s": 26928, "text": "Get the Stream from the array using range() method." }, { "code": null, "e": 27069, "s": 26980, "text": "Map each elements of the stream with an index associated with it using mapToObj() method" }, { "code": null, "e": 27101, "s": 27069, "text": "Print the elements with indices" }, { "code": "// Java program to iterate over Stream with Indices import java.util.stream.IntStream; class GFG { public static void main(String[] args) { String[] array = { \"G\", \"e\", \"e\", \"k\", \"s\" }; // Iterate over the Stream with indices IntStream // Get the Stream from the array .range(0, array.length) // Map each elements of the stream // with an index associated with it .mapToObj(index -> String.format(\"%d -> %s\", index, array[index])) // Print the elements with indices .forEach(System.out::println); }}", "e": 27759, "s": 27101, "text": null }, { "code": null, "e": 27795, "s": 27759, "text": "0 -> G\n1 -> e\n2 -> e\n3 -> k\n4 -> s\n" }, { "code": null, "e": 28961, "s": 27795, "text": "Method 2: Using AtomicInteger.Create an AtomicInteger for index.Get the Stream from the array using Arrays.stream() method.Map each elements of the stream with an index associated with it using map() method where the index is fetched from the AtomicInteger by auto-incrementing index everytime with the help of getAndIncrement() method.Print the elements with indices.// Java program to iterate over Stream with Indices import java.util.stream.IntStream;import java.util.*;import java.util.concurrent.atomic.AtomicInteger; class GFG { public static void main(String[] args) { String[] array = { \"G\", \"e\", \"e\", \"k\", \"s\" }; // Create an AtomicInteger for index AtomicInteger index = new AtomicInteger(); // Iterate over the Stream with indices Arrays // Get the Stream from the array .stream(array) // Map each elements of the stream // with an index associated with it .map(str -> index.getAndIncrement() + \" -> \" + str) // Print the elements with indices .forEach(System.out::println); }}Output:0 -> G\n1 -> e\n2 -> e\n3 -> k\n4 -> s\n" }, { "code": null, "e": 29300, "s": 28961, "text": "Create an AtomicInteger for index.Get the Stream from the array using Arrays.stream() method.Map each elements of the stream with an index associated with it using map() method where the index is fetched from the AtomicInteger by auto-incrementing index everytime with the help of getAndIncrement() method.Print the elements with indices." }, { "code": null, "e": 29335, "s": 29300, "text": "Create an AtomicInteger for index." }, { "code": null, "e": 29395, "s": 29335, "text": "Get the Stream from the array using Arrays.stream() method." }, { "code": null, "e": 29609, "s": 29395, "text": "Map each elements of the stream with an index associated with it using map() method where the index is fetched from the AtomicInteger by auto-incrementing index everytime with the help of getAndIncrement() method." }, { "code": null, "e": 29642, "s": 29609, "text": "Print the elements with indices." }, { "code": "// Java program to iterate over Stream with Indices import java.util.stream.IntStream;import java.util.*;import java.util.concurrent.atomic.AtomicInteger; class GFG { public static void main(String[] args) { String[] array = { \"G\", \"e\", \"e\", \"k\", \"s\" }; // Create an AtomicInteger for index AtomicInteger index = new AtomicInteger(); // Iterate over the Stream with indices Arrays // Get the Stream from the array .stream(array) // Map each elements of the stream // with an index associated with it .map(str -> index.getAndIncrement() + \" -> \" + str) // Print the elements with indices .forEach(System.out::println); }}", "e": 30398, "s": 29642, "text": null }, { "code": null, "e": 30434, "s": 30398, "text": "0 -> G\n1 -> e\n2 -> e\n3 -> k\n4 -> s\n" }, { "code": null, "e": 30441, "s": 30434, "text": "Java 8" }, { "code": null, "e": 30453, "s": 30441, "text": "java-basics" }, { "code": null, "e": 30465, "s": 30453, "text": "java-stream" }, { "code": null, "e": 30486, "s": 30465, "text": "Java-Stream-programs" }, { "code": null, "e": 30491, "s": 30486, "text": "Java" }, { "code": null, "e": 30505, "s": 30491, "text": "Java Programs" }, { "code": null, "e": 30510, "s": 30505, "text": "Java" }, { "code": null, "e": 30608, "s": 30510, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30659, "s": 30608, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 30689, "s": 30659, "text": "HashMap in Java with Examples" }, { "code": null, "e": 30708, "s": 30689, "text": "Interfaces in Java" }, { "code": null, "e": 30739, "s": 30708, "text": "How to iterate any Map in Java" }, { "code": null, "e": 30757, "s": 30739, "text": "ArrayList in Java" }, { "code": null, "e": 30785, "s": 30757, "text": "Initializing a List in Java" }, { "code": null, "e": 30829, "s": 30785, "text": "Convert a String to Character Array in Java" }, { "code": null, "e": 30855, "s": 30829, "text": "Java Programming Examples" }, { "code": null, "e": 30889, "s": 30855, "text": "Convert Double to Integer in Java" } ]
Servlet - Sending Email - GeeksforGeeks
31 Mar, 2022 E-mail is considered the most secure, reliable, fast, and cheapest way of official communication over the internet. That’s the reason every second almost 2.7M emails are being sent. Therefore, your Web-Application may need an email service for many needs like – communication, Multi-Factor Authentication, etc. Working with mailing service within servlet requires – SMTP server(local/remote) and the two following APIs. Java Mail API (JMA) – javax.mail.jarJavaBeans Activation Framework API (JAF) – activation.jar Java Mail API (JMA) – javax.mail.jar JavaBeans Activation Framework API (JAF) – activation.jar Pre-requisites: If you use the Gmail SMTP server, the Sign-in attempt can be blocked due to2-step verification is turned on,Less secure app access is turned off. 2-step verification is turned on, Less secure app access is turned off. You can either change the google account settings or use Sign-in with Google / Google generated App code. Understanding mailing service protocols Protocols Description SMTP POP IMAP MIME Life-Cycle of Email Steps to associate Java Mail API: Download the javax.mail.jar file.Copy the javax.mail.jar file to the application’s WEB-INF\lib directory.Add the javax.mail.jar file to the classpath for your application. Download the javax.mail.jar file. Copy the javax.mail.jar file to the application’s WEB-INF\lib directory. Add the javax.mail.jar file to the classpath for your application. Steps to associate JavaBeans Activation Framework API: Download the ZIP file and extract the files.Copy the activation.jar file to the application’s WEB-INF\lib directory.Add the activation.jar file to the classpath for your application. Download the ZIP file and extract the files. Copy the activation.jar file to the application’s WEB-INF\lib directory. Add the activation.jar file to the classpath for your application. Note: The JavaBeans Activation Framework API is included with Java SE 6. As a result, if you’re using Java SE 6 or later, you don’t need to install this API. Web-Application (Servlet) Structure: Association of files in Servlet Web-Application 1] web.xml (configuration) XML <?xml version="1.0" encoding="UTF-8"?><web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"> <servlet> <servlet-name>Email</servlet-name> <servlet-class>mail.Servlet.Email</servlet-class> </servlet> <servlet-mapping> <servlet-name>Email</servlet-name> <url-pattern>/Email</url-pattern> </servlet-mapping> <session-config> <session-timeout> 30 </session-timeout> </session-config></web-app> 2] index.html (Entering Details) HTML <!DOCTYPE html><html> <head> <title>GeeksforGeeks</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <form action="Email" method="post"> <div align="center"> <h1>Enter the Credentials: </h1> <input type="hidden" name="action" value="add"> <label for="sID">Sender ID :</label> <br> <input id="sID" type="text" name="id"> <br> <label for="sMail">Sender Email :</label> <br> <input id="sMail" type="email" name="emailSender"> <br> <label for="pw">Password :</label> <br> <input id="pw" type="password" name="password"> <br> <label for="rMail">Receiver Email :</label> <br> <input id="rMail" type="email" name="emailReceiver"> <br> <label for="sub">Subject :</label> <br> <input id="sub" type="text" name="subject"> <br> <label for="message">Message :</label> <br> <input id="message" type="text" name="message"><br> <input type="submit" value="Send"> </div> </form> </body></html> Output: Fill details in output of Mail.java 3] Email.java (Servlet for handling details) Java package mail.Servlet; import static mail.Servlet.Mail.sendMail; import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; public class Email extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id, sender, receiver, password, subject, message; // check if directed url String action = request.getParameter("action"); String url = "/index.html"; if (action == null) { // directed to email interface action = "join"; } if (action.equals("join")) { url = "/index.html"; } if (action.equals("add")) { // retrieve the entered credentials id = request.getParameter("id"); sender = request.getParameter("emailSender"); receiver = request.getParameter("emailReceiver"); password = request.getParameter("password"); subject = request.getParameter("subject"); message = request.getParameter("message"); // get and set String value of email status request.setAttribute( "message", sendMail(id, receiver, sender, subject, message, true, password)); // directed to page showing the status of email url = "/confirmation.jsp"; } getServletContext() .getRequestDispatcher(url) .forward(request, response); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } // Returns a short description of the servlet. // @return a String containing servlet description @Override public String getServletInfo() { return "Short description"; }} 4] Mail.java (Helper class for creating and sending mail) Essential classes: Packages Description java.util javax.mail Create and Send an Email Message: Creating Mail Session: You have to create a mail session to create and send an email message.Before session creation, you need to create a Properties object containing properties (key-value pair) using the put(key, value) method that the session needs to send or receive mail.You at the least need to specify SMTP host property – use the ‘localhost’ keyword to specify SMTP server running on the same server as web-application. If you are using a remote SMTP server(e.g. Gmail server), use SMTPS protocol ( Secure connection and Authentication ).You can use other properties as well to configure mail sessions.Get Session object by wrapping Properties object into getDefaultInstance(Properties Object) method of Session class. You have to create a mail session to create and send an email message. Before session creation, you need to create a Properties object containing properties (key-value pair) using the put(key, value) method that the session needs to send or receive mail. You at the least need to specify SMTP host property – use the ‘localhost’ keyword to specify SMTP server running on the same server as web-application. If you are using a remote SMTP server(e.g. Gmail server), use SMTPS protocol ( Secure connection and Authentication ). You can use other properties as well to configure mail sessions. Get Session object by wrapping Properties object into getDefaultInstance(Properties Object) method of Session class. Common Properties Description mail.smtp.host mail.smtp.port mail.smtp.auth mail.smtp.quitwait // local SMTP server - Default Properties props = new Properties(); props.put("mail.smtp.host", "localhost"); Session session = Session.getDefaultInstance(props); // local SMTP server - Configure Properties props = new Properties(); props.put("mail.transport.protocol", "smtp"); props.put("mail.smtp.host", "localhost"); props.put("mail.smtp.port", 25); Session session = Session.getDefaultInstance(props); session.setDebug(true); // remote SMTP server Properties props = new Properties(); props.put("mail.transport.protocol", "smtps"); props.put("mail.smtps.host", "smtp.gmail.com"); props.put("mail.smtps.port", 465); props.put("mail.smtps.auth","true"); props.put("mail.smtps.quitwait","false"); Session session = Session.getDefaultInstance(props); session.setDebug(true); Creating Message: To create a message, you need to pass a Session object to the constructor of the MimeMessage class to create a MimeMessage object.You can set the subject, body, and addresses for the message.If the body is other than plain text, use the setContent() method to change the MIME type of message. To create a message, you need to pass a Session object to the constructor of the MimeMessage class to create a MimeMessage object. You can set the subject, body, and addresses for the message. If the body is other than plain text, use the setContent() method to change the MIME type of message. Message message = new MimeMessage(session); message.setSubject("Test"); // automatically sets to text/plain message.setText("Test Successful"); message.setContent("<h1>Test Successful<h1>", "text/html"); Note: All of the Message methods used above throws javax.mail.MessagingException. // add attachments within email // create 1'st part of body BodyPart bodyPart = new MimeBodyPart(); bodyPart.setText("Body Message"); Multipart multiPart = new MimeMultipart(); // wrap up 1'st part multiPart.addBodyPart(bodyPart); // create 2'nd part of body bodyPart = new MimeBodyPart(); DataSource source = new FileDataSource("Filename.txt"); bodyPart.setDataHandler(new DataHandler(source)); bodyPart.setFileName("Filename.txt"); // wrap up 2'nd part. multiPart.addBodyPart(bodyPart); // adds wrapped parts in message message.setContent(multiPart); Addressing a message: Create an object of InternetAddress (Sub-class of Address class).The first argument specifies the email address.You can add a second argument to associate an ID or email address to be displayed.To set FROM address. use setFrom(Address add) method of the MimeMessage object.To set TO, CC (carbon copy), BCC (blind carbon copy) address, use setRecipient(Type type, Address add) method of MimeMessage object.For multiple recipients, you can use setRecipients(Type type, Address[] add) method of the MimeMessage object. Create an object of InternetAddress (Sub-class of Address class). The first argument specifies the email address. You can add a second argument to associate an ID or email address to be displayed. To set FROM address. use setFrom(Address add) method of the MimeMessage object. To set TO, CC (carbon copy), BCC (blind carbon copy) address, use setRecipient(Type type, Address add) method of MimeMessage object. For multiple recipients, you can use setRecipients(Type type, Address[] add) method of the MimeMessage object. // set sender Address fromAdd = new InternetAddress("from@gmail.com", "from ID"); message.setFrom(fromAdd); // set recipient Address toAdd = new InternetAddress("to@gmail.com"); message.setRecipient(Message.RecipientType.TO, toAdd); message.setRecipient(Message.RecipientType.CC, toAdd); message.setRecipient(Message.RecipientType.BCC, toAdd); // set recipients message.setRecipients(Message.RecipientType.TO, new Address[]{new InternetAddress("to1@gmail.com"),new InternetAddress("to2@gmail.com")}); // add recipients Address toAdd1 = new InternetAddress("to@gmail.com"); message.addRecipient(Message.RecipientType.TO, toAdd1); Note: When you send a carbon copy, the CC addresses appear in the message. When you send a blind carbon copy, the BCC address doesn’t appear in the message. If you use the two-argument constructor of InternetAddress, it throws the java.io.UnsupportedEncoding Exception. Sending a message: If the SMTP doesn’t require authentication, you can use the static send(Message msg) method of the Transport class to send a message. Transport.send(message); If the SMTP requires authentication, you can use the getTransport() method of the session object.Then you can use connect method – public void connect(String user, String password) , to specify credentials (username, password) to connect to the server.Use abstract void sendMessage(Message msg, Address[] addresses) method to send the message.You need to close the connection using the close() method if not used try-with-resources block. If the SMTP requires authentication, you can use the getTransport() method of the session object. Then you can use connect method – public void connect(String user, String password) , to specify credentials (username, password) to connect to the server. Use abstract void sendMessage(Message msg, Address[] addresses) method to send the message. You need to close the connection using the close() method if not used try-with-resources block. Transport transport = session.getTransport(); transport.connect("email-id", "password"); transport.sendMessage("message", message.getAllRecipients()); transport.close(); Note: If the SMTP host is incorrect, the – static void send(Message msg) method throws SendFailedException. Java package mail.Servlet; import java.io.UnsupportedEncodingException;import java.util.Properties;import javax.mail.Address;import javax.mail.Message;import javax.mail.MessagingException;import javax.mail.Session;import javax.mail.Transport;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeMessage; public class Mail { public static String sendMail(String id, String to, String from, String subject, String body, boolean content, String password) { String status = null; try { // acquire a secure SMTPs session Properties pros = new Properties(); pros.put("mail.transport.protocol", "smtps"); pros.put("mail.smtps.host", "smtp.gmail.com"); pros.put("mail.smtps.port", 465); pros.put("mail.smtps.auth", "true"); pros.put("mail.smtps.quitwait", "false"); Session session = Session.getDefaultInstance(pros); session.setDebug(true); // Wrap a message in session Message message = new MimeMessage(session); message.setSubject(subject); if (content) { message.setContent(body, "text/html"); } else { message.setText(body); } // specify E-mail address of Sender and Receiver Address sender = new InternetAddress(from, id); Address receiver = new InternetAddress(to); message.setFrom(sender); message.setRecipient(Message.RecipientType.TO, receiver); // sending an E-mail try (Transport tt = session.getTransport()) { // acqruiring a connection to remote server tt.connect(from, password); tt.sendMessage(message, message.getAllRecipients()); status = "E-Mail Sent Successfully"; } } catch (MessagingException e) { status = e.toString(); } catch (UnsupportedEncodingException e) { status = e.toString(); } // return the status of email return status; }} 5] confirmation.jsp (Check the status of email) HTML <%@page contentType="text/html" pageEncoding="UTF-8"%><!DOCTYPE html><html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>GeeksforGeeks</title> </head> <body> <h3 align="center">Status of E-Mail : </h3> <h1 align="center">${requestScope.message}</h1> </body></html> Output: Mail Status after life-cycle adnanirshad158 sagartomar9927 java-servlet Picked Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Comparator Interface in Java with Examples Internal Working of HashMap in Java Strings in Java
[ { "code": null, "e": 25225, "s": 25197, "text": "\n31 Mar, 2022" }, { "code": null, "e": 25646, "s": 25225, "text": "E-mail is considered the most secure, reliable, fast, and cheapest way of official communication over the internet. That’s the reason every second almost 2.7M emails are being sent. Therefore, your Web-Application may need an email service for many needs like – communication, Multi-Factor Authentication, etc. Working with mailing service within servlet requires – SMTP server(local/remote) and the two following APIs." }, { "code": null, "e": 25741, "s": 25646, "text": "Java Mail API (JMA) – javax.mail.jarJavaBeans Activation Framework API (JAF) – activation.jar" }, { "code": null, "e": 25778, "s": 25741, "text": "Java Mail API (JMA) – javax.mail.jar" }, { "code": null, "e": 25837, "s": 25778, "text": "JavaBeans Activation Framework API (JAF) – activation.jar" }, { "code": null, "e": 25854, "s": 25837, "text": "Pre-requisites: " }, { "code": null, "e": 26000, "s": 25854, "text": "If you use the Gmail SMTP server, the Sign-in attempt can be blocked due to2-step verification is turned on,Less secure app access is turned off." }, { "code": null, "e": 26034, "s": 26000, "text": "2-step verification is turned on," }, { "code": null, "e": 26072, "s": 26034, "text": "Less secure app access is turned off." }, { "code": null, "e": 26178, "s": 26072, "text": "You can either change the google account settings or use Sign-in with Google / Google generated App code." }, { "code": null, "e": 26218, "s": 26178, "text": "Understanding mailing service protocols" }, { "code": null, "e": 26232, "s": 26218, "text": " Protocols " }, { "code": null, "e": 26244, "s": 26232, "text": "Description" }, { "code": null, "e": 26267, "s": 26244, "text": " SMTP " }, { "code": null, "e": 26271, "s": 26267, "text": "POP" }, { "code": null, "e": 26276, "s": 26271, "text": "IMAP" }, { "code": null, "e": 26281, "s": 26276, "text": "MIME" }, { "code": null, "e": 26301, "s": 26281, "text": "Life-Cycle of Email" }, { "code": null, "e": 26335, "s": 26301, "text": "Steps to associate Java Mail API:" }, { "code": null, "e": 26507, "s": 26335, "text": "Download the javax.mail.jar file.Copy the javax.mail.jar file to the application’s WEB-INF\\lib directory.Add the javax.mail.jar file to the classpath for your application." }, { "code": null, "e": 26541, "s": 26507, "text": "Download the javax.mail.jar file." }, { "code": null, "e": 26614, "s": 26541, "text": "Copy the javax.mail.jar file to the application’s WEB-INF\\lib directory." }, { "code": null, "e": 26681, "s": 26614, "text": "Add the javax.mail.jar file to the classpath for your application." }, { "code": null, "e": 26736, "s": 26681, "text": "Steps to associate JavaBeans Activation Framework API:" }, { "code": null, "e": 26919, "s": 26736, "text": "Download the ZIP file and extract the files.Copy the activation.jar file to the application’s WEB-INF\\lib directory.Add the activation.jar file to the classpath for your application." }, { "code": null, "e": 26964, "s": 26919, "text": "Download the ZIP file and extract the files." }, { "code": null, "e": 27037, "s": 26964, "text": "Copy the activation.jar file to the application’s WEB-INF\\lib directory." }, { "code": null, "e": 27104, "s": 27037, "text": "Add the activation.jar file to the classpath for your application." }, { "code": null, "e": 27262, "s": 27104, "text": "Note: The JavaBeans Activation Framework API is included with Java SE 6. As a result, if you’re using Java SE 6 or later, you don’t need to install this API." }, { "code": null, "e": 27299, "s": 27262, "text": "Web-Application (Servlet) Structure:" }, { "code": null, "e": 27347, "s": 27299, "text": "Association of files in Servlet Web-Application" }, { "code": null, "e": 27374, "s": 27347, "text": "1] web.xml (configuration)" }, { "code": null, "e": 27378, "s": 27374, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"UTF-8\"?><web-app version=\"3.1\" xmlns=\"http://xmlns.jcp.org/xml/ns/javaee\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd\"> <servlet> <servlet-name>Email</servlet-name> <servlet-class>mail.Servlet.Email</servlet-class> </servlet> <servlet-mapping> <servlet-name>Email</servlet-name> <url-pattern>/Email</url-pattern> </servlet-mapping> <session-config> <session-timeout> 30 </session-timeout> </session-config></web-app>", "e": 28021, "s": 27378, "text": null }, { "code": null, "e": 28054, "s": 28021, "text": "2] index.html (Entering Details)" }, { "code": null, "e": 28059, "s": 28054, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>GeeksforGeeks</title> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> </head> <body> <form action=\"Email\" method=\"post\"> <div align=\"center\"> <h1>Enter the Credentials: </h1> <input type=\"hidden\" name=\"action\" value=\"add\"> <label for=\"sID\">Sender ID :</label> <br> <input id=\"sID\" type=\"text\" name=\"id\"> <br> <label for=\"sMail\">Sender Email :</label> <br> <input id=\"sMail\" type=\"email\" name=\"emailSender\"> <br> <label for=\"pw\">Password :</label> <br> <input id=\"pw\" type=\"password\" name=\"password\"> <br> <label for=\"rMail\">Receiver Email :</label> <br> <input id=\"rMail\" type=\"email\" name=\"emailReceiver\"> <br> <label for=\"sub\">Subject :</label> <br> <input id=\"sub\" type=\"text\" name=\"subject\"> <br> <label for=\"message\">Message :</label> <br> <input id=\"message\" type=\"text\" name=\"message\"><br> <input type=\"submit\" value=\"Send\"> </div> </form> </body></html>", "e": 29314, "s": 28059, "text": null }, { "code": null, "e": 29322, "s": 29314, "text": "Output:" }, { "code": null, "e": 29358, "s": 29322, "text": "Fill details in output of Mail.java" }, { "code": null, "e": 29403, "s": 29358, "text": "3] Email.java (Servlet for handling details)" }, { "code": null, "e": 29408, "s": 29403, "text": "Java" }, { "code": "package mail.Servlet; import static mail.Servlet.Mail.sendMail; import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; public class Email extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id, sender, receiver, password, subject, message; // check if directed url String action = request.getParameter(\"action\"); String url = \"/index.html\"; if (action == null) { // directed to email interface action = \"join\"; } if (action.equals(\"join\")) { url = \"/index.html\"; } if (action.equals(\"add\")) { // retrieve the entered credentials id = request.getParameter(\"id\"); sender = request.getParameter(\"emailSender\"); receiver = request.getParameter(\"emailReceiver\"); password = request.getParameter(\"password\"); subject = request.getParameter(\"subject\"); message = request.getParameter(\"message\"); // get and set String value of email status request.setAttribute( \"message\", sendMail(id, receiver, sender, subject, message, true, password)); // directed to page showing the status of email url = \"/confirmation.jsp\"; } getServletContext() .getRequestDispatcher(url) .forward(request, response); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } // Returns a short description of the servlet. // @return a String containing servlet description @Override public String getServletInfo() { return \"Short description\"; }}", "e": 31743, "s": 29408, "text": null }, { "code": null, "e": 31804, "s": 31746, "text": "4] Mail.java (Helper class for creating and sending mail)" }, { "code": null, "e": 31825, "s": 31806, "text": "Essential classes:" }, { "code": null, "e": 31836, "s": 31827, "text": "Packages" }, { "code": null, "e": 31848, "s": 31836, "text": "Description" }, { "code": null, "e": 31858, "s": 31848, "text": "java.util" }, { "code": null, "e": 31869, "s": 31858, "text": "javax.mail" }, { "code": null, "e": 31905, "s": 31871, "text": "Create and Send an Email Message:" }, { "code": null, "e": 31930, "s": 31907, "text": "Creating Mail Session:" }, { "code": null, "e": 32636, "s": 31932, "text": "You have to create a mail session to create and send an email message.Before session creation, you need to create a Properties object containing properties (key-value pair) using the put(key, value) method that the session needs to send or receive mail.You at the least need to specify SMTP host property – use the ‘localhost’ keyword to specify SMTP server running on the same server as web-application. If you are using a remote SMTP server(e.g. Gmail server), use SMTPS protocol ( Secure connection and Authentication ).You can use other properties as well to configure mail sessions.Get Session object by wrapping Properties object into getDefaultInstance(Properties Object) method of Session class." }, { "code": null, "e": 32707, "s": 32636, "text": "You have to create a mail session to create and send an email message." }, { "code": null, "e": 32891, "s": 32707, "text": "Before session creation, you need to create a Properties object containing properties (key-value pair) using the put(key, value) method that the session needs to send or receive mail." }, { "code": null, "e": 33162, "s": 32891, "text": "You at the least need to specify SMTP host property – use the ‘localhost’ keyword to specify SMTP server running on the same server as web-application. If you are using a remote SMTP server(e.g. Gmail server), use SMTPS protocol ( Secure connection and Authentication )." }, { "code": null, "e": 33227, "s": 33162, "text": "You can use other properties as well to configure mail sessions." }, { "code": null, "e": 33344, "s": 33227, "text": "Get Session object by wrapping Properties object into getDefaultInstance(Properties Object) method of Session class." }, { "code": null, "e": 33362, "s": 33344, "text": "Common Properties" }, { "code": null, "e": 33374, "s": 33362, "text": "Description" }, { "code": null, "e": 33389, "s": 33374, "text": "mail.smtp.host" }, { "code": null, "e": 33404, "s": 33389, "text": "mail.smtp.port" }, { "code": null, "e": 33419, "s": 33404, "text": "mail.smtp.auth" }, { "code": null, "e": 33438, "s": 33419, "text": "mail.smtp.quitwait" }, { "code": null, "e": 33602, "s": 33438, "text": "// local SMTP server - Default \nProperties props = new Properties();\nprops.put(\"mail.smtp.host\", \"localhost\");\nSession session = Session.getDefaultInstance(props);" }, { "code": null, "e": 33870, "s": 33602, "text": "// local SMTP server - Configure\nProperties props = new Properties();\nprops.put(\"mail.transport.protocol\", \"smtp\");\nprops.put(\"mail.smtp.host\", \"localhost\");\nprops.put(\"mail.smtp.port\", 25);\nSession session = Session.getDefaultInstance(props);\nsession.setDebug(true);" }, { "code": null, "e": 34215, "s": 33870, "text": "// remote SMTP server\nProperties props = new Properties();\nprops.put(\"mail.transport.protocol\", \"smtps\");\nprops.put(\"mail.smtps.host\", \"smtp.gmail.com\");\nprops.put(\"mail.smtps.port\", 465);\nprops.put(\"mail.smtps.auth\",\"true\");\nprops.put(\"mail.smtps.quitwait\",\"false\");\nSession session = Session.getDefaultInstance(props);\nsession.setDebug(true);" }, { "code": null, "e": 34235, "s": 34217, "text": "Creating Message:" }, { "code": null, "e": 34530, "s": 34237, "text": "To create a message, you need to pass a Session object to the constructor of the MimeMessage class to create a MimeMessage object.You can set the subject, body, and addresses for the message.If the body is other than plain text, use the setContent() method to change the MIME type of message." }, { "code": null, "e": 34661, "s": 34530, "text": "To create a message, you need to pass a Session object to the constructor of the MimeMessage class to create a MimeMessage object." }, { "code": null, "e": 34723, "s": 34661, "text": "You can set the subject, body, and addresses for the message." }, { "code": null, "e": 34825, "s": 34723, "text": "If the body is other than plain text, use the setContent() method to change the MIME type of message." }, { "code": null, "e": 35030, "s": 34825, "text": "Message message = new MimeMessage(session);\nmessage.setSubject(\"Test\");\n// automatically sets to text/plain\nmessage.setText(\"Test Successful\"); \nmessage.setContent(\"<h1>Test Successful<h1>\", \"text/html\");" }, { "code": null, "e": 35112, "s": 35030, "text": "Note: All of the Message methods used above throws javax.mail.MessagingException." }, { "code": null, "e": 35674, "s": 35112, "text": "// add attachments within email\n\n// create 1'st part of body\nBodyPart bodyPart = new MimeBodyPart(); \nbodyPart.setText(\"Body Message\");\n\nMultipart multiPart = new MimeMultipart();\n// wrap up 1'st part\nmultiPart.addBodyPart(bodyPart); \n\n// create 2'nd part of body\nbodyPart = new MimeBodyPart(); \nDataSource source = new FileDataSource(\"Filename.txt\");\nbodyPart.setDataHandler(new DataHandler(source));\nbodyPart.setFileName(\"Filename.txt\");\n\n// wrap up 2'nd part.\nmultiPart.addBodyPart(bodyPart);\n// adds wrapped parts in message \nmessage.setContent(multiPart); " }, { "code": null, "e": 35698, "s": 35676, "text": "Addressing a message:" }, { "code": null, "e": 36217, "s": 35700, "text": "Create an object of InternetAddress (Sub-class of Address class).The first argument specifies the email address.You can add a second argument to associate an ID or email address to be displayed.To set FROM address. use setFrom(Address add) method of the MimeMessage object.To set TO, CC (carbon copy), BCC (blind carbon copy) address, use setRecipient(Type type, Address add) method of MimeMessage object.For multiple recipients, you can use setRecipients(Type type, Address[] add) method of the MimeMessage object." }, { "code": null, "e": 36283, "s": 36217, "text": "Create an object of InternetAddress (Sub-class of Address class)." }, { "code": null, "e": 36331, "s": 36283, "text": "The first argument specifies the email address." }, { "code": null, "e": 36414, "s": 36331, "text": "You can add a second argument to associate an ID or email address to be displayed." }, { "code": null, "e": 36494, "s": 36414, "text": "To set FROM address. use setFrom(Address add) method of the MimeMessage object." }, { "code": null, "e": 36628, "s": 36494, "text": "To set TO, CC (carbon copy), BCC (blind carbon copy) address, use setRecipient(Type type, Address add) method of MimeMessage object." }, { "code": null, "e": 36739, "s": 36628, "text": "For multiple recipients, you can use setRecipients(Type type, Address[] add) method of the MimeMessage object." }, { "code": null, "e": 36847, "s": 36739, "text": "// set sender\nAddress fromAdd = new InternetAddress(\"from@gmail.com\", \"from ID\");\nmessage.setFrom(fromAdd);" }, { "code": null, "e": 37370, "s": 36847, "text": "// set recipient\nAddress toAdd = new InternetAddress(\"to@gmail.com\");\nmessage.setRecipient(Message.RecipientType.TO, toAdd);\nmessage.setRecipient(Message.RecipientType.CC, toAdd);\nmessage.setRecipient(Message.RecipientType.BCC, toAdd);\n// set recipients\nmessage.setRecipients(Message.RecipientType.TO, new Address[]{new InternetAddress(\"to1@gmail.com\"),new InternetAddress(\"to2@gmail.com\")});\n \n// add recipients\nAddress toAdd1 = new InternetAddress(\"to@gmail.com\");\nmessage.addRecipient(Message.RecipientType.TO, toAdd1);" }, { "code": null, "e": 37640, "s": 37370, "text": "Note: When you send a carbon copy, the CC addresses appear in the message. When you send a blind carbon copy, the BCC address doesn’t appear in the message. If you use the two-argument constructor of InternetAddress, it throws the java.io.UnsupportedEncoding Exception." }, { "code": null, "e": 37661, "s": 37642, "text": "Sending a message:" }, { "code": null, "e": 37797, "s": 37663, "text": "If the SMTP doesn’t require authentication, you can use the static send(Message msg) method of the Transport class to send a message." }, { "code": null, "e": 37824, "s": 37799, "text": "Transport.send(message);" }, { "code": null, "e": 38263, "s": 37824, "text": "If the SMTP requires authentication, you can use the getTransport() method of the session object.Then you can use connect method – public void connect(String user, String password) , to specify credentials (username, password) to connect to the server.Use abstract void sendMessage(Message msg, Address[] addresses) method to send the message.You need to close the connection using the close() method if not used try-with-resources block." }, { "code": null, "e": 38361, "s": 38263, "text": "If the SMTP requires authentication, you can use the getTransport() method of the session object." }, { "code": null, "e": 38517, "s": 38361, "text": "Then you can use connect method – public void connect(String user, String password) , to specify credentials (username, password) to connect to the server." }, { "code": null, "e": 38609, "s": 38517, "text": "Use abstract void sendMessage(Message msg, Address[] addresses) method to send the message." }, { "code": null, "e": 38705, "s": 38609, "text": "You need to close the connection using the close() method if not used try-with-resources block." }, { "code": null, "e": 38875, "s": 38705, "text": "Transport transport = session.getTransport();\ntransport.connect(\"email-id\", \"password\");\ntransport.sendMessage(\"message\", message.getAllRecipients());\ntransport.close();" }, { "code": null, "e": 38983, "s": 38875, "text": "Note: If the SMTP host is incorrect, the – static void send(Message msg) method throws SendFailedException." }, { "code": null, "e": 38990, "s": 38985, "text": "Java" }, { "code": "package mail.Servlet; import java.io.UnsupportedEncodingException;import java.util.Properties;import javax.mail.Address;import javax.mail.Message;import javax.mail.MessagingException;import javax.mail.Session;import javax.mail.Transport;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeMessage; public class Mail { public static String sendMail(String id, String to, String from, String subject, String body, boolean content, String password) { String status = null; try { // acquire a secure SMTPs session Properties pros = new Properties(); pros.put(\"mail.transport.protocol\", \"smtps\"); pros.put(\"mail.smtps.host\", \"smtp.gmail.com\"); pros.put(\"mail.smtps.port\", 465); pros.put(\"mail.smtps.auth\", \"true\"); pros.put(\"mail.smtps.quitwait\", \"false\"); Session session = Session.getDefaultInstance(pros); session.setDebug(true); // Wrap a message in session Message message = new MimeMessage(session); message.setSubject(subject); if (content) { message.setContent(body, \"text/html\"); } else { message.setText(body); } // specify E-mail address of Sender and Receiver Address sender = new InternetAddress(from, id); Address receiver = new InternetAddress(to); message.setFrom(sender); message.setRecipient(Message.RecipientType.TO, receiver); // sending an E-mail try (Transport tt = session.getTransport()) { // acqruiring a connection to remote server tt.connect(from, password); tt.sendMessage(message, message.getAllRecipients()); status = \"E-Mail Sent Successfully\"; } } catch (MessagingException e) { status = e.toString(); } catch (UnsupportedEncodingException e) { status = e.toString(); } // return the status of email return status; }}", "e": 41210, "s": 38990, "text": null }, { "code": null, "e": 41261, "s": 41213, "text": "5] confirmation.jsp (Check the status of email)" }, { "code": null, "e": 41268, "s": 41263, "text": "HTML" }, { "code": "<%@page contentType=\"text/html\" pageEncoding=\"UTF-8\"%><!DOCTYPE html><html> <head> <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"> <title>GeeksforGeeks</title> </head> <body> <h3 align=\"center\">Status of E-Mail : </h3> <h1 align=\"center\">${requestScope.message}</h1> </body></html>", "e": 41610, "s": 41268, "text": null }, { "code": null, "e": 41618, "s": 41610, "text": "Output:" }, { "code": null, "e": 41647, "s": 41618, "text": "Mail Status after life-cycle" }, { "code": null, "e": 41662, "s": 41647, "text": "adnanirshad158" }, { "code": null, "e": 41677, "s": 41662, "text": "sagartomar9927" }, { "code": null, "e": 41690, "s": 41677, "text": "java-servlet" }, { "code": null, "e": 41697, "s": 41690, "text": "Picked" }, { "code": null, "e": 41702, "s": 41697, "text": "Java" }, { "code": null, "e": 41707, "s": 41702, "text": "Java" }, { "code": null, "e": 41805, "s": 41707, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41820, "s": 41805, "text": "Stream In Java" }, { "code": null, "e": 41841, "s": 41820, "text": "Constructors in Java" }, { "code": null, "e": 41860, "s": 41841, "text": "Exceptions in Java" }, { "code": null, "e": 41890, "s": 41860, "text": "Functional Interfaces in Java" }, { "code": null, "e": 41936, "s": 41890, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 41953, "s": 41936, "text": "Generics in Java" }, { "code": null, "e": 41974, "s": 41953, "text": "Introduction to Java" }, { "code": null, "e": 42017, "s": 41974, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 42053, "s": 42017, "text": "Internal Working of HashMap in Java" } ]
Minimum distance between the maximum and minimum element of a given Array - GeeksforGeeks
14 Jan, 2022 Given an array A[] consisting of N elements, the task is to find the minimum distance between the minimum and the maximum element of the array.Examples: Input: arr[] = {3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 8, 2} Output: 3 Explanation: The minimum element(= 1) is present at indices {2, 4} The maximum element(= 8) is present at indices {7, 10}. The minimum distance between an occurrence of 1 and 8 is 7 – 4 = 3Input: arr[] = {1, 3, 69} Output: 2 Explanation: The minimum element(= 1) is present at index 0. The maximum element(= 69) is present at index 2. Therefore, the minimum distance between them is 2. Naive Approach: The simplest approach to solve this problem is as follows: Find the minimum and maximum elements of the array. Traverse the array and for every occurrence of the maximum element, calculate its distance from all occurrences of the minimum element in the array and update the minimum distance. After complete traversal of the array, print all the minimum distance obtained. Time Complexity: O(N2) Auxiliary Space: O(1) Efficient Approach: Follow the steps below to optimize the above approach: Traverse the array to find the minimum and maximum elements. Initialize two variables min_index and max_index to store the indices of the minimum and maximum elements of the array respectively. Initialize them with -1. Traverse the array. If at any instant, both min_index and max_index is not equal to -1, i.e. both of them have stored a valid index, calculate there a difference. Compare this difference with the minimum distance(say, min_dist) and update min_dist accordingly. Finally, print the final value of min_dist obtained after the complete traversal of the array. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ Program to implement the// above approach#include <bits/stdc++.h>using namespace std; // Function to find the minimum// distance between the minimum// and the maximum elementint minDistance(int a[], int n){ // Stores the minimum and maximum // array element int maximum = -1, minimum = INT_MAX; // Stores the most recently traversed // indices of the minimum and the // maximum element int min_index = -1, max_index = -1; // Stores the minimum distance // between the minimum and the // maximum int min_dist = n + 1; // Find the maximum and // the minimum element // from the given array for (int i = 0; i < n; i++) { if (a[i] > maximum) maximum = a[i]; if (a[i] < minimum) minimum = a[i]; } // Find the minimum distance for (int i = 0; i < n; i++) { // Check if current element // is equal to minimum if (a[i] == minimum) min_index = i; // Check if current element // is equal to maximum if (a[i] == maximum) max_index = i; // If both the minimum and the // maximum element has // occurred at least once if (min_index != -1 && max_index != -1) // Update the minimum distance min_dist = min(min_dist, abs(min_index - max_index)); } // Return the answer return min_dist;} // Driver Codeint main(){ int a[] = { 3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 8, 2 }; int n = sizeof a / sizeof a[0]; cout << minDistance(a, n);} // Java Program to implement// the above approachimport java.util.*;class GFG { // Function to find the minimum // distance between the minimum // and the maximum element public static int minDistance(int a[], int n) { // Stores the minimum and maximum // array element int max = -1, min = Integer.MAX_VALUE; // Stores the most recently traversed // indices of the minimum and the // maximum element int min_index = -1, max_index = -1; // Stores the minimum distance // between the minimum and the // maximum int min_dist = n + 1; // Find the maximum and // the minimum element // from the given array for (int i = 0; i < n; i++) { if (a[i] > max) max = a[i]; if (a[i] < min) min = a[i]; } // Find the minimum distance for (int i = 0; i < n; i++) { // Check if current element // is equal to minimum if (a[i] == min) min_index = i; // Check if current element // is equal to maximum if (a[i] == max) max_index = i; // If both the minimum and the // maximum element has // occurred at least once if (min_index != -1 && max_index != -1) min_dist = Math.min(min_dist, Math.abs(min_index - max_index)); } return min_dist; } // Driver Code public static void main(String[] args) { int n = 12; int a[] = { 3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 8, 2 }; System.out.println(minDistance(a, n)); }} # Python3 Program to implement the# above approachimport sys # Function to find the minimum# distance between the minimum# and the maximum elementdef minDistance(a, n): # Stores the minimum and maximum # array element maximum = -1 minimum = sys.maxsize # Stores the most recently traversed # indices of the minimum and the # maximum element min_index = -1 max_index = -1 # Stores the minimum distance # between the minimum and the # maximum min_dist = n + 1 # Find the maximum and # the minimum element # from the given array for i in range (n): if (a[i] > maximum): maximum = a[i] if (a[i] < minimum): minimum = a[i] # Find the minimum distance for i in range (n): # Check if current element # is equal to minimum if (a[i] == minimum): min_index = i # Check if current element # is equal to maximum if (a[i] == maximum): max_index = i # If both the minimum and the # maximum element has # occurred at least once if (min_index != -1 and max_index != -1): # Update the minimum distance min_dist = (min(min_dist, abs(min_index - max_index))) # Return the answer return min_dist # Driver Codeif __name__ == "__main__": a = [3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 8, 2] n = len(a) print (minDistance(a, n)) # This code is contributed by Chitranayal // C# program to implement// the above approachusing System; class GFG{ // Function to find the minimum// distance between the minimum// and the maximum elementstatic int minDistance(int []a, int n){ // Stores the minimum and maximum // array element int max = -1, min = Int32.MaxValue; // Stores the most recently traversed // indices of the minimum and the // maximum element int min_index = -1, max_index = -1; // Stores the minimum distance // between the minimum and the // maximum int min_dist = n + 1; // Find the maximum and // the minimum element // from the given array for(int i = 0; i < n; i++) { if (a[i] > max) max = a[i]; if (a[i] < min) min = a[i]; } // Find the minimum distance for(int i = 0; i < n; i++) { // Check if current element // is equal to minimum if (a[i] == min) min_index = i; // Check if current element // is equal to maximum if (a[i] == max) max_index = i; // If both the minimum and the // maximum element has // occurred at least once if (min_index != -1 && max_index != -1) min_dist = Math.Min(min_dist, Math.Abs( min_index - max_index)); } return min_dist;} // Driver Codepublic static void Main(){ int n = 12; int []a = { 3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 8, 2 }; Console.WriteLine(minDistance(a, n));}} // This code is contributed by piyush3010 <script> // Javascript program to implement// the above approach // Function to find the minimum // distance between the minimum // and the maximum element function minDistance(a, n) { // Stores the minimum and maximum // array element let max = -1, min = Number.MAX_VALUE; // Stores the most recently traversed // indices of the minimum and the // maximum element let min_index = -1, max_index = -1; // Stores the minimum distance // between the minimum and the // maximum let min_dist = n + 1; // Find the maximum and // the minimum element // from the given array for (let i = 0; i < n; i++) { if (a[i] > max) max = a[i]; if (a[i] < min) min = a[i]; } // Find the minimum distance for (let i = 0; i < n; i++) { // Check if current element // is equal to minimum if (a[i] == min) min_index = i; // Check if current element // is equal to maximum if (a[i] == max) max_index = i; // If both the minimum and the // maximum element has // occurred at least once if (min_index != -1 && max_index != -1) min_dist = Math.min(min_dist, Math.abs(min_index - max_index)); } return min_dist; } // Driver Code let n = 12; let a = [ 3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 8, 2 ]; document.write(minDistance(a, n)); </script> 3 Time Complexity: O(N) Auxiliary Space: O(1) piyush3010 ukasp avijitmondal1998 sumitgumber28 array-traversal-question frequency-counting Arrays Mathematical Searching Arrays Searching Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Chocolate Distribution Problem Count pairs with given sum Window Sliding Technique Reversal algorithm for array rotation Next Greater Element Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 26067, "s": 26039, "text": "\n14 Jan, 2022" }, { "code": null, "e": 26222, "s": 26067, "text": "Given an array A[] consisting of N elements, the task is to find the minimum distance between the minimum and the maximum element of the array.Examples: " }, { "code": null, "e": 26672, "s": 26222, "text": "Input: arr[] = {3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 8, 2} Output: 3 Explanation: The minimum element(= 1) is present at indices {2, 4} The maximum element(= 8) is present at indices {7, 10}. The minimum distance between an occurrence of 1 and 8 is 7 – 4 = 3Input: arr[] = {1, 3, 69} Output: 2 Explanation: The minimum element(= 1) is present at index 0. The maximum element(= 69) is present at index 2. Therefore, the minimum distance between them is 2. " }, { "code": null, "e": 26749, "s": 26672, "text": "Naive Approach: The simplest approach to solve this problem is as follows: " }, { "code": null, "e": 26801, "s": 26749, "text": "Find the minimum and maximum elements of the array." }, { "code": null, "e": 26982, "s": 26801, "text": "Traverse the array and for every occurrence of the maximum element, calculate its distance from all occurrences of the minimum element in the array and update the minimum distance." }, { "code": null, "e": 27062, "s": 26982, "text": "After complete traversal of the array, print all the minimum distance obtained." }, { "code": null, "e": 27184, "s": 27062, "text": "Time Complexity: O(N2) Auxiliary Space: O(1) Efficient Approach: Follow the steps below to optimize the above approach: " }, { "code": null, "e": 27245, "s": 27184, "text": "Traverse the array to find the minimum and maximum elements." }, { "code": null, "e": 27403, "s": 27245, "text": "Initialize two variables min_index and max_index to store the indices of the minimum and maximum elements of the array respectively. Initialize them with -1." }, { "code": null, "e": 27566, "s": 27403, "text": "Traverse the array. If at any instant, both min_index and max_index is not equal to -1, i.e. both of them have stored a valid index, calculate there a difference." }, { "code": null, "e": 27664, "s": 27566, "text": "Compare this difference with the minimum distance(say, min_dist) and update min_dist accordingly." }, { "code": null, "e": 27759, "s": 27664, "text": "Finally, print the final value of min_dist obtained after the complete traversal of the array." }, { "code": null, "e": 27811, "s": 27759, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27815, "s": 27811, "text": "C++" }, { "code": null, "e": 27820, "s": 27815, "text": "Java" }, { "code": null, "e": 27828, "s": 27820, "text": "Python3" }, { "code": null, "e": 27831, "s": 27828, "text": "C#" }, { "code": null, "e": 27842, "s": 27831, "text": "Javascript" }, { "code": "// C++ Program to implement the// above approach#include <bits/stdc++.h>using namespace std; // Function to find the minimum// distance between the minimum// and the maximum elementint minDistance(int a[], int n){ // Stores the minimum and maximum // array element int maximum = -1, minimum = INT_MAX; // Stores the most recently traversed // indices of the minimum and the // maximum element int min_index = -1, max_index = -1; // Stores the minimum distance // between the minimum and the // maximum int min_dist = n + 1; // Find the maximum and // the minimum element // from the given array for (int i = 0; i < n; i++) { if (a[i] > maximum) maximum = a[i]; if (a[i] < minimum) minimum = a[i]; } // Find the minimum distance for (int i = 0; i < n; i++) { // Check if current element // is equal to minimum if (a[i] == minimum) min_index = i; // Check if current element // is equal to maximum if (a[i] == maximum) max_index = i; // If both the minimum and the // maximum element has // occurred at least once if (min_index != -1 && max_index != -1) // Update the minimum distance min_dist = min(min_dist, abs(min_index - max_index)); } // Return the answer return min_dist;} // Driver Codeint main(){ int a[] = { 3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 8, 2 }; int n = sizeof a / sizeof a[0]; cout << minDistance(a, n);}", "e": 29476, "s": 27842, "text": null }, { "code": "// Java Program to implement// the above approachimport java.util.*;class GFG { // Function to find the minimum // distance between the minimum // and the maximum element public static int minDistance(int a[], int n) { // Stores the minimum and maximum // array element int max = -1, min = Integer.MAX_VALUE; // Stores the most recently traversed // indices of the minimum and the // maximum element int min_index = -1, max_index = -1; // Stores the minimum distance // between the minimum and the // maximum int min_dist = n + 1; // Find the maximum and // the minimum element // from the given array for (int i = 0; i < n; i++) { if (a[i] > max) max = a[i]; if (a[i] < min) min = a[i]; } // Find the minimum distance for (int i = 0; i < n; i++) { // Check if current element // is equal to minimum if (a[i] == min) min_index = i; // Check if current element // is equal to maximum if (a[i] == max) max_index = i; // If both the minimum and the // maximum element has // occurred at least once if (min_index != -1 && max_index != -1) min_dist = Math.min(min_dist, Math.abs(min_index - max_index)); } return min_dist; } // Driver Code public static void main(String[] args) { int n = 12; int a[] = { 3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 8, 2 }; System.out.println(minDistance(a, n)); }}", "e": 31286, "s": 29476, "text": null }, { "code": "# Python3 Program to implement the# above approachimport sys # Function to find the minimum# distance between the minimum# and the maximum elementdef minDistance(a, n): # Stores the minimum and maximum # array element maximum = -1 minimum = sys.maxsize # Stores the most recently traversed # indices of the minimum and the # maximum element min_index = -1 max_index = -1 # Stores the minimum distance # between the minimum and the # maximum min_dist = n + 1 # Find the maximum and # the minimum element # from the given array for i in range (n): if (a[i] > maximum): maximum = a[i] if (a[i] < minimum): minimum = a[i] # Find the minimum distance for i in range (n): # Check if current element # is equal to minimum if (a[i] == minimum): min_index = i # Check if current element # is equal to maximum if (a[i] == maximum): max_index = i # If both the minimum and the # maximum element has # occurred at least once if (min_index != -1 and max_index != -1): # Update the minimum distance min_dist = (min(min_dist, abs(min_index - max_index))) # Return the answer return min_dist # Driver Codeif __name__ == \"__main__\": a = [3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 8, 2] n = len(a) print (minDistance(a, n)) # This code is contributed by Chitranayal", "e": 32835, "s": 31286, "text": null }, { "code": "// C# program to implement// the above approachusing System; class GFG{ // Function to find the minimum// distance between the minimum// and the maximum elementstatic int minDistance(int []a, int n){ // Stores the minimum and maximum // array element int max = -1, min = Int32.MaxValue; // Stores the most recently traversed // indices of the minimum and the // maximum element int min_index = -1, max_index = -1; // Stores the minimum distance // between the minimum and the // maximum int min_dist = n + 1; // Find the maximum and // the minimum element // from the given array for(int i = 0; i < n; i++) { if (a[i] > max) max = a[i]; if (a[i] < min) min = a[i]; } // Find the minimum distance for(int i = 0; i < n; i++) { // Check if current element // is equal to minimum if (a[i] == min) min_index = i; // Check if current element // is equal to maximum if (a[i] == max) max_index = i; // If both the minimum and the // maximum element has // occurred at least once if (min_index != -1 && max_index != -1) min_dist = Math.Min(min_dist, Math.Abs( min_index - max_index)); } return min_dist;} // Driver Codepublic static void Main(){ int n = 12; int []a = { 3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 8, 2 }; Console.WriteLine(minDistance(a, n));}} // This code is contributed by piyush3010", "e": 34470, "s": 32835, "text": null }, { "code": "<script> // Javascript program to implement// the above approach // Function to find the minimum // distance between the minimum // and the maximum element function minDistance(a, n) { // Stores the minimum and maximum // array element let max = -1, min = Number.MAX_VALUE; // Stores the most recently traversed // indices of the minimum and the // maximum element let min_index = -1, max_index = -1; // Stores the minimum distance // between the minimum and the // maximum let min_dist = n + 1; // Find the maximum and // the minimum element // from the given array for (let i = 0; i < n; i++) { if (a[i] > max) max = a[i]; if (a[i] < min) min = a[i]; } // Find the minimum distance for (let i = 0; i < n; i++) { // Check if current element // is equal to minimum if (a[i] == min) min_index = i; // Check if current element // is equal to maximum if (a[i] == max) max_index = i; // If both the minimum and the // maximum element has // occurred at least once if (min_index != -1 && max_index != -1) min_dist = Math.min(min_dist, Math.abs(min_index - max_index)); } return min_dist; } // Driver Code let n = 12; let a = [ 3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 8, 2 ]; document.write(minDistance(a, n)); </script>", "e": 36217, "s": 34470, "text": null }, { "code": null, "e": 36219, "s": 36217, "text": "3" }, { "code": null, "e": 36266, "s": 36221, "text": "Time Complexity: O(N) Auxiliary Space: O(1) " }, { "code": null, "e": 36277, "s": 36266, "text": "piyush3010" }, { "code": null, "e": 36283, "s": 36277, "text": "ukasp" }, { "code": null, "e": 36300, "s": 36283, "text": "avijitmondal1998" }, { "code": null, "e": 36314, "s": 36300, "text": "sumitgumber28" }, { "code": null, "e": 36339, "s": 36314, "text": "array-traversal-question" }, { "code": null, "e": 36358, "s": 36339, "text": "frequency-counting" }, { "code": null, "e": 36365, "s": 36358, "text": "Arrays" }, { "code": null, "e": 36378, "s": 36365, "text": "Mathematical" }, { "code": null, "e": 36388, "s": 36378, "text": "Searching" }, { "code": null, "e": 36395, "s": 36388, "text": "Arrays" }, { "code": null, "e": 36405, "s": 36395, "text": "Searching" }, { "code": null, "e": 36418, "s": 36405, "text": "Mathematical" }, { "code": null, "e": 36516, "s": 36418, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36547, "s": 36516, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 36574, "s": 36547, "text": "Count pairs with given sum" }, { "code": null, "e": 36599, "s": 36574, "text": "Window Sliding Technique" }, { "code": null, "e": 36637, "s": 36599, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 36658, "s": 36637, "text": "Next Greater Element" }, { "code": null, "e": 36688, "s": 36658, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 36748, "s": 36688, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 36763, "s": 36748, "text": "C++ Data Types" }, { "code": null, "e": 36806, "s": 36763, "text": "Set in C++ Standard Template Library (STL)" } ]
How to return a JSON response form a Flask API ? - GeeksforGeeks
21 Oct, 2021 Flask is one of the most widely used python micro-frameworks to design a REST API. In this article, we are going to learn how to create a simple REST API that returns a simple JSON object, with the help of a flask. Prerequisites: Introduction to REST API What is a REST API? REST stands for Representational State Transfer and is an architectural style used in modern web development. It defines a set or rules/constraints for a web application to send and receive data. In this article, we will build a REST API in Python using the Flask framework. Flask is a popular micro framework for building web applications. Approaches: We are going to write a simple flask API that returns a JSON response using two approaches: Using Flask jsonify object.Using the flask_restful library with Flask. Using Flask jsonify object. Using the flask_restful library with Flask. Libraries Required: Install the python Flask library using the following command: pip install Flask Install the flask-restful library using the following command: pip install Flask-RESTful Approach 1: Using Flask jsonify object – In this approach, we are going to return a JSON response using the flask jsonify method. We are not going to use the flask-restful library in this method. Create a new python file named ‘main.py’. import Flask, jsonify, and request from the flask framework. Register the web app into an app variable using the following syntax. app = Flask(__name__) Create a new function named ‘ReturnJSON’. This function is going to return the sample JSON response. Route the ‘ReturnJSON’ function to your desired URL using the following syntax. @app.route('/path_of_the_response', methods = ['GET']) def ReturnJSON(): pass Inside the ‘ReturnJSON’ function if the request method is ‘GET’ then create a python dictionary with the two elements message. Jsonify the python dictionary and return it. Build the flask application using the following command. if __name__=='__main__': app.run(debug=True) Run the ‘main.py’ file in the terminal or the IDE. Code: Python3 from flask import Flask,jsonify,request app = Flask(__name__) @app.route('/returnjson', methods = ['GET'])def ReturnJSON(): if(request.method == 'GET'): data = { "Modules" : 15, "Subject" : "Data Structures and Algorithms", } return jsonify(data) if __name__=='__main__': app.run(debug=True) Output: Approach 2: Using the flask_restful library with Flask – In this approach, we are going to create a simple JSON response with the help of the flask-restful library. The steps are discussed below: Create a new python file named ‘main.py’. Import Flask from the flask framework. Import API and Resource from the ‘flask_restful’ library. Register the web app into an app variable using the following syntax. app = Flask(__name__) Register the app variable as an API object using the API method of the ‘flask_restful’ library. api = Api(app) Create a resource class named ‘ReturnJSON’. Inside the resource, the class creates a ‘get’ method. Return a dictionary with the simple JSON response from the ‘get’ method. Add the resource class to the API using the add_resource method. Build the flask application using the following command. if __name__=='__main__': app.run(debug=True) Run the ‘main.py’ file in the terminal or the IDE. Code: Python3 from flask import Flaskfrom flask_restful import Api, Resource app = Flask(__name__) api = Api(app) class returnjson(Resource): def get(self): data={ "Modules": 15, "Subject": "Data Structures and Algorithms" } return data api.add_resource(returnjson,'/returnjson') if __name__=='__main__': app.run(debug=True) Output: Picked Python Flask Python Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25512, "s": 25484, "text": "\n21 Oct, 2021" }, { "code": null, "e": 25727, "s": 25512, "text": "Flask is one of the most widely used python micro-frameworks to design a REST API. In this article, we are going to learn how to create a simple REST API that returns a simple JSON object, with the help of a flask." }, { "code": null, "e": 25767, "s": 25727, "text": "Prerequisites: Introduction to REST API" }, { "code": null, "e": 25787, "s": 25767, "text": "What is a REST API?" }, { "code": null, "e": 26128, "s": 25787, "text": "REST stands for Representational State Transfer and is an architectural style used in modern web development. It defines a set or rules/constraints for a web application to send and receive data. In this article, we will build a REST API in Python using the Flask framework. Flask is a popular micro framework for building web applications." }, { "code": null, "e": 26232, "s": 26128, "text": "Approaches: We are going to write a simple flask API that returns a JSON response using two approaches:" }, { "code": null, "e": 26303, "s": 26232, "text": "Using Flask jsonify object.Using the flask_restful library with Flask." }, { "code": null, "e": 26331, "s": 26303, "text": "Using Flask jsonify object." }, { "code": null, "e": 26375, "s": 26331, "text": "Using the flask_restful library with Flask." }, { "code": null, "e": 26395, "s": 26375, "text": "Libraries Required:" }, { "code": null, "e": 26457, "s": 26395, "text": "Install the python Flask library using the following command:" }, { "code": null, "e": 26475, "s": 26457, "text": "pip install Flask" }, { "code": null, "e": 26538, "s": 26475, "text": "Install the flask-restful library using the following command:" }, { "code": null, "e": 26564, "s": 26538, "text": "pip install Flask-RESTful" }, { "code": null, "e": 26760, "s": 26564, "text": "Approach 1: Using Flask jsonify object – In this approach, we are going to return a JSON response using the flask jsonify method. We are not going to use the flask-restful library in this method." }, { "code": null, "e": 26802, "s": 26760, "text": "Create a new python file named ‘main.py’." }, { "code": null, "e": 26863, "s": 26802, "text": "import Flask, jsonify, and request from the flask framework." }, { "code": null, "e": 26933, "s": 26863, "text": "Register the web app into an app variable using the following syntax." }, { "code": null, "e": 26955, "s": 26933, "text": "app = Flask(__name__)" }, { "code": null, "e": 27056, "s": 26955, "text": "Create a new function named ‘ReturnJSON’. This function is going to return the sample JSON response." }, { "code": null, "e": 27136, "s": 27056, "text": "Route the ‘ReturnJSON’ function to your desired URL using the following syntax." }, { "code": null, "e": 27216, "s": 27136, "text": "@app.route('/path_of_the_response', methods = ['GET'])\ndef ReturnJSON():\n pass" }, { "code": null, "e": 27343, "s": 27216, "text": "Inside the ‘ReturnJSON’ function if the request method is ‘GET’ then create a python dictionary with the two elements message." }, { "code": null, "e": 27388, "s": 27343, "text": "Jsonify the python dictionary and return it." }, { "code": null, "e": 27445, "s": 27388, "text": "Build the flask application using the following command." }, { "code": null, "e": 27494, "s": 27445, "text": "if __name__=='__main__':\n app.run(debug=True)" }, { "code": null, "e": 27545, "s": 27494, "text": "Run the ‘main.py’ file in the terminal or the IDE." }, { "code": null, "e": 27551, "s": 27545, "text": "Code:" }, { "code": null, "e": 27559, "s": 27551, "text": "Python3" }, { "code": "from flask import Flask,jsonify,request app = Flask(__name__) @app.route('/returnjson', methods = ['GET'])def ReturnJSON(): if(request.method == 'GET'): data = { \"Modules\" : 15, \"Subject\" : \"Data Structures and Algorithms\", } return jsonify(data) if __name__=='__main__': app.run(debug=True)", "e": 27907, "s": 27559, "text": null }, { "code": null, "e": 27915, "s": 27907, "text": "Output:" }, { "code": null, "e": 28111, "s": 27915, "text": "Approach 2: Using the flask_restful library with Flask – In this approach, we are going to create a simple JSON response with the help of the flask-restful library. The steps are discussed below:" }, { "code": null, "e": 28153, "s": 28111, "text": "Create a new python file named ‘main.py’." }, { "code": null, "e": 28192, "s": 28153, "text": "Import Flask from the flask framework." }, { "code": null, "e": 28250, "s": 28192, "text": "Import API and Resource from the ‘flask_restful’ library." }, { "code": null, "e": 28320, "s": 28250, "text": "Register the web app into an app variable using the following syntax." }, { "code": null, "e": 28342, "s": 28320, "text": "app = Flask(__name__)" }, { "code": null, "e": 28439, "s": 28342, "text": "Register the app variable as an API object using the API method of the ‘flask_restful’ library." }, { "code": null, "e": 28454, "s": 28439, "text": "api = Api(app)" }, { "code": null, "e": 28498, "s": 28454, "text": "Create a resource class named ‘ReturnJSON’." }, { "code": null, "e": 28553, "s": 28498, "text": "Inside the resource, the class creates a ‘get’ method." }, { "code": null, "e": 28626, "s": 28553, "text": "Return a dictionary with the simple JSON response from the ‘get’ method." }, { "code": null, "e": 28691, "s": 28626, "text": "Add the resource class to the API using the add_resource method." }, { "code": null, "e": 28748, "s": 28691, "text": "Build the flask application using the following command." }, { "code": null, "e": 28797, "s": 28748, "text": "if __name__=='__main__':\n app.run(debug=True)" }, { "code": null, "e": 28848, "s": 28797, "text": "Run the ‘main.py’ file in the terminal or the IDE." }, { "code": null, "e": 28854, "s": 28848, "text": "Code:" }, { "code": null, "e": 28862, "s": 28854, "text": "Python3" }, { "code": "from flask import Flaskfrom flask_restful import Api, Resource app = Flask(__name__) api = Api(app) class returnjson(Resource): def get(self): data={ \"Modules\": 15, \"Subject\": \"Data Structures and Algorithms\" } return data api.add_resource(returnjson,'/returnjson') if __name__=='__main__': app.run(debug=True)", "e": 29234, "s": 28862, "text": null }, { "code": null, "e": 29242, "s": 29234, "text": "Output:" }, { "code": null, "e": 29249, "s": 29242, "text": "Picked" }, { "code": null, "e": 29262, "s": 29249, "text": "Python Flask" }, { "code": null, "e": 29269, "s": 29262, "text": "Python" }, { "code": null, "e": 29286, "s": 29269, "text": "Web Technologies" }, { "code": null, "e": 29384, "s": 29286, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29419, "s": 29384, "text": "Read a file line by line in Python" }, { "code": null, "e": 29451, "s": 29419, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29473, "s": 29451, "text": "Enumerate() in Python" }, { "code": null, "e": 29515, "s": 29473, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29545, "s": 29515, "text": "Iterate over a list in Python" }, { "code": null, "e": 29585, "s": 29545, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29618, "s": 29585, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29663, "s": 29618, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29706, "s": 29663, "text": "How to fetch data from an API in ReactJS ?" } ]
Longest subsequence such that difference between adjacents is one - GeeksforGeeks
25 Mar, 2022 Given an array of n size, the task is to find the longest subsequence such that difference between adjacents is one. Examples: Input : arr[] = {10, 9, 4, 5, 4, 8, 6} Output : 3 As longest subsequences with difference 1 are, "10, 9, 8", "4, 5, 4" and "4, 5, 6" Input : arr[] = {1, 2, 3, 2, 3, 7, 2, 1} Output : 7 As longest consecutive sequence is "1, 2, 3, 2, 3, 2, 1" This problem is based upon the concept of Longest Increasing Subsequence Problem. Let arr[0..n-1] be the input array and dp[i] be the length of the longest subsequence (with differences one) ending at index i such that arr[i] is the last element of the subsequence. Then, dp[i] can be recursively written as: dp[i] = 1 + max(dp[j]) where 0 < j < i and [arr[j] = arr[i] -1 or arr[j] = arr[i] + 1] dp[i] = 1, if no such j exists. To find the result for a given array, we need to return max(dp[i]) where 0 < i < n. Following is a Dynamic Programming based implementation. It follows the recursive structure discussed above. C++ Java Python3 C# PHP Javascript // C++ program to find the longest subsequence such// the difference between adjacent elements of the// subsequence is one.#include <bits/stdc++.h>using namespace std; // Function to find the length of longest subsequenceint longestSubseqWithDiffOne(int arr[], int n){ // Initialize the dp[] array with 1 as a // single element will be of 1 length int dp[n]; for (int i = 0; i < n; i++) dp[i] = 1; // Start traversing the given array for (int i = 1; i < n; i++) { // Compare with all the previous elements for (int j = 0; j < i; j++) { // If the element is consecutive then // consider this subsequence and update // dp[i] if required. if ((arr[i] == arr[j] + 1) || (arr[i] == arr[j] - 1)) dp[i] = max(dp[i], dp[j] + 1); } } // Longest length will be the maximum value // of dp array. int result = 1; for (int i = 0; i < n; i++) if (result < dp[i]) result = dp[i]; return result;} // Driver codeint main(){ // Longest subsequence with one difference is // {1, 2, 3, 4, 3, 2} int arr[] = { 1, 2, 3, 4, 5, 3, 2 }; int n = sizeof(arr) / sizeof(arr[0]); cout << longestSubseqWithDiffOne(arr, n); return 0;} // Java program to find the longest subsequence// such that the difference between adjacent// elements of the subsequence is one.import java.io.*; class GFG { // Function to find the length of longest // subsequence static int longestSubseqWithDiffOne(int arr[], int n) { // Initialize the dp[] array with 1 as a // single element will be of 1 length int dp[] = new int[n]; for (int i = 0; i < n; i++) dp[i] = 1; // Start traversing the given array for (int i = 1; i < n; i++) { // Compare with all the previous // elements for (int j = 0; j < i; j++) { // If the element is consecutive // then consider this subsequence // and update dp[i] if required. if ((arr[i] == arr[j] + 1) || (arr[i] == arr[j] - 1)) dp[i] = Math.max(dp[i], dp[j] + 1); } } // Longest length will be the maximum // value of dp array. int result = 1; for (int i = 0; i < n; i++) if (result < dp[i]) result = dp[i]; return result; } // Driver code public static void main(String[] args) { // Longest subsequence with one // difference is // {1, 2, 3, 4, 3, 2} int arr[] = { 1, 2, 3, 4, 5, 3, 2 }; int n = arr.length; System.out.println(longestSubseqWithDiffOne( arr, n)); }} // This code is contributed by Prerna Saini # Function to find the length of longest subsequencedef longestSubseqWithDiffOne(arr, n): # Initialize the dp[] array with 1 as a # single element will be of 1 length dp = [1 for i in range(n)] # Start traversing the given array for i in range(n): # Compare with all the previous elements for j in range(i): # If the element is consecutive then # consider this subsequence and update # dp[i] if required. if ((arr[i] == arr[j]+1) or (arr[i] == arr[j]-1)): dp[i] = max(dp[i], dp[j]+1) # Longest length will be the maximum value # of dp array. result = 1 for i in range(n): if (result < dp[i]): result = dp[i] return result # Driver codearr = [1, 2, 3, 4, 5, 3, 2]# Longest subsequence with one difference is# {1, 2, 3, 4, 3, 2}n = len(arr)print (longestSubseqWithDiffOne(arr, n)) # This code is contributed by Afzal Ansari // C# program to find the longest subsequence// such that the difference between adjacent// elements of the subsequence is one.using System; class GFG { // Function to find the length of longest // subsequence static int longestSubseqWithDiffOne(int[] arr, int n) { // Initialize the dp[] array with 1 as a // single element will be of 1 length int[] dp = new int[n]; for (int i = 0; i < n; i++) dp[i] = 1; // Start traversing the given array for (int i = 1; i < n; i++) { // Compare with all the previous // elements for (int j = 0; j < i; j++) { // If the element is consecutive // then consider this subsequence // and update dp[i] if required. if ((arr[i] == arr[j] + 1) || (arr[i] == arr[j] - 1)) dp[i] = Math.Max(dp[i], dp[j] + 1); } } // Longest length will be the maximum // value of dp array. int result = 1; for (int i = 0; i < n; i++) if (result < dp[i]) result = dp[i]; return result; } // Driver code public static void Main() { // Longest subsequence with one // difference is // {1, 2, 3, 4, 3, 2} int[] arr = { 1, 2, 3, 4, 5, 3, 2 }; int n = arr.Length; Console.Write( longestSubseqWithDiffOne(arr, n)); }} // This code is contributed by nitin mittal. <?php// PHP program to find the longest// subsequence such the difference// between adjacent elements of the// subsequence is one. // Function to find the length of// longest subsequencefunction longestSubseqWithDiffOne($arr, $n){ // Initialize the dp[] // array with 1 as a // single element will // be of 1 length $dp[$n] = 0; for($i = 0; $i< $n; $i++) $dp[$i] = 1; // Start traversing the // given array for($i = 1; $i < $n; $i++) { // Compare with all the // previous elements for($j = 0; $j < $i; $j++) { // If the element is // consecutive then // consider this // subsequence and // update dp[i] if // required. if (($arr[$i] == $arr[$j] + 1) || ($arr[$i] == $arr[$j] - 1)) $dp[$i] = max($dp[$i], $dp[$j] + 1); } } // Longest length will be // the maximum value // of dp array. $result = 1; for($i = 0 ; $i < $n ; $i++) if ($result < $dp[$i]) $result = $dp[$i]; return $result;} // Driver code // Longest subsequence with // one difference is // {1, 2, 3, 4, 3, 2} $arr = array(1, 2, 3, 4, 5, 3, 2); $n = sizeof($arr); echo longestSubseqWithDiffOne($arr, $n); // This code is contributed by nitin mittal.?> <script> // JavaScript program to find the// longest subsequence such that the// difference between adjacent elements// of the subsequence is one. // Function to find the length of longest// subsequencefunction longestSubseqWithDiffOne(arr, n){ // Initialize the dp[] array with 1 as a // single element will be of 1 length let dp = []; for(let i = 0; i < n; i++) dp[i] = 1; // Start traversing the given array for(let i = 1; i < n; i++) { // Compare with all the previous // elements for(let j = 0; j < i; j++) { // If the element is consecutive // then consider this subsequence // and update dp[i] if required. if ((arr[i] == arr[j] + 1) || (arr[i] == arr[j] - 1)) dp[i] = Math.max(dp[i], dp[j] + 1); } } // Longest length will be the maximum // value of dp array. let result = 1; for(let i = 0; i < n; i++) if (result < dp[i]) result = dp[i]; return result;} // Driver Code // Longest subsequence with one// difference is// {1, 2, 3, 4, 3, 2}let arr = [1, 2, 3, 4, 5, 3, 2];let n = arr.length; document.write(longestSubseqWithDiffOne(arr, n)); // This code is contributed by souravghosh0416 </script> 6 Time Complexity: O(n2) Auxiliary Space: O(n) Efficient Approach C++ Java Python3 #include<bits/stdc++.h>using namespace std;int longestSubsequence(int n, int arr[]) { if(n==1) return 1; unordered_map<int,int> mapp; int res = 1; for(int i=0;i<n;i++){ if(mapp.count(arr[i]+1) >0 || mapp.count(arr[i]-1)>0){ mapp[arr[i]]=1+max(mapp[arr[i]+1],mapp[arr[i]-1]); } else mapp[arr[i]]=1; res = max(res, mapp[arr[i]]); } return res; //This code is contributed by Akansha Mittal }int main(){ // Longest subsequence with one difference is // {1, 2, 3, 4, 3, 2} int arr[] = {1, 2, 3, 4, 5, 3, 2}; int n = sizeof(arr)/sizeof(arr[0]); cout << longestSubsequence(n, arr); return 0;} import java.lang.Math;import java.util.*; class GFG { static int longestSubsequence(int n, int arr[]) { if (n == 1) return 1; Integer dp[] = new Integer[n]; HashMap<Integer, Integer> mapp = new HashMap<>(); dp[0] = 1; mapp.put(arr[0], 0); for (int i = 1; i < n; i++) { if (Math.abs(arr[i] - arr[i - 1]) == 1) dp[i] = dp[i - 1] + 1; else { if (mapp.containsKey(arr[i] + 1) || mapp.containsKey(arr[i] - 1)) { dp[i] = 1 + Math.max(mapp.getOrDefault( arr[i] + 1, 0), mapp.getOrDefault( arr[i] - 1, 0)); } else dp[i] = 1; } mapp.put(arr[i], dp[i]); } return Collections.max(Arrays.asList(dp)); } public static void main(String[] args) { // Longest subsequence with one // difference is // {1, 2, 3, 4, 3, 2} int arr[] = { 1, 2, 3, 4, 5, 3, 2 }; int n = arr.length; System.out.println(longestSubsequence(n, arr)); }} // This code is contributed by rajsanghavi9. def longestSubsequence(A, N): L = [1]*N hm = {} for i in range(1,N): if abs(A[i]-A[i-1]) == 1: L[i] = 1 + L[i-1] elif hm.get(A[i]+1,0) or hm.get(A[i]-1,0): L[i] = 1+max(hm.get(A[i]+1,0), hm.get(A[i]-1,0)) hm[A[i]] = L[i] return max(L)# Driver codeA = [1, 2, 3, 4, 5, 3, 2]N = len(A)print(longestSubsequence(A, N)) 6 This article is contributed by Sahil Chhabra (KILLER). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal souravghosh0416 rajsanghavi9 praveen7230 amartyaghoshgfg aakankshamittal22 LIS Dynamic Programming Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Subset Sum Problem | DP-25 Coin Change | DP-7 Matrix Chain Multiplication | DP-8 Longest Palindromic Substring | Set 1 Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Sieve of Eratosthenes Edit Distance | DP-5 Overlapping Subproblems Property in Dynamic Programming | DP-1
[ { "code": null, "e": 26627, "s": 26599, "text": "\n25 Mar, 2022" }, { "code": null, "e": 26745, "s": 26627, "text": "Given an array of n size, the task is to find the longest subsequence such that difference between adjacents is one. " }, { "code": null, "e": 26756, "s": 26745, "text": "Examples: " }, { "code": null, "e": 27004, "s": 26756, "text": "Input : arr[] = {10, 9, 4, 5, 4, 8, 6}\nOutput : 3\nAs longest subsequences with difference 1 are, \"10, 9, 8\", \n\"4, 5, 4\" and \"4, 5, 6\"\n\nInput : arr[] = {1, 2, 3, 2, 3, 7, 2, 1}\nOutput : 7\nAs longest consecutive sequence is \"1, 2, 3, 2, 3, 2, 1\"" }, { "code": null, "e": 27087, "s": 27004, "text": "This problem is based upon the concept of Longest Increasing Subsequence Problem. " }, { "code": null, "e": 27531, "s": 27087, "text": "Let arr[0..n-1] be the input array and \ndp[i] be the length of the longest subsequence (with\ndifferences one) ending at index i such that arr[i] \nis the last element of the subsequence.\n\nThen, dp[i] can be recursively written as:\ndp[i] = 1 + max(dp[j]) where 0 < j < i and \n [arr[j] = arr[i] -1 or arr[j] = arr[i] + 1]\ndp[i] = 1, if no such j exists.\n\nTo find the result for a given array, we need \nto return max(dp[i]) where 0 < i < n." }, { "code": null, "e": 27641, "s": 27531, "text": "Following is a Dynamic Programming based implementation. It follows the recursive structure discussed above. " }, { "code": null, "e": 27645, "s": 27641, "text": "C++" }, { "code": null, "e": 27650, "s": 27645, "text": "Java" }, { "code": null, "e": 27658, "s": 27650, "text": "Python3" }, { "code": null, "e": 27661, "s": 27658, "text": "C#" }, { "code": null, "e": 27665, "s": 27661, "text": "PHP" }, { "code": null, "e": 27676, "s": 27665, "text": "Javascript" }, { "code": "// C++ program to find the longest subsequence such// the difference between adjacent elements of the// subsequence is one.#include <bits/stdc++.h>using namespace std; // Function to find the length of longest subsequenceint longestSubseqWithDiffOne(int arr[], int n){ // Initialize the dp[] array with 1 as a // single element will be of 1 length int dp[n]; for (int i = 0; i < n; i++) dp[i] = 1; // Start traversing the given array for (int i = 1; i < n; i++) { // Compare with all the previous elements for (int j = 0; j < i; j++) { // If the element is consecutive then // consider this subsequence and update // dp[i] if required. if ((arr[i] == arr[j] + 1) || (arr[i] == arr[j] - 1)) dp[i] = max(dp[i], dp[j] + 1); } } // Longest length will be the maximum value // of dp array. int result = 1; for (int i = 0; i < n; i++) if (result < dp[i]) result = dp[i]; return result;} // Driver codeint main(){ // Longest subsequence with one difference is // {1, 2, 3, 4, 3, 2} int arr[] = { 1, 2, 3, 4, 5, 3, 2 }; int n = sizeof(arr) / sizeof(arr[0]); cout << longestSubseqWithDiffOne(arr, n); return 0;}", "e": 28941, "s": 27676, "text": null }, { "code": "// Java program to find the longest subsequence// such that the difference between adjacent// elements of the subsequence is one.import java.io.*; class GFG { // Function to find the length of longest // subsequence static int longestSubseqWithDiffOne(int arr[], int n) { // Initialize the dp[] array with 1 as a // single element will be of 1 length int dp[] = new int[n]; for (int i = 0; i < n; i++) dp[i] = 1; // Start traversing the given array for (int i = 1; i < n; i++) { // Compare with all the previous // elements for (int j = 0; j < i; j++) { // If the element is consecutive // then consider this subsequence // and update dp[i] if required. if ((arr[i] == arr[j] + 1) || (arr[i] == arr[j] - 1)) dp[i] = Math.max(dp[i], dp[j] + 1); } } // Longest length will be the maximum // value of dp array. int result = 1; for (int i = 0; i < n; i++) if (result < dp[i]) result = dp[i]; return result; } // Driver code public static void main(String[] args) { // Longest subsequence with one // difference is // {1, 2, 3, 4, 3, 2} int arr[] = { 1, 2, 3, 4, 5, 3, 2 }; int n = arr.length; System.out.println(longestSubseqWithDiffOne( arr, n)); }} // This code is contributed by Prerna Saini", "e": 30500, "s": 28941, "text": null }, { "code": "# Function to find the length of longest subsequencedef longestSubseqWithDiffOne(arr, n): # Initialize the dp[] array with 1 as a # single element will be of 1 length dp = [1 for i in range(n)] # Start traversing the given array for i in range(n): # Compare with all the previous elements for j in range(i): # If the element is consecutive then # consider this subsequence and update # dp[i] if required. if ((arr[i] == arr[j]+1) or (arr[i] == arr[j]-1)): dp[i] = max(dp[i], dp[j]+1) # Longest length will be the maximum value # of dp array. result = 1 for i in range(n): if (result < dp[i]): result = dp[i] return result # Driver codearr = [1, 2, 3, 4, 5, 3, 2]# Longest subsequence with one difference is# {1, 2, 3, 4, 3, 2}n = len(arr)print (longestSubseqWithDiffOne(arr, n)) # This code is contributed by Afzal Ansari", "e": 31459, "s": 30500, "text": null }, { "code": "// C# program to find the longest subsequence// such that the difference between adjacent// elements of the subsequence is one.using System; class GFG { // Function to find the length of longest // subsequence static int longestSubseqWithDiffOne(int[] arr, int n) { // Initialize the dp[] array with 1 as a // single element will be of 1 length int[] dp = new int[n]; for (int i = 0; i < n; i++) dp[i] = 1; // Start traversing the given array for (int i = 1; i < n; i++) { // Compare with all the previous // elements for (int j = 0; j < i; j++) { // If the element is consecutive // then consider this subsequence // and update dp[i] if required. if ((arr[i] == arr[j] + 1) || (arr[i] == arr[j] - 1)) dp[i] = Math.Max(dp[i], dp[j] + 1); } } // Longest length will be the maximum // value of dp array. int result = 1; for (int i = 0; i < n; i++) if (result < dp[i]) result = dp[i]; return result; } // Driver code public static void Main() { // Longest subsequence with one // difference is // {1, 2, 3, 4, 3, 2} int[] arr = { 1, 2, 3, 4, 5, 3, 2 }; int n = arr.Length; Console.Write( longestSubseqWithDiffOne(arr, n)); }} // This code is contributed by nitin mittal.", "e": 33001, "s": 31459, "text": null }, { "code": "<?php// PHP program to find the longest// subsequence such the difference// between adjacent elements of the// subsequence is one. // Function to find the length of// longest subsequencefunction longestSubseqWithDiffOne($arr, $n){ // Initialize the dp[] // array with 1 as a // single element will // be of 1 length $dp[$n] = 0; for($i = 0; $i< $n; $i++) $dp[$i] = 1; // Start traversing the // given array for($i = 1; $i < $n; $i++) { // Compare with all the // previous elements for($j = 0; $j < $i; $j++) { // If the element is // consecutive then // consider this // subsequence and // update dp[i] if // required. if (($arr[$i] == $arr[$j] + 1) || ($arr[$i] == $arr[$j] - 1)) $dp[$i] = max($dp[$i], $dp[$j] + 1); } } // Longest length will be // the maximum value // of dp array. $result = 1; for($i = 0 ; $i < $n ; $i++) if ($result < $dp[$i]) $result = $dp[$i]; return $result;} // Driver code // Longest subsequence with // one difference is // {1, 2, 3, 4, 3, 2} $arr = array(1, 2, 3, 4, 5, 3, 2); $n = sizeof($arr); echo longestSubseqWithDiffOne($arr, $n); // This code is contributed by nitin mittal.?>", "e": 34418, "s": 33001, "text": null }, { "code": "<script> // JavaScript program to find the// longest subsequence such that the// difference between adjacent elements// of the subsequence is one. // Function to find the length of longest// subsequencefunction longestSubseqWithDiffOne(arr, n){ // Initialize the dp[] array with 1 as a // single element will be of 1 length let dp = []; for(let i = 0; i < n; i++) dp[i] = 1; // Start traversing the given array for(let i = 1; i < n; i++) { // Compare with all the previous // elements for(let j = 0; j < i; j++) { // If the element is consecutive // then consider this subsequence // and update dp[i] if required. if ((arr[i] == arr[j] + 1) || (arr[i] == arr[j] - 1)) dp[i] = Math.max(dp[i], dp[j] + 1); } } // Longest length will be the maximum // value of dp array. let result = 1; for(let i = 0; i < n; i++) if (result < dp[i]) result = dp[i]; return result;} // Driver Code // Longest subsequence with one// difference is// {1, 2, 3, 4, 3, 2}let arr = [1, 2, 3, 4, 5, 3, 2];let n = arr.length; document.write(longestSubseqWithDiffOne(arr, n)); // This code is contributed by souravghosh0416 </script>", "e": 35747, "s": 34418, "text": null }, { "code": null, "e": 35749, "s": 35747, "text": "6" }, { "code": null, "e": 35794, "s": 35749, "text": "Time Complexity: O(n2) Auxiliary Space: O(n)" }, { "code": null, "e": 35814, "s": 35794, "text": "Efficient Approach " }, { "code": null, "e": 35818, "s": 35814, "text": "C++" }, { "code": null, "e": 35823, "s": 35818, "text": "Java" }, { "code": null, "e": 35831, "s": 35823, "text": "Python3" }, { "code": "#include<bits/stdc++.h>using namespace std;int longestSubsequence(int n, int arr[]) { if(n==1) return 1; unordered_map<int,int> mapp; int res = 1; for(int i=0;i<n;i++){ if(mapp.count(arr[i]+1) >0 || mapp.count(arr[i]-1)>0){ mapp[arr[i]]=1+max(mapp[arr[i]+1],mapp[arr[i]-1]); } else mapp[arr[i]]=1; res = max(res, mapp[arr[i]]); } return res; //This code is contributed by Akansha Mittal }int main(){ // Longest subsequence with one difference is // {1, 2, 3, 4, 3, 2} int arr[] = {1, 2, 3, 4, 5, 3, 2}; int n = sizeof(arr)/sizeof(arr[0]); cout << longestSubsequence(n, arr); return 0;}", "e": 36577, "s": 35831, "text": null }, { "code": "import java.lang.Math;import java.util.*; class GFG { static int longestSubsequence(int n, int arr[]) { if (n == 1) return 1; Integer dp[] = new Integer[n]; HashMap<Integer, Integer> mapp = new HashMap<>(); dp[0] = 1; mapp.put(arr[0], 0); for (int i = 1; i < n; i++) { if (Math.abs(arr[i] - arr[i - 1]) == 1) dp[i] = dp[i - 1] + 1; else { if (mapp.containsKey(arr[i] + 1) || mapp.containsKey(arr[i] - 1)) { dp[i] = 1 + Math.max(mapp.getOrDefault( arr[i] + 1, 0), mapp.getOrDefault( arr[i] - 1, 0)); } else dp[i] = 1; } mapp.put(arr[i], dp[i]); } return Collections.max(Arrays.asList(dp)); } public static void main(String[] args) { // Longest subsequence with one // difference is // {1, 2, 3, 4, 3, 2} int arr[] = { 1, 2, 3, 4, 5, 3, 2 }; int n = arr.length; System.out.println(longestSubsequence(n, arr)); }} // This code is contributed by rajsanghavi9.", "e": 37872, "s": 36577, "text": null }, { "code": "def longestSubsequence(A, N): L = [1]*N hm = {} for i in range(1,N): if abs(A[i]-A[i-1]) == 1: L[i] = 1 + L[i-1] elif hm.get(A[i]+1,0) or hm.get(A[i]-1,0): L[i] = 1+max(hm.get(A[i]+1,0), hm.get(A[i]-1,0)) hm[A[i]] = L[i] return max(L)# Driver codeA = [1, 2, 3, 4, 5, 3, 2]N = len(A)print(longestSubsequence(A, N))", "e": 38242, "s": 37872, "text": null }, { "code": null, "e": 38244, "s": 38242, "text": "6" }, { "code": null, "e": 38675, "s": 38244, "text": "This article is contributed by Sahil Chhabra (KILLER). 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": 38688, "s": 38675, "text": "nitin mittal" }, { "code": null, "e": 38704, "s": 38688, "text": "souravghosh0416" }, { "code": null, "e": 38717, "s": 38704, "text": "rajsanghavi9" }, { "code": null, "e": 38729, "s": 38717, "text": "praveen7230" }, { "code": null, "e": 38745, "s": 38729, "text": "amartyaghoshgfg" }, { "code": null, "e": 38763, "s": 38745, "text": "aakankshamittal22" }, { "code": null, "e": 38767, "s": 38763, "text": "LIS" }, { "code": null, "e": 38787, "s": 38767, "text": "Dynamic Programming" }, { "code": null, "e": 38807, "s": 38787, "text": "Dynamic Programming" }, { "code": null, "e": 38905, "s": 38807, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38936, "s": 38905, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 38969, "s": 38936, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 38996, "s": 38969, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 39015, "s": 38996, "text": "Coin Change | DP-7" }, { "code": null, "e": 39050, "s": 39015, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 39088, "s": 39050, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 39156, "s": 39088, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 39178, "s": 39156, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 39199, "s": 39178, "text": "Edit Distance | DP-5" } ]
Note : Range VS Xrange - GeeksforGeeks
13 May, 2022 The range() and xrange() are two functions that could be used to iterate a certain number of times in for loops in Python. In Python 3, there is no xrange, but the range function behaves like xrange in Python 2. If you want to write code that will run on both Python 2 and Python 3, you should use range(). range() – This returns a range object (a type of iterable). xrange() – This function returns the generator object that can be used to display numbers only by looping. The only particular range is displayed on demand and hence called “lazy evaluation“. Both are implemented in different ways and have different characteristics associated with them. The points of comparison are: Return Type Memory Operation Usage Speed range() returns – range object. xrange() returns – xrange() object. Python # Python code to demonstrate range() vs xrange()# on basis of return type # initializing a with range()a = range(1,10000) # initializing a with xrange()x = xrange(1,10000) # testing the type of aprint ("The return type of range() is : ")print (type(a)) # testing the type of xprint ("The return type of xrange() is : ")print (type(x)) Output: The return type of range() is : <type 'list'> The return type of xrange() is : <type 'xrange'> The variable storing the range created by range() takes more memory as compared to the variable storing the range using xrange(). The basic reason for this is the return type of range() is list and xrange() is xrange() object. Python # Python code to demonstrate range() vs xrange()# on basis of memory import sys # initializing a with range()a = range(1,10000) # initializing a with xrange()x = xrange(1,10000) # testing the size of a# range() takes more memoryprint ("The size allotted using range() is : ")print (sys.getsizeof(a)) # testing the size of x# xrange() takes less memoryprint ("The size allotted using xrange() is : ")print (sys.getsizeof(x)) Output: The size allotted using range() is : 80064 The size allotted using xrange() is : 40 As range() returns the list, all the operations that can be applied on the list can be used on it. On the other hand, as xrange() returns the xrange object, operations associated to list cannot be applied on them, hence a disadvantage. Python # Python code to demonstrate range() vs xrange()# on basis of operations usage # initializing a with range()a = range(1,6) # initializing a with xrange()x = xrange(1,6) # testing usage of slice operation on range()# prints without errorprint ("The list after slicing using range is : ")print (a[2:5]) # testing usage of slice operation on xrange()# raises errorprint ("The list after slicing using xrange is : ")print (x[2:5]) Error: Traceback (most recent call last): File "1f2d94c59aea6aed795b05a19e44474d.py", line 18, in print (x[2:5]) TypeError: sequence index must be integer, not 'slice' Output: The list after slicing using range is : [3, 4, 5] The list after slicing using xrange is : Because of the fact that xrange() evaluates only the generator object containing only the values that are required by lazy evaluation, therefore is faster in implementation than range(). Important Points: If you want to write code that will run on both Python 2 and Python 3, use range() as the xrange function is deprecated in Python 3. range() is faster if iterating over the same sequence multiple times. xrange() has to reconstruct the integer object every time, but range() will have real integer objects. (It will always perform worse in terms of memory however) apurvkolte10 Akanksha_Rai pradm007 umutpc97 rushi_javiya Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Taking input in Python Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python
[ { "code": null, "e": 24977, "s": 24949, "text": "\n13 May, 2022" }, { "code": null, "e": 25284, "s": 24977, "text": "The range() and xrange() are two functions that could be used to iterate a certain number of times in for loops in Python. In Python 3, there is no xrange, but the range function behaves like xrange in Python 2. If you want to write code that will run on both Python 2 and Python 3, you should use range()." }, { "code": null, "e": 25344, "s": 25284, "text": "range() – This returns a range object (a type of iterable)." }, { "code": null, "e": 25536, "s": 25344, "text": "xrange() – This function returns the generator object that can be used to display numbers only by looping. The only particular range is displayed on demand and hence called “lazy evaluation“." }, { "code": null, "e": 25663, "s": 25536, "text": "Both are implemented in different ways and have different characteristics associated with them. The points of comparison are: " }, { "code": null, "e": 25675, "s": 25663, "text": "Return Type" }, { "code": null, "e": 25682, "s": 25675, "text": "Memory" }, { "code": null, "e": 25698, "s": 25682, "text": "Operation Usage" }, { "code": null, "e": 25704, "s": 25698, "text": "Speed" }, { "code": null, "e": 25773, "s": 25704, "text": "range() returns – range object. xrange() returns – xrange() object. " }, { "code": null, "e": 25780, "s": 25773, "text": "Python" }, { "code": "# Python code to demonstrate range() vs xrange()# on basis of return type # initializing a with range()a = range(1,10000) # initializing a with xrange()x = xrange(1,10000) # testing the type of aprint (\"The return type of range() is : \")print (type(a)) # testing the type of xprint (\"The return type of xrange() is : \")print (type(x))", "e": 26120, "s": 25780, "text": null }, { "code": null, "e": 26128, "s": 26120, "text": "Output:" }, { "code": null, "e": 26225, "s": 26128, "text": "The return type of range() is : \n<type 'list'>\nThe return type of xrange() is : \n<type 'xrange'>" }, { "code": null, "e": 26453, "s": 26225, "text": "The variable storing the range created by range() takes more memory as compared to the variable storing the range using xrange(). The basic reason for this is the return type of range() is list and xrange() is xrange() object. " }, { "code": null, "e": 26460, "s": 26453, "text": "Python" }, { "code": "# Python code to demonstrate range() vs xrange()# on basis of memory import sys # initializing a with range()a = range(1,10000) # initializing a with xrange()x = xrange(1,10000) # testing the size of a# range() takes more memoryprint (\"The size allotted using range() is : \")print (sys.getsizeof(a)) # testing the size of x# xrange() takes less memoryprint (\"The size allotted using xrange() is : \")print (sys.getsizeof(x))", "e": 26890, "s": 26460, "text": null }, { "code": null, "e": 26899, "s": 26890, "text": "Output: " }, { "code": null, "e": 26985, "s": 26899, "text": "The size allotted using range() is : \n80064\nThe size allotted using xrange() is : \n40" }, { "code": null, "e": 27221, "s": 26985, "text": "As range() returns the list, all the operations that can be applied on the list can be used on it. On the other hand, as xrange() returns the xrange object, operations associated to list cannot be applied on them, hence a disadvantage." }, { "code": null, "e": 27228, "s": 27221, "text": "Python" }, { "code": "# Python code to demonstrate range() vs xrange()# on basis of operations usage # initializing a with range()a = range(1,6) # initializing a with xrange()x = xrange(1,6) # testing usage of slice operation on range()# prints without errorprint (\"The list after slicing using range is : \")print (a[2:5]) # testing usage of slice operation on xrange()# raises errorprint (\"The list after slicing using xrange is : \")print (x[2:5])", "e": 27661, "s": 27228, "text": null }, { "code": null, "e": 27669, "s": 27661, "text": "Error: " }, { "code": null, "e": 27837, "s": 27669, "text": "Traceback (most recent call last):\n File \"1f2d94c59aea6aed795b05a19e44474d.py\", line 18, in \n print (x[2:5])\nTypeError: sequence index must be integer, not 'slice'" }, { "code": null, "e": 27846, "s": 27837, "text": "Output: " }, { "code": null, "e": 27939, "s": 27846, "text": "The list after slicing using range is : \n[3, 4, 5]\nThe list after slicing using xrange is : " }, { "code": null, "e": 28126, "s": 27939, "text": "Because of the fact that xrange() evaluates only the generator object containing only the values that are required by lazy evaluation, therefore is faster in implementation than range()." }, { "code": null, "e": 28145, "s": 28126, "text": "Important Points: " }, { "code": null, "e": 28278, "s": 28145, "text": "If you want to write code that will run on both Python 2 and Python 3, use range() as the xrange function is deprecated in Python 3." }, { "code": null, "e": 28348, "s": 28278, "text": "range() is faster if iterating over the same sequence multiple times." }, { "code": null, "e": 28509, "s": 28348, "text": "xrange() has to reconstruct the integer object every time, but range() will have real integer objects. (It will always perform worse in terms of memory however)" }, { "code": null, "e": 28522, "s": 28509, "text": "apurvkolte10" }, { "code": null, "e": 28535, "s": 28522, "text": "Akanksha_Rai" }, { "code": null, "e": 28544, "s": 28535, "text": "pradm007" }, { "code": null, "e": 28553, "s": 28544, "text": "umutpc97" }, { "code": null, "e": 28566, "s": 28553, "text": "rushi_javiya" }, { "code": null, "e": 28573, "s": 28566, "text": "Python" }, { "code": null, "e": 28671, "s": 28573, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28699, "s": 28671, "text": "Read JSON file using Python" }, { "code": null, "e": 28749, "s": 28699, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 28771, "s": 28749, "text": "Python map() function" }, { "code": null, "e": 28815, "s": 28771, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 28838, "s": 28815, "text": "Taking input in Python" }, { "code": null, "e": 28873, "s": 28838, "text": "Read a file line by line in Python" }, { "code": null, "e": 28905, "s": 28873, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28927, "s": 28905, "text": "Enumerate() in Python" }, { "code": null, "e": 28969, "s": 28927, "text": "Different ways to create Pandas Dataframe" } ]