title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Java - ByteArrayInputStream
The ByteArrayInputStream class allows a buffer in the memory to be used as an InputStream. The input source is a byte array. ByteArrayInputStream class provides the following constructors. ByteArrayInputStream(byte [] a) This constructor accepts a byte array as a parameter. ByteArrayInputStream(byte [] a, int off, int len) This constructor takes an array of bytes, and two integer values, where off is the first byte to be read and len is the number of bytes to be read. Once you have ByteArrayInputStream object in hand then there is a list of helper methods which can be used to read the stream or to do other operations on the stream. public int read() This method reads the next byte of data from the InputStream. Returns an int as the next byte of data. If it is the end of the file, then it returns -1. public int read(byte[] r, int off, int len) This method reads upto len number of bytes starting from off from the input stream into an array. Returns the total number of bytes read. If it is the end of the file, -1 will be returned. public int available() Gives the number of bytes that can be read from this file input stream. Returns an int that gives the number of bytes to be read. public void mark(int read) This sets the current marked position in the stream. The parameter gives the maximum limit of bytes that can be read before the marked position becomes invalid. public long skip(long n) Skips ‘n’ number of bytes from the stream. This returns the actual number of bytes skipped. Following is the example to demonstrate ByteArrayInputStream and ByteArrayOutputStream. import java.io.*; public class ByteStreamTest { public static void main(String args[])throws IOException { ByteArrayOutputStream bOutput = new ByteArrayOutputStream(12); while( bOutput.size()!= 10 ) { // Gets the inputs from the user bOutput.write("hello".getBytes()); } byte b [] = bOutput.toByteArray(); System.out.println("Print the content"); for(int x = 0 ; x < b.length; x++) { // printing the characters System.out.print((char)b[x] + " "); } System.out.println(" "); int c; ByteArrayInputStream bInput = new ByteArrayInputStream(b); System.out.println("Converting characters to Upper case " ); for(int y = 0 ; y < 1; y++) { while(( c = bInput.read())!= -1) { System.out.println(Character.toUpperCase((char)c)); } bInput.reset(); } } } Following is the sample run of the above program − Print the content h e l l o h e l l o Converting characters to Upper case H E L L O H E L L O 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2502, "s": 2377, "text": "The ByteArrayInputStream class allows a buffer in the memory to be used as an InputStream. The input source is a byte array." }, { "code": null, "e": 2566, "s": 2502, "text": "ByteArrayInputStream class provides the following constructors." }, { "code": null, "e": 2598, "s": 2566, "text": "ByteArrayInputStream(byte [] a)" }, { "code": null, "e": 2652, "s": 2598, "text": "This constructor accepts a byte array as a parameter." }, { "code": null, "e": 2702, "s": 2652, "text": "ByteArrayInputStream(byte [] a, int off, int len)" }, { "code": null, "e": 2850, "s": 2702, "text": "This constructor takes an array of bytes, and two integer values, where off is the first byte to be read and len is the number of bytes to be read." }, { "code": null, "e": 3017, "s": 2850, "text": "Once you have ByteArrayInputStream object in hand then there is a list of helper methods which can be used to read the stream or to do other operations on the stream." }, { "code": null, "e": 3035, "s": 3017, "text": "public int read()" }, { "code": null, "e": 3188, "s": 3035, "text": "This method reads the next byte of data from the InputStream. Returns an int as the next byte of data. If it is the end of the file, then it returns -1." }, { "code": null, "e": 3232, "s": 3188, "text": "public int read(byte[] r, int off, int len)" }, { "code": null, "e": 3421, "s": 3232, "text": "This method reads upto len number of bytes starting from off from the input stream into an array. Returns the total number of bytes read. If it is the end of the file, -1 will be returned." }, { "code": null, "e": 3444, "s": 3421, "text": "public int available()" }, { "code": null, "e": 3574, "s": 3444, "text": "Gives the number of bytes that can be read from this file input stream. Returns an int that gives the number of bytes to be read." }, { "code": null, "e": 3601, "s": 3574, "text": "public void mark(int read)" }, { "code": null, "e": 3762, "s": 3601, "text": "This sets the current marked position in the stream. The parameter gives the maximum limit of bytes that can be read before the marked position becomes invalid." }, { "code": null, "e": 3787, "s": 3762, "text": "public long skip(long n)" }, { "code": null, "e": 3879, "s": 3787, "text": "Skips ‘n’ number of bytes from the stream. This returns the actual number of bytes skipped." }, { "code": null, "e": 3967, "s": 3879, "text": "Following is the example to demonstrate ByteArrayInputStream and ByteArrayOutputStream." }, { "code": null, "e": 4899, "s": 3967, "text": "import java.io.*;\npublic class ByteStreamTest {\n\n public static void main(String args[])throws IOException {\n ByteArrayOutputStream bOutput = new ByteArrayOutputStream(12);\n\n while( bOutput.size()!= 10 ) {\n // Gets the inputs from the user\n bOutput.write(\"hello\".getBytes()); \n }\n byte b [] = bOutput.toByteArray();\n System.out.println(\"Print the content\");\n \n for(int x = 0 ; x < b.length; x++) {\n // printing the characters\n System.out.print((char)b[x] + \" \"); \n }\n System.out.println(\" \");\n \n int c;\n ByteArrayInputStream bInput = new ByteArrayInputStream(b);\n System.out.println(\"Converting characters to Upper case \" );\n \n for(int y = 0 ; y < 1; y++) {\n while(( c = bInput.read())!= -1) {\n System.out.println(Character.toUpperCase((char)c));\n }\n bInput.reset(); \n }\n }\n}" }, { "code": null, "e": 4950, "s": 4899, "text": "Following is the sample run of the above program −" }, { "code": null, "e": 5070, "s": 4950, "text": "Print the content\nh e l l o h e l l o \nConverting characters to Upper case \nH\nE\nL\nL\nO\nH\nE\nL\nL\nO\n" }, { "code": null, "e": 5103, "s": 5070, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 5119, "s": 5103, "text": " Malhar Lathkar" }, { "code": null, "e": 5152, "s": 5119, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 5168, "s": 5152, "text": " Malhar Lathkar" }, { "code": null, "e": 5203, "s": 5168, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5217, "s": 5203, "text": " Anadi Sharma" }, { "code": null, "e": 5251, "s": 5217, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 5265, "s": 5251, "text": " Tushar Kale" }, { "code": null, "e": 5302, "s": 5265, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 5317, "s": 5302, "text": " Monica Mittal" }, { "code": null, "e": 5350, "s": 5317, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 5369, "s": 5350, "text": " Arnab Chakraborty" }, { "code": null, "e": 5376, "s": 5369, "text": " Print" }, { "code": null, "e": 5387, "s": 5376, "text": " Add Notes" } ]
What’s New In Python 3.9 Dictionaries? | by Anupam Chugh | Towards Data Science
Python 3.9 is currently in beta and with a release scheduled in October 2020, there’s a lot to look forward to. For Python developers eagerly waiting for the update, there are a few interesting additions, be it new string methods, topological ordering, or type hinting. But the one that stands out for me is the new union operator that provides a cleaner way to merge or update dictionaries. In the next sections, we’ll look at how the new union operators make manipulating dictionaries a whole lot easier and concise. Dictionaries are a built-in Python data type used to hold mutable, insertion ordered collection of key-value pairs. Up until Python 3.8, we’d typically use the update method or the ** unpacking operator but the most trivial way to update a dictionary is by inserting a key-value pair in it as shown below: d1 = {'a': 'Cat', 'b': 10}d1['type'] = 'animal'{'a': 'Cat', 'b': 10, 'type': 'animal'} But this doesn’t take us very far when it comes to updating a dictionary with multiple new key-value pairs. The update() method is clearly the better bet in such cases: dict1 = {'a': 'Cat', 'b': 10}dict2 = {'c': 'Dog', 'd': 11}dict1.update(dict2)#prints {'a': 'Cat', 'b': 10, 'c': 'Dog', 'd': 11} Though the above way works fine for updating a dictionary but for merging dictionaries, you need to fall back on the copy() method. This is because the update() method executes in-place and would modify the original dictionary. So, you’d have to create a clone of the first dictionary in order to merge without modifying as shown below: d3 = d1.copy()d3.update(d2) This looks fine, but it’s not pythonic. We can do better by using the double-asterisk operator ** to merge dictionaries in a single line of code. dict4 = {**dict1, **dict2, **dict3}#ord3 = dict(d1, **d2) While the above approach works and is certainly concise, however, there is a caveat. For a high-level language like Python which wins brownie points for its readability, the above unpacking operator can seem ugly to many developers. No wonder, there’s are two new union operators in Python 3.9. Python 3.9 introduces new clean union operators in the form of | and |+ for merging and updating dictionaries respectively. For merging two dictionaries we use the operator like this: d3 = d1 | d2 The above operator trims the copy() and update() methods in a neat way. Also, the operator brings a consistent behavior in Python as it’s already used for merging two sets. At the same time, we can use the in-place merging or updating of dictionaries by using the |= operator. It works the same way as the augmented assignment operator +=. d1 |= d2#equivalent tod1 = d1 | d2 In case, we have common keys in two or more dictionaries, the key-value from the second or last dictionary gets picked in the merge or update operations. It’s important to note that the insertion order matters, as we can see above. The new union operators that’ll roll out with Python 3.9 are a small but welcome addition. The good thing is, they’d work when merging a dictionary with iterables as well. That’s it for this one. Thanks for reading.
[ { "code": null, "e": 442, "s": 172, "text": "Python 3.9 is currently in beta and with a release scheduled in October 2020, there’s a lot to look forward to. For Python developers eagerly waiting for the update, there are a few interesting additions, be it new string methods, topological ordering, or type hinting." }, { "code": null, "e": 691, "s": 442, "text": "But the one that stands out for me is the new union operator that provides a cleaner way to merge or update dictionaries. In the next sections, we’ll look at how the new union operators make manipulating dictionaries a whole lot easier and concise." }, { "code": null, "e": 997, "s": 691, "text": "Dictionaries are a built-in Python data type used to hold mutable, insertion ordered collection of key-value pairs. Up until Python 3.8, we’d typically use the update method or the ** unpacking operator but the most trivial way to update a dictionary is by inserting a key-value pair in it as shown below:" }, { "code": null, "e": 1084, "s": 997, "text": "d1 = {'a': 'Cat', 'b': 10}d1['type'] = 'animal'{'a': 'Cat', 'b': 10, 'type': 'animal'}" }, { "code": null, "e": 1192, "s": 1084, "text": "But this doesn’t take us very far when it comes to updating a dictionary with multiple new key-value pairs." }, { "code": null, "e": 1253, "s": 1192, "text": "The update() method is clearly the better bet in such cases:" }, { "code": null, "e": 1381, "s": 1253, "text": "dict1 = {'a': 'Cat', 'b': 10}dict2 = {'c': 'Dog', 'd': 11}dict1.update(dict2)#prints {'a': 'Cat', 'b': 10, 'c': 'Dog', 'd': 11}" }, { "code": null, "e": 1718, "s": 1381, "text": "Though the above way works fine for updating a dictionary but for merging dictionaries, you need to fall back on the copy() method. This is because the update() method executes in-place and would modify the original dictionary. So, you’d have to create a clone of the first dictionary in order to merge without modifying as shown below:" }, { "code": null, "e": 1746, "s": 1718, "text": "d3 = d1.copy()d3.update(d2)" }, { "code": null, "e": 1892, "s": 1746, "text": "This looks fine, but it’s not pythonic. We can do better by using the double-asterisk operator ** to merge dictionaries in a single line of code." }, { "code": null, "e": 1950, "s": 1892, "text": "dict4 = {**dict1, **dict2, **dict3}#ord3 = dict(d1, **d2)" }, { "code": null, "e": 2183, "s": 1950, "text": "While the above approach works and is certainly concise, however, there is a caveat. For a high-level language like Python which wins brownie points for its readability, the above unpacking operator can seem ugly to many developers." }, { "code": null, "e": 2245, "s": 2183, "text": "No wonder, there’s are two new union operators in Python 3.9." }, { "code": null, "e": 2369, "s": 2245, "text": "Python 3.9 introduces new clean union operators in the form of | and |+ for merging and updating dictionaries respectively." }, { "code": null, "e": 2429, "s": 2369, "text": "For merging two dictionaries we use the operator like this:" }, { "code": null, "e": 2442, "s": 2429, "text": "d3 = d1 | d2" }, { "code": null, "e": 2615, "s": 2442, "text": "The above operator trims the copy() and update() methods in a neat way. Also, the operator brings a consistent behavior in Python as it’s already used for merging two sets." }, { "code": null, "e": 2782, "s": 2615, "text": "At the same time, we can use the in-place merging or updating of dictionaries by using the |= operator. It works the same way as the augmented assignment operator +=." }, { "code": null, "e": 2817, "s": 2782, "text": "d1 |= d2#equivalent tod1 = d1 | d2" }, { "code": null, "e": 2971, "s": 2817, "text": "In case, we have common keys in two or more dictionaries, the key-value from the second or last dictionary gets picked in the merge or update operations." }, { "code": null, "e": 3049, "s": 2971, "text": "It’s important to note that the insertion order matters, as we can see above." }, { "code": null, "e": 3221, "s": 3049, "text": "The new union operators that’ll roll out with Python 3.9 are a small but welcome addition. The good thing is, they’d work when merging a dictionary with iterables as well." } ]
How can we apply different borders to JButton in Java?
A JButton is a subclass of AbstractButton class and it can be used for adding platform-independent buttons in a Java Swing application. A JButon can generate an ActionListener interface when the user clicking on a button, it can also generate MouseListener when a user can do some actions from the mouse and KeyListener when a user can do some actions from the keyboard. We can set different borders like LineBorder, BevelBorder, EtchcedBorder, EmptyBorder, TitledBorder, etc to JButton using the setBorder() method of JComponent class. public void setBorder(Border border) import javax.swing.*; import java.awt.*; public class JButtonBordersTest extends JFrame { private JButton button[]; private JPanel panel; public JButtonBordersTest() { setTitle("JButton Borders"); panel = new JPanel(); panel.setLayout(new GridLayout(7, 1)); button = new JButton[7]; for(int count = 0; count < button.length; count++) { button[count] = new JButton("Button "+(count+1)); panel.add(button[count]); } button[0].setBorder(BorderFactory.createLineBorder(Color.blue)); button[1].setBorder(BorderFactory.createBevelBorder(0)); button[2].setBorder(BorderFactory.createBevelBorder(1, Color.red, Color.blue)); button[3].setBorder(BorderFactory.createBevelBorder(1, Color.green, Color.orange, Color.red, Color.blue)); button[4].setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); button[5].setBorder(BorderFactory.createEtchedBorder(0)); button[6].setBorder(BorderFactory.createTitledBorder("Titled Border")); add(panel, BorderLayout.CENTER); setSize(400, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } public static void main(String[] args) { new JButtonBordersTest(); } }
[ { "code": null, "e": 1433, "s": 1062, "text": "A JButton is a subclass of AbstractButton class and it can be used for adding platform-independent buttons in a Java Swing application. A JButon can generate an ActionListener interface when the user clicking on a button, it can also generate MouseListener when a user can do some actions from the mouse and KeyListener when a user can do some actions from the keyboard." }, { "code": null, "e": 1599, "s": 1433, "text": "We can set different borders like LineBorder, BevelBorder, EtchcedBorder, EmptyBorder, TitledBorder, etc to JButton using the setBorder() method of JComponent class." }, { "code": null, "e": 1636, "s": 1599, "text": "public void setBorder(Border border)" }, { "code": null, "e": 2930, "s": 1636, "text": "import javax.swing.*;\nimport java.awt.*;\npublic class JButtonBordersTest extends JFrame {\n private JButton button[];\n private JPanel panel;\n public JButtonBordersTest() {\n setTitle(\"JButton Borders\");\n panel = new JPanel();\n panel.setLayout(new GridLayout(7, 1));\n button = new JButton[7];\n for(int count = 0; count < button.length; count++) {\n button[count] = new JButton(\"Button \"+(count+1));\n panel.add(button[count]);\n }\n button[0].setBorder(BorderFactory.createLineBorder(Color.blue));\n button[1].setBorder(BorderFactory.createBevelBorder(0));\n button[2].setBorder(BorderFactory.createBevelBorder(1, Color.red, Color.blue));\n button[3].setBorder(BorderFactory.createBevelBorder(1, Color.green, Color.orange, Color.red, Color.blue));\n button[4].setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));\n button[5].setBorder(BorderFactory.createEtchedBorder(0));\n button[6].setBorder(BorderFactory.createTitledBorder(\"Titled Border\"));\n\n add(panel, BorderLayout.CENTER);\n setSize(400, 300);\n setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n setLocationRelativeTo(null);\n setVisible(true);\n }\n public static void main(String[] args) {\n new JButtonBordersTest();\n }\n}" } ]
BabylonJS - VectorPosition and Rotation
Run the demo links given below in your browser. In the demos given below, we have drawn the x,y and z-axis. There are numbers plotted on the x,y and z-axis in the positive and negative direction. Run the same in browser, change the values in case you need and draw your shapes, meshes, position them and see how they render in the x, y and z –axis.With the numbers mentioned on the x,y and z axis, it will be helpful to see how the positioning of the mesh is done. <!doctype html> <html> <head> <meta charset = "utf-8"> <title>BabylonJs - Basic Element-Creating Scene</title> <script src = "babylon.js"></script> <style> canvas {width: 100%; height: 100%;} </style> </head> <body> <canvas id = "renderCanvas"></canvas> <script type = "text/javascript"> var canvas = document.getElementById("renderCanvas"); var engine = new BABYLON.Engine(canvas, true); var createScene = function() { var scene = new BABYLON.Scene(engine); scene.clearColor = new BABYLON.Color3( .5, .5, .5); // camera var camera = new BABYLON.ArcRotateCamera("camera1", 0, 0, 0, new BABYLON.Vector3(5, 3, 0), scene); camera.setPosition(new BABYLON.Vector3(5, 10, -10)); camera.attachControl(canvas, true); // lights var light = new BABYLON.HemisphericLight("light1", new BABYLON.Vector3(1, 0.5, 0), scene); light.intensity = 0.8; var spot = new BABYLON.SpotLight( "spot", new BABYLON.Vector3(25, 15, -10), new BABYLON.Vector3(-1, -0.8, 1), 15, 1, scene); spot.diffuse = new BABYLON.Color3(1, 1, 1); spot.specular = new BABYLON.Color3(0, 0, 0); spot.intensity = 0.2; // material var mat = new BABYLON.StandardMaterial("mat1", scene); mat.alpha = 1.0; mat.diffuseColor = new BABYLON.Color3(0.5, 0.5, 1.0); mat.backFaceCulling = false; //mat.wireframe = true; // show axis var showAxis = function(size) { var makeTextPlane = function(text, color, size) { var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", 50, scene, true); dynamicTexture.hasAlpha = true; dynamicTexture.drawText(text, 5, 40, "bold 36px Arial", color , "transparent", true); var plane = new BABYLON.Mesh.CreatePlane("TextPlane", size, scene, true); plane.material = new BABYLON.StandardMaterial("TextPlaneMaterial", scene); plane.material.backFaceCulling = false; plane.material.specularColor = new BABYLON.Color3(0, 0, 0); plane.material.diffuseTexture = dynamicTexture; return plane; }; var axisX = BABYLON.Mesh.CreateLines("axisX", [ new BABYLON.Vector3(-size * 0.95, 0.05 * size, 0), new BABYLON.Vector3(-size, 0, 0), new BABYLON.Vector3(-size * 0.95, -0.05 * size, 0), new BABYLON.Vector3(-size, 0, 0), new BABYLON.Vector3.Zero(), new BABYLON.Vector3(size, 0, 0), new BABYLON.Vector3(size * 0.95, 0.05 * size, 0), new BABYLON.Vector3(size, 0, 0), new BABYLON.Vector3(size * 0.95, -0.05 * size, 0) ], scene); axisX.color = new BABYLON.Color3(1, 0, 0); var xChar = makeTextPlane("X", "red", size / 10); xChar.position = new BABYLON.Vector3(0.9 * size, -0.05 * size, 0); var xChar1 = makeTextPlane("-X", "red", size / 10); xChar1.position = new BABYLON.Vector3(-0.9 * size, 0.05 * size, 0); var axisY = BABYLON.Mesh.CreateLines("axisY", [ new BABYLON.Vector3( -0.05 * size, -size * 0.95, 0), new BABYLON.Vector3(0, -size, 0), new BABYLON.Vector3(0.05 * size, -size * 0.95, 0), new BABYLON.Vector3(0, -size, 0), new BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, size, 0), new BABYLON.Vector3( -0.05 * size, size * 0.95, 0), new BABYLON.Vector3(0, size, 0), new BABYLON.Vector3( 0.05 * size, size * 0.95, 0) ], scene); axisY.color = new BABYLON.Color3(0, 1, 0); var yChar = makeTextPlane("Y", "green", size / 10); yChar.position = new BABYLON.Vector3(0, 0.9 * size, -0.05 * size); var yChar1 = makeTextPlane("-Y", "green", size / 10); yChar1.position = new BABYLON.Vector3(0, -0.9 * size, 0.05 * size); var axisZ = BABYLON.Mesh.CreateLines("axisZ", [ new BABYLON.Vector3( 0 , -0.05 * size, -size * 0.95), new BABYLON.Vector3(0, 0, -size), new BABYLON.Vector3( 0 , 0.05 * size, -size * 0.95), new BABYLON.Vector3(0, 0, -size), new BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, size), new BABYLON.Vector3( 0 , -0.05 * size, size * 0.95), new BABYLON.Vector3(0, 0, size), new BABYLON.Vector3( 0, 0.05 * size, size * 0.95) ], scene); axisZ.color = new BABYLON.Color3(0, 0, 1); var zChar = makeTextPlane("Z", "blue", size / 10); zChar.position = new BABYLON.Vector3(0, 0.05 * size, 0.9 * size); var zChar1 = makeTextPlane("-Z", "blue", size / 10); zChar1.position = new BABYLON.Vector3(0, 0.05 * size, -0.9 * size); }; showAxis(10); return scene; }; var scene = createScene(); engine.runRenderLoop(function() { scene.render(); }); </script> </body> </html> Let us have the co-ordinates defined along the x, y and z axis. <!doctype html> <html> <head> <meta charset = "utf-8"> <title>BabylonJs - Basic Element-Creating Scene</title> <script src = "babylon.js"></script> <style> canvas {width: 100%; height: 100%;} </style> </head> <body> <canvas id = "renderCanvas"></canvas> <script type = "text/javascript"> var canvas = document.getElementById("renderCanvas"); var engine = new BABYLON.Engine(canvas, true); var createScene = function() { var scene = new BABYLON.Scene(engine); scene.clearColor = new BABYLON.Color3( .5, .5, .5); // camera var camera = new BABYLON.ArcRotateCamera("camera1", 0, 0, 0, new BABYLON.Vector3(5, 3, 0), scene); camera.setPosition(new BABYLON.Vector3(5, 10, -10)); camera.attachControl(canvas, true); // lights var light = new BABYLON.HemisphericLight("light1", new BABYLON.Vector3(1, 0.5, 0), scene); light.intensity = 0.8; var spot = new BABYLON.SpotLight( "spot", new BABYLON.Vector3(25, 15, -10), new BABYLON.Vector3(-1, -0.8, 1), 15, 1, scene); spot.diffuse = new BABYLON.Color3(1, 1, 1); spot.specular = new BABYLON.Color3(0, 0, 0); spot.intensity = 0.2; // material var mat = new BABYLON.StandardMaterial("mat1", scene); mat.alpha = 1.0; mat.diffuseColor = new BABYLON.Color3(0.5, 0.5, 1.0); mat.backFaceCulling = false; //mat.wireframe = true; var makeTextPlane = function(text, color, size) { var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", 50, scene, true); dynamicTexture.hasAlpha = true; dynamicTexture.drawText(text, 5, 40, "bold 36px Arial", color , "transparent", true); var plane = new BABYLON.Mesh.CreatePlane("TextPlane", size, scene, true); plane.material = new BABYLON.StandardMaterial("TextPlaneMaterial", scene); plane.material.backFaceCulling = false; plane.material.specularColor = new BABYLON.Color3(0, 0, 0); plane.material.diffuseTexture = dynamicTexture; return plane; }; // show axis var showAxis = function(size) { var axisX = BABYLON.Mesh.CreateLines("axisX", [ new BABYLON.Vector3(-size * 0.95, 0.05 * size, 0), new BABYLON.Vector3(-size, 0, 0), new BABYLON.Vector3(-size * 0.95, -0.05 * size, 0), new BABYLON.Vector3(-size, 0, 0), new BABYLON.Vector3.Zero(), new BABYLON.Vector3(size, 0, 0), new BABYLON.Vector3(size * 0.95, 0.05 * size, 0), new BABYLON.Vector3(size, 0, 0), new BABYLON.Vector3(size * 0.95, -0.05 * size, 0) ], scene); axisX.color = new BABYLON.Color3(1, 0, 0); var xChar = makeTextPlane("X", "red", size / 10); xChar.position = new BABYLON.Vector3(0.9 * size, -0.05 * size, 0); var xChar1 = makeTextPlane("-X", "red", size / 10); xChar1.position = new BABYLON.Vector3(-0.9 * size, 0.05 * size, 0); var xcor = []; for (i =- 10; i <= 10; i++) { xcor[i] = makeTextPlane(i, "red", size / 10); xcor[i].position = new BABYLON.Vector3(i, 0, 0); } var axisY = BABYLON.Mesh.CreateLines("axisY", [ new BABYLON.Vector3( -0.05 * size, -size * 0.95, 0), new BABYLON.Vector3(0, -size, 0), new BABYLON.Vector3(0.05 * size, -size * 0.95, 0), new BABYLON.Vector3(0, -size, 0), new BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, size, 0), new BABYLON.Vector3( -0.05 * size, size * 0.95, 0), new BABYLON.Vector3(0, size, 0), new BABYLON.Vector3( 0.05 * size, size * 0.95, 0) ], scene); axisY.color = new BABYLON.Color3(0, 1, 0); var yChar = makeTextPlane("Y", "green", size / 10); yChar.position = new BABYLON.Vector3(0, 0.9 * size, -0.05 * size); var yChar1 = makeTextPlane("-Y", "green", size / 10); yChar1.position = new BABYLON.Vector3(0, -0.9 * size, 0.05 * size); var ycor = []; for (y=-10;y<=10;y++) { xcor[y] = makeTextPlane(y, "green", size / 10); xcor[y].position = new BABYLON.Vector3(0, y, 0); } var axisZ = BABYLON.Mesh.CreateLines("axisZ", [ new BABYLON.Vector3( 0 , -0.05 * size, -size * 0.95), new BABYLON.Vector3(0, 0, -size), new BABYLON.Vector3( 0 , 0.05 * size, -size * 0.95), new BABYLON.Vector3(0, 0, -size), new BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, size), new BABYLON.Vector3( 0 , -0.05 * size, size * 0.95), new BABYLON.Vector3(0, 0, size), new BABYLON.Vector3( 0, 0.05 * size, size * 0.95) ], scene); axisZ.color = new BABYLON.Color3(0, 0, 1); var zChar = makeTextPlane("Z", "blue", size / 10); zChar.position = new BABYLON.Vector3(0, 0.05 * size, 0.9 * size); var zChar1 = makeTextPlane("-Z", "blue", size / 10); zChar1.position = new BABYLON.Vector3(0, 0.05 * size, -0.9 * size); var zcor = []; for (z =- 10; z <= 10; z++) { xcor[z] = makeTextPlane(z, "green", size / 10); xcor[z].position = new BABYLON.Vector3(0, 0, z); } }; //Lets draw a mesh along the axis. var spriteManagerPlayer = new BABYLON.SpriteManager("playerManager", "images/bird.png", 1, 200, scene); var player = new BABYLON.Sprite("player", spriteManagerPlayer); player.position.x = 2; player.position.y = 2; player.position.z = 0; var zChardot = makeTextPlane(".", "red", 1); zChardot.position = new BABYLON.Vector3(1.8, 1.8,0); var box = BABYLON.Mesh.CreateBox("box", '2', scene); box.position = new BABYLON.Vector3(-5,3,0); // center point of box x-axis is -5 and y axis is 3. var box = BABYLON.Mesh.CreateBox("box", '2', scene); box.position = new BABYLON.Vector3(0,3,-3); // center point of box x-axis is -5 and y axis is 3. var redSphere = BABYLON.Mesh.CreateSphere("red", 32, 1, scene); //no position for sphere so by default it takes 0,0,0 showAxis(10); returnscene; }; var scene = createScene(); engine.runRenderLoop(function() { scene.render(); }); </script> </body> </html> The above line of code generates the following output − In this demo, we have used image bird.png. The images are stored in the images/ folder locally and are also pasted below for reference. You can download any image of your choice and use in the demo link. Images/bird.png <!doctype html> <html> <head> <meta charset = "utf-8"> <title>BabylonJs - Basic Element-Creating Scene</title> <script src = "babylon.js"></script> <style> canvas {width: 100%; height: 100%;} </style> </head> <body> <canvas id = "renderCanvas"></canvas> <script type = "text/javascript"> var canvas = document.getElementById("renderCanvas"); var engine = new BABYLON.Engine(canvas, true); var createScene = function() { var scene = new BABYLON.Scene(engine); scene.clearColor = new BABYLON.Color3( .5, .5, .5); // camera var camera = new BABYLON.ArcRotateCamera("camera1", 0, 0, 0, new BABYLON.Vector3(5, 3, 0), scene); camera.setPosition(new BABYLON.Vector3(5, 10, -10)); camera.attachControl(canvas, true); // lights var light = new BABYLON.HemisphericLight("light1", new BABYLON.Vector3(1, 0.5, 0), scene); light.intensity = 0.8; var spot = new BABYLON.SpotLight( "spot", new BABYLON.Vector3(25, 15, -10), new BABYLON.Vector3(-1, -0.8, 1), 15, 1, scene); spot.diffuse = new BABYLON.Color3(1, 1, 1); spot.specular = new BABYLON.Color3(0, 0, 0); spot.intensity = 0.2; // material var mat = new BABYLON.StandardMaterial("mat1", scene); mat.alpha = 1.0; mat.diffuseColor = new BABYLON.Color3(0.5, 0.5, 1.0); mat.backFaceCulling = false; //mat.wireframe = true; var makeTextPlane = function(text, color, size) { var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", 50, scene, true); dynamicTexture.hasAlpha = true; dynamicTexture.drawText(text, 5, 40, "bold 36px Arial", color , "transparent", true); var plane = new BABYLON.Mesh.CreatePlane("TextPlane", size, scene, true); plane.material = new BABYLON.StandardMaterial("TextPlaneMaterial", scene); plane.material.backFaceCulling = false; plane.material.specularColor = new BABYLON.Color3(0, 0, 0); plane.material.diffuseTexture = dynamicTexture; return plane; }; // show axis var showAxis = function(size) { var axisX = BABYLON.Mesh.CreateLines("axisX", [ new BABYLON.Vector3(-size * 0.95, 0.05 * size, 0), new BABYLON.Vector3(-size, 0, 0), new BABYLON.Vector3(-size * 0.95, -0.05 * size, 0), new BABYLON.Vector3(-size, 0, 0), new BABYLON.Vector3.Zero(), new BABYLON.Vector3(size, 0, 0), new BABYLON.Vector3(size * 0.95, 0.05 * size, 0), new BABYLON.Vector3(size, 0, 0), new BABYLON.Vector3(size * 0.95, -0.05 * size, 0)], scene); axisX.color = new BABYLON.Color3(1, 0, 0); var xChar = makeTextPlane("X", "red", size / 10); xChar.position = new BABYLON.Vector3(0.9 * size, -0.05 * size, 0); var xChar1 = makeTextPlane("-X", "red", size / 10); xChar1.position = new BABYLON.Vector3(-0.9 * size, 0.05 * size, 0); var xcor = []; for (i =- 10; i <= 10; i++) { xcor[i] = makeTextPlane(i, "red", size / 10); xcor[i].position = new BABYLON.Vector3(i, 0, 0); } var axisY = BABYLON.Mesh.CreateLines("axisY", [ new BABYLON.Vector3( -0.05 * size, -size * 0.95, 0), new BABYLON.Vector3(0, -size, 0), new BABYLON.Vector3(0.05 * size, -size * 0.95, 0), new BABYLON.Vector3(0, -size, 0), new BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, size, 0), new BABYLON.Vector3( -0.05 * size, size * 0.95, 0), new BABYLON.Vector3(0, size, 0), new BABYLON.Vector3( 0.05 * size, size * 0.95, 0) ], scene); axisY.color = new BABYLON.Color3(0, 1, 0); var yChar = makeTextPlane("Y", "green", size / 10); yChar.position = new BABYLON.Vector3(0, 0.9 * size, -0.05 * size); var yChar1 = makeTextPlane("-Y", "green", size / 10); yChar1.position = new BABYLON.Vector3(0, -0.9 * size, 0.05 * size); var ycor = []; for (y =- 10; y <= 10; y++) { xcor[y] = makeTextPlane(y, "green", size / 10); xcor[y].position = new BABYLON.Vector3(0, y, 0); } var axisZ = BABYLON.Mesh.CreateLines("axisZ", [ new BABYLON.Vector3( 0 , -0.05 * size, -size * 0.95), new BABYLON.Vector3(0, 0, -size), new BABYLON.Vector3( 0 , 0.05 * size, -size * 0.95), new BABYLON.Vector3(0, 0, -size), new BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, size), new BABYLON.Vector3( 0 , -0.05 * size, size * 0.95), new BABYLON.Vector3(0, 0, size), new BABYLON.Vector3( 0, 0.05 * size, size * 0.95) ], scene); axisZ.color = new BABYLON.Color3(0, 0, 1); var zChar = makeTextPlane("Z", "blue", size / 10); zChar.position = new BABYLON.Vector3(0, 0.05 * size, 0.9 * size); var zChar1 = makeTextPlane("-Z", "blue", size / 10); zChar1.position = new BABYLON.Vector3(0, 0.05 * size, -0.9 * size); var zcor = []; for (z =- 10; z <= 10; z++) { xcor[z] = makeTextPlane(z, "green", size / 10); xcor[z].position = new BABYLON.Vector3(0, 0, z); } }; var kite = BABYLON.Mesh.CreateLines("kite", [ new BABYLON.Vector3(-4,0,0), new BABYLON.Vector3(0,4,0), new BABYLON.Vector3(4,0,0), new BABYLON.Vector3(0,-4,0), new BABYLON.Vector3(-4,0,0) ], scene); kite.color = new BABYLON.Color3(1, 1, 1); var path = []; path.push(new BABYLON.Vector3(-4, 0, 0)); path.push(new BABYLON.Vector3(0, 0, 0)); path.push(new BABYLON.Vector3(4, 0, 0)); var lines1 = BABYLON.Mesh.CreateLines("lines",path, scene, true); lines1.color = new BABYLON.Color3(1, 1, 1); showAxis(10); return scene; }; var scene = createScene(); engine.runRenderLoop(function() { scene.render(); }); </script> </body> </html> The above line of code will generate the following output: Let us now see how the vector rotate works. <!doctype html> <html> <head> <meta charset = "utf-8"> <title>BabylonJs - Basic Element-Creating Scene</title> <script src = "babylon.js"></script> <style> canvas {width: 100%; height: 100%;} </style> </head> <body> <canvas id = "renderCanvas"></canvas> <script type = "text/javascript"> var canvas = document.getElementById("renderCanvas"); var engine = new BABYLON.Engine(canvas, true); var createScene = function() { var scene = new BABYLON.Scene(engine); scene.clearColor = new BABYLON.Color3( .5, .5, .5); // camera var camera = new BABYLON.ArcRotateCamera("camera1", 0, 0, 0, new BABYLON.Vector3(5, 3, 0), scene); camera.setPosition(new BABYLON.Vector3(0, 0, 0)); camera.attachControl(canvas, true); // lights var light = new BABYLON.HemisphericLight("light1", new BABYLON.Vector3(1, 0.5, 0), scene); light.intensity = 0.8; var spot = new BABYLON.SpotLight( "spot", new BABYLON.Vector3(25, 15, -10), new BABYLON.Vector3(-1, -0.8, 1), 15, 1, scene); spot.diffuse = new BABYLON.Color3(1, 1, 1); spot.specular = new BABYLON.Color3(0, 0, 0); spot.intensity = 0.2; // material var mat = new BABYLON.StandardMaterial("mat1", scene); mat.alpha = 1.0; mat.diffuseColor = new BABYLON.Color3(0.5, 0.5, 1.0); mat.backFaceCulling = false; //mat.wireframe = true; var makeTextPlane = function(text, color, size) { var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", 50, scene, true); dynamicTexture.hasAlpha = true; dynamicTexture.drawText(text, 5, 40, "bold 36px Arial", color , "transparent", true); var plane = new BABYLON.Mesh.CreatePlane("TextPlane", size, scene, true); plane.material = new BABYLON.StandardMaterial("TextPlaneMaterial", scene); plane.material.backFaceCulling = false; plane.material.specularColor = new BABYLON.Color3(0, 0, 0); plane.material.diffuseTexture = dynamicTexture; return plane; }; // show axis var showAxis = function(size) { var axisX = BABYLON.Mesh.CreateLines("axisX", [ new BABYLON.Vector3(-size * 0.95, 0.05 * size, 0), new BABYLON.Vector3(-size, 0, 0), new BABYLON.Vector3(-size * 0.95, -0.05 * size, 0), new BABYLON.Vector3(-size, 0, 0), new BABYLON.Vector3.Zero(), new BABYLON.Vector3(size, 0, 0), new BABYLON.Vector3(size * 0.95, 0.05 * size, 0), new BABYLON.Vector3(size, 0, 0), new BABYLON.Vector3(size * 0.95, -0.05 * size, 0) ], scene); axisX.color = new BABYLON.Color3(1, 0, 0); var xChar = makeTextPlane("X", "red", size / 10); xChar.position = new BABYLON.Vector3(0.9 * size, -0.05 * size, 0); var xChar1 = makeTextPlane("-X", "red", size / 10); xChar1.position = new BABYLON.Vector3(-0.9 * size, 0.05 * size, 0); var xcor = []; for (i =- 10; i <= 10; i++) { xcor[i] = makeTextPlane(i, "red", size / 10); xcor[i].position = new BABYLON.Vector3(i, 0, 0); } var axisY = BABYLON.Mesh.CreateLines("axisY", [ new BABYLON.Vector3( -0.05 * size, -size * 0.95, 0), new BABYLON.Vector3(0, -size, 0), new BABYLON.Vector3(0.05 * size, -size * 0.95, 0), new BABYLON.Vector3(0, -size, 0), new BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, size, 0), new BABYLON.Vector3( -0.05 * size, size * 0.95, 0), new BABYLON.Vector3(0, size, 0), new BABYLON.Vector3( 0.05 * size, size * 0.95, 0) ], scene); axisY.color = new BABYLON.Color3(0, 1, 0); var yChar = makeTextPlane("Y", "green", size / 10); yChar.position = new BABYLON.Vector3(0, 0.9 * size, -0.05 * size); var yChar1 = makeTextPlane("-Y", "green", size / 10); yChar1.position = new BABYLON.Vector3(0, -0.9 * size, 0.05 * size); var ycor = []; for (y =- 10; y <= 10; y++) { xcor[y] = makeTextPlane(y, "green", size / 10); xcor[y].position = new BABYLON.Vector3(0, y, 0); } var axisZ = BABYLON.Mesh.CreateLines("axisZ", [ new BABYLON.Vector3( 0 , -0.05 * size, -size * 0.95), new BABYLON.Vector3(0, 0, -size), new BABYLON.Vector3( 0 , 0.05 * size, -size * 0.95), new BABYLON.Vector3(0, 0, -size), new BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, size), new BABYLON.Vector3( 0 , -0.05 * size, size * 0.95), new BABYLON.Vector3(0, 0, size), new BABYLON.Vector3( 0, 0.05 * size, size * 0.95) ], scene); axisZ.color = new BABYLON.Color3(0, 0, 1); var zChar = makeTextPlane("Z", "blue", size / 10); zChar.position = new BABYLON.Vector3(0, 0.05 * size, 0.9 * size); var zChar1 = makeTextPlane("-Z", "blue", size / 10); zChar1.position = new BABYLON.Vector3(0, 0.05 * size, -0.9 * size); var zcor = []; for (z =- 10; z <= 10; z++) { xcor[z] = makeTextPlane(z, "green", size / 10); xcor[z].position = new BABYLON.Vector3(0, 0, z); } }; var yellowSphere = BABYLON.Mesh.CreateSphere("yellowSphere",32, 1, scene); yellowSphere.setPivotMatrix(BABYLON.Matrix.Translation(2, 0, 0)); var yellowMaterial = new BABYLON.StandardMaterial("yellowMaterial", scene); yellowMaterial.diffuseColor = BABYLON.Color3.Yellow(); yellowSphere.material = yellowMaterial; var wheel1 = BABYLON.MeshBuilder.CreateTorus('t1', {diameter: 2.0}, scene); wheel1.position.x = -2.0 wheel1.position.z = -2.0; showAxis(10); var k = 0.0; var y = 0.0; var x = 0.0; scene.registerBeforeRender(function () { wheel1.rotation.copyFromFloats(0.0, 0.0, Math.PI / 2); wheel1.addRotation(0.0, y, 0.0); wheel1.addRotation(x, 0.0, 0.0); yellowSphere.rotation.y += 0.01; y += 0.05; }); return scene; }; var scene = createScene(); engine.runRenderLoop(function() { scene.render(); }); </script> </body> </html> The above line of code generates the following output − Print Add Notes Bookmark this page
[ { "code": null, "e": 2648, "s": 2183, "text": "Run the demo links given below in your browser. In the demos given below, we have drawn the x,y and z-axis. There are numbers plotted on the x,y and z-axis in the positive and negative direction. Run the same in browser, change the values in case you need and draw your shapes, meshes, position them and see how they render in the x, y and z –axis.With the numbers mentioned on the x,y and z axis, it will be helpful to see how the positioning of the mesh is done." }, { "code": null, "e": 8397, "s": 2648, "text": "<!doctype html>\n<html>\n <head>\n <meta charset = \"utf-8\">\n <title>BabylonJs - Basic Element-Creating Scene</title>\n <script src = \"babylon.js\"></script>\n <style>\n canvas {width: 100%; height: 100%;}\n </style>\n </head>\n\n <body>\n <canvas id = \"renderCanvas\"></canvas>\n <script type = \"text/javascript\">\n var canvas = document.getElementById(\"renderCanvas\");\n var engine = new BABYLON.Engine(canvas, true);\n var createScene = function() {\n var scene = new BABYLON.Scene(engine);\n scene.clearColor = new BABYLON.Color3( .5, .5, .5);\n\n // camera\n var camera = new BABYLON.ArcRotateCamera(\"camera1\", 0, 0, 0, new BABYLON.Vector3(5, 3, 0), scene);\n camera.setPosition(new BABYLON.Vector3(5, 10, -10));\n camera.attachControl(canvas, true);\n \n // lights\n var light = new BABYLON.HemisphericLight(\"light1\", new BABYLON.Vector3(1, 0.5, 0), scene);\n light.intensity = 0.8;\n var spot = new BABYLON.SpotLight(\n \"spot\", \n new BABYLON.Vector3(25, 15, -10), \n new BABYLON.Vector3(-1, -0.8, 1), 15, 1, scene);\n spot.diffuse = new BABYLON.Color3(1, 1, 1);\n spot.specular = new BABYLON.Color3(0, 0, 0);\n spot.intensity = 0.2; \n \n // material\n var mat = new BABYLON.StandardMaterial(\"mat1\", scene);\n mat.alpha = 1.0;\n mat.diffuseColor = new BABYLON.Color3(0.5, 0.5, 1.0);\n mat.backFaceCulling = false;\n //mat.wireframe = true;\n\n // show axis\n var showAxis = function(size) {\n var makeTextPlane = function(text, color, size) {\n var dynamicTexture = new BABYLON.DynamicTexture(\"DynamicTexture\", 50, scene, true);\n dynamicTexture.hasAlpha = true;\n dynamicTexture.drawText(text, 5, 40, \"bold 36px Arial\", color , \"transparent\", true);\n \n var plane = new BABYLON.Mesh.CreatePlane(\"TextPlane\", size, scene, true);\n plane.material = new BABYLON.StandardMaterial(\"TextPlaneMaterial\", scene);\n plane.material.backFaceCulling = false;\n \n plane.material.specularColor = new BABYLON.Color3(0, 0, 0);\n plane.material.diffuseTexture = dynamicTexture;\n return plane;\n };\n\n var axisX = BABYLON.Mesh.CreateLines(\"axisX\", [ \n new BABYLON.Vector3(-size * 0.95, 0.05 * size, 0),\n new BABYLON.Vector3(-size, 0, 0), \n new BABYLON.Vector3(-size * 0.95, -0.05 * size, 0),\n new BABYLON.Vector3(-size, 0, 0),\n new BABYLON.Vector3.Zero(), \n new BABYLON.Vector3(size, 0, 0), \n new BABYLON.Vector3(size * 0.95, 0.05 * size, 0), \n new BABYLON.Vector3(size, 0, 0), \n new BABYLON.Vector3(size * 0.95, -0.05 * size, 0)\n ], scene);\n \n axisX.color = new BABYLON.Color3(1, 0, 0);\n var xChar = makeTextPlane(\"X\", \"red\", size / 10);\n xChar.position = new BABYLON.Vector3(0.9 * size, -0.05 * size, 0);\n\n var xChar1 = makeTextPlane(\"-X\", \"red\", size / 10);\n xChar1.position = new BABYLON.Vector3(-0.9 * size, 0.05 * size, 0);\n\n var axisY = BABYLON.Mesh.CreateLines(\"axisY\", [\n new BABYLON.Vector3( -0.05 * size, -size * 0.95, 0),\n new BABYLON.Vector3(0, -size, 0),\n new BABYLON.Vector3(0.05 * size, -size * 0.95, 0),\n new BABYLON.Vector3(0, -size, 0), \n new BABYLON.Vector3.Zero(), \n new BABYLON.Vector3(0, size, 0), \n new BABYLON.Vector3( -0.05 * size, size * 0.95, 0), \n new BABYLON.Vector3(0, size, 0), \n new BABYLON.Vector3( 0.05 * size, size * 0.95, 0)\n ], scene);\n \n axisY.color = new BABYLON.Color3(0, 1, 0);\n var yChar = makeTextPlane(\"Y\", \"green\", size / 10);\n yChar.position = new BABYLON.Vector3(0, 0.9 * size, -0.05 * size);\n var yChar1 = makeTextPlane(\"-Y\", \"green\", size / 10);\n yChar1.position = new BABYLON.Vector3(0, -0.9 * size, 0.05 * size);\n\n var axisZ = BABYLON.Mesh.CreateLines(\"axisZ\", [\n new BABYLON.Vector3( 0 , -0.05 * size, -size * 0.95), \n new BABYLON.Vector3(0, 0, -size),\n new BABYLON.Vector3( 0 , 0.05 * size, -size * 0.95),\n new BABYLON.Vector3(0, 0, -size), \n new BABYLON.Vector3.Zero(), \n new BABYLON.Vector3(0, 0, size), \n new BABYLON.Vector3( 0 , -0.05 * size, size * 0.95),\n new BABYLON.Vector3(0, 0, size), \n new BABYLON.Vector3( 0, 0.05 * size, size * 0.95)\n ], scene);\n \n axisZ.color = new BABYLON.Color3(0, 0, 1);\n var zChar = makeTextPlane(\"Z\", \"blue\", size / 10);\n zChar.position = new BABYLON.Vector3(0, 0.05 * size, 0.9 * size);\n var zChar1 = makeTextPlane(\"-Z\", \"blue\", size / 10);\n zChar1.position = new BABYLON.Vector3(0, 0.05 * size, -0.9 * size);\n };\n showAxis(10);\n return scene;\n };\n var scene = createScene();\n engine.runRenderLoop(function() {\n scene.render();\n });\n </script>\n </body>\n</html>" }, { "code": null, "e": 8461, "s": 8397, "text": "Let us have the co-ordinates defined along the x, y and z axis." }, { "code": null, "e": 15772, "s": 8461, "text": "<!doctype html>\n<html>\n <head>\n <meta charset = \"utf-8\">\n <title>BabylonJs - Basic Element-Creating Scene</title>\n <script src = \"babylon.js\"></script>\n <style>\n canvas {width: 100%; height: 100%;}\n </style>\n </head>\n\n <body>\n <canvas id = \"renderCanvas\"></canvas>\n <script type = \"text/javascript\">\n var canvas = document.getElementById(\"renderCanvas\");\n var engine = new BABYLON.Engine(canvas, true);\n var createScene = function() {\n var scene = new BABYLON.Scene(engine);\n scene.clearColor = new BABYLON.Color3( .5, .5, .5);\n\n // camera\n var camera = new BABYLON.ArcRotateCamera(\"camera1\", 0, 0, 0, new BABYLON.Vector3(5, 3, 0), scene);\n camera.setPosition(new BABYLON.Vector3(5, 10, -10));\n camera.attachControl(canvas, true);\n \n // lights\n var light = new BABYLON.HemisphericLight(\"light1\", new BABYLON.Vector3(1, 0.5, 0), scene);\n light.intensity = 0.8;\n var spot = new BABYLON.SpotLight(\n \"spot\", new BABYLON.Vector3(25, 15, -10), \n new BABYLON.Vector3(-1, -0.8, 1), 15, 1, scene);\n spot.diffuse = new BABYLON.Color3(1, 1, 1);\n spot.specular = new BABYLON.Color3(0, 0, 0);\n spot.intensity = 0.2; \n \n // material\n var mat = new BABYLON.StandardMaterial(\"mat1\", scene);\n mat.alpha = 1.0;\n mat.diffuseColor = new BABYLON.Color3(0.5, 0.5, 1.0);\n mat.backFaceCulling = false;\n \n //mat.wireframe = true;\n var makeTextPlane = function(text, color, size) {\n var dynamicTexture = new BABYLON.DynamicTexture(\"DynamicTexture\", 50, scene, true);\n dynamicTexture.hasAlpha = true;\n dynamicTexture.drawText(text, 5, 40, \"bold 36px Arial\", color , \"transparent\", true);\n \n var plane = new BABYLON.Mesh.CreatePlane(\"TextPlane\", size, scene, true);\n plane.material = new BABYLON.StandardMaterial(\"TextPlaneMaterial\", scene);\n plane.material.backFaceCulling = false;\n plane.material.specularColor = new BABYLON.Color3(0, 0, 0);\n plane.material.diffuseTexture = dynamicTexture;\n return plane;\n };\n \n // show axis\n var showAxis = function(size) {\n var axisX = BABYLON.Mesh.CreateLines(\"axisX\", [ \n new BABYLON.Vector3(-size * 0.95, 0.05 * size, 0),\n new BABYLON.Vector3(-size, 0, 0), \n new BABYLON.Vector3(-size * 0.95, -0.05 * size, 0),\n new BABYLON.Vector3(-size, 0, 0),\n new BABYLON.Vector3.Zero(), \n new BABYLON.Vector3(size, 0, 0), \n new BABYLON.Vector3(size * 0.95, 0.05 * size, 0), \n new BABYLON.Vector3(size, 0, 0), \n new BABYLON.Vector3(size * 0.95, -0.05 * size, 0)\n ], scene);\n axisX.color = new BABYLON.Color3(1, 0, 0);\n var xChar = makeTextPlane(\"X\", \"red\", size / 10);\n xChar.position = new BABYLON.Vector3(0.9 * size, -0.05 * size, 0);\n\n var xChar1 = makeTextPlane(\"-X\", \"red\", size / 10);\n xChar1.position = new BABYLON.Vector3(-0.9 * size, 0.05 * size, 0);\n var xcor = [];\n for (i =- 10; i <= 10; i++) {\n xcor[i] = makeTextPlane(i, \"red\", size / 10);\n xcor[i].position = new BABYLON.Vector3(i, 0, 0);\n }\n\n var axisY = BABYLON.Mesh.CreateLines(\"axisY\", [\n new BABYLON.Vector3( -0.05 * size, -size * 0.95, 0),\n new BABYLON.Vector3(0, -size, 0),\n new BABYLON.Vector3(0.05 * size, -size * 0.95, 0),\n new BABYLON.Vector3(0, -size, 0), \n new BABYLON.Vector3.Zero(), \n new BABYLON.Vector3(0, size, 0), \n new BABYLON.Vector3( -0.05 * size, size * 0.95, 0), \n new BABYLON.Vector3(0, size, 0), \n new BABYLON.Vector3( 0.05 * size, size * 0.95, 0)\n ], scene);\n \n axisY.color = new BABYLON.Color3(0, 1, 0);\n var yChar = makeTextPlane(\"Y\", \"green\", size / 10);\n yChar.position = new BABYLON.Vector3(0, 0.9 * size, -0.05 * size);\n var yChar1 = makeTextPlane(\"-Y\", \"green\", size / 10);\n yChar1.position = new BABYLON.Vector3(0, -0.9 * size, 0.05 * size);\n\n var ycor = [];\n for (y=-10;y<=10;y++) {\n xcor[y] = makeTextPlane(y, \"green\", size / 10);\n xcor[y].position = new BABYLON.Vector3(0, y, 0);\n }\t\t\n\n var axisZ = BABYLON.Mesh.CreateLines(\"axisZ\", [\n new BABYLON.Vector3( 0 , -0.05 * size, -size * 0.95), \n new BABYLON.Vector3(0, 0, -size),\n new BABYLON.Vector3( 0 , 0.05 * size, -size * 0.95),\n new BABYLON.Vector3(0, 0, -size), \n new BABYLON.Vector3.Zero(), \n new BABYLON.Vector3(0, 0, size), \n new BABYLON.Vector3( 0 , -0.05 * size, size * 0.95),\n new BABYLON.Vector3(0, 0, size), \n new BABYLON.Vector3( 0, 0.05 * size, size * 0.95)\n ], scene);\n \n axisZ.color = new BABYLON.Color3(0, 0, 1);\n var zChar = makeTextPlane(\"Z\", \"blue\", size / 10);\n zChar.position = new BABYLON.Vector3(0, 0.05 * size, 0.9 * size);\n var zChar1 = makeTextPlane(\"-Z\", \"blue\", size / 10);\n zChar1.position = new BABYLON.Vector3(0, 0.05 * size, -0.9 * size);\n\n var zcor = [];\n for (z =- 10; z <= 10; z++) {\n xcor[z] = makeTextPlane(z, \"green\", size / 10);\n xcor[z].position = new BABYLON.Vector3(0, 0, z);\n }\n };\t\n\n //Lets draw a mesh along the axis.\n\n var spriteManagerPlayer = new BABYLON.SpriteManager(\"playerManager\", \"images/bird.png\", 1, 200, scene);\n var player = new BABYLON.Sprite(\"player\", spriteManagerPlayer);\n player.position.x = 2;\n player.position.y = 2;\t\n player.position.z = 0;\t\n\n var zChardot = makeTextPlane(\".\", \"red\", 1);\t\t\n zChardot.position = new BABYLON.Vector3(1.8, 1.8,0);\n\n var box = BABYLON.Mesh.CreateBox(\"box\", '2', scene);\n box.position = new BABYLON.Vector3(-5,3,0); // center point of box x-axis is -5 and y axis is 3.\n\n var box = BABYLON.Mesh.CreateBox(\"box\", '2', scene);\n box.position = new BABYLON.Vector3(0,3,-3); // center point of box x-axis is -5 and y axis is 3.\n\n var redSphere = BABYLON.Mesh.CreateSphere(\"red\", 32, 1, scene); //no position for sphere so by default it takes 0,0,0\n showAxis(10);\n returnscene;\n };\n var scene = createScene();\n engine.runRenderLoop(function() {\n scene.render();\n });\n </script>\n </body>\n</html>" }, { "code": null, "e": 15828, "s": 15772, "text": "The above line of code generates the following output −" }, { "code": null, "e": 16032, "s": 15828, "text": "In this demo, we have used image bird.png. The images are stored in the images/ folder locally and are also pasted below for reference. You can download any image of your choice and use in the demo link." }, { "code": null, "e": 16048, "s": 16032, "text": "Images/bird.png" }, { "code": null, "e": 23070, "s": 16048, "text": "<!doctype html>\n<html>\n <head>\n <meta charset = \"utf-8\">\n <title>BabylonJs - Basic Element-Creating Scene</title>\n <script src = \"babylon.js\"></script>\n <style>\n canvas {width: 100%; height: 100%;}\n </style>\n </head>\n\n <body>\n <canvas id = \"renderCanvas\"></canvas>\n <script type = \"text/javascript\">\n var canvas = document.getElementById(\"renderCanvas\");\n var engine = new BABYLON.Engine(canvas, true);\n var createScene = function() {\n var scene = new BABYLON.Scene(engine);\n scene.clearColor = new BABYLON.Color3( .5, .5, .5);\n\n // camera\n var camera = new BABYLON.ArcRotateCamera(\"camera1\", 0, 0, 0, new BABYLON.Vector3(5, 3, 0), scene);\n camera.setPosition(new BABYLON.Vector3(5, 10, -10));\n camera.attachControl(canvas, true);\n \n // lights\n var light = new BABYLON.HemisphericLight(\"light1\", new BABYLON.Vector3(1, 0.5, 0), scene);\n light.intensity = 0.8;\n \n var spot = new BABYLON.SpotLight(\n \"spot\", \n new BABYLON.Vector3(25, 15, -10), \n new BABYLON.Vector3(-1, -0.8, 1), 15, 1, scene);\n spot.diffuse = new BABYLON.Color3(1, 1, 1);\n spot.specular = new BABYLON.Color3(0, 0, 0);\n spot.intensity = 0.2; \n \n // material\n var mat = new BABYLON.StandardMaterial(\"mat1\", scene);\n mat.alpha = 1.0;\n mat.diffuseColor = new BABYLON.Color3(0.5, 0.5, 1.0);\n mat.backFaceCulling = false;\n \n //mat.wireframe = true;\n var makeTextPlane = function(text, color, size) {\n var dynamicTexture = new BABYLON.DynamicTexture(\"DynamicTexture\", 50, scene, true);\n dynamicTexture.hasAlpha = true;\n dynamicTexture.drawText(text, 5, 40, \"bold 36px Arial\", color , \"transparent\", true);\n var plane = new BABYLON.Mesh.CreatePlane(\"TextPlane\", size, scene, true);\n plane.material = new BABYLON.StandardMaterial(\"TextPlaneMaterial\", scene);\n plane.material.backFaceCulling = false;\n plane.material.specularColor = new BABYLON.Color3(0, 0, 0);\n plane.material.diffuseTexture = dynamicTexture;\n return plane;\n };\n \n // show axis\n var showAxis = function(size) {\t\n var axisX = BABYLON.Mesh.CreateLines(\"axisX\", [ \n new BABYLON.Vector3(-size * 0.95, 0.05 * size, 0),\n new BABYLON.Vector3(-size, 0, 0), \n new BABYLON.Vector3(-size * 0.95, -0.05 * size, 0),\n new BABYLON.Vector3(-size, 0, 0),\n new BABYLON.Vector3.Zero(), \n new BABYLON.Vector3(size, 0, 0), \n new BABYLON.Vector3(size * 0.95, 0.05 * size, 0), \n new BABYLON.Vector3(size, 0, 0), \n new BABYLON.Vector3(size * 0.95, -0.05 * size, 0)], scene);\n axisX.color = new BABYLON.Color3(1, 0, 0);\n var xChar = makeTextPlane(\"X\", \"red\", size / 10);\n xChar.position = new BABYLON.Vector3(0.9 * size, -0.05 * size, 0);\n\n var xChar1 = makeTextPlane(\"-X\", \"red\", size / 10);\n xChar1.position = new BABYLON.Vector3(-0.9 * size, 0.05 * size, 0);\n var xcor = [];\n for (i =- 10; i <= 10; i++) {\n xcor[i] = makeTextPlane(i, \"red\", size / 10);\n xcor[i].position = new BABYLON.Vector3(i, 0, 0);\n }\n\n var axisY = BABYLON.Mesh.CreateLines(\"axisY\", [\n new BABYLON.Vector3( -0.05 * size, -size * 0.95, 0),\n new BABYLON.Vector3(0, -size, 0),\n new BABYLON.Vector3(0.05 * size, -size * 0.95, 0),\n new BABYLON.Vector3(0, -size, 0), \n new BABYLON.Vector3.Zero(), \n new BABYLON.Vector3(0, size, 0), \n new BABYLON.Vector3( -0.05 * size, size * 0.95, 0), \n new BABYLON.Vector3(0, size, 0), \n new BABYLON.Vector3( 0.05 * size, size * 0.95, 0)\n ], scene);\n \n axisY.color = new BABYLON.Color3(0, 1, 0);\n var yChar = makeTextPlane(\"Y\", \"green\", size / 10);\n yChar.position = new BABYLON.Vector3(0, 0.9 * size, -0.05 * size);\n var yChar1 = makeTextPlane(\"-Y\", \"green\", size / 10);\n yChar1.position = new BABYLON.Vector3(0, -0.9 * size, 0.05 * size);\n\n var ycor = [];\n for (y =- 10; y <= 10; y++) {\n xcor[y] = makeTextPlane(y, \"green\", size / 10);\n xcor[y].position = new BABYLON.Vector3(0, y, 0);\n }\n\n var axisZ = BABYLON.Mesh.CreateLines(\"axisZ\", [\n new BABYLON.Vector3( 0 , -0.05 * size, -size * 0.95), \n new BABYLON.Vector3(0, 0, -size),\n new BABYLON.Vector3( 0 , 0.05 * size, -size * 0.95),\n new BABYLON.Vector3(0, 0, -size), \n new BABYLON.Vector3.Zero(), \n new BABYLON.Vector3(0, 0, size), \n new BABYLON.Vector3( 0 , -0.05 * size, size * 0.95),\n new BABYLON.Vector3(0, 0, size), \n new BABYLON.Vector3( 0, 0.05 * size, size * 0.95)\n ], scene);\n axisZ.color = new BABYLON.Color3(0, 0, 1);\n var zChar = makeTextPlane(\"Z\", \"blue\", size / 10);\n zChar.position = new BABYLON.Vector3(0, 0.05 * size, 0.9 * size);\n var zChar1 = makeTextPlane(\"-Z\", \"blue\", size / 10);\n zChar1.position = new BABYLON.Vector3(0, 0.05 * size, -0.9 * size);\n\n var zcor = [];\n for (z =- 10; z <= 10; z++) {\n xcor[z] = makeTextPlane(z, \"green\", size / 10);\n xcor[z].position = new BABYLON.Vector3(0, 0, z);\n }\n };\n\n var kite = BABYLON.Mesh.CreateLines(\"kite\", [\n new BABYLON.Vector3(-4,0,0),\n new BABYLON.Vector3(0,4,0), \n new BABYLON.Vector3(4,0,0), \n new BABYLON.Vector3(0,-4,0),\n new BABYLON.Vector3(-4,0,0)\n ], scene);\n kite.color = new BABYLON.Color3(1, 1, 1);\n\n var path = [];\n path.push(new BABYLON.Vector3(-4, 0, 0));\n path.push(new BABYLON.Vector3(0, 0, 0));\n path.push(new BABYLON.Vector3(4, 0, 0));\n\n var lines1 = BABYLON.Mesh.CreateLines(\"lines\",path, scene, true);\n lines1.color = new BABYLON.Color3(1, 1, 1);\n showAxis(10);\t\n return scene;\n };\n var scene = createScene();\n engine.runRenderLoop(function() {\n scene.render();\n });\n </script>\n </body>\n</html>" }, { "code": null, "e": 23129, "s": 23070, "text": "The above line of code will generate the following output:" }, { "code": null, "e": 23173, "s": 23129, "text": "Let us now see how the vector rotate works." }, { "code": null, "e": 30460, "s": 23173, "text": "<!doctype html>\n<html>\n <head>\n <meta charset = \"utf-8\">\n <title>BabylonJs - Basic Element-Creating Scene</title>\n <script src = \"babylon.js\"></script>\n <style>\n canvas {width: 100%; height: 100%;}\n </style>\n </head>\n\n <body>\n <canvas id = \"renderCanvas\"></canvas>\n <script type = \"text/javascript\">\n var canvas = document.getElementById(\"renderCanvas\");\n var engine = new BABYLON.Engine(canvas, true);\n var createScene = function() {\n var scene = new BABYLON.Scene(engine);\n scene.clearColor = new BABYLON.Color3( .5, .5, .5);\n\n // camera\n var camera = new BABYLON.ArcRotateCamera(\"camera1\", 0, 0, 0, new BABYLON.Vector3(5, 3, 0), scene);\n camera.setPosition(new BABYLON.Vector3(0, 0, 0));\n camera.attachControl(canvas, true);\n \n // lights\n var light = new BABYLON.HemisphericLight(\"light1\", new BABYLON.Vector3(1, 0.5, 0), scene);\n light.intensity = 0.8;\n var spot = new BABYLON.SpotLight(\n \"spot\", \n new BABYLON.Vector3(25, 15, -10), \n new BABYLON.Vector3(-1, -0.8, 1), 15, 1, scene);\n spot.diffuse = new BABYLON.Color3(1, 1, 1);\n spot.specular = new BABYLON.Color3(0, 0, 0);\n spot.intensity = 0.2; \n \n // material\n var mat = new BABYLON.StandardMaterial(\"mat1\", scene);\n mat.alpha = 1.0;\n mat.diffuseColor = new BABYLON.Color3(0.5, 0.5, 1.0);\n mat.backFaceCulling = false;\n \n //mat.wireframe = true;\n var makeTextPlane = function(text, color, size) {\n var dynamicTexture = new BABYLON.DynamicTexture(\"DynamicTexture\", 50, scene, true);\n dynamicTexture.hasAlpha = true;\n dynamicTexture.drawText(text, 5, 40, \"bold 36px Arial\", color , \"transparent\", true);\n var plane = new BABYLON.Mesh.CreatePlane(\"TextPlane\", size, scene, true);\n plane.material = new BABYLON.StandardMaterial(\"TextPlaneMaterial\", scene);\n plane.material.backFaceCulling = false;\n plane.material.specularColor = new BABYLON.Color3(0, 0, 0);\n plane.material.diffuseTexture = dynamicTexture;\n return plane;\n };\n // show axis\n var showAxis = function(size) {\n var axisX = BABYLON.Mesh.CreateLines(\"axisX\", [ \n new BABYLON.Vector3(-size * 0.95, 0.05 * size, 0),\n new BABYLON.Vector3(-size, 0, 0), \n new BABYLON.Vector3(-size * 0.95, -0.05 * size, 0),\n new BABYLON.Vector3(-size, 0, 0),\n new BABYLON.Vector3.Zero(), \n new BABYLON.Vector3(size, 0, 0), \n new BABYLON.Vector3(size * 0.95, 0.05 * size, 0), \n new BABYLON.Vector3(size, 0, 0), \n new BABYLON.Vector3(size * 0.95, -0.05 * size, 0)\n ], scene);\n \n axisX.color = new BABYLON.Color3(1, 0, 0);\n var xChar = makeTextPlane(\"X\", \"red\", size / 10);\n xChar.position = new BABYLON.Vector3(0.9 * size, -0.05 * size, 0);\n\n var xChar1 = makeTextPlane(\"-X\", \"red\", size / 10);\n xChar1.position = new BABYLON.Vector3(-0.9 * size, 0.05 * size, 0);\n var xcor = [];\n for (i =- 10; i <= 10; i++) {\n xcor[i] = makeTextPlane(i, \"red\", size / 10);\n xcor[i].position = new BABYLON.Vector3(i, 0, 0);\n }\n\n var axisY = BABYLON.Mesh.CreateLines(\"axisY\", [\n new BABYLON.Vector3( -0.05 * size, -size * 0.95, 0),\n new BABYLON.Vector3(0, -size, 0),\n new BABYLON.Vector3(0.05 * size, -size * 0.95, 0),\n new BABYLON.Vector3(0, -size, 0), \n new BABYLON.Vector3.Zero(), \n new BABYLON.Vector3(0, size, 0), \n new BABYLON.Vector3( -0.05 * size, size * 0.95, 0), \n new BABYLON.Vector3(0, size, 0), \n new BABYLON.Vector3( 0.05 * size, size * 0.95, 0)\n ], scene);\n \n axisY.color = new BABYLON.Color3(0, 1, 0);\n var yChar = makeTextPlane(\"Y\", \"green\", size / 10);\n yChar.position = new BABYLON.Vector3(0, 0.9 * size, -0.05 * size);\n var yChar1 = makeTextPlane(\"-Y\", \"green\", size / 10);\n yChar1.position = new BABYLON.Vector3(0, -0.9 * size, 0.05 * size);\n\n var ycor = [];\n for (y =- 10; y <= 10; y++) {\n xcor[y] = makeTextPlane(y, \"green\", size / 10);\n xcor[y].position = new BABYLON.Vector3(0, y, 0);\n }\n\n var axisZ = BABYLON.Mesh.CreateLines(\"axisZ\", [\n new BABYLON.Vector3( 0 , -0.05 * size, -size * 0.95), \n new BABYLON.Vector3(0, 0, -size),\n new BABYLON.Vector3( 0 , 0.05 * size, -size * 0.95),\n new BABYLON.Vector3(0, 0, -size), \n new BABYLON.Vector3.Zero(), \n new BABYLON.Vector3(0, 0, size), \n new BABYLON.Vector3( 0 , -0.05 * size, size * 0.95),\n new BABYLON.Vector3(0, 0, size), \n new BABYLON.Vector3( 0, 0.05 * size, size * 0.95)\n ], scene);\n \n axisZ.color = new BABYLON.Color3(0, 0, 1);\n var zChar = makeTextPlane(\"Z\", \"blue\", size / 10);\n zChar.position = new BABYLON.Vector3(0, 0.05 * size, 0.9 * size);\n var zChar1 = makeTextPlane(\"-Z\", \"blue\", size / 10);\n zChar1.position = new BABYLON.Vector3(0, 0.05 * size, -0.9 * size);\n\n var zcor = [];\n for (z =- 10; z <= 10; z++) {\n xcor[z] = makeTextPlane(z, \"green\", size / 10);\n xcor[z].position = new BABYLON.Vector3(0, 0, z);\n }\n };\n\n var yellowSphere = BABYLON.Mesh.CreateSphere(\"yellowSphere\",32, 1, scene);\n yellowSphere.setPivotMatrix(BABYLON.Matrix.Translation(2, 0, 0));\n var yellowMaterial = new BABYLON.StandardMaterial(\"yellowMaterial\", scene);\n yellowMaterial.diffuseColor = BABYLON.Color3.Yellow();\n yellowSphere.material = yellowMaterial;\n\n var wheel1 = BABYLON.MeshBuilder.CreateTorus('t1', {diameter: 2.0}, scene);\n wheel1.position.x = -2.0\n wheel1.position.z = -2.0;\n\n showAxis(10);\t\n var k = 0.0;\n var y = 0.0;\n var x = 0.0;\n scene.registerBeforeRender(function () {\n wheel1.rotation.copyFromFloats(0.0, 0.0, Math.PI / 2);\n wheel1.addRotation(0.0, y, 0.0); \n wheel1.addRotation(x, 0.0, 0.0);\n yellowSphere.rotation.y += 0.01;\n y += 0.05; \n });\t\n return scene;\n };\n var scene = createScene();\n engine.runRenderLoop(function() {\n scene.render();\n });\n </script>\n </body>\n</html>" }, { "code": null, "e": 30516, "s": 30460, "text": "The above line of code generates the following output −" }, { "code": null, "e": 30523, "s": 30516, "text": " Print" }, { "code": null, "e": 30534, "s": 30523, "text": " Add Notes" } ]
Sort the words in lexicographical order in Java
The words are sorted in lexicographical order or dictionary order. This means that the words are alphabetically ordered based on their component alphabets. An example of this is given as follows. The original order of the words is Tom Anne Sally John The lexicographical order of the words is Anne John Sally Tom A program that demonstrates this is given as follows. Live Demo public class Example { public static void main(String[] args) { String[] words = { "Peach", "Orange", "Mango", "Cherry", "Apple" }; int n = 5; System.out.println("The original order of the words is: "); for(int i = 0; i < n; i++) { System.out.println(words[i]); } for(int i = 0; i < n-1; ++i) { for (int j = i + 1; j < n; ++j) { if (words[i].compareTo(words[j]) > 0) { String temp = words[i]; words[i] = words[j]; words[j] = temp; } } } System.out.println("\nThe lexicographical order of the words is: "); for(int i = 0; i < n; i++) { System.out.println(words[i]); } } } The original order of the words is: Peach Orange Mango Cherry Apple The lexicographical order of the words is: Apple Cherry Mango Orange Peach
[ { "code": null, "e": 1258, "s": 1062, "text": "The words are sorted in lexicographical order or dictionary order. This means that the words are alphabetically ordered based on their component alphabets. An example of this is given as follows." }, { "code": null, "e": 1375, "s": 1258, "text": "The original order of the words is\nTom\nAnne\nSally\nJohn\nThe lexicographical order of the words is\nAnne\nJohn\nSally\nTom" }, { "code": null, "e": 1429, "s": 1375, "text": "A program that demonstrates this is given as follows." }, { "code": null, "e": 1440, "s": 1429, "text": " Live Demo" }, { "code": null, "e": 2182, "s": 1440, "text": "public class Example {\n public static void main(String[] args) {\n String[] words = { \"Peach\", \"Orange\", \"Mango\", \"Cherry\", \"Apple\" };\n int n = 5;\n System.out.println(\"The original order of the words is: \");\n for(int i = 0; i < n; i++) {\n System.out.println(words[i]);\n }\n for(int i = 0; i < n-1; ++i) {\n for (int j = i + 1; j < n; ++j) {\n if (words[i].compareTo(words[j]) > 0) {\n String temp = words[i];\n words[i] = words[j];\n words[j] = temp;\n }\n }\n }\n System.out.println(\"\\nThe lexicographical order of the words is: \");\n for(int i = 0; i < n; i++) {\n System.out.println(words[i]);\n }\n }\n}" }, { "code": null, "e": 2325, "s": 2182, "text": "The original order of the words is:\nPeach\nOrange\nMango\nCherry\nApple\nThe lexicographical order of the words is:\nApple\nCherry\nMango\nOrange\nPeach" } ]
Bootstrap 4 - Carousel
Carousel is a flexible, responsive way to add a slider to your site. To create a carousel, Add the .carousel and .slide classes to the container along with an id. Add the .carousel and .slide classes to the container along with an id. Specify the slides in a <div> with class .carousel-inner and each slide defined with .carousel-item class. Specify the slides in a <div> with class .carousel-inner and each slide defined with .carousel-item class. Add the .active class to one of the slides to make carousel visible; otherwise the carousel will not be visible. Add the .active class to one of the slides to make carousel visible; otherwise the carousel will not be visible. A simple slideshow below shows basic carousel with indicators and controls − <html lang = "en"> <head> <!-- Meta tags --> <meta charset = "utf-8"> <meta name = "viewport" content = "width = device-width, initial-scale = 1, shrink-to-fit = no"> <!-- Bootstrap CSS --> <link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity = "sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin = "anonymous"> <title>Bootstrap 4 Example</title> </head> <body> <div class = "container"> <h2>Basic Carousel</h2> <div id = "carouselwithIndicators" class = "carousel slide w-50" data-ride = "carousel"> <ol class = "carousel-indicators"> <li data-target = "#carouselExampleIndicators" data-slide-to = "0" class = "active"></li> <li data-target = "#carouselExampleIndicators" data-slide-to = "1"></li> <li data-target = "#carouselExampleIndicators" data-slide-to = "2s"></li> </ol> <div class =" carousel-inner"> <div class = "carousel-item active"> <img class = "d-block w-100" src = "https://www.tutorialspoint.com/bootstrap/images/slide1.png" alt = "First slide"> </div> <div class = "carousel-item"> <img class = "d-block w-100" src = "https://www.tutorialspoint.com/bootstrap/images/slide2.png" alt = "Second slide"> </div> <div class = "carousel-item"> <img class = "d-block w-100" src = "https://www.tutorialspoint.com/bootstrap/images/slide3.png" alt = "Third slide"> </div> </div> <a class = "carousel-control-prev" href = "#carouselwithIndicators" role = "button" data-slide = "prev"> <span class = "carousel-control-prev-icon" aria-hidden = "true"></span> <span class = "sr-only">Previous</span> </a> <a class = "carousel-control-next" href = "#carouselwithIndicators" role = "button" data-slide = "next"> <span class = "carousel-control-next-icon" aria-hidden = "true"></span> <span class = "sr-only">Next</span> </a> </div> </div> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src = "https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity = "sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin = "anonymous"> </script> <script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity = "sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin = "anonymous"> </script> <script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity = "sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin = "anonymous"> </script> </body> </html> It will produce the following result − Note − In the example, we have used w-50 to the carousel and w-100 to the images, which provides width of 50% and a left and right margin of auto and 100% width for the carousel images. Add the captions to the slideshow by using .carousel-caption class within the .carousel-item class. The following example demonstrates adding captions to the slideshow − <html lang = "en"> <head> <!-- Meta tags --> <meta charset = "utf-8"> <meta name = "viewport" content = "width = device-width, initial-scale = 1, shrink-to-fit = no"> <!-- Bootstrap CSS --> <link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity = "sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin = "anonymous"> <title>Bootstrap 4 Example</title> </head> <body> <div class = "container"> <h2>Carousel with Caption</h2> <div id = "carouselwithIndicators" class = "carousel slide w-50" data-ride = "carousel"> <ol class = "carousel-indicators"> <li data-target = "#carouselExampleIndicators" data-slide-to = "0" class = "active"></li> <li data-target = "#carouselExampleIndicators" data-slide-to = "1"></li> <li data-target = "#carouselExampleIndicators" data-slide-to = "2"></li> </ol> <div class = "carousel-inner"> <div class = "carousel-item active"> <img class = "d-block w-100" src = "https://www.tutorialspoint.com/bootstrap/images/slide1.png" alt = "First slide"> <div class = "carousel-caption d-none d-md-block"> <h5>HTML</h5> <p>Hypertext Markup Language</p> </div> </div> <div class = "carousel-item"> <img class = "d-block w-100" src = "https://www.tutorialspoint.com/bootstrap/images/slide2.png" alt = "Second slide"> <div class = "carousel-caption d-none d-md-block"> <h5>CSS</h5> <p>Cascading Style Sheets</p> </div> </div> <div class = "carousel-item"> <img class = "d-block w-100" src = "https://www.tutorialspoint.com/bootstrap/images/slide3.png" alt = "Third slide"> <div class = "carousel-caption d-none d-md-block"> <h5>PHP</h5> <p>Hypertext Preprocessor</p> </div> </div> </div> <a class = "carousel-control-prev" href = "#carouselwithIndicators" role = "button" data-slide = "prev"> <span class = "carousel-control-prev-icon" aria-hidden = "true"></span> <span class = "sr-only">Previous</span> </a> <a class = "carousel-control-next" href = "#carouselwithIndicators" role =" button" data-slide = "next"> <span class = "carousel-control-next-icon" aria-hidden = "true"></span> <span class = "sr-only">Next</span> </a> </div> </div> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src = "https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity = "sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin = "anonymous"> </script> <script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity = "sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin = "anonymous"> </script> <script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity = "sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin = "anonymous"> </script> </body> </html> It will produce the following result − Hypertext Markup Language Cascading Style Sheets Hypertext Preprocessor You can add fade transition effect to animate the slides of carousel by using the .carousel-fade class as shown in the below example − <html lang = "en"> <head> <!-- Meta tags --> <meta charset = "utf-8"> <meta name = "viewport" content = "width = device-width, initial-scale = 1, shrink-to-fit = no"> <!-- Bootstrap CSS --> <link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity = "sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin = "anonymous"> <title>Bootstrap 4 Example</title> </head> <body> <div class = "container"> <h2>Carousel with Crossfade</h2> <div id = "carouselExampleFade" class = "carousel carousel-fade w-50" data-ride = "carousel"> <div class = "carousel-inner"> <div class = "carousel-item active"> <img class = "d-block w-100" src = "https://www.tutorialspoint.com/bootstrap/images/slide1.png" alt = "First slide"> </div> <div class = "carousel-item"> <img class = "d-block w-100" src = "https://www.tutorialspoint.com/bootstrap/images/slide2.png" alt = "Second slide"> </div> <div class = "carousel-item"> <img class = "d-block w-100" src = "https://www.tutorialspoint.com/bootstrap/images/slide3.png" alt = "Third slide"> </div> </div> <a class = "carousel-control-prev" href = "#carouselExampleFade" role = "button" data-slide = "prev"> <span class = "carousel-control-prev-icon" aria-hidden = "true"></span> <span class = "sr-only">Previous</span> </a> <a class = "carousel-control-next" href = "#carouselExampleFade" role = "button" data-slide = "next"> <span class = "carousel-control-next-icon" aria-hidden = "true"></span> <span class = "sr-only">Next</span> </a> </div> </div> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src = "https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity = "sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin = "anonymous"> </script> <script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity = "sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin = "anonymous"> </script> <script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity = "sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin = "anonymous"> </script> </body> </html> It will produce the following result − 26 Lectures 2 hours Anadi Sharma 54 Lectures 4.5 hours Frahaan Hussain 161 Lectures 14.5 hours Eduonix Learning Solutions 20 Lectures 4 hours Azaz Patel 15 Lectures 1.5 hours Muhammad Ismail 62 Lectures 8 hours Yossef Ayman Zedan Print Add Notes Bookmark this page
[ { "code": null, "e": 1907, "s": 1816, "text": "Carousel is a flexible, responsive way to add a slider to your site. To create a carousel," }, { "code": null, "e": 1979, "s": 1907, "text": "Add the .carousel and .slide classes to the container along with an id." }, { "code": null, "e": 2051, "s": 1979, "text": "Add the .carousel and .slide classes to the container along with an id." }, { "code": null, "e": 2158, "s": 2051, "text": "Specify the slides in a <div> with class .carousel-inner and each slide defined with .carousel-item class." }, { "code": null, "e": 2265, "s": 2158, "text": "Specify the slides in a <div> with class .carousel-inner and each slide defined with .carousel-item class." }, { "code": null, "e": 2378, "s": 2265, "text": "Add the .active class to one of the slides to make carousel visible; otherwise the carousel will not be visible." }, { "code": null, "e": 2491, "s": 2378, "text": "Add the .active class to one of the slides to make carousel visible; otherwise the carousel will not be visible." }, { "code": null, "e": 2568, "s": 2491, "text": "A simple slideshow below shows basic carousel with indicators and controls −" }, { "code": null, "e": 5888, "s": 2568, "text": "<html lang = \"en\">\n <head>\n <!-- Meta tags -->\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1, shrink-to-fit = no\">\n \n <!-- Bootstrap CSS -->\n <link rel = \"stylesheet\" \n href = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" \n integrity = \"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\" \n crossorigin = \"anonymous\">\n \n <title>Bootstrap 4 Example</title>\n </head>\n \n <body>\n <div class = \"container\">\n <h2>Basic Carousel</h2>\n <div id = \"carouselwithIndicators\" class = \"carousel slide w-50\" data-ride = \"carousel\">\n <ol class = \"carousel-indicators\">\n <li data-target = \"#carouselExampleIndicators\" data-slide-to = \"0\" class = \"active\"></li>\n <li data-target = \"#carouselExampleIndicators\" data-slide-to = \"1\"></li>\n <li data-target = \"#carouselExampleIndicators\" data-slide-to = \"2s\"></li>\n </ol>\n \n <div class =\" carousel-inner\">\n <div class = \"carousel-item active\">\n <img class = \"d-block w-100\" \n src = \"https://www.tutorialspoint.com/bootstrap/images/slide1.png\" \n alt = \"First slide\">\n </div>\n \n <div class = \"carousel-item\">\n <img class = \"d-block w-100\" \n src = \"https://www.tutorialspoint.com/bootstrap/images/slide2.png\" \n alt = \"Second slide\">\n </div>\n <div class = \"carousel-item\">\n <img class = \"d-block w-100\" \n src = \"https://www.tutorialspoint.com/bootstrap/images/slide3.png\" \n alt = \"Third slide\">\n </div>\n </div>\n \n <a class = \"carousel-control-prev\" href = \"#carouselwithIndicators\" role = \"button\" data-slide = \"prev\">\n <span class = \"carousel-control-prev-icon\" aria-hidden = \"true\"></span>\n <span class = \"sr-only\">Previous</span>\n </a>\n \n <a class = \"carousel-control-next\" href = \"#carouselwithIndicators\" role = \"button\" data-slide = \"next\">\n <span class = \"carousel-control-next-icon\" aria-hidden = \"true\"></span>\n <span class = \"sr-only\">Next</span>\n </a>\n </div>\n </div>\n \n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src = \"https://code.jquery.com/jquery-3.3.1.slim.min.js\" \n integrity = \"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js\" \n integrity = \"sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js\" \n integrity = \"sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy\" \n crossorigin = \"anonymous\">\n </script>\n \n </body>\n</html>" }, { "code": null, "e": 5927, "s": 5888, "text": "It will produce the following result −" }, { "code": null, "e": 6118, "s": 5932, "text": "Note − In the example, we have used w-50 to the carousel and w-100 to the images, which provides width of 50% and a left and right margin of auto and 100% width for the carousel images." }, { "code": null, "e": 6218, "s": 6118, "text": "Add the captions to the slideshow by using .carousel-caption class within the .carousel-item class." }, { "code": null, "e": 6288, "s": 6218, "text": "The following example demonstrates adding captions to the slideshow −" }, { "code": null, "e": 10181, "s": 6288, "text": "<html lang = \"en\">\n <head>\n <!-- Meta tags -->\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1, shrink-to-fit = no\">\n \n <!-- Bootstrap CSS -->\n <link rel = \"stylesheet\" \n href = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" \n integrity = \"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\" \n crossorigin = \"anonymous\">\n \n <title>Bootstrap 4 Example</title>\n </head>\n \n <body>\n <div class = \"container\">\n <h2>Carousel with Caption</h2>\n <div id = \"carouselwithIndicators\" class = \"carousel slide w-50\" data-ride = \"carousel\">\n <ol class = \"carousel-indicators\">\n <li data-target = \"#carouselExampleIndicators\" data-slide-to = \"0\" class = \"active\"></li>\n <li data-target = \"#carouselExampleIndicators\" data-slide-to = \"1\"></li>\n <li data-target = \"#carouselExampleIndicators\" data-slide-to = \"2\"></li>\n </ol>\n \n <div class = \"carousel-inner\">\n <div class = \"carousel-item active\">\n <img class = \"d-block w-100\" \n src = \"https://www.tutorialspoint.com/bootstrap/images/slide1.png\" \n alt = \"First slide\">\n <div class = \"carousel-caption d-none d-md-block\">\n <h5>HTML</h5>\n <p>Hypertext Markup Language</p>\n </div>\n </div>\n \n <div class = \"carousel-item\">\n <img class = \"d-block w-100\" \n src = \"https://www.tutorialspoint.com/bootstrap/images/slide2.png\" \n alt = \"Second slide\">\n <div class = \"carousel-caption d-none d-md-block\">\n <h5>CSS</h5>\n <p>Cascading Style Sheets</p>\n </div>\n </div>\n \n <div class = \"carousel-item\">\n <img class = \"d-block w-100\" \n src = \"https://www.tutorialspoint.com/bootstrap/images/slide3.png\" \n alt = \"Third slide\">\n <div class = \"carousel-caption d-none d-md-block\">\n <h5>PHP</h5>\n <p>Hypertext Preprocessor</p>\n </div>\n </div>\n \n </div>\n \n <a class = \"carousel-control-prev\" href = \"#carouselwithIndicators\" role = \"button\" data-slide = \"prev\">\n <span class = \"carousel-control-prev-icon\" aria-hidden = \"true\"></span>\n <span class = \"sr-only\">Previous</span>\n </a>\n \n <a class = \"carousel-control-next\" href = \"#carouselwithIndicators\" role =\" button\" data-slide = \"next\">\n <span class = \"carousel-control-next-icon\" aria-hidden = \"true\"></span>\n <span class = \"sr-only\">Next</span>\n </a>\n </div>\n </div>\n \n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src = \"https://code.jquery.com/jquery-3.3.1.slim.min.js\" \n integrity = \"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js\" \n integrity = \"sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js\" \n integrity = \"sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy\" \n crossorigin = \"anonymous\">\n </script>\n \n </body>\n</html>" }, { "code": null, "e": 10220, "s": 10181, "text": "It will produce the following result −" }, { "code": null, "e": 10251, "s": 10225, "text": "Hypertext Markup Language" }, { "code": null, "e": 10274, "s": 10251, "text": "Cascading Style Sheets" }, { "code": null, "e": 10297, "s": 10274, "text": "Hypertext Preprocessor" }, { "code": null, "e": 10432, "s": 10297, "text": "You can add fade transition effect to animate the slides of carousel by using the .carousel-fade class as shown in the below example −" }, { "code": null, "e": 13415, "s": 10432, "text": "<html lang = \"en\">\n <head>\n <!-- Meta tags -->\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1, shrink-to-fit = no\">\n \n <!-- Bootstrap CSS -->\n <link rel = \"stylesheet\" \n href = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" \n integrity = \"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\" \n crossorigin = \"anonymous\">\n \n <title>Bootstrap 4 Example</title>\n </head>\n \n <body>\n <div class = \"container\">\n <h2>Carousel with Crossfade</h2>\n <div id = \"carouselExampleFade\" class = \"carousel carousel-fade w-50\" data-ride = \"carousel\">\n <div class = \"carousel-inner\">\n <div class = \"carousel-item active\">\n <img class = \"d-block w-100\" \n src = \"https://www.tutorialspoint.com/bootstrap/images/slide1.png\" \n alt = \"First slide\">\n </div>\n \n <div class = \"carousel-item\">\n <img class = \"d-block w-100\" \n src = \"https://www.tutorialspoint.com/bootstrap/images/slide2.png\"\n alt = \"Second slide\">\n </div>\n \n <div class = \"carousel-item\">\n <img class = \"d-block w-100\" \n src = \"https://www.tutorialspoint.com/bootstrap/images/slide3.png\" \n alt = \"Third slide\">\n </div>\n </div>\n \n <a class = \"carousel-control-prev\" href = \"#carouselExampleFade\" role = \"button\" data-slide = \"prev\">\n <span class = \"carousel-control-prev-icon\" aria-hidden = \"true\"></span>\n <span class = \"sr-only\">Previous</span>\n </a>\n \n <a class = \"carousel-control-next\" href = \"#carouselExampleFade\" role = \"button\" data-slide = \"next\">\n <span class = \"carousel-control-next-icon\" aria-hidden = \"true\"></span>\n <span class = \"sr-only\">Next</span>\n </a>\n </div>\n </div>\n \n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src = \"https://code.jquery.com/jquery-3.3.1.slim.min.js\" \n integrity = \"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js\" \n integrity = \"sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js\" \n integrity = \"sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy\" \n crossorigin = \"anonymous\">\n </script>\n \n </body>\n</html>" }, { "code": null, "e": 13454, "s": 13415, "text": "It will produce the following result −" }, { "code": null, "e": 13487, "s": 13454, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 13501, "s": 13487, "text": " Anadi Sharma" }, { "code": null, "e": 13536, "s": 13501, "text": "\n 54 Lectures \n 4.5 hours \n" }, { "code": null, "e": 13553, "s": 13536, "text": " Frahaan Hussain" }, { "code": null, "e": 13590, "s": 13553, "text": "\n 161 Lectures \n 14.5 hours \n" }, { "code": null, "e": 13618, "s": 13590, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 13651, "s": 13618, "text": "\n 20 Lectures \n 4 hours \n" }, { "code": null, "e": 13663, "s": 13651, "text": " Azaz Patel" }, { "code": null, "e": 13698, "s": 13663, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 13715, "s": 13698, "text": " Muhammad Ismail" }, { "code": null, "e": 13748, "s": 13715, "text": "\n 62 Lectures \n 8 hours \n" }, { "code": null, "e": 13768, "s": 13748, "text": " Yossef Ayman Zedan" }, { "code": null, "e": 13775, "s": 13768, "text": " Print" }, { "code": null, "e": 13786, "s": 13775, "text": " Add Notes" } ]
Difference between HashTable and HashMap in Java
Following are the notable differences between HashTable and HashMap classes in Java. import java.util.HashMap; import java.util.Hashtable; import java.util.Map; public class Tester { public static void main(String args[]) { Map<String, String> map = new HashMap<String, String>(); map.put("1", "One"); map.put("2", "Two"); map.put("3", "Three"); map.put("5", "Five"); map.put("6", "Six"); System.out.println("HashMap: " + map); Map<String, String> map1 = new Hashtable<String, String>(); map1.put("1", "One"); map1.put("2", "Two"); map1.put("3", "Three"); map1.put("5", "Five"); map1.put("6", "Six"); System.out.println("HashTable: " + map1); } } HashMap: {1 = One, 2 = Two, 3 = Three, 5 = Five, 6 = Six} HashTable: {6 = Six, 5 = Five, 3 = Three, 2 = Two, 1 = One}
[ { "code": null, "e": 1147, "s": 1062, "text": "Following are the notable differences between HashTable and HashMap classes in Java." }, { "code": null, "e": 1809, "s": 1147, "text": "import java.util.HashMap;\nimport java.util.Hashtable;\nimport java.util.Map;\n\npublic class Tester {\n public static void main(String args[]) {\n\n Map<String, String> map = new HashMap<String, String>();\n\n map.put(\"1\", \"One\");\n map.put(\"2\", \"Two\");\n map.put(\"3\", \"Three\");\n map.put(\"5\", \"Five\");\n map.put(\"6\", \"Six\");\n\n System.out.println(\"HashMap: \" + map);\n\n Map<String, String> map1 = new Hashtable<String, String>();\n \n map1.put(\"1\", \"One\");\n map1.put(\"2\", \"Two\");\n map1.put(\"3\", \"Three\");\n map1.put(\"5\", \"Five\");\n map1.put(\"6\", \"Six\");\n\n System.out.println(\"HashTable: \" + map1);\n }\n}" }, { "code": null, "e": 1927, "s": 1809, "text": "HashMap: {1 = One, 2 = Two, 3 = Three, 5 = Five, 6 = Six}\nHashTable: {6 = Six, 5 = Five, 3 = Three, 2 = Two, 1 = One}" } ]
Where and how to use to static variables in android studio?
This example demonstrates about how and where do I use static variable in android studio. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="MainActivity"> <TextView android:id="@+id/Question" android:layout_width="wrap_content" android:layout_height="93dp" android:padding="8dp" android:text="I'm a Static Variable" android:layout_marginTop="32sp" android:layout_marginLeft="8dp" android:textSize="32dp" tools:layout_editor_absoluteY="8dp" /> </LinearLayout> Step 3 − Add the following code to src/MainActivity.java import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; public class MainActivity extends AppCompatActivity { public static final String TAG = "I'm a Static Variable"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } protected void onStart() { super.onStart(); Log.i(TAG, "onStart"); } protected void onPause() { super.onPause(); Log.i(TAG, "onPause"); } protected void onStop() { super.onStop(); Log.i(TAG, "onStop"); } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − Click here to download the project code.
[ { "code": null, "e": 1152, "s": 1062, "text": "This example demonstrates about how and where do I use static variable in android studio." }, { "code": null, "e": 1280, "s": 1152, "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": 1345, "s": 1280, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2035, "s": 1345, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\"MainActivity\">\n <TextView\n android:id=\"@+id/Question\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"93dp\"\n android:padding=\"8dp\"\n android:text=\"I'm a Static Variable\"\n android:layout_marginTop=\"32sp\"\n android:layout_marginLeft=\"8dp\"\n android:textSize=\"32dp\"\n tools:layout_editor_absoluteY=\"8dp\" />\n</LinearLayout>" }, { "code": null, "e": 2092, "s": 2035, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 2729, "s": 2092, "text": "import android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.util.Log;\npublic class MainActivity extends AppCompatActivity {\n public static final String TAG = \"I'm a Static Variable\";\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n }\n protected void onStart() {\n super.onStart();\n Log.i(TAG, \"onStart\");\n }\n protected void onPause() {\n super.onPause();\n Log.i(TAG, \"onPause\");\n }\n protected void onStop() {\n super.onStop();\n Log.i(TAG, \"onStop\");\n }\n}" }, { "code": null, "e": 2784, "s": 2729, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 3454, "s": 2784, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 3801, "s": 3454, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 3842, "s": 3801, "text": "Click here to download the project code." } ]
Creating Colormaps in Matplotlib | by Rizky Maulana N | Towards Data Science
Almost all the programmers who work with Python programming language know Matplotlib. It is one of the most used libraries. It is a multi-platform library that can play with many operating systems and was built in 2002 by John Hunter. Nowadays, people start to develop new packages with more simple and more modern styles than in Matplotlib, like Seaborn, Plotly, and even Pandas uses Matplotlib’s API wrappers. But, I think Matplotlib still in many programmer’s hearts. If you need to learn the introductory in using Matplotlib, you can check this link out. medium.comI In visualizing the 3D plot, we need colormaps to differ and make some intuitions in 3D parameters. Scientifically, the human brain perceives various intuition based on the different colors they see. Matplotlib provides some nice colormaps you can use, such as Sequential colormaps, Diverging colormaps, Cyclic colormaps, and Qualitative colormaps. For practical purposes, I did not explain in more detail the differences among them. I think it will be simple if I show you the examples of each categorical colormaps in Matplotlib. Here are some examples (not all) of Sequential colormaps. Matplotlib will give you viridis as a default colormaps. Then, next are the examples of Diverging, Cyclic, Qualitative, and Misc colormaps in Matplotlib. Are you not interested in all of the provided colormaps? Or you need other fancy colormaps? If yes, you need to read this article until the end. I will guide you through customizing and creating your own colormaps. But before customizing it, I will show you an example of colormaps use. I used the ‘ RdYlBu_r ‘ colormaps to visualize my data. Let’s modify your own colormaps. Firstly, we need to create mock data that will be visualized, using this code # import some libraries / modulesimport numpy as npimport matplotlib.pyplot as plt# create mock datadata = np.random.random([100, 100]) * 10 The data variable is an array that consists of 100 x 100 random numbers from 0–10. You can check it by writing this code. After that, we will show the mock data with a default colormaps using the simple code below. plt.figure(figsize=(7, 6)) plt.pcolormesh(data)plt.colorbar() The code will show you a figure like this. As I mentioned before, if you didn’t define the colormaps you used, you will get the default colormaps, named ‘ viridis ‘. Next, I will change the colormaps from ‘ viridis ‘ to ‘inferno’ colormaps with this code plt.pcolormesh(data, cmap='inferno') You will get a result like this Now, to modify the colormaps, you need to import these following sublibraries in Matplotlib. from matplotlib import cm from matplotlib.colors import ListedColormap,LinearSegmentedColormap To modify the number of color class in your colormaps, you can use this code new_inferno = cm.get_cmap('inferno', 5)# visualize with the new_inferno colormapsplt.pcolormesh(data, cmap = new_inferno)plt.colorbar() and will get a result like this Next is modifying the range color in a colormap. I will give you an example in ‘hsv’ colormaps. You need to understand the range of colors using this figure. If we want to use only green color (about 0.3) to blue color (0.7), we can use the following code. # modified hsv in 256 color classhsv_modified = cm.get_cmap('hsv', 256)# create new hsv colormaps in range of 0.3 (green) to 0.7 (blue)newcmp = ListedColormap(hsv_modified(np.linspace(0.3, 0.7, 256)))# show figureplt.figure(figsize=(7, 6))plt.pcolormesh(data, cmap = newcmp)plt.colorbar() It will give you a figure like this To create your own colormaps, there are at least two methods. First, you can combine two Sequential colormaps in Matplotlib. Second, you can choose and combine your favorite color in RGB to create colormaps. We will give you a demo in combining two Sequential colormaps to create a new colormap. We want to combine ‘Oranges’ and ‘Blues’. You can read this code carefully. # define top and bottom colormaps top = cm.get_cmap('Oranges_r', 128) # r means reversed versionbottom = cm.get_cmap('Blues', 128)# combine it allnewcolors = np.vstack((top(np.linspace(0, 1, 128)), bottom(np.linspace(0, 1, 128))))# create a new colormaps with a name of OrangeBlueorange_blue = ListedColormap(newcolors, name='OrangeBlue') If you visualize the mock data using ‘OrangeBlue’ colormaps, you will get a figure like this. Next is creating a colormap from two different color you likes. In this case, I will try to create it from yellow and red color as shown in the following picture First, you need to create yellow colormaps # create yellow colormapsN = 256yellow = np.ones((N, 4))yellow[:, 0] = np.linspace(255/256, 1, N) # R = 255yellow[:, 1] = np.linspace(232/256, 1, N) # G = 232yellow[:, 2] = np.linspace(11/256, 1, N) # B = 11yellow_cmp = ListedColormap(yellow) and red colormaps red = np.ones((N, 4))red[:, 0] = np.linspace(255/256, 1, N)red[:, 1] = np.linspace(0/256, 1, N)red[:, 2] = np.linspace(65/256, 1, N)red_cmp = ListedColormap(red) The visualization of yellow and red colormaps you have created is shown in the following picture After that, you can combine it using the previous methods. newcolors2 = np.vstack((yellow_cmp(np.linspace(0, 1, 128)), red_cmp(np.linspace(1, 0, 128))))double = ListedColormap(newcolors2, name='double')plt.figure(figsize=(7, 6))plt.pcolormesh(data, cmap=double)plt.colorbar() You will get a figure like this You can also adjust the orientation, the extend, and the pad distance of the colormaps using this code. plt.figure(figsize=(6, 7))plt.pcolormesh(data, cmap = double)plt.colorbar(orientation = 'horizontal', label = 'My Favourite Colormaps', extend = 'both', pad = 0.1) You will be shown a figure like this Selecting the right color for your colormaps is essential because of the human mind representation. Color expresses ideas, messages, and emotions. Matplotlib provides many colormaps, but some people have a different tendency in choosing the colormaps. If they want to build their own branding, they need to create their own colormaps. I hope this story can help you in creating and modifying your own colormaps in Matplotlib. towardsdatascience.com towardsdatascience.com towardsdatascience.com towardsdatascience.com towardsdatascience.com That’s all. Thanks for reading this story. Comment and share if you like it. I also recommend you follow my account to get a notification when I post my new story.
[ { "code": null, "e": 407, "s": 172, "text": "Almost all the programmers who work with Python programming language know Matplotlib. It is one of the most used libraries. It is a multi-platform library that can play with many operating systems and was built in 2002 by John Hunter." }, { "code": null, "e": 643, "s": 407, "text": "Nowadays, people start to develop new packages with more simple and more modern styles than in Matplotlib, like Seaborn, Plotly, and even Pandas uses Matplotlib’s API wrappers. But, I think Matplotlib still in many programmer’s hearts." }, { "code": null, "e": 731, "s": 643, "text": "If you need to learn the introductory in using Matplotlib, you can check this link out." }, { "code": null, "e": 743, "s": 731, "text": "medium.comI" }, { "code": null, "e": 942, "s": 743, "text": "In visualizing the 3D plot, we need colormaps to differ and make some intuitions in 3D parameters. Scientifically, the human brain perceives various intuition based on the different colors they see." }, { "code": null, "e": 1274, "s": 942, "text": "Matplotlib provides some nice colormaps you can use, such as Sequential colormaps, Diverging colormaps, Cyclic colormaps, and Qualitative colormaps. For practical purposes, I did not explain in more detail the differences among them. I think it will be simple if I show you the examples of each categorical colormaps in Matplotlib." }, { "code": null, "e": 1332, "s": 1274, "text": "Here are some examples (not all) of Sequential colormaps." }, { "code": null, "e": 1486, "s": 1332, "text": "Matplotlib will give you viridis as a default colormaps. Then, next are the examples of Diverging, Cyclic, Qualitative, and Misc colormaps in Matplotlib." }, { "code": null, "e": 1701, "s": 1486, "text": "Are you not interested in all of the provided colormaps? Or you need other fancy colormaps? If yes, you need to read this article until the end. I will guide you through customizing and creating your own colormaps." }, { "code": null, "e": 1829, "s": 1701, "text": "But before customizing it, I will show you an example of colormaps use. I used the ‘ RdYlBu_r ‘ colormaps to visualize my data." }, { "code": null, "e": 1862, "s": 1829, "text": "Let’s modify your own colormaps." }, { "code": null, "e": 1940, "s": 1862, "text": "Firstly, we need to create mock data that will be visualized, using this code" }, { "code": null, "e": 2082, "s": 1940, "text": "# import some libraries / modulesimport numpy as npimport matplotlib.pyplot as plt# create mock datadata = np.random.random([100, 100]) * 10" }, { "code": null, "e": 2204, "s": 2082, "text": "The data variable is an array that consists of 100 x 100 random numbers from 0–10. You can check it by writing this code." }, { "code": null, "e": 2297, "s": 2204, "text": "After that, we will show the mock data with a default colormaps using the simple code below." }, { "code": null, "e": 2359, "s": 2297, "text": "plt.figure(figsize=(7, 6)) plt.pcolormesh(data)plt.colorbar()" }, { "code": null, "e": 2402, "s": 2359, "text": "The code will show you a figure like this." }, { "code": null, "e": 2525, "s": 2402, "text": "As I mentioned before, if you didn’t define the colormaps you used, you will get the default colormaps, named ‘ viridis ‘." }, { "code": null, "e": 2614, "s": 2525, "text": "Next, I will change the colormaps from ‘ viridis ‘ to ‘inferno’ colormaps with this code" }, { "code": null, "e": 2651, "s": 2614, "text": "plt.pcolormesh(data, cmap='inferno')" }, { "code": null, "e": 2683, "s": 2651, "text": "You will get a result like this" }, { "code": null, "e": 2776, "s": 2683, "text": "Now, to modify the colormaps, you need to import these following sublibraries in Matplotlib." }, { "code": null, "e": 2871, "s": 2776, "text": "from matplotlib import cm from matplotlib.colors import ListedColormap,LinearSegmentedColormap" }, { "code": null, "e": 2948, "s": 2871, "text": "To modify the number of color class in your colormaps, you can use this code" }, { "code": null, "e": 3084, "s": 2948, "text": "new_inferno = cm.get_cmap('inferno', 5)# visualize with the new_inferno colormapsplt.pcolormesh(data, cmap = new_inferno)plt.colorbar()" }, { "code": null, "e": 3116, "s": 3084, "text": "and will get a result like this" }, { "code": null, "e": 3274, "s": 3116, "text": "Next is modifying the range color in a colormap. I will give you an example in ‘hsv’ colormaps. You need to understand the range of colors using this figure." }, { "code": null, "e": 3373, "s": 3274, "text": "If we want to use only green color (about 0.3) to blue color (0.7), we can use the following code." }, { "code": null, "e": 3662, "s": 3373, "text": "# modified hsv in 256 color classhsv_modified = cm.get_cmap('hsv', 256)# create new hsv colormaps in range of 0.3 (green) to 0.7 (blue)newcmp = ListedColormap(hsv_modified(np.linspace(0.3, 0.7, 256)))# show figureplt.figure(figsize=(7, 6))plt.pcolormesh(data, cmap = newcmp)plt.colorbar()" }, { "code": null, "e": 3698, "s": 3662, "text": "It will give you a figure like this" }, { "code": null, "e": 3906, "s": 3698, "text": "To create your own colormaps, there are at least two methods. First, you can combine two Sequential colormaps in Matplotlib. Second, you can choose and combine your favorite color in RGB to create colormaps." }, { "code": null, "e": 4036, "s": 3906, "text": "We will give you a demo in combining two Sequential colormaps to create a new colormap. We want to combine ‘Oranges’ and ‘Blues’." }, { "code": null, "e": 4070, "s": 4036, "text": "You can read this code carefully." }, { "code": null, "e": 4431, "s": 4070, "text": "# define top and bottom colormaps top = cm.get_cmap('Oranges_r', 128) # r means reversed versionbottom = cm.get_cmap('Blues', 128)# combine it allnewcolors = np.vstack((top(np.linspace(0, 1, 128)), bottom(np.linspace(0, 1, 128))))# create a new colormaps with a name of OrangeBlueorange_blue = ListedColormap(newcolors, name='OrangeBlue')" }, { "code": null, "e": 4525, "s": 4431, "text": "If you visualize the mock data using ‘OrangeBlue’ colormaps, you will get a figure like this." }, { "code": null, "e": 4687, "s": 4525, "text": "Next is creating a colormap from two different color you likes. In this case, I will try to create it from yellow and red color as shown in the following picture" }, { "code": null, "e": 4730, "s": 4687, "text": "First, you need to create yellow colormaps" }, { "code": null, "e": 4974, "s": 4730, "text": "# create yellow colormapsN = 256yellow = np.ones((N, 4))yellow[:, 0] = np.linspace(255/256, 1, N) # R = 255yellow[:, 1] = np.linspace(232/256, 1, N) # G = 232yellow[:, 2] = np.linspace(11/256, 1, N) # B = 11yellow_cmp = ListedColormap(yellow)" }, { "code": null, "e": 4992, "s": 4974, "text": "and red colormaps" }, { "code": null, "e": 5154, "s": 4992, "text": "red = np.ones((N, 4))red[:, 0] = np.linspace(255/256, 1, N)red[:, 1] = np.linspace(0/256, 1, N)red[:, 2] = np.linspace(65/256, 1, N)red_cmp = ListedColormap(red)" }, { "code": null, "e": 5251, "s": 5154, "text": "The visualization of yellow and red colormaps you have created is shown in the following picture" }, { "code": null, "e": 5310, "s": 5251, "text": "After that, you can combine it using the previous methods." }, { "code": null, "e": 5549, "s": 5310, "text": "newcolors2 = np.vstack((yellow_cmp(np.linspace(0, 1, 128)), red_cmp(np.linspace(1, 0, 128))))double = ListedColormap(newcolors2, name='double')plt.figure(figsize=(7, 6))plt.pcolormesh(data, cmap=double)plt.colorbar()" }, { "code": null, "e": 5581, "s": 5549, "text": "You will get a figure like this" }, { "code": null, "e": 5685, "s": 5581, "text": "You can also adjust the orientation, the extend, and the pad distance of the colormaps using this code." }, { "code": null, "e": 5849, "s": 5685, "text": "plt.figure(figsize=(6, 7))plt.pcolormesh(data, cmap = double)plt.colorbar(orientation = 'horizontal', label = 'My Favourite Colormaps', extend = 'both', pad = 0.1)" }, { "code": null, "e": 5886, "s": 5849, "text": "You will be shown a figure like this" }, { "code": null, "e": 6312, "s": 5886, "text": "Selecting the right color for your colormaps is essential because of the human mind representation. Color expresses ideas, messages, and emotions. Matplotlib provides many colormaps, but some people have a different tendency in choosing the colormaps. If they want to build their own branding, they need to create their own colormaps. I hope this story can help you in creating and modifying your own colormaps in Matplotlib." }, { "code": null, "e": 6335, "s": 6312, "text": "towardsdatascience.com" }, { "code": null, "e": 6358, "s": 6335, "text": "towardsdatascience.com" }, { "code": null, "e": 6381, "s": 6358, "text": "towardsdatascience.com" }, { "code": null, "e": 6404, "s": 6381, "text": "towardsdatascience.com" }, { "code": null, "e": 6427, "s": 6404, "text": "towardsdatascience.com" } ]
Overview of Data modeling in Apache Cassandra - GeeksforGeeks
09 Oct, 2019 In this article we will learn about these three data model in Cassandra: Conceptual, Logical, and Physical. Learning Objective: To Build database using quick design techniques in Cassandra. To Improve existing model using a query driven methodology in Cassandra. To Optimize Existing model via analysis and validation techniques in Cassandra. Data modelling in Apache Cassandra:In Apache Cassandra data modelling play a vital role to manage huge amount of data with correct methodology. Methodology is one important aspect in Apache Cassandra. Data modelling describes the strategy in Apache Cassandra. 1. Conceptual Data Model:Conceptual model is an abstract view of your domain. It is Technology independent. Conceptual model is not specific to any database system. Purpose: To understand data which is applicable for data modeling. To define Essential objects. To define constraints which is applicable for data modeling. Advantages of conceptual data modeling in Cassandra is collaboration. Entity- Relationship(ER) Model:ER diagram will represent abstract view of data model and give a pictorial view. ER diagram simplified the data model. For example, lets take an example where m:n cardinality in which many to many relationship between student and course means many students can enrolled in many course and many course is enrolled by many students. In this Example s_id, s_name, s_course, s_branch is an attribute of student Entity and p_id, p_name, p_head is an attribute of project Entity and ‘enrolled in’ is a relationship in student record. This is how we will be convert ER diagram into Conceptual data model. Student(S_id, S_name, S_branch, S_course) Project(P_id, P_name, P_head) enrolled in(S_id, P_id, S_name) Application Workflow:In each application there is work flow in which task and dependencies such that In application where number of students want to enroll for many projects. This is actual Data model flow diagram from DataStax. 2. Logical Data Model:In logical data model we will define each attribute or field or column with functionality such that S_id is a key partition in Student Entity And P_id is a partition key in Project Entity. Partition key is play a vital role in Cassandra in which we can execute query accordingly. In Cassandra Partition key is helpful when we will execute the CQL query and in indexing as well. For example, in Relational database this query would work but in Cassandra it would not work like this. Select * From student_data Where S_branch = 'CSE'; Because, in Cassandra S_branch is not a part of partition key of the table, so first defined the partition key for such type of Query in Cassandra. Select * From student_data Where S_id = '123'; This query would work fine in Cassandra. 3. Physical Data Model:In this data model we will describe table Query and we will write query to build table and this is one of the actual data model where we need to write Query specifically required and implement the database functionality what we actual want. For example, lets define table one by one for student_record database by using CQL query. Table: Student CREATE TABLE student_record.student ( S_id int, S_name text, S_branch, S_course, PRIMARY KEY((S_id), S_name), ); Table: Project CREATE TABLE student_record.Project ( P_id int, P_name text, P_head, PRIMARY KEY(P_id), ); Table: Enrolled_in CREATE TABLE student_record.Enrolled_in ( S_id int, P_id int, S_name text, PRIMARY KEY((S_id, P_id), S_name)), ); Apache Compiler Design Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Construction of LL(1) Parsing Table Introduction of Lexical Analysis Flex (Fast Lexical Analyzer Generator ) C program to detect tokens in a C program Introduction of Compiler Design Code Optimization in Compiler Design Ambiguous Grammar Recursive Descent Parser Difference between Compiler and Interpreter Program to calculate First and Follow sets of given grammar
[ { "code": null, "e": 23727, "s": 23699, "text": "\n09 Oct, 2019" }, { "code": null, "e": 23835, "s": 23727, "text": "In this article we will learn about these three data model in Cassandra: Conceptual, Logical, and Physical." }, { "code": null, "e": 23855, "s": 23835, "text": "Learning Objective:" }, { "code": null, "e": 23917, "s": 23855, "text": "To Build database using quick design techniques in Cassandra." }, { "code": null, "e": 23990, "s": 23917, "text": "To Improve existing model using a query driven methodology in Cassandra." }, { "code": null, "e": 24070, "s": 23990, "text": "To Optimize Existing model via analysis and validation techniques in Cassandra." }, { "code": null, "e": 24330, "s": 24070, "text": "Data modelling in Apache Cassandra:In Apache Cassandra data modelling play a vital role to manage huge amount of data with correct methodology. Methodology is one important aspect in Apache Cassandra. Data modelling describes the strategy in Apache Cassandra." }, { "code": null, "e": 24495, "s": 24330, "text": "1. Conceptual Data Model:Conceptual model is an abstract view of your domain. It is Technology independent. Conceptual model is not specific to any database system." }, { "code": null, "e": 24504, "s": 24495, "text": "Purpose:" }, { "code": null, "e": 24562, "s": 24504, "text": "To understand data which is applicable for data modeling." }, { "code": null, "e": 24591, "s": 24562, "text": "To define Essential objects." }, { "code": null, "e": 24652, "s": 24591, "text": "To define constraints which is applicable for data modeling." }, { "code": null, "e": 24722, "s": 24652, "text": "Advantages of conceptual data modeling in Cassandra is collaboration." }, { "code": null, "e": 25084, "s": 24722, "text": "Entity- Relationship(ER) Model:ER diagram will represent abstract view of data model and give a pictorial view. ER diagram simplified the data model. For example, lets take an example where m:n cardinality in which many to many relationship between student and course means many students can enrolled in many course and many course is enrolled by many students." }, { "code": null, "e": 25351, "s": 25084, "text": "In this Example s_id, s_name, s_course, s_branch is an attribute of student Entity and p_id, p_name, p_head is an attribute of project Entity and ‘enrolled in’ is a relationship in student record. This is how we will be convert ER diagram into Conceptual data model." }, { "code": null, "e": 25455, "s": 25351, "text": "Student(S_id, S_name, S_branch, S_course)\nProject(P_id, P_name, P_head)\nenrolled in(S_id, P_id, S_name)" }, { "code": null, "e": 25630, "s": 25455, "text": "Application Workflow:In each application there is work flow in which task and dependencies such that In application where number of students want to enroll for many projects." }, { "code": null, "e": 25684, "s": 25630, "text": "This is actual Data model flow diagram from DataStax." }, { "code": null, "e": 26188, "s": 25684, "text": "2. Logical Data Model:In logical data model we will define each attribute or field or column with functionality such that S_id is a key partition in Student Entity And P_id is a partition key in Project Entity. Partition key is play a vital role in Cassandra in which we can execute query accordingly. In Cassandra Partition key is helpful when we will execute the CQL query and in indexing as well. For example, in Relational database this query would work but in Cassandra it would not work like this." }, { "code": null, "e": 26242, "s": 26188, "text": "Select * \nFrom student_data \nWhere S_branch = 'CSE'; " }, { "code": null, "e": 26390, "s": 26242, "text": "Because, in Cassandra S_branch is not a part of partition key of the table, so first defined the partition key for such type of Query in Cassandra." }, { "code": null, "e": 26440, "s": 26390, "text": "Select * \nFrom student_data \nWhere S_id = '123'; " }, { "code": null, "e": 26481, "s": 26440, "text": "This query would work fine in Cassandra." }, { "code": null, "e": 26835, "s": 26481, "text": "3. Physical Data Model:In this data model we will describe table Query and we will write query to build table and this is one of the actual data model where we need to write Query specifically required and implement the database functionality what we actual want. For example, lets define table one by one for student_record database by using CQL query." }, { "code": null, "e": 26850, "s": 26835, "text": "Table: Student" }, { "code": null, "e": 26976, "s": 26850, "text": "CREATE TABLE student_record.student\n ( \n S_id int,\n S_name text,\n S_branch,\n S_course,\n PRIMARY KEY((S_id), S_name),\n );" }, { "code": null, "e": 26991, "s": 26976, "text": "Table: Project" }, { "code": null, "e": 27094, "s": 26991, "text": "CREATE TABLE student_record.Project\n ( \n P_id int,\n P_name text,\n P_head,\n PRIMARY KEY(P_id),\n ); " }, { "code": null, "e": 27113, "s": 27094, "text": "Table: Enrolled_in" }, { "code": null, "e": 27239, "s": 27113, "text": "CREATE TABLE student_record.Enrolled_in\n ( \n S_id int,\n P_id int,\n S_name text,\n PRIMARY KEY((S_id, P_id), S_name)),\n ); " }, { "code": null, "e": 27246, "s": 27239, "text": "Apache" }, { "code": null, "e": 27262, "s": 27246, "text": "Compiler Design" }, { "code": null, "e": 27360, "s": 27262, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27369, "s": 27360, "text": "Comments" }, { "code": null, "e": 27382, "s": 27369, "text": "Old Comments" }, { "code": null, "e": 27418, "s": 27382, "text": "Construction of LL(1) Parsing Table" }, { "code": null, "e": 27451, "s": 27418, "text": "Introduction of Lexical Analysis" }, { "code": null, "e": 27491, "s": 27451, "text": "Flex (Fast Lexical Analyzer Generator )" }, { "code": null, "e": 27533, "s": 27491, "text": "C program to detect tokens in a C program" }, { "code": null, "e": 27565, "s": 27533, "text": "Introduction of Compiler Design" }, { "code": null, "e": 27602, "s": 27565, "text": "Code Optimization in Compiler Design" }, { "code": null, "e": 27620, "s": 27602, "text": "Ambiguous Grammar" }, { "code": null, "e": 27645, "s": 27620, "text": "Recursive Descent Parser" }, { "code": null, "e": 27689, "s": 27645, "text": "Difference between Compiler and Interpreter" } ]
JavaScript String - length Property
This property returns the number of characters in a string. Use the following syntax to find the length of a string − string.length Returns the number of characters in the string. Try the following example. <html> <head> <title>JavaScript String length Property</title> </head> <body> <script type = "text/javascript"> var str = new String( "This is string" ); document.write("str.length is:" + str.length); </script> </body> </html> str.length is:14 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": 2526, "s": 2466, "text": "This property returns the number of characters in a string." }, { "code": null, "e": 2584, "s": 2526, "text": "Use the following syntax to find the length of a string −" }, { "code": null, "e": 2599, "s": 2584, "text": "string.length\n" }, { "code": null, "e": 2647, "s": 2599, "text": "Returns the number of characters in the string." }, { "code": null, "e": 2674, "s": 2647, "text": "Try the following example." }, { "code": null, "e": 2963, "s": 2674, "text": "<html>\n <head>\n <title>JavaScript String length Property</title>\n </head>\n \n <body> \n <script type = \"text/javascript\">\n var str = new String( \"This is string\" );\n document.write(\"str.length is:\" + str.length); \n </script> \n </body>\n</html>" }, { "code": null, "e": 2982, "s": 2963, "text": "str.length is:14 \n" }, { "code": null, "e": 3017, "s": 2982, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3031, "s": 3017, "text": " Anadi Sharma" }, { "code": null, "e": 3065, "s": 3031, "text": "\n 74 Lectures \n 10 hours \n" }, { "code": null, "e": 3079, "s": 3065, "text": " Lets Kode It" }, { "code": null, "e": 3114, "s": 3079, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3131, "s": 3114, "text": " Frahaan Hussain" }, { "code": null, "e": 3166, "s": 3131, "text": "\n 70 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3183, "s": 3166, "text": " Frahaan Hussain" }, { "code": null, "e": 3216, "s": 3183, "text": "\n 46 Lectures \n 6 hours \n" }, { "code": null, "e": 3244, "s": 3216, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3278, "s": 3244, "text": "\n 88 Lectures \n 14 hours \n" }, { "code": null, "e": 3306, "s": 3278, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3313, "s": 3306, "text": " Print" }, { "code": null, "e": 3324, "s": 3313, "text": " Add Notes" } ]
CakePHP - Redirect Routing
Redirect routing is useful when we want to inform client applications that this URL has been moved. The URL can be redirected using the following function. static Cake\Routing\Router::redirect($route, $url, $options =[]) There are three arguments to the above function − A string describing the template of the route. A string describing the template of the route. A URL to redirect to. A URL to redirect to. An array matching the named elements in the route to regular expressions which that element should match. An array matching the named elements in the route to regular expressions which that element should match. Make Changes in the config/routes.php file as shown below. Here, we have used controllers that were created previously. config/routes.php <?php use Cake\Core\Plugin; use Cake\Routing\RouteBuilder; use Cake\Routing\Router; Router::defaultRouteClass('DashedRoute'); Router::scope('/', function (RouteBuilder $routes) { $routes->connect('/generate2', ['controller' => 'Tests', 'action' => 'index']); $routes->redirect('/generate1','http://tutorialspoint.com/'); $routes->connect('/generate_url',['controller'=>'Generates','action'=>'index']); $routes->fallbacks('DashedRoute'); }); Plugin::routes(); Execute the above example by visiting the following URLs. URL 1 — http://localhost:85/CakePHP/generate_url URL 1 — http://localhost:85/CakePHP/generate_url URL 2 — http://localhost:85/CakePHP/generate1 URL 2 — http://localhost:85/CakePHP/generate1 URL 3 — http://localhost:85/CakePHP/generate2 URL 3 — http://localhost:85/CakePHP/generate2 You will be redirected to http://tutorialspoint.com Print Add Notes Bookmark this page
[ { "code": null, "e": 2398, "s": 2242, "text": "Redirect routing is useful when we want to inform client applications that this URL has been moved. The URL can be redirected using the following function." }, { "code": null, "e": 2464, "s": 2398, "text": "static Cake\\Routing\\Router::redirect($route, $url, $options =[])\n" }, { "code": null, "e": 2514, "s": 2464, "text": "There are three arguments to the above function −" }, { "code": null, "e": 2561, "s": 2514, "text": "A string describing the template of the route." }, { "code": null, "e": 2608, "s": 2561, "text": "A string describing the template of the route." }, { "code": null, "e": 2630, "s": 2608, "text": "A URL to redirect to." }, { "code": null, "e": 2652, "s": 2630, "text": "A URL to redirect to." }, { "code": null, "e": 2758, "s": 2652, "text": "An array matching the named elements in the route to regular expressions which that element should match." }, { "code": null, "e": 2864, "s": 2758, "text": "An array matching the named elements in the route to regular expressions which that element should match." }, { "code": null, "e": 2984, "s": 2864, "text": "Make Changes in the config/routes.php file as shown below. Here, we have used controllers that were created previously." }, { "code": null, "e": 3002, "s": 2984, "text": "config/routes.php" }, { "code": null, "e": 3507, "s": 3002, "text": "<?php\n use Cake\\Core\\Plugin;\n use Cake\\Routing\\RouteBuilder;\n use Cake\\Routing\\Router;\n\n Router::defaultRouteClass('DashedRoute');\n Router::scope('/', function (RouteBuilder $routes) {\n $routes->connect('/generate2', ['controller' => 'Tests', 'action' => 'index']);\n $routes->redirect('/generate1','http://tutorialspoint.com/');\n $routes->connect('/generate_url',['controller'=>'Generates','action'=>'index']);\n $routes->fallbacks('DashedRoute');\n });\n Plugin::routes();" }, { "code": null, "e": 3565, "s": 3507, "text": "Execute the above example by visiting the following URLs." }, { "code": null, "e": 3614, "s": 3565, "text": "URL 1 — http://localhost:85/CakePHP/generate_url" }, { "code": null, "e": 3663, "s": 3614, "text": "URL 1 — http://localhost:85/CakePHP/generate_url" }, { "code": null, "e": 3709, "s": 3663, "text": "URL 2 — http://localhost:85/CakePHP/generate1" }, { "code": null, "e": 3755, "s": 3709, "text": "URL 2 — http://localhost:85/CakePHP/generate1" }, { "code": null, "e": 3801, "s": 3755, "text": "URL 3 — http://localhost:85/CakePHP/generate2" }, { "code": null, "e": 3847, "s": 3801, "text": "URL 3 — http://localhost:85/CakePHP/generate2" }, { "code": null, "e": 3899, "s": 3847, "text": "You will be redirected to http://tutorialspoint.com" }, { "code": null, "e": 3906, "s": 3899, "text": " Print" }, { "code": null, "e": 3917, "s": 3906, "text": " Add Notes" } ]
clear() method in PyQt5 - GeeksforGeeks
26 Mar, 2020 While using PyQt5, there occur a need of removing or clearing labels in order to do so clear() method is used. This method belongs to the QLabel class, and can be used on only label widgets. Syntax : label.clear()Argument : It takes no argument.Action Performed : It clears(remove) the label from main window. Below is the implementation of this method. Code : # importing the required librariesfrom PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle("Move") # setting the geometry of window self.setGeometry(0, 0, 500, 300) # creating a label widget self.label1 = QLabel('Label 1', self) # moving the widget # move(left, top) self.label1.move(100, 100) # creating a label widget self.label2 = QLabel('Label 2 ', self) # moving the widget # move(left, top) self.label2.move(100, 120) # clearing label 2 self.label2.clear() # creating a label widget self.label3 = QLabel('Label 3', self) # moving the widget # move(left, top) self.label3.move(100, 140) # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output :As on the above image we can see Label2 will not be seen because of clear() method. Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() Reading and Writing to text files in Python *args and **kwargs in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 26399, "s": 26371, "text": "\n26 Mar, 2020" }, { "code": null, "e": 26590, "s": 26399, "text": "While using PyQt5, there occur a need of removing or clearing labels in order to do so clear() method is used. This method belongs to the QLabel class, and can be used on only label widgets." }, { "code": null, "e": 26709, "s": 26590, "text": "Syntax : label.clear()Argument : It takes no argument.Action Performed : It clears(remove) the label from main window." }, { "code": null, "e": 26753, "s": 26709, "text": "Below is the implementation of this method." }, { "code": null, "e": 26760, "s": 26753, "text": "Code :" }, { "code": "# importing the required librariesfrom PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle(\"Move\") # setting the geometry of window self.setGeometry(0, 0, 500, 300) # creating a label widget self.label1 = QLabel('Label 1', self) # moving the widget # move(left, top) self.label1.move(100, 100) # creating a label widget self.label2 = QLabel('Label 2 ', self) # moving the widget # move(left, top) self.label2.move(100, 120) # clearing label 2 self.label2.clear() # creating a label widget self.label3 = QLabel('Label 3', self) # moving the widget # move(left, top) self.label3.move(100, 140) # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 27835, "s": 26760, "text": null }, { "code": null, "e": 27927, "s": 27835, "text": "Output :As on the above image we can see Label2 will not be seen because of clear() method." }, { "code": null, "e": 27938, "s": 27927, "text": "Python-gui" }, { "code": null, "e": 27950, "s": 27938, "text": "Python-PyQt" }, { "code": null, "e": 27957, "s": 27950, "text": "Python" }, { "code": null, "e": 28055, "s": 27957, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28073, "s": 28055, "text": "Python Dictionary" }, { "code": null, "e": 28108, "s": 28073, "text": "Read a file line by line in Python" }, { "code": null, "e": 28140, "s": 28108, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28162, "s": 28140, "text": "Enumerate() in Python" }, { "code": null, "e": 28204, "s": 28162, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28234, "s": 28204, "text": "Iterate over a list in Python" }, { "code": null, "e": 28260, "s": 28234, "text": "Python String | replace()" }, { "code": null, "e": 28304, "s": 28260, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 28333, "s": 28304, "text": "*args and **kwargs in Python" } ]
Hive - Built-in Functions
This chapter explains the built-in functions available in Hive. The functions look quite similar to SQL functions, except for their usage. Hive supports the following built-in functions: The following queries demonstrate some built-in functions: hive> SELECT round(2.6) from temp; On successful execution of query, you get to see the following response: 3.0 hive> SELECT floor(2.6) from temp; On successful execution of the query, you get to see the following response: 2.0 hive> SELECT ceil(2.6) from temp; On successful execution of the query, you get to see the following response: 3.0 Hive supports the following built-in aggregate functions. The usage of these functions is as same as the SQL aggregate functions. 50 Lectures 4 hours Navdeep Kaur 67 Lectures 4 hours Bigdata Engineer 109 Lectures 2 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2089, "s": 1950, "text": "This chapter explains the built-in functions available in Hive. The functions look quite similar to SQL functions, except for their usage." }, { "code": null, "e": 2137, "s": 2089, "text": "Hive supports the following built-in functions:" }, { "code": null, "e": 2196, "s": 2137, "text": "The following queries demonstrate some built-in functions:" }, { "code": null, "e": 2231, "s": 2196, "text": "hive> SELECT round(2.6) from temp;" }, { "code": null, "e": 2304, "s": 2231, "text": "On successful execution of query, you get to see the following response:" }, { "code": null, "e": 2309, "s": 2304, "text": "3.0\n" }, { "code": null, "e": 2344, "s": 2309, "text": "hive> SELECT floor(2.6) from temp;" }, { "code": null, "e": 2421, "s": 2344, "text": "On successful execution of the query, you get to see the following response:" }, { "code": null, "e": 2426, "s": 2421, "text": "2.0\n" }, { "code": null, "e": 2460, "s": 2426, "text": "hive> SELECT ceil(2.6) from temp;" }, { "code": null, "e": 2537, "s": 2460, "text": "On successful execution of the query, you get to see the following response:" }, { "code": null, "e": 2542, "s": 2537, "text": "3.0\n" }, { "code": null, "e": 2672, "s": 2542, "text": "Hive supports the following built-in aggregate functions. The usage of these functions is as same as the SQL aggregate functions." }, { "code": null, "e": 2705, "s": 2672, "text": "\n 50 Lectures \n 4 hours \n" }, { "code": null, "e": 2719, "s": 2705, "text": " Navdeep Kaur" }, { "code": null, "e": 2752, "s": 2719, "text": "\n 67 Lectures \n 4 hours \n" }, { "code": null, "e": 2770, "s": 2752, "text": " Bigdata Engineer" }, { "code": null, "e": 2804, "s": 2770, "text": "\n 109 Lectures \n 2 hours \n" }, { "code": null, "e": 2822, "s": 2804, "text": " Bigdata Engineer" }, { "code": null, "e": 2829, "s": 2822, "text": " Print" }, { "code": null, "e": 2840, "s": 2829, "text": " Add Notes" } ]
random.choices() method in Python - GeeksforGeeks
27 Jan, 2022 The choices() method returns multiple random elements from the list with replacement. You can weigh the possibility of each result with the weights parameter or the cum_weights parameter. The elements can be a string, a range, a list, a tuple or any other kind of sequence. Syntax : random.choices(sequence, weights=None, cum_weights=None, k=1) Parameters :1. sequence is a mandatory parameter that can be a list, tuple, or string.2. weights is an optional parameter which is used to weigh the possibility for each value.3. cum_weights is an optional parameter which is used to weigh the possibility for each value but in this the possibility is accumulated4. k is an optional parameter that is used to define the length of the returned list. Note: This method is different from random.choice(). Example: import random mylist = ["geeks", "for", "python"] print(random.choices(mylist, weights = [10, 1, 1], k = 5)) Note: Every time output will be different as the system returns random elements.Output: ['geeks', 'geeks', 'geeks', 'for', 'for'] Practical application: Print a random list with 6 items. import random mylist = ["apple", "banana", "mango"] print(random.choices(mylist, weights = [10, 1, 1], k = 6)) Note: The output changes every time as choices() function is used.Output: ['apple', 'banana', 'apple', 'apple', 'apple', 'banana'] harsh khanna Python-random Python Write From Home 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 Python Dictionary Convert integer to string in Python Convert string to integer in Python How to set input type date in dd-mm-yyyy format using HTML ? Python infinity Matplotlib.pyplot.title() in Python
[ { "code": null, "e": 23926, "s": 23898, "text": "\n27 Jan, 2022" }, { "code": null, "e": 24200, "s": 23926, "text": "The choices() method returns multiple random elements from the list with replacement. You can weigh the possibility of each result with the weights parameter or the cum_weights parameter. The elements can be a string, a range, a list, a tuple or any other kind of sequence." }, { "code": null, "e": 24271, "s": 24200, "text": "Syntax : random.choices(sequence, weights=None, cum_weights=None, k=1)" }, { "code": null, "e": 24669, "s": 24271, "text": "Parameters :1. sequence is a mandatory parameter that can be a list, tuple, or string.2. weights is an optional parameter which is used to weigh the possibility for each value.3. cum_weights is an optional parameter which is used to weigh the possibility for each value but in this the possibility is accumulated4. k is an optional parameter that is used to define the length of the returned list." }, { "code": null, "e": 24722, "s": 24669, "text": "Note: This method is different from random.choice()." }, { "code": null, "e": 24731, "s": 24722, "text": "Example:" }, { "code": "import random mylist = [\"geeks\", \"for\", \"python\"] print(random.choices(mylist, weights = [10, 1, 1], k = 5))", "e": 24842, "s": 24731, "text": null }, { "code": null, "e": 24930, "s": 24842, "text": "Note: Every time output will be different as the system returns random elements.Output:" }, { "code": null, "e": 24973, "s": 24930, "text": "['geeks', 'geeks', 'geeks', 'for', 'for']\n" }, { "code": null, "e": 25030, "s": 24973, "text": "Practical application: Print a random list with 6 items." }, { "code": "import random mylist = [\"apple\", \"banana\", \"mango\"] print(random.choices(mylist, weights = [10, 1, 1], k = 6))", "e": 25143, "s": 25030, "text": null }, { "code": null, "e": 25217, "s": 25143, "text": "Note: The output changes every time as choices() function is used.Output:" }, { "code": null, "e": 25275, "s": 25217, "text": "['apple', 'banana', 'apple', 'apple', 'apple', 'banana']\n" }, { "code": null, "e": 25288, "s": 25275, "text": "harsh khanna" }, { "code": null, "e": 25302, "s": 25288, "text": "Python-random" }, { "code": null, "e": 25309, "s": 25302, "text": "Python" }, { "code": null, "e": 25325, "s": 25309, "text": "Write From Home" }, { "code": null, "e": 25423, "s": 25325, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25451, "s": 25423, "text": "Read JSON file using Python" }, { "code": null, "e": 25501, "s": 25451, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 25523, "s": 25501, "text": "Python map() function" }, { "code": null, "e": 25567, "s": 25523, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 25585, "s": 25567, "text": "Python Dictionary" }, { "code": null, "e": 25621, "s": 25585, "text": "Convert integer to string in Python" }, { "code": null, "e": 25657, "s": 25621, "text": "Convert string to integer in Python" }, { "code": null, "e": 25718, "s": 25657, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 25734, "s": 25718, "text": "Python infinity" } ]
Longest Consecutive 1's | Practice | GeeksforGeeks
Given a number N. Find the length of the longest consecutive 1s in its binary representation. Example 1: Input: N = 14 Output: 3 Explanation: Binary representation of 14 is 1110, in which 111 is the longest consecutive set bits of length is 3. Example 2: Input: N = 222 Output: 4 Explanation: Binary representation of 222 is 11011110, in which 1111 is the longest consecutive set bits of length 4. +1 ayushshukla3466in 9 hours class Solution{ public: int maxConsecutiveOnes(int N) { // code here int ans = 0,count = 0; while(N > 0) { while(((N & 1) == 1) && (N > 0)) { count++; N = N >> 1; } if((N & 1) == 0) { ans = max(ans,count); count = 0; N = N >> 1; } } return ans; }}; 0 vishnu12656 days ago public static int maxConsecutiveOnes(int N) { int count = 0; int maxCount = 0; while(N>0){ if(N%2==1){ count++; } else{ maxCount = Math.max(maxCount,count); count = 0; } N = N/2; } maxCount = Math.max(maxCount,count); return maxCount; } 0 sachinupreti1901 week ago Easiest one ever seen class Solution{ public: int maxConsecutiveOnes(int N) { // code here //int p=log2(N)+1; bitset<32>ok(N); string s=ok.to_string(); int i,c=0,maxi=-3222; for(i=0;i<s.size();i++) { if(s[i]=='1') c++; else { maxi=max(maxi,c); c=0; } } maxi=max(maxi,c); return maxi; }}; 0 mankesh0162 weeks ago int ans=0; while(N){ N&=(N<<1); ans++; } return ans; 0 amansidd178613 weeks ago int maxConsecutiveOnes(int N) { // code here int mx = 0; int cnt = 0; int flag = 0; while(N){ int rem = N%2; if(rem==1){ cnt++; mx = max(mx,cnt); } else cnt = 0; N/=2; } return mx; } 0 gauty verma3 weeks ago private static int count1sCon(int n) { // TODO Auto-generated method stub int count = 0; int maxCount = 0; boolean flag = true; for(int i = 0;i< 32;i++) { if((n&(1<<i))!=0) { flag = true; count++; if(count>maxCount) { maxCount = count; } }else { flag = false; count = 0; } } return maxCount;} 0 adityagagtiwari4 weeks ago easy logn O(1) solution public static int maxConsecutiveOnes(int n) { // Your code here int maxcount = Integer.MIN_VALUE; int count = 0; while(n!=0) { if(n%2==1) { count++; // System.out.println(count); } else { if(maxcount<count) { maxcount = count; } // System.out.println(maxcount); //reinitializing count for calculating next series of 1s count = 0; } //.out.println(n); n=n/2; } if(count>maxcount) { maxcount = count; } return maxcount; } 0 ayushahuja2001 month ago class Solution{ public static int maxConsecutiveOnes(int N) { int max = Integer.MIN_VALUE; String ans = Integer.toBinaryString(N); // System.out.println(ans); int count = 0; for(int i = 0;i<ans.length();i++){ if(ans.charAt(i) == '1'){ count ++; }else{ if(count>max){ max = Math.max(count,max); count = 0; }else{ count = 0; } } } return Math.max(max,count); }} 0 arjunnigam17131 month ago def maxConsecutiveOnes(self, n): ##Your code here global_max = 0 current_max = 0 while n>0: if n&1!=0: current_max +=1 else: global_max = max(global_max, current_max) current_max = 0 n=n>>1 return max(global_max, current_max) 0 vermaashitiit This comment was deleted. 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": 332, "s": 238, "text": "Given a number N. Find the length of the longest consecutive 1s in its binary representation." }, { "code": null, "e": 343, "s": 332, "text": "Example 1:" }, { "code": null, "e": 485, "s": 343, "text": "Input: N = 14\nOutput: 3\nExplanation: \nBinary representation of 14 is \n1110, in which 111 is the longest \nconsecutive set bits of length is 3." }, { "code": null, "e": 496, "s": 485, "text": "Example 2:" }, { "code": null, "e": 645, "s": 496, "text": "Input: N = 222\nOutput: 4\nExplanation: \nBinary representation of 222 is \n11011110, in which 1111 is the \nlongest consecutive set bits of length 4. \n\n" }, { "code": null, "e": 648, "s": 645, "text": "+1" }, { "code": null, "e": 674, "s": 648, "text": "ayushshukla3466in 9 hours" }, { "code": null, "e": 1097, "s": 674, "text": "class Solution{ public: int maxConsecutiveOnes(int N) { // code here int ans = 0,count = 0; while(N > 0) { while(((N & 1) == 1) && (N > 0)) { count++; N = N >> 1; } if((N & 1) == 0) { ans = max(ans,count); count = 0; N = N >> 1; } } return ans; }};" }, { "code": null, "e": 1099, "s": 1097, "text": "0" }, { "code": null, "e": 1120, "s": 1099, "text": "vishnu12656 days ago" }, { "code": null, "e": 1526, "s": 1120, "text": "public static int maxConsecutiveOnes(int N) {\n int count = 0;\n int maxCount = 0;\n while(N>0){\n if(N%2==1){\n count++;\n }\n else{\n maxCount = Math.max(maxCount,count);\n count = 0;\n }\n N = N/2;\n }\n maxCount = Math.max(maxCount,count);\n return maxCount;\n \n }" }, { "code": null, "e": 1528, "s": 1526, "text": "0" }, { "code": null, "e": 1554, "s": 1528, "text": "sachinupreti1901 week ago" }, { "code": null, "e": 1576, "s": 1554, "text": "Easiest one ever seen" }, { "code": null, "e": 2003, "s": 1578, "text": "class Solution{ public: int maxConsecutiveOnes(int N) { // code here //int p=log2(N)+1; bitset<32>ok(N); string s=ok.to_string(); int i,c=0,maxi=-3222; for(i=0;i<s.size();i++) { if(s[i]=='1') c++; else { maxi=max(maxi,c); c=0; } } maxi=max(maxi,c); return maxi; }};" }, { "code": null, "e": 2005, "s": 2003, "text": "0" }, { "code": null, "e": 2027, "s": 2005, "text": "mankesh0162 weeks ago" }, { "code": null, "e": 2118, "s": 2027, "text": "int ans=0; while(N){ N&=(N<<1); ans++; } return ans;" }, { "code": null, "e": 2120, "s": 2118, "text": "0" }, { "code": null, "e": 2145, "s": 2120, "text": "amansidd178613 weeks ago" }, { "code": null, "e": 2452, "s": 2145, "text": "int maxConsecutiveOnes(int N) { // code here int mx = 0; int cnt = 0; int flag = 0; while(N){ int rem = N%2; if(rem==1){ cnt++; mx = max(mx,cnt); } else cnt = 0; N/=2; } return mx; }" }, { "code": null, "e": 2454, "s": 2452, "text": "0" }, { "code": null, "e": 2477, "s": 2454, "text": "gauty verma3 weeks ago" }, { "code": null, "e": 2788, "s": 2477, "text": "private static int count1sCon(int n) { // TODO Auto-generated method stub int count = 0; int maxCount = 0; boolean flag = true; for(int i = 0;i< 32;i++) { if((n&(1<<i))!=0) { flag = true; count++; if(count>maxCount) { maxCount = count; } }else { flag = false; count = 0; } } return maxCount;}" }, { "code": null, "e": 2790, "s": 2788, "text": "0" }, { "code": null, "e": 2817, "s": 2790, "text": "adityagagtiwari4 weeks ago" }, { "code": null, "e": 2843, "s": 2817, "text": "easy logn O(1) solution " }, { "code": null, "e": 3539, "s": 2843, "text": "public static int maxConsecutiveOnes(int n) { // Your code here int maxcount = Integer.MIN_VALUE; int count = 0; while(n!=0) { if(n%2==1) { count++; // System.out.println(count); } else { if(maxcount<count) { maxcount = count; } // System.out.println(maxcount); //reinitializing count for calculating next series of 1s count = 0; } //.out.println(n); n=n/2; } if(count>maxcount) { maxcount = count; } return maxcount; }" }, { "code": null, "e": 3541, "s": 3539, "text": "0" }, { "code": null, "e": 3566, "s": 3541, "text": "ayushahuja2001 month ago" }, { "code": null, "e": 4112, "s": 3566, "text": "class Solution{ public static int maxConsecutiveOnes(int N) { int max = Integer.MIN_VALUE; String ans = Integer.toBinaryString(N); // System.out.println(ans); int count = 0; for(int i = 0;i<ans.length();i++){ if(ans.charAt(i) == '1'){ count ++; }else{ if(count>max){ max = Math.max(count,max); count = 0; }else{ count = 0; } } } return Math.max(max,count); }}" }, { "code": null, "e": 4114, "s": 4112, "text": "0" }, { "code": null, "e": 4140, "s": 4114, "text": "arjunnigam17131 month ago" }, { "code": null, "e": 4509, "s": 4140, "text": "def maxConsecutiveOnes(self, n):\n ##Your code here\n global_max = 0\n current_max = 0\n while n>0:\n if n&1!=0:\n current_max +=1\n else:\n global_max = max(global_max, current_max)\n current_max = 0\n \n n=n>>1\n return max(global_max, current_max)\n\n" }, { "code": null, "e": 4511, "s": 4509, "text": "0" }, { "code": null, "e": 4525, "s": 4511, "text": "vermaashitiit" }, { "code": null, "e": 4551, "s": 4525, "text": "This comment was deleted." }, { "code": null, "e": 4697, "s": 4551, "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": 4733, "s": 4697, "text": " Login to access your submissions. " }, { "code": null, "e": 4743, "s": 4733, "text": "\nProblem\n" }, { "code": null, "e": 4753, "s": 4743, "text": "\nContest\n" }, { "code": null, "e": 4816, "s": 4753, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4964, "s": 4816, "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": 5172, "s": 4964, "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": 5278, "s": 5172, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Rexx - Best Programming Practices
Every programmer wants their program to be the best when it comes to quality and efficiency. The following are some of the best programming practices or hints when writing Rexx programs which can help one achieve these goals. Use the address command before you issue any command to the operating system or command prompt. This will help you get the address space beforehand in memory and cause your program to run more efficiently. An example of the address command is shown below. /* Main program */ address system dir The output of the command is as follows, but it could vary from system to system. Volume in drive H is Apps Volume Serial Number is 8E66-AC3D Directory of H:\ 06/30/2016 01:28 AM <DIR> Apps 07/05/2016 03:40 AM 463 main.class 07/07/2016 01:30 AM 46 main.nrx 07/07/2016 01:42 AM 38 main.rexx 3 File(s) 547 bytes Dir(s) 313,085,173,760 bytes free Ensure all commands to the operating system are in upper case and in quotes wherever possible. An example for the same is shown below. /* Main program */ options arexx_bifs say chdir('\REXXML100') say directory() When we run the above program, we will get the following result. 0 D:\rexxxml100 Avoid creating big comment blocks as shown in the following program. /******/ /* */ /* */ /* */ /******/ /* Main program */ address system dir Use the Parse statement to assign default values. An example for the same is shown below. parse value 0 1 with a, b Use the "Left(var1,2)" statement wherever possible instead of the “substr(var1,1,2)" statement. Use the "Right(var1,2)" statement wherever possible instead of the “substr(var1,length(var1),2)" statement. Print Add Notes Bookmark this page
[ { "code": null, "e": 2565, "s": 2339, "text": "Every programmer wants their program to be the best when it comes to quality and efficiency. The following are some of the best programming practices or hints when writing Rexx programs which can help one achieve these goals." }, { "code": null, "e": 2771, "s": 2565, "text": "Use the address command before you issue any command to the operating system or command prompt. This will help you get the address space beforehand in memory and cause your program to run more efficiently." }, { "code": null, "e": 2821, "s": 2771, "text": "An example of the address command is shown below." }, { "code": null, "e": 2861, "s": 2821, "text": "/* Main program */ \naddress system dir " }, { "code": null, "e": 2943, "s": 2861, "text": "The output of the command is as follows, but it could vary from system to system." }, { "code": null, "e": 3288, "s": 2943, "text": "Volume in drive H is Apps \nVolume Serial Number is 8E66-AC3D \nDirectory of H:\\ \n06/30/2016 01:28 AM <DIR> Apps \n07/05/2016 03:40 AM 463 main.class \n07/07/2016 01:30 AM 46 main.nrx \n07/07/2016 01:42 AM 38 main.rexx \n3 File(s) 547 bytes \nDir(s) 313,085,173,760 bytes free\n" }, { "code": null, "e": 3383, "s": 3288, "text": "Ensure all commands to the operating system are in upper case and in quotes wherever possible." }, { "code": null, "e": 3423, "s": 3383, "text": "An example for the same is shown below." }, { "code": null, "e": 3504, "s": 3423, "text": "/* Main program */ \noptions arexx_bifs \nsay chdir('\\REXXML100') \nsay directory()" }, { "code": null, "e": 3569, "s": 3504, "text": "When we run the above program, we will get the following result." }, { "code": null, "e": 3588, "s": 3569, "text": "0 \nD:\\rexxxml100 \n" }, { "code": null, "e": 3657, "s": 3588, "text": "Avoid creating big comment blocks as shown in the following program." }, { "code": null, "e": 3737, "s": 3657, "text": "/******/ \n/* */ \n/* */ \n/* */ \n/******/ \n/* Main program */ \naddress system dir" }, { "code": null, "e": 3827, "s": 3737, "text": "Use the Parse statement to assign default values. An example for the same is shown below." }, { "code": null, "e": 3856, "s": 3827, "text": "parse value 0 1 with \na, \nb " }, { "code": null, "e": 3952, "s": 3856, "text": "Use the \"Left(var1,2)\" statement wherever possible instead of the “substr(var1,1,2)\" statement." }, { "code": null, "e": 4060, "s": 3952, "text": "Use the \"Right(var1,2)\" statement wherever possible instead of the “substr(var1,length(var1),2)\" statement." }, { "code": null, "e": 4067, "s": 4060, "text": " Print" }, { "code": null, "e": 4078, "s": 4067, "text": " Add Notes" } ]
Python unittest - assertIsNotNone() function - GeeksforGeeks
29 Aug, 2020 assertIsNotNone() in Python is a unittest library function that is used in unit testing to check that input value is not None. This function will take two parameters as input and return a boolean value depending upon assert condition. If input value is not equal to None assertIsNotNone() will return true else return false. Syntax: assertIsNotNone(testValue, message) Parameters: assertIsNotNone() accept two parameters which are listed below with explanation: testValue: test variable as the input value to check equality with None message: a string sentence as a message which got displayed when the test case got failed. Listed below are two different examples illustrating the positive and negative test case for given assert function: Example 1: Negative Test case Python3 # unit test caseimport unittest class TestMethods(unittest.TestCase): # test function def test_negative(self): firstValue = None # error message in case if test case got failed message = "Test value is none." # assertIsNotNone() to check that if input value is not none self.assertIsNotNone(firstValue, message) if __name__ == '__main__': unittest.main() Output: F ====================================================================== FAIL: test_negative (__main__.TestMethods) ---------------------------------------------------------------------- Traceback (most recent call last): File "p1.py", line 11, in test_negative self.assertIsNotNone(firstValue, message) AssertionError: unexpectedly None : Test value is none. ---------------------------------------------------------------------- Ran 1 test in 0.000s FAILED (failures=1) Example 2: Positive Test case Python3 # unit test caseimport unittest class TestMethods(unittest.TestCase): # test function def test_positive(self): firstValue = "geeks" # error message in case if test case got failed message = "Test value is none." # assertIsNotNone() to check that if input value is not none self.assertIsNotNone(firstValue, message) if __name__ == '__main__': unittest.main() Output: . ---------------------------------------------------------------------- Ran 1 test in 0.000s OK Reference: https://docs.python.org/3/library/unittest.html Python unittest-library 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 How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Defaultdict in Python Python | Get unique values from a list Python Classes and Objects Python | os.path.join() method Create a directory in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n29 Aug, 2020" }, { "code": null, "e": 24226, "s": 23901, "text": "assertIsNotNone() in Python is a unittest library function that is used in unit testing to check that input value is not None. This function will take two parameters as input and return a boolean value depending upon assert condition. If input value is not equal to None assertIsNotNone() will return true else return false." }, { "code": null, "e": 24270, "s": 24226, "text": "Syntax: assertIsNotNone(testValue, message)" }, { "code": null, "e": 24363, "s": 24270, "text": "Parameters: assertIsNotNone() accept two parameters which are listed below with explanation:" }, { "code": null, "e": 24436, "s": 24363, "text": "testValue: test variable as the input value to check equality with None" }, { "code": null, "e": 24527, "s": 24436, "text": "message: a string sentence as a message which got displayed when the test case got failed." }, { "code": null, "e": 24643, "s": 24527, "text": "Listed below are two different examples illustrating the positive and negative test case for given assert function:" }, { "code": null, "e": 24673, "s": 24643, "text": "Example 1: Negative Test case" }, { "code": null, "e": 24681, "s": 24673, "text": "Python3" }, { "code": "# unit test caseimport unittest class TestMethods(unittest.TestCase): # test function def test_negative(self): firstValue = None # error message in case if test case got failed message = \"Test value is none.\" # assertIsNotNone() to check that if input value is not none self.assertIsNotNone(firstValue, message) if __name__ == '__main__': unittest.main()", "e": 25083, "s": 24681, "text": null }, { "code": null, "e": 25091, "s": 25083, "text": "Output:" }, { "code": null, "e": 25574, "s": 25091, "text": "F\n======================================================================\nFAIL: test_negative (__main__.TestMethods)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"p1.py\", line 11, in test_negative\n self.assertIsNotNone(firstValue, message)\nAssertionError: unexpectedly None : Test value is none.\n\n----------------------------------------------------------------------\nRan 1 test in 0.000s\n\nFAILED (failures=1)\n\n\n" }, { "code": null, "e": 25604, "s": 25574, "text": "Example 2: Positive Test case" }, { "code": null, "e": 25612, "s": 25604, "text": "Python3" }, { "code": "# unit test caseimport unittest class TestMethods(unittest.TestCase): # test function def test_positive(self): firstValue = \"geeks\" # error message in case if test case got failed message = \"Test value is none.\" # assertIsNotNone() to check that if input value is not none self.assertIsNotNone(firstValue, message) if __name__ == '__main__': unittest.main()", "e": 26018, "s": 25612, "text": null }, { "code": null, "e": 26026, "s": 26018, "text": "Output:" }, { "code": null, "e": 26125, "s": 26026, "text": ".\n----------------------------------------------------------------------\nRan 1 test in 0.000s\n\nOK\n" }, { "code": null, "e": 26184, "s": 26125, "text": "Reference: https://docs.python.org/3/library/unittest.html" }, { "code": null, "e": 26208, "s": 26184, "text": "Python unittest-library" }, { "code": null, "e": 26215, "s": 26208, "text": "Python" }, { "code": null, "e": 26313, "s": 26215, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26322, "s": 26313, "text": "Comments" }, { "code": null, "e": 26335, "s": 26322, "text": "Old Comments" }, { "code": null, "e": 26367, "s": 26335, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26423, "s": 26367, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26465, "s": 26423, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26507, "s": 26465, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26543, "s": 26507, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 26565, "s": 26543, "text": "Defaultdict in Python" }, { "code": null, "e": 26604, "s": 26565, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26631, "s": 26604, "text": "Python Classes and Objects" }, { "code": null, "e": 26662, "s": 26631, "text": "Python | os.path.join() method" } ]
How to create a table in a database using JDBC API?
A. You can create a table in a database using the CREATE TABLE query. CREATE TABLE table_name( column1 datatype, column2 datatype, column3 datatype, ..... columnN datatype, PRIMARY KEY( one or more columns ) ); To create a table in a database using JDBC API you need to: Register the driver: Register the driver class using the registerDriver() method of the DriverManager class. Pass the driver class name to it, as parameter. Establish a connection: Connect ot the database using the getConnection() method of the DriverManager class. Passing URL (String), username (String), password (String) as parameters to it. Create Statement: Create a Statement object using the createStatement() method of the Connection interface. Execute the Query: Execute the query using the execute() method of the Statement interface. Following JDBC program establishes connection with MySQL and creates a table named customers in the database named SampleDB: import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class CreateTableExample { public static void main(String args[]) throws SQLException { //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://localhost/SampleDB"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //Creating the Statement Statement stmt = con.createStatement(); //Query to create a table String query = "CREATE TABLE CUSTOMERS(" + "ID INT NOT NULL, " + "NAME VARCHAR (20) NOT NULL, " + "AGE INT NOT NULL, " + "SALARY DECIMAL (18, 2), " + "ADDRESS CHAR (25) , " + "PRIMARY KEY (ID))"; stmt.execute(query); System.out.println("Table Created......"); } } Connection established...... Table Created...... The show tables command gives you the list of tables in the current database in MySQL. If you verify the list of tables in the database named sampledb, you can observe the newly created table in it as: mysql> show tables; +--------------------+ | Tables_in_sampledb | +--------------------+ | articles | | customers | | dispatches | | technologies | | tutorial | +--------------------+ 5 rows in set (0.00 sec)
[ { "code": null, "e": 1132, "s": 1062, "text": "A. You can create a table in a database using the CREATE TABLE query." }, { "code": null, "e": 1273, "s": 1132, "text": "CREATE TABLE table_name(\ncolumn1 datatype,\ncolumn2 datatype,\ncolumn3 datatype,\n.....\ncolumnN datatype,\nPRIMARY KEY( one or more columns )\n);" }, { "code": null, "e": 1333, "s": 1273, "text": "To create a table in a database using JDBC API you need to:" }, { "code": null, "e": 1490, "s": 1333, "text": "Register the driver: Register the driver class using the registerDriver() method of the DriverManager class. Pass the driver class name to it, as parameter." }, { "code": null, "e": 1679, "s": 1490, "text": "Establish a connection: Connect ot the database using the getConnection() method of the DriverManager class. Passing URL (String), username (String), password (String) as parameters to it." }, { "code": null, "e": 1787, "s": 1679, "text": "Create Statement: Create a Statement object using the createStatement() method of the Connection interface." }, { "code": null, "e": 1879, "s": 1787, "text": "Execute the Query: Execute the query using the execute() method of the Statement interface." }, { "code": null, "e": 2004, "s": 1879, "text": "Following JDBC program establishes connection with MySQL and creates a table named customers in the database named SampleDB:" }, { "code": null, "e": 2992, "s": 2004, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.SQLException;\nimport java.sql.Statement;\npublic class CreateTableExample {\n public static void main(String args[]) throws SQLException {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/SampleDB\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Creating the Statement\n Statement stmt = con.createStatement();\n //Query to create a table\n String query = \"CREATE TABLE CUSTOMERS(\"\n + \"ID INT NOT NULL, \"\n + \"NAME VARCHAR (20) NOT NULL, \"\n + \"AGE INT NOT NULL, \"\n + \"SALARY DECIMAL (18, 2), \"\n + \"ADDRESS CHAR (25) , \"\n + \"PRIMARY KEY (ID))\";\n stmt.execute(query);\n System.out.println(\"Table Created......\");\n }\n}" }, { "code": null, "e": 3041, "s": 2992, "text": "Connection established......\nTable Created......" }, { "code": null, "e": 3128, "s": 3041, "text": "The show tables command gives you the list of tables in the current database in MySQL." }, { "code": null, "e": 3243, "s": 3128, "text": "If you verify the list of tables in the database named sampledb, you can observe the newly created table in it as:" }, { "code": null, "e": 3495, "s": 3243, "text": "mysql> show tables;\n+--------------------+\n| Tables_in_sampledb |\n+--------------------+\n| articles |\n| customers |\n| dispatches |\n| technologies |\n| tutorial |\n+--------------------+\n5 rows in set (0.00 sec)" } ]
Select and sum with grouping in MySQL?
To sum, use the aggregate function SUM(). With that, group using MySQL GROUP BY. Let us first create a table − mysql> create table DemoTable -> ( -> ProductName varchar(20), -> ProductQuantity int, -> ProductPrice int -> ); Query OK, 0 rows affected (0.63 sec) Insert some records in the table using insert command − mysql> insert into DemoTable values('Product-1',2,50); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values('Product-2',3,80); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values('Product-2',4,100); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values('Product-1',4,150); Query OK, 1 row affected (0.11 sec) Display all records from the table using select statement − mysql> select *from DemoTable; This will produce the following output− +-------------+-----------------+--------------+ | ProductName | ProductQuantity | ProductPrice | +-------------+-----------------+--------------+ | Product-1 | 2 | 50 | | Product-2 | 3 | 80 | | Product-2 | 4 | 100 | | Product-1 | 4 | 150 | +-------------+-----------------+--------------+ 4 rows in set (0.00 sec) Following is the query to select with grouping in MySQL − mysql> select *,sum(ProductQuantity*ProductPrice) as Total from DemoTable -> group by ProductName; This will produce the following output− +-------------+-----------------+--------------+-------+ | ProductName | ProductQuantity | ProductPrice | Total | +-------------+-----------------+--------------+-------+ | Product-1 | 2 | 50 | 700 | | Product-2 | 3 | 80 | 640 | +-------------+-----------------+--------------+-------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1173, "s": 1062, "text": "To sum, use the aggregate function SUM(). With that, group using MySQL GROUP BY. Let us first create a table −" }, { "code": null, "e": 1338, "s": 1173, "text": "mysql> create table DemoTable\n -> (\n -> ProductName varchar(20),\n -> ProductQuantity int,\n -> ProductPrice int\n -> );\nQuery OK, 0 rows affected (0.63 sec)" }, { "code": null, "e": 1394, "s": 1338, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1760, "s": 1394, "text": "mysql> insert into DemoTable values('Product-1',2,50);\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into DemoTable values('Product-2',3,80);\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into DemoTable values('Product-2',4,100);\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into DemoTable values('Product-1',4,150);\nQuery OK, 1 row affected (0.11 sec)" }, { "code": null, "e": 1820, "s": 1760, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1851, "s": 1820, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 1891, "s": 1851, "text": "This will produce the following output−" }, { "code": null, "e": 2308, "s": 1891, "text": "+-------------+-----------------+--------------+\n| ProductName | ProductQuantity | ProductPrice |\n+-------------+-----------------+--------------+\n| Product-1 | 2 | 50 |\n| Product-2 | 3 | 80 |\n| Product-2 | 4 | 100 |\n| Product-1 | 4 | 150 |\n+-------------+-----------------+--------------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2366, "s": 2308, "text": "Following is the query to select with grouping in MySQL −" }, { "code": null, "e": 2468, "s": 2366, "text": "mysql> select *,sum(ProductQuantity*ProductPrice) as Total from DemoTable\n -> group by ProductName;" }, { "code": null, "e": 2508, "s": 2468, "text": "This will produce the following output−" }, { "code": null, "e": 2875, "s": 2508, "text": "+-------------+-----------------+--------------+-------+\n| ProductName | ProductQuantity | ProductPrice | Total |\n+-------------+-----------------+--------------+-------+\n| Product-1 | 2 | 50 | 700 |\n| Product-2 | 3 | 80 | 640 |\n+-------------+-----------------+--------------+-------+\n2 rows in set (0.00 sec)" } ]
Can we declare a static variable within a method in java?
A static filed/variable belongs to the class and it will be loaded into the memory along with the class. You can invoke them without creating an object. (using the class name as reference). There is only one copy of the static field available throughout the class i.e. the value of the static field will be same in all objects. You can define a static field using the static keyword. public class Sample{ static int num = 50; public void demo(){ System.out.println("Value of num in the demo method "+ Sample.num); } public static void main(String args[]){ System.out.println("Value of num in the main method "+ Sample.num); new Sample().demo(); } } Value of num in the main method 50 Value of num in the demo method 50 The variables with in a method are local variables and their scope lies within the method and they get destroyed after the method execution. i.e. you cannot use a local variable outside the current method which contradicts with the definition of class/static variable. Therefore, declaring a static variable inside a method makes no sense, if you still try to do so, a compile time error will be generated. In the following Java program, we are trying to declare a static variable inside a method import java.io.IOException; import java.util.Scanner; public class Sample { static int num; public void sampleMethod(Scanner sc){ static int num = 50; } public static void main(String args[]) throws IOException { static int num = 50; } } If you try to execute the above program it generates the following error − Sample.java:6: error: illegal start of expression static int num = 50; ^ Sample.java:9: error: illegal start of expression static int num = 50; ^ 2 errors
[ { "code": null, "e": 1446, "s": 1062, "text": "A static filed/variable belongs to the class and it will be loaded into the memory along with the class. You can invoke them without creating an object. (using the class name as reference). There is only one copy of the static field available throughout the class i.e. the value of the static field will be same in all objects. You can define a static field using the static keyword." }, { "code": null, "e": 1744, "s": 1446, "text": "public class Sample{\n static int num = 50;\n public void demo(){\n System.out.println(\"Value of num in the demo method \"+ Sample.num);\n }\n public static void main(String args[]){\n System.out.println(\"Value of num in the main method \"+ Sample.num);\n new Sample().demo();\n }\n}" }, { "code": null, "e": 1814, "s": 1744, "text": "Value of num in the main method 50\nValue of num in the demo method 50" }, { "code": null, "e": 2221, "s": 1814, "text": "The variables with in a method are local variables and their scope lies within the method and they get destroyed after the method execution. i.e. you cannot use a local variable outside the current method which contradicts with the definition of class/static variable. Therefore, declaring a static variable inside a method makes no sense, if you still try to do so, a compile time error will be generated." }, { "code": null, "e": 2311, "s": 2221, "text": "In the following Java program, we are trying to declare a static variable inside a method" }, { "code": null, "e": 2576, "s": 2311, "text": "import java.io.IOException;\nimport java.util.Scanner;\npublic class Sample {\n static int num;\n public void sampleMethod(Scanner sc){\n static int num = 50;\n }\n public static void main(String args[]) throws IOException {\n static int num = 50;\n }\n}" }, { "code": null, "e": 2651, "s": 2576, "text": "If you try to execute the above program it generates the following error −" }, { "code": null, "e": 2814, "s": 2651, "text": "Sample.java:6: error: illegal start of expression\n static int num = 50;\n ^\nSample.java:9: error: illegal start of expression\n static int num = 50;\n^\n2 errors" } ]
Binary Indexed Tree : Range Update and Range Queries - GeeksforGeeks
16 Jun, 2021 Given an array arr[0..n-1]. The following operations need to be performed. update(l, r, val) : Add ‘val’ to all the elements in the array from [l, r].getRangeSum(l, r) : Find sum of all elements in array from [l, r]. update(l, r, val) : Add ‘val’ to all the elements in the array from [l, r]. getRangeSum(l, r) : Find sum of all elements in array from [l, r]. Initially all the elements in the array are 0. Queries can be in any order, i.e., there can be many updates before range sum.Example: Input : n = 5 // {0, 0, 0, 0, 0} Queries: update : l = 0, r = 4, val = 2 update : l = 3, r = 4, val = 3 getRangeSum : l = 2, r = 4 Output: Sum of elements of range [2, 4] is 12 Explanation : Array after first update becomes {2, 2, 2, 2, 2} Array after second update becomes {2, 2, 2, 5, 5} In the previous post, we discussed range update and point query solutions using BIT. rangeUpdate(l, r, val) : We add ‘val’ to element at index ‘l’. We subtract ‘val’ from element at index ‘r+1’. getElement(index) [or getSum()]: We return sum of elements from 0 to index which can be quickly obtained using BIT.We can compute rangeSum() using getSum() queries. rangeSum(l, r) = getSum(r) – getSum(l-1)A Simple Solution is to use solutions discussed in previous post. Range update query is same. Range sum query can be achieved by doing get query for all elements in range. An Efficient Solution is to make sure that both queries can be done in O(Log n) time. We get range sum using prefix sums. How to make sure that update is done in a way so that prefix sum can be done quickly? Consider a situation where prefix sum [0, k] (where 0 <= k < n) is needed after range update on range [l, r]. Three cases arises as k can possibly lie in 3 regions.Case 1: 0 < k < l The update query won’t affect sum query.Case 2: l <= k <= r Consider an example: Add 2 to range [2, 4], the resultant array would be: 0 0 2 2 2 If k = 3 Sum from [0, k] = 4 How to get this result? Simply add the val from lth index to kth index. Sum is incremented by “val*(k) – val*(l-1)” after update query. Case 3: k > r For this case, we need to add “val” from lth index to rth index. Sum is incremented by “val*r – val*(l-1)” due to update query.Observations : Case 1: is simple as sum would remain same as it was before update.Case 2: Sum was incremented by val*k – val*(l-1). We can find “val”, it is similar to finding the ith element in range update and point query article. So we maintain one BIT for Range Update and Point Queries, this BIT will be helpful in finding the value at kth index. Now val * k is computed, how to handle extra term val*(l-1)? In order to handle this extra term, we maintain another BIT (BIT2). Update val * (l-1) at lth index, so when getSum query is performed on BIT2 will give result as val*(l-1).Case 3 : The sum in case 3 was incremented by “val*r – val *(l-1)”, the value of this term can be obtained using BIT2. Instead of adding, we subtract “val*(l-1) – val*r” as we can get this value from BIT2 by adding val*(l-1) as we did in case 2 and subtracting val*r in every update operation. Update Query Update(BITree1, l, val) Update(BITree1, r+1, -val) UpdateBIT2(BITree2, l, val*(l-1)) UpdateBIT2(BITree2, r+1, -val*r) Range Sum getSum(BITTree1, k) *k) - getSum(BITTree2, k) Implementation of above idea C++ Java Python3 C# Javascript // C++ program to demonstrate Range Update// and Range Queries using BIT#include <bits/stdc++.h>using namespace std; // Returns sum of arr[0..index]. This function assumes// that the array is preprocessed and partial sums of// array elements are stored in BITree[]int getSum(int BITree[], int index){ int sum = 0; // Initialize result // index in BITree[] is 1 more than the index in arr[] index = index + 1; // Traverse ancestors of BITree[index] while (index>0) { // Add current element of BITree to sum sum += BITree[index]; // Move index to parent node in getSum View index -= index & (-index); } return sum;} // Updates a node in Binary Index Tree (BITree) at given// index in BITree. The given value 'val' is added to// BITree[i] and all of its ancestors in tree.void updateBIT(int BITree[], int n, int index, int val){ // index in BITree[] is 1 more than the index in arr[] index = index + 1; // Traverse all ancestors and add 'val' while (index <= n) { // Add 'val' to current node of BI Tree BITree[index] += val; // Update index to that of parent in update View index += index & (-index); }} // Returns the sum of array from [0, x]int sum(int x, int BITTree1[], int BITTree2[]){ return (getSum(BITTree1, x) * x) - getSum(BITTree2, x);} void updateRange(int BITTree1[], int BITTree2[], int n, int val, int l, int r){ // Update Both the Binary Index Trees // As discussed in the article // Update BIT1 updateBIT(BITTree1,n,l,val); updateBIT(BITTree1,n,r+1,-val); // Update BIT2 updateBIT(BITTree2,n,l,val*(l-1)); updateBIT(BITTree2,n,r+1,-val*r);} int rangeSum(int l, int r, int BITTree1[], int BITTree2[]){ // Find sum from [0,r] then subtract sum // from [0,l-1] in order to find sum from // [l,r] return sum(r, BITTree1, BITTree2) - sum(l-1, BITTree1, BITTree2);} int *constructBITree(int n){ // Create and initialize BITree[] as 0 int *BITree = new int[n+1]; for (int i=1; i<=n; i++) BITree[i] = 0; return BITree;} // Driver Program to test above functionint main(){ int n = 5; // Construct two BIT int *BITTree1, *BITTree2; // BIT1 to get element at any index // in the array BITTree1 = constructBITree(n); // BIT 2 maintains the extra term // which needs to be subtracted BITTree2 = constructBITree(n); // Add 5 to all the elements from [0,4] int l = 0 , r = 4 , val = 5; updateRange(BITTree1,BITTree2,n,val,l,r); // Add 2 to all the elements from [2,4] l = 2 , r = 4 , val = 10; updateRange(BITTree1,BITTree2,n,val,l,r); // Find sum of all the elements from // [1,4] l = 1 , r = 4; cout << "Sum of elements from [" << l << "," << r << "] is "; cout << rangeSum(l,r,BITTree1,BITTree2) << "\n"; return 0;} // Java program to demonstrate Range Update// and Range Queries using BITimport java.util.*; class GFG{ // Returns sum of arr[0..index]. This function assumes// that the array is preprocessed and partial sums of// array elements are stored in BITree[]static int getSum(int BITree[], int index){ int sum = 0; // Initialize result // index in BITree[] is 1 more than the index in arr[] index = index + 1; // Traverse ancestors of BITree[index] while (index > 0) { // Add current element of BITree to sum sum += BITree[index]; // Move index to parent node in getSum View index -= index & (-index); } return sum;} // Updates a node in Binary Index Tree (BITree) at given// index in BITree. The given value 'val' is added to// BITree[i] and all of its ancestors in tree.static void updateBIT(int BITree[], int n, int index, int val){ // index in BITree[] is 1 more than the index in arr[] index = index + 1; // Traverse all ancestors and add 'val' while (index <= n) { // Add 'val' to current node of BI Tree BITree[index] += val; // Update index to that of parent in update View index += index & (-index); }} // Returns the sum of array from [0, x]static int sum(int x, int BITTree1[], int BITTree2[]){ return (getSum(BITTree1, x) * x) - getSum(BITTree2, x);} static void updateRange(int BITTree1[], int BITTree2[], int n, int val, int l, int r){ // Update Both the Binary Index Trees // As discussed in the article // Update BIT1 updateBIT(BITTree1, n, l, val); updateBIT(BITTree1, n, r + 1, -val); // Update BIT2 updateBIT(BITTree2, n, l, val * (l - 1)); updateBIT(BITTree2, n, r + 1, -val * r);} static int rangeSum(int l, int r, int BITTree1[], int BITTree2[]){ // Find sum from [0,r] then subtract sum // from [0,l-1] in order to find sum from // [l,r] return sum(r, BITTree1, BITTree2) - sum(l - 1, BITTree1, BITTree2);} static int[] constructBITree(int n){ // Create and initialize BITree[] as 0 int []BITree = new int[n + 1]; for (int i = 1; i <= n; i++) BITree[i] = 0; return BITree;} // Driver Program to test above functionpublic static void main(String[] args){ int n = 5; // Contwo BIT int []BITTree1; int []BITTree2; // BIT1 to get element at any index // in the array BITTree1 = constructBITree(n); // BIT 2 maintains the extra term // which needs to be subtracted BITTree2 = constructBITree(n); // Add 5 to all the elements from [0,4] int l = 0 , r = 4 , val = 5; updateRange(BITTree1, BITTree2, n, val, l, r); // Add 2 to all the elements from [2,4] l = 2 ; r = 4 ; val = 10; updateRange(BITTree1, BITTree2, n, val, l, r); // Find sum of all the elements from // [1,4] l = 1 ; r = 4; System.out.print("Sum of elements from [" + l + "," + r+ "] is "); System.out.print(rangeSum(l, r, BITTree1, BITTree2)+ "\n");}} // This code is contributed by 29AjayKumar # Python program to demonstrate Range Update# and Range Queries using BIT # Returns sum of arr[0..index]. This function assumes# that the array is preprocessed and partial sums of# array elements are stored in BITree[]def getSum(BITree: list, index: int) -> int: summ = 0 # Initialize result # index in BITree[] is 1 more than the index in arr[] index = index + 1 # Traverse ancestors of BITree[index] while index > 0: # Add current element of BITree to sum summ += BITree[index] # Move index to parent node in getSum View index -= index & (-index) return summ # Updates a node in Binary Index Tree (BITree) at given# index in BITree. The given value 'val' is added to# BITree[i] and all of its ancestors in tree.def updateBit(BITTree: list, n: int, index: int, val: int) -> None: # index in BITree[] is 1 more than the index in arr[] index = index + 1 # Traverse all ancestors and add 'val' while index <= n: # Add 'val' to current node of BI Tree BITTree[index] += val # Update index to that of parent in update View index += index & (-index) # Returns the sum of array from [0, x]def summation(x: int, BITTree1: list, BITTree2: list) -> int: return (getSum(BITTree1, x) * x) - getSum(BITTree2, x) def updateRange(BITTree1: list, BITTree2: list, n: int, val: int, l: int, r: int) -> None: # Update Both the Binary Index Trees # As discussed in the article # Update BIT1 updateBit(BITTree1, n, l, val) updateBit(BITTree1, n, r + 1, -val) # Update BIT2 updateBit(BITTree2, n, l, val * (l - 1)) updateBit(BITTree2, n, r + 1, -val * r) def rangeSum(l: int, r: int, BITTree1: list, BITTree2: list) -> int: # Find sum from [0,r] then subtract sum # from [0,l-1] in order to find sum from # [l,r] return summation(r, BITTree1, BITTree2) - summation( l - 1, BITTree1, BITTree2) # Driver Codeif __name__ == "__main__": n = 5 # BIT1 to get element at any index # in the array BITTree1 = [0] * (n + 1) # BIT 2 maintains the extra term # which needs to be subtracted BITTree2 = [0] * (n + 1) # Add 5 to all the elements from [0,4] l = 0 r = 4 val = 5 updateRange(BITTree1, BITTree2, n, val, l, r) # Add 2 to all the elements from [2,4] l = 2 r = 4 val = 10 updateRange(BITTree1, BITTree2, n, val, l, r) # Find sum of all the elements from # [1,4] l = 1 r = 4 print("Sum of elements from [%d,%d] is %d" % (l, r, rangeSum(l, r, BITTree1, BITTree2))) # This code is contributed by# sanjeev2552 // C# program to demonstrate Range Update// and Range Queries using BITusing System; class GFG{ // Returns sum of arr[0..index]. This function assumes// that the array is preprocessed and partial sums of// array elements are stored in BITree[]static int getSum(int []BITree, int index){ int sum = 0; // Initialize result // index in BITree[] is 1 more than // the index in []arr index = index + 1; // Traverse ancestors of BITree[index] while (index > 0) { // Add current element of BITree to sum sum += BITree[index]; // Move index to parent node in getSum View index -= index & (-index); } return sum;} // Updates a node in Binary Index Tree (BITree) at given// index in BITree. The given value 'val' is added to// BITree[i] and all of its ancestors in tree.static void updateBIT(int []BITree, int n, int index, int val){ // index in BITree[] is 1 more than // the index in []arr index = index + 1; // Traverse all ancestors and add 'val' while (index <= n) { // Add 'val' to current node of BI Tree BITree[index] += val; // Update index to that of // parent in update View index += index & (-index); }} // Returns the sum of array from [0, x]static int sum(int x, int []BITTree1, int []BITTree2){ return (getSum(BITTree1, x) * x) - getSum(BITTree2, x);} static void updateRange(int []BITTree1, int []BITTree2, int n, int val, int l, int r){ // Update Both the Binary Index Trees // As discussed in the article // Update BIT1 updateBIT(BITTree1, n, l, val); updateBIT(BITTree1, n, r + 1, -val); // Update BIT2 updateBIT(BITTree2, n, l, val * (l - 1)); updateBIT(BITTree2, n, r + 1, -val * r);} static int rangeSum(int l, int r, int []BITTree1, int []BITTree2){ // Find sum from [0,r] then subtract sum // from [0,l-1] in order to find sum from // [l,r] return sum(r, BITTree1, BITTree2) - sum(l - 1, BITTree1, BITTree2);} static int[] constructBITree(int n){ // Create and initialize BITree[] as 0 int []BITree = new int[n + 1]; for (int i = 1; i <= n; i++) BITree[i] = 0; return BITree;} // Driver Codepublic static void Main(String[] args){ int n = 5; // Contwo BIT int []BITTree1; int []BITTree2; // BIT1 to get element at any index // in the array BITTree1 = constructBITree(n); // BIT 2 maintains the extra term // which needs to be subtracted BITTree2 = constructBITree(n); // Add 5 to all the elements from [0,4] int l = 0 , r = 4 , val = 5; updateRange(BITTree1, BITTree2, n, val, l, r); // Add 2 to all the elements from [2,4] l = 2 ; r = 4 ; val = 10; updateRange(BITTree1, BITTree2, n, val, l, r); // Find sum of all the elements from // [1,4] l = 1 ; r = 4; Console.Write("Sum of elements from [" + l + "," + r + "] is "); Console.Write(rangeSum(l, r, BITTree1, BITTree2) + "\n");}} // This code is contributed by 29AjayKumar <script> // JavaScript program to demonstrate Range Update// and Range Queries using BIT // Returns sum of arr[0..index]. This function assumes// that the array is preprocessed and partial sums of// array elements are stored in BITree[]function getSum(BITree,index){ let sum = 0; // Initialize result // index in BITree[] is 1 more than the index in arr[] index = index + 1; // Traverse ancestors of BITree[index] while (index > 0) { // Add current element of BITree to sum sum += BITree[index]; // Move index to parent node in getSum View index -= index & (-index); } return sum;} // Updates a node in Binary Index Tree (BITree) at given// index in BITree. The given value 'val' is added to// BITree[i] and all of its ancestors in tree.function updateBIT(BITree,n,index,val){ // index in BITree[] is 1 more than the index in arr[] index = index + 1; // Traverse all ancestors and add 'val' while (index <= n) { // Add 'val' to current node of BI Tree BITree[index] += val; // Update index to that of parent in update View index += index & (-index); }} // Returns the sum of array from [0, x]function sum(x,BITTree1,BITTree2){ return (getSum(BITTree1, x) * x) - getSum(BITTree2, x);} function updateRange(BITTree1,BITTree2,n,val,l,r){ // Update Both the Binary Index Trees // As discussed in the article // Update BIT1 updateBIT(BITTree1, n, l, val); updateBIT(BITTree1, n, r + 1, -val); // Update BIT2 updateBIT(BITTree2, n, l, val * (l - 1)); updateBIT(BITTree2, n, r + 1, -val * r);} function rangeSum(l,r,BITTree1,BITTree2){ // Find sum from [0,r] then subtract sum // from [0,l-1] in order to find sum from // [l,r] return sum(r, BITTree1, BITTree2) - sum(l - 1, BITTree1, BITTree2);} function constructBITree(n){ // Create and initialize BITree[] as 0 let BITree = new Array(n + 1); for (let i = 1; i <= n; i++) BITree[i] = 0; return BITree;} // Driver Program to test above functionlet n = 5; // Contwo BITlet BITTree1;let BITTree2; // BIT1 to get element at any index// in the arrayBITTree1 = constructBITree(n); // BIT 2 maintains the extra term// which needs to be subtractedBITTree2 = constructBITree(n); // Add 5 to all the elements from [0,4]let l = 0 , r = 4 , val = 5;updateRange(BITTree1, BITTree2, n, val, l, r); // Add 2 to all the elements from [2,4]l = 2 ; r = 4 ; val = 10;updateRange(BITTree1, BITTree2, n, val, l, r); // Find sum of all the elements from// [1,4]l = 1 ; r = 4;document.write("Sum of elements from [" + l + "," + r+ "] is ");document.write(rangeSum(l, r, BITTree1, BITTree2)+ "<br>"); // This code is contributed by rag2127 </script> Output: Sum of elements from [1,4] is 50 Time Complexity : O(q*log(n)) where q is number of queries.This article is contributed by Chirag Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nidhi_biet 29AjayKumar sanjeev2552 rag2127 array-range-queries Binary Indexed Tree Advanced Data Structure Technical Scripter Binary Indexed Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Agents in Artificial Intelligence Decision Tree Introduction with example AVL Tree | Set 2 (Deletion) Red-Black Tree | Set 2 (Insert) Disjoint Set Data Structures Insert Operation in B-Tree How to design a tiny URL or URL shortener? Design a Chess Game Design a data structure that supports insert, delete, search and getRandom in constant time Red-Black Tree | Set 3 (Delete)
[ { "code": null, "e": 24273, "s": 24245, "text": "\n16 Jun, 2021" }, { "code": null, "e": 24349, "s": 24273, "text": "Given an array arr[0..n-1]. The following operations need to be performed. " }, { "code": null, "e": 24491, "s": 24349, "text": "update(l, r, val) : Add ‘val’ to all the elements in the array from [l, r].getRangeSum(l, r) : Find sum of all elements in array from [l, r]." }, { "code": null, "e": 24567, "s": 24491, "text": "update(l, r, val) : Add ‘val’ to all the elements in the array from [l, r]." }, { "code": null, "e": 24634, "s": 24567, "text": "getRangeSum(l, r) : Find sum of all elements in array from [l, r]." }, { "code": null, "e": 24770, "s": 24634, "text": "Initially all the elements in the array are 0. Queries can be in any order, i.e., there can be many updates before range sum.Example: " }, { "code": null, "e": 25125, "s": 24770, "text": "Input : n = 5 // {0, 0, 0, 0, 0}\nQueries: update : l = 0, r = 4, val = 2\n update : l = 3, r = 4, val = 3 \n getRangeSum : l = 2, r = 4\n\nOutput: Sum of elements of range [2, 4] is 12\n\nExplanation : Array after first update becomes\n {2, 2, 2, 2, 2}\n Array after second update becomes\n {2, 2, 2, 5, 5}" }, { "code": null, "e": 26172, "s": 25127, "text": "In the previous post, we discussed range update and point query solutions using BIT. rangeUpdate(l, r, val) : We add ‘val’ to element at index ‘l’. We subtract ‘val’ from element at index ‘r+1’. getElement(index) [or getSum()]: We return sum of elements from 0 to index which can be quickly obtained using BIT.We can compute rangeSum() using getSum() queries. rangeSum(l, r) = getSum(r) – getSum(l-1)A Simple Solution is to use solutions discussed in previous post. Range update query is same. Range sum query can be achieved by doing get query for all elements in range. An Efficient Solution is to make sure that both queries can be done in O(Log n) time. We get range sum using prefix sums. How to make sure that update is done in a way so that prefix sum can be done quickly? Consider a situation where prefix sum [0, k] (where 0 <= k < n) is needed after range update on range [l, r]. Three cases arises as k can possibly lie in 3 regions.Case 1: 0 < k < l The update query won’t affect sum query.Case 2: l <= k <= r Consider an example: " }, { "code": null, "e": 26264, "s": 26172, "text": "Add 2 to range [2, 4], the resultant array would be:\n0 0 2 2 2\nIf k = 3\nSum from [0, k] = 4" }, { "code": null, "e": 27422, "s": 26264, "text": "How to get this result? Simply add the val from lth index to kth index. Sum is incremented by “val*(k) – val*(l-1)” after update query. Case 3: k > r For this case, we need to add “val” from lth index to rth index. Sum is incremented by “val*r – val*(l-1)” due to update query.Observations : Case 1: is simple as sum would remain same as it was before update.Case 2: Sum was incremented by val*k – val*(l-1). We can find “val”, it is similar to finding the ith element in range update and point query article. So we maintain one BIT for Range Update and Point Queries, this BIT will be helpful in finding the value at kth index. Now val * k is computed, how to handle extra term val*(l-1)? In order to handle this extra term, we maintain another BIT (BIT2). Update val * (l-1) at lth index, so when getSum query is performed on BIT2 will give result as val*(l-1).Case 3 : The sum in case 3 was incremented by “val*r – val *(l-1)”, the value of this term can be obtained using BIT2. Instead of adding, we subtract “val*(l-1) – val*r” as we can get this value from BIT2 by adding val*(l-1) as we did in case 2 and subtracting val*r in every update operation. " }, { "code": null, "e": 27612, "s": 27422, "text": "Update Query \nUpdate(BITree1, l, val)\nUpdate(BITree1, r+1, -val)\nUpdateBIT2(BITree2, l, val*(l-1))\nUpdateBIT2(BITree2, r+1, -val*r)\n\nRange Sum \ngetSum(BITTree1, k) *k) - getSum(BITTree2, k)" }, { "code": null, "e": 27643, "s": 27612, "text": "Implementation of above idea " }, { "code": null, "e": 27647, "s": 27643, "text": "C++" }, { "code": null, "e": 27652, "s": 27647, "text": "Java" }, { "code": null, "e": 27660, "s": 27652, "text": "Python3" }, { "code": null, "e": 27663, "s": 27660, "text": "C#" }, { "code": null, "e": 27674, "s": 27663, "text": "Javascript" }, { "code": "// C++ program to demonstrate Range Update// and Range Queries using BIT#include <bits/stdc++.h>using namespace std; // Returns sum of arr[0..index]. This function assumes// that the array is preprocessed and partial sums of// array elements are stored in BITree[]int getSum(int BITree[], int index){ int sum = 0; // Initialize result // index in BITree[] is 1 more than the index in arr[] index = index + 1; // Traverse ancestors of BITree[index] while (index>0) { // Add current element of BITree to sum sum += BITree[index]; // Move index to parent node in getSum View index -= index & (-index); } return sum;} // Updates a node in Binary Index Tree (BITree) at given// index in BITree. The given value 'val' is added to// BITree[i] and all of its ancestors in tree.void updateBIT(int BITree[], int n, int index, int val){ // index in BITree[] is 1 more than the index in arr[] index = index + 1; // Traverse all ancestors and add 'val' while (index <= n) { // Add 'val' to current node of BI Tree BITree[index] += val; // Update index to that of parent in update View index += index & (-index); }} // Returns the sum of array from [0, x]int sum(int x, int BITTree1[], int BITTree2[]){ return (getSum(BITTree1, x) * x) - getSum(BITTree2, x);} void updateRange(int BITTree1[], int BITTree2[], int n, int val, int l, int r){ // Update Both the Binary Index Trees // As discussed in the article // Update BIT1 updateBIT(BITTree1,n,l,val); updateBIT(BITTree1,n,r+1,-val); // Update BIT2 updateBIT(BITTree2,n,l,val*(l-1)); updateBIT(BITTree2,n,r+1,-val*r);} int rangeSum(int l, int r, int BITTree1[], int BITTree2[]){ // Find sum from [0,r] then subtract sum // from [0,l-1] in order to find sum from // [l,r] return sum(r, BITTree1, BITTree2) - sum(l-1, BITTree1, BITTree2);} int *constructBITree(int n){ // Create and initialize BITree[] as 0 int *BITree = new int[n+1]; for (int i=1; i<=n; i++) BITree[i] = 0; return BITree;} // Driver Program to test above functionint main(){ int n = 5; // Construct two BIT int *BITTree1, *BITTree2; // BIT1 to get element at any index // in the array BITTree1 = constructBITree(n); // BIT 2 maintains the extra term // which needs to be subtracted BITTree2 = constructBITree(n); // Add 5 to all the elements from [0,4] int l = 0 , r = 4 , val = 5; updateRange(BITTree1,BITTree2,n,val,l,r); // Add 2 to all the elements from [2,4] l = 2 , r = 4 , val = 10; updateRange(BITTree1,BITTree2,n,val,l,r); // Find sum of all the elements from // [1,4] l = 1 , r = 4; cout << \"Sum of elements from [\" << l << \",\" << r << \"] is \"; cout << rangeSum(l,r,BITTree1,BITTree2) << \"\\n\"; return 0;}", "e": 30564, "s": 27674, "text": null }, { "code": "// Java program to demonstrate Range Update// and Range Queries using BITimport java.util.*; class GFG{ // Returns sum of arr[0..index]. This function assumes// that the array is preprocessed and partial sums of// array elements are stored in BITree[]static int getSum(int BITree[], int index){ int sum = 0; // Initialize result // index in BITree[] is 1 more than the index in arr[] index = index + 1; // Traverse ancestors of BITree[index] while (index > 0) { // Add current element of BITree to sum sum += BITree[index]; // Move index to parent node in getSum View index -= index & (-index); } return sum;} // Updates a node in Binary Index Tree (BITree) at given// index in BITree. The given value 'val' is added to// BITree[i] and all of its ancestors in tree.static void updateBIT(int BITree[], int n, int index, int val){ // index in BITree[] is 1 more than the index in arr[] index = index + 1; // Traverse all ancestors and add 'val' while (index <= n) { // Add 'val' to current node of BI Tree BITree[index] += val; // Update index to that of parent in update View index += index & (-index); }} // Returns the sum of array from [0, x]static int sum(int x, int BITTree1[], int BITTree2[]){ return (getSum(BITTree1, x) * x) - getSum(BITTree2, x);} static void updateRange(int BITTree1[], int BITTree2[], int n, int val, int l, int r){ // Update Both the Binary Index Trees // As discussed in the article // Update BIT1 updateBIT(BITTree1, n, l, val); updateBIT(BITTree1, n, r + 1, -val); // Update BIT2 updateBIT(BITTree2, n, l, val * (l - 1)); updateBIT(BITTree2, n, r + 1, -val * r);} static int rangeSum(int l, int r, int BITTree1[], int BITTree2[]){ // Find sum from [0,r] then subtract sum // from [0,l-1] in order to find sum from // [l,r] return sum(r, BITTree1, BITTree2) - sum(l - 1, BITTree1, BITTree2);} static int[] constructBITree(int n){ // Create and initialize BITree[] as 0 int []BITree = new int[n + 1]; for (int i = 1; i <= n; i++) BITree[i] = 0; return BITree;} // Driver Program to test above functionpublic static void main(String[] args){ int n = 5; // Contwo BIT int []BITTree1; int []BITTree2; // BIT1 to get element at any index // in the array BITTree1 = constructBITree(n); // BIT 2 maintains the extra term // which needs to be subtracted BITTree2 = constructBITree(n); // Add 5 to all the elements from [0,4] int l = 0 , r = 4 , val = 5; updateRange(BITTree1, BITTree2, n, val, l, r); // Add 2 to all the elements from [2,4] l = 2 ; r = 4 ; val = 10; updateRange(BITTree1, BITTree2, n, val, l, r); // Find sum of all the elements from // [1,4] l = 1 ; r = 4; System.out.print(\"Sum of elements from [\" + l + \",\" + r+ \"] is \"); System.out.print(rangeSum(l, r, BITTree1, BITTree2)+ \"\\n\");}} // This code is contributed by 29AjayKumar", "e": 33597, "s": 30564, "text": null }, { "code": "# Python program to demonstrate Range Update# and Range Queries using BIT # Returns sum of arr[0..index]. This function assumes# that the array is preprocessed and partial sums of# array elements are stored in BITree[]def getSum(BITree: list, index: int) -> int: summ = 0 # Initialize result # index in BITree[] is 1 more than the index in arr[] index = index + 1 # Traverse ancestors of BITree[index] while index > 0: # Add current element of BITree to sum summ += BITree[index] # Move index to parent node in getSum View index -= index & (-index) return summ # Updates a node in Binary Index Tree (BITree) at given# index in BITree. The given value 'val' is added to# BITree[i] and all of its ancestors in tree.def updateBit(BITTree: list, n: int, index: int, val: int) -> None: # index in BITree[] is 1 more than the index in arr[] index = index + 1 # Traverse all ancestors and add 'val' while index <= n: # Add 'val' to current node of BI Tree BITTree[index] += val # Update index to that of parent in update View index += index & (-index) # Returns the sum of array from [0, x]def summation(x: int, BITTree1: list, BITTree2: list) -> int: return (getSum(BITTree1, x) * x) - getSum(BITTree2, x) def updateRange(BITTree1: list, BITTree2: list, n: int, val: int, l: int, r: int) -> None: # Update Both the Binary Index Trees # As discussed in the article # Update BIT1 updateBit(BITTree1, n, l, val) updateBit(BITTree1, n, r + 1, -val) # Update BIT2 updateBit(BITTree2, n, l, val * (l - 1)) updateBit(BITTree2, n, r + 1, -val * r) def rangeSum(l: int, r: int, BITTree1: list, BITTree2: list) -> int: # Find sum from [0,r] then subtract sum # from [0,l-1] in order to find sum from # [l,r] return summation(r, BITTree1, BITTree2) - summation( l - 1, BITTree1, BITTree2) # Driver Codeif __name__ == \"__main__\": n = 5 # BIT1 to get element at any index # in the array BITTree1 = [0] * (n + 1) # BIT 2 maintains the extra term # which needs to be subtracted BITTree2 = [0] * (n + 1) # Add 5 to all the elements from [0,4] l = 0 r = 4 val = 5 updateRange(BITTree1, BITTree2, n, val, l, r) # Add 2 to all the elements from [2,4] l = 2 r = 4 val = 10 updateRange(BITTree1, BITTree2, n, val, l, r) # Find sum of all the elements from # [1,4] l = 1 r = 4 print(\"Sum of elements from [%d,%d] is %d\" % (l, r, rangeSum(l, r, BITTree1, BITTree2))) # This code is contributed by# sanjeev2552", "e": 36217, "s": 33597, "text": null }, { "code": "// C# program to demonstrate Range Update// and Range Queries using BITusing System; class GFG{ // Returns sum of arr[0..index]. This function assumes// that the array is preprocessed and partial sums of// array elements are stored in BITree[]static int getSum(int []BITree, int index){ int sum = 0; // Initialize result // index in BITree[] is 1 more than // the index in []arr index = index + 1; // Traverse ancestors of BITree[index] while (index > 0) { // Add current element of BITree to sum sum += BITree[index]; // Move index to parent node in getSum View index -= index & (-index); } return sum;} // Updates a node in Binary Index Tree (BITree) at given// index in BITree. The given value 'val' is added to// BITree[i] and all of its ancestors in tree.static void updateBIT(int []BITree, int n, int index, int val){ // index in BITree[] is 1 more than // the index in []arr index = index + 1; // Traverse all ancestors and add 'val' while (index <= n) { // Add 'val' to current node of BI Tree BITree[index] += val; // Update index to that of // parent in update View index += index & (-index); }} // Returns the sum of array from [0, x]static int sum(int x, int []BITTree1, int []BITTree2){ return (getSum(BITTree1, x) * x) - getSum(BITTree2, x);} static void updateRange(int []BITTree1, int []BITTree2, int n, int val, int l, int r){ // Update Both the Binary Index Trees // As discussed in the article // Update BIT1 updateBIT(BITTree1, n, l, val); updateBIT(BITTree1, n, r + 1, -val); // Update BIT2 updateBIT(BITTree2, n, l, val * (l - 1)); updateBIT(BITTree2, n, r + 1, -val * r);} static int rangeSum(int l, int r, int []BITTree1, int []BITTree2){ // Find sum from [0,r] then subtract sum // from [0,l-1] in order to find sum from // [l,r] return sum(r, BITTree1, BITTree2) - sum(l - 1, BITTree1, BITTree2);} static int[] constructBITree(int n){ // Create and initialize BITree[] as 0 int []BITree = new int[n + 1]; for (int i = 1; i <= n; i++) BITree[i] = 0; return BITree;} // Driver Codepublic static void Main(String[] args){ int n = 5; // Contwo BIT int []BITTree1; int []BITTree2; // BIT1 to get element at any index // in the array BITTree1 = constructBITree(n); // BIT 2 maintains the extra term // which needs to be subtracted BITTree2 = constructBITree(n); // Add 5 to all the elements from [0,4] int l = 0 , r = 4 , val = 5; updateRange(BITTree1, BITTree2, n, val, l, r); // Add 2 to all the elements from [2,4] l = 2 ; r = 4 ; val = 10; updateRange(BITTree1, BITTree2, n, val, l, r); // Find sum of all the elements from // [1,4] l = 1 ; r = 4; Console.Write(\"Sum of elements from [\" + l + \",\" + r + \"] is \"); Console.Write(rangeSum(l, r, BITTree1, BITTree2) + \"\\n\");}} // This code is contributed by 29AjayKumar", "e": 39411, "s": 36217, "text": null }, { "code": "<script> // JavaScript program to demonstrate Range Update// and Range Queries using BIT // Returns sum of arr[0..index]. This function assumes// that the array is preprocessed and partial sums of// array elements are stored in BITree[]function getSum(BITree,index){ let sum = 0; // Initialize result // index in BITree[] is 1 more than the index in arr[] index = index + 1; // Traverse ancestors of BITree[index] while (index > 0) { // Add current element of BITree to sum sum += BITree[index]; // Move index to parent node in getSum View index -= index & (-index); } return sum;} // Updates a node in Binary Index Tree (BITree) at given// index in BITree. The given value 'val' is added to// BITree[i] and all of its ancestors in tree.function updateBIT(BITree,n,index,val){ // index in BITree[] is 1 more than the index in arr[] index = index + 1; // Traverse all ancestors and add 'val' while (index <= n) { // Add 'val' to current node of BI Tree BITree[index] += val; // Update index to that of parent in update View index += index & (-index); }} // Returns the sum of array from [0, x]function sum(x,BITTree1,BITTree2){ return (getSum(BITTree1, x) * x) - getSum(BITTree2, x);} function updateRange(BITTree1,BITTree2,n,val,l,r){ // Update Both the Binary Index Trees // As discussed in the article // Update BIT1 updateBIT(BITTree1, n, l, val); updateBIT(BITTree1, n, r + 1, -val); // Update BIT2 updateBIT(BITTree2, n, l, val * (l - 1)); updateBIT(BITTree2, n, r + 1, -val * r);} function rangeSum(l,r,BITTree1,BITTree2){ // Find sum from [0,r] then subtract sum // from [0,l-1] in order to find sum from // [l,r] return sum(r, BITTree1, BITTree2) - sum(l - 1, BITTree1, BITTree2);} function constructBITree(n){ // Create and initialize BITree[] as 0 let BITree = new Array(n + 1); for (let i = 1; i <= n; i++) BITree[i] = 0; return BITree;} // Driver Program to test above functionlet n = 5; // Contwo BITlet BITTree1;let BITTree2; // BIT1 to get element at any index// in the arrayBITTree1 = constructBITree(n); // BIT 2 maintains the extra term// which needs to be subtractedBITTree2 = constructBITree(n); // Add 5 to all the elements from [0,4]let l = 0 , r = 4 , val = 5;updateRange(BITTree1, BITTree2, n, val, l, r); // Add 2 to all the elements from [2,4]l = 2 ; r = 4 ; val = 10;updateRange(BITTree1, BITTree2, n, val, l, r); // Find sum of all the elements from// [1,4]l = 1 ; r = 4;document.write(\"Sum of elements from [\" + l + \",\" + r+ \"] is \");document.write(rangeSum(l, r, BITTree1, BITTree2)+ \"<br>\"); // This code is contributed by rag2127 </script>", "e": 42188, "s": 39411, "text": null }, { "code": null, "e": 42198, "s": 42188, "text": "Output: " }, { "code": null, "e": 42231, "s": 42198, "text": "Sum of elements from [1,4] is 50" }, { "code": null, "e": 42713, "s": 42231, "text": "Time Complexity : O(q*log(n)) where q is number of queries.This article is contributed by Chirag Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 42724, "s": 42713, "text": "nidhi_biet" }, { "code": null, "e": 42736, "s": 42724, "text": "29AjayKumar" }, { "code": null, "e": 42748, "s": 42736, "text": "sanjeev2552" }, { "code": null, "e": 42756, "s": 42748, "text": "rag2127" }, { "code": null, "e": 42776, "s": 42756, "text": "array-range-queries" }, { "code": null, "e": 42796, "s": 42776, "text": "Binary Indexed Tree" }, { "code": null, "e": 42820, "s": 42796, "text": "Advanced Data Structure" }, { "code": null, "e": 42839, "s": 42820, "text": "Technical Scripter" }, { "code": null, "e": 42859, "s": 42839, "text": "Binary Indexed Tree" }, { "code": null, "e": 42957, "s": 42859, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42966, "s": 42957, "text": "Comments" }, { "code": null, "e": 42979, "s": 42966, "text": "Old Comments" }, { "code": null, "e": 43013, "s": 42979, "text": "Agents in Artificial Intelligence" }, { "code": null, "e": 43053, "s": 43013, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 43081, "s": 43053, "text": "AVL Tree | Set 2 (Deletion)" }, { "code": null, "e": 43113, "s": 43081, "text": "Red-Black Tree | Set 2 (Insert)" }, { "code": null, "e": 43142, "s": 43113, "text": "Disjoint Set Data Structures" }, { "code": null, "e": 43169, "s": 43142, "text": "Insert Operation in B-Tree" }, { "code": null, "e": 43212, "s": 43169, "text": "How to design a tiny URL or URL shortener?" }, { "code": null, "e": 43232, "s": 43212, "text": "Design a Chess Game" }, { "code": null, "e": 43324, "s": 43232, "text": "Design a data structure that supports insert, delete, search and getRandom in constant time" } ]
CSS | column-span Property - GeeksforGeeks
06 Sep, 2021 The column-span property of CSS sets the number of columns an element can span across. Its value can be none | all | initial | inherit Syntax: column-span: none|all|initial|inherit; Default Value: None Property Values: all: It allows to span in all the columns equally.Syntax: column-span: all; Example: html <!DOCTYPE html><html> <head> <title> CSS | column-span Property </title> <style> .paragraph { column-count: 3; } h2 { column-span: all; } </style></head> <body> <div class="paragraph "> <h2> Here we used col-span:all; It had done span across three columns </h2> GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks </div></body></html> Output: none: This value kills the spanning element and sets it to none. Syntax: column-span: none; Example: html <!DOCTYPE html><html> <head> <title> CSS | column-span Property </title> <style> .paragraph { column-count: 3; } h2 { column-span: none; } </style></head> <body> <div class="paragraph "> <h2> Here we used col-span:none; It had done span across three columns </h2> GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks </div></body></html> Output: initial: This value makes this property set to its default value.Syntax: column-span: initial; Example: html <!DOCTYPE html><html> <head> <title> CSS | column-span Property </title> <style> .paragraph { column-count: 3; } h2 { column-span: initial; } </style></head> <div class="paragraph "> <h2> Here we used col-span:initial; It had done span across three columns </h2> GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks </div></body></html> Output: inherit: The associated element takes the evaluated value of its parent element’s specified column-span property i.e. it will take the inherited property of the parent element. This is not supported by the column-span property of CSS.Syntax: column-span: inherit; Example: html <!DOCTYPE html><html> <head> <title> CSS | column-span Property </title> <style> .paragraph { column-count: 3; } h2 { column-span: all; } </style></head> <body> <div class="paragraph "> <h1>Here colspan: all; Inheritance is done in next paragraph </h1> GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks </div> <br> <br> <div class="paragraph "> <h2>Here we used colspan: inherit.;</h2> GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks </div> </body> </html> Output: Supported Browsers: The browser supported by CSS | column-span Property are listed below: Google Chrome 50.0, 4.0 -webkit-Internet Explorer 10.0Opera 37.0, 15.0 -webkit-Safari 9.0, 3.1 -webkit- Google Chrome 50.0, 4.0 -webkit- Internet Explorer 10.0 Opera 37.0, 15.0 -webkit- Safari 9.0, 3.1 -webkit- sweetyty sagartomar9927 ManasChhabra2 CSS-Properties Picked CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? How to update Node.js and NPM to next version ? Types of CSS (Cascading Style Sheet) Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 23237, "s": 23209, "text": "\n06 Sep, 2021" }, { "code": null, "e": 23382, "s": 23237, "text": "The column-span property of CSS sets the number of columns an element can span across. Its value can be none | all | initial | inherit Syntax: " }, { "code": null, "e": 23421, "s": 23382, "text": "column-span: none|all|initial|inherit;" }, { "code": null, "e": 23441, "s": 23421, "text": "Default Value: None" }, { "code": null, "e": 23460, "s": 23441, "text": "Property Values: " }, { "code": null, "e": 23520, "s": 23460, "text": "all: It allows to span in all the columns equally.Syntax: " }, { "code": null, "e": 23539, "s": 23520, "text": " column-span: all;" }, { "code": null, "e": 23550, "s": 23539, "text": "Example: " }, { "code": null, "e": 23555, "s": 23550, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> CSS | column-span Property </title> <style> .paragraph { column-count: 3; } h2 { column-span: all; } </style></head> <body> <div class=\"paragraph \"> <h2> Here we used col-span:all; It had done span across three columns </h2> GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks </div></body></html>", "e": 25666, "s": 23555, "text": null }, { "code": null, "e": 25676, "s": 25666, "text": "Output: " }, { "code": null, "e": 25751, "s": 25676, "text": "none: This value kills the spanning element and sets it to none. Syntax: " }, { "code": null, "e": 25771, "s": 25751, "text": " column-span: none;" }, { "code": null, "e": 25782, "s": 25771, "text": "Example: " }, { "code": null, "e": 25787, "s": 25782, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> CSS | column-span Property </title> <style> .paragraph { column-count: 3; } h2 { column-span: none; } </style></head> <body> <div class=\"paragraph \"> <h2> Here we used col-span:none; It had done span across three columns </h2> GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks </div></body></html>", "e": 27899, "s": 25787, "text": null }, { "code": null, "e": 27909, "s": 27899, "text": "Output: " }, { "code": null, "e": 27984, "s": 27909, "text": "initial: This value makes this property set to its default value.Syntax: " }, { "code": null, "e": 28007, "s": 27984, "text": " column-span: initial;" }, { "code": null, "e": 28018, "s": 28007, "text": "Example: " }, { "code": null, "e": 28023, "s": 28018, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> CSS | column-span Property </title> <style> .paragraph { column-count: 3; } h2 { column-span: initial; } </style></head> <div class=\"paragraph \"> <h2> Here we used col-span:initial; It had done span across three columns </h2> GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks </div></body></html>", "e": 30135, "s": 28023, "text": null }, { "code": null, "e": 30145, "s": 30135, "text": "Output: " }, { "code": null, "e": 30389, "s": 30145, "text": "inherit: The associated element takes the evaluated value of its parent element’s specified column-span property i.e. it will take the inherited property of the parent element. This is not supported by the column-span property of CSS.Syntax: " }, { "code": null, "e": 30412, "s": 30389, "text": " column-span: inherit;" }, { "code": null, "e": 30423, "s": 30412, "text": "Example: " }, { "code": null, "e": 30428, "s": 30423, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> CSS | column-span Property </title> <style> .paragraph { column-count: 3; } h2 { column-span: all; } </style></head> <body> <div class=\"paragraph \"> <h1>Here colspan: all; Inheritance is done in next paragraph </h1> GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks </div> <br> <br> <div class=\"paragraph \"> <h2>Here we used colspan: inherit.;</h2> GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks </div> </body> </html>", "e": 32636, "s": 30428, "text": null }, { "code": null, "e": 32646, "s": 32636, "text": "Output: " }, { "code": null, "e": 32840, "s": 32646, "text": "Supported Browsers: The browser supported by CSS | column-span Property are listed below: Google Chrome 50.0, 4.0 -webkit-Internet Explorer 10.0Opera 37.0, 15.0 -webkit-Safari 9.0, 3.1 -webkit-" }, { "code": null, "e": 32873, "s": 32840, "text": "Google Chrome 50.0, 4.0 -webkit-" }, { "code": null, "e": 32896, "s": 32873, "text": "Internet Explorer 10.0" }, { "code": null, "e": 32922, "s": 32896, "text": "Opera 37.0, 15.0 -webkit-" }, { "code": null, "e": 32947, "s": 32922, "text": "Safari 9.0, 3.1 -webkit-" }, { "code": null, "e": 32956, "s": 32947, "text": "sweetyty" }, { "code": null, "e": 32971, "s": 32956, "text": "sagartomar9927" }, { "code": null, "e": 32985, "s": 32971, "text": "ManasChhabra2" }, { "code": null, "e": 33000, "s": 32985, "text": "CSS-Properties" }, { "code": null, "e": 33007, "s": 33000, "text": "Picked" }, { "code": null, "e": 33011, "s": 33007, "text": "CSS" }, { "code": null, "e": 33028, "s": 33011, "text": "Web Technologies" }, { "code": null, "e": 33126, "s": 33028, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33135, "s": 33126, "text": "Comments" }, { "code": null, "e": 33148, "s": 33135, "text": "Old Comments" }, { "code": null, "e": 33210, "s": 33148, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 33260, "s": 33210, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 33318, "s": 33260, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 33366, "s": 33318, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 33403, "s": 33366, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 33459, "s": 33403, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 33492, "s": 33459, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 33554, "s": 33492, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 33597, "s": 33554, "text": "How to fetch data from an API in ReactJS ?" } ]
Check if a large number is divisible by 11 or not in java
A number is divisible by 11 if the difference between the sum of its alternative digits is divisible by 11. i.e. if (sum of odd digits) – ( sum of even digits) is 0 or divisible by 11 then the given number is divisible by 11. import java.util.Scanner; public class DivisibleBy11 { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter a number :"); String num = sc.nextLine(); int digitSumEve = 0; int digitSumOdd = 0; for(int i = 0; i<num.length(); i++) { if(i%2 == 0) { digitSumEve = digitSumEve + num.charAt(i)-'0'; } else { digitSumOdd = digitSumOdd + num.charAt(i)-'0'; } } int res = digitSumOdd-digitSumEve; if(res % 11 == 0) { System.out.println("Given number is divisible by 11"); } else { System.out.println("Given number is not divisible by 11"); } } } Enter a number : 121 Given number is divisible by 11
[ { "code": null, "e": 1170, "s": 1062, "text": "A number is divisible by 11 if the difference between the sum of its alternative digits is divisible by 11." }, { "code": null, "e": 1288, "s": 1170, "text": "i.e. if (sum of odd digits) – ( sum of even digits) is 0 or divisible by 11 then the given number is divisible by 11." }, { "code": null, "e": 2022, "s": 1288, "text": "import java.util.Scanner;\n\npublic class DivisibleBy11 {\n public static void main(String args[]) {\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter a number :\");\n String num = sc.nextLine();\n int digitSumEve = 0;\n int digitSumOdd = 0;\n \n for(int i = 0; i<num.length(); i++) {\n if(i%2 == 0) {\n digitSumEve = digitSumEve + num.charAt(i)-'0';\n } else {\n digitSumOdd = digitSumOdd + num.charAt(i)-'0';\n }\n }\n int res = digitSumOdd-digitSumEve;\n if(res % 11 == 0) {\n System.out.println(\"Given number is divisible by 11\");\n } else {\n System.out.println(\"Given number is not divisible by 11\");\n }\n }\n}" }, { "code": null, "e": 2075, "s": 2022, "text": "Enter a number :\n121\nGiven number is divisible by 11" } ]
PHP program to calculate the sum of square of first n natural numbers
To calculate the sum of square of first n natural numbers in PHP, the code is as follows − Live Demo <?php function sum_of_squares($limit) { $ini_sum = 0; for ($i = 1; $i <= $limit; $i++) $ini_sum += ($limit * $limit); return $ini_sum; } $limit = 5; print_r("The sum of square of first 5 natural numbers is "); echo sum_of_squares ($limit); ?> The sum of square of first 5 natural numbers is 125 A function named ‘sum_of_squares’ is defined that takes the limit up to which square of natural number needs to be found. In this function, a sum value is initialized to 0. A ‘for’ loop is run over the elements ranging from 1 to the limit. Every time, to the ‘sum’ variable, square of the iterated value is added. When the control reaches the end, the value of sum is returned as the output. Outside the function, a limit value is specified and the function is called by passing the limit value to it.
[ { "code": null, "e": 1153, "s": 1062, "text": "To calculate the sum of square of first n natural numbers in PHP, the code is as follows −" }, { "code": null, "e": 1164, "s": 1153, "text": " Live Demo" }, { "code": null, "e": 1422, "s": 1164, "text": "<?php\nfunction sum_of_squares($limit)\n{\n $ini_sum = 0;\n for ($i = 1; $i <= $limit; $i++)\n $ini_sum += ($limit * $limit);\n return $ini_sum;\n}\n$limit = 5;\nprint_r(\"The sum of square of first 5 natural numbers is \");\necho sum_of_squares ($limit);\n?>" }, { "code": null, "e": 1474, "s": 1422, "text": "The sum of square of first 5 natural numbers is 125" }, { "code": null, "e": 1976, "s": 1474, "text": "A function named ‘sum_of_squares’ is defined that takes the limit up to which square of natural number needs to be found. In this function, a sum value is initialized to 0. A ‘for’ loop is run over the elements ranging from 1 to the limit. Every time, to the ‘sum’ variable, square of the iterated value is\nadded. When the control reaches the end, the value of sum is returned as the output. Outside the function, a limit value is specified and the function is called by passing the limit value to it." } ]
Annotate data points while plotting from Pandas DataFrame
To annotate data points while plotting from pandas data frame, we can take the following steps − Create df using DataFrame with x, y and index keys. Create df using DataFrame with x, y and index keys. Create a figure and a set of subplots using subplots() method. Create a figure and a set of subplots using subplots() method. Plot a series of data frame using plot() method, kind='scatter', ax=ax, c='red' and marker='x'. Plot a series of data frame using plot() method, kind='scatter', ax=ax, c='red' and marker='x'. To annotate the scatter point with the index value, iterate the data frame. To annotate the scatter point with the index value, iterate the data frame. To display the figure, use show() method. To display the figure, use show() method. import numpy as np import pandas as pd from matplotlib import pyplot as plt import string plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True df = pd.DataFrame({'x': np.random.rand(10), 'y': np.random.rand(10)}, index=list(string.ascii_lowercase[:10])) fig, ax = plt.subplots() df.plot('x', 'y', kind='scatter', ax=ax, c='red', marker='x') for k, v in df.iterrows(): ax.annotate(k, v) plt.show()
[ { "code": null, "e": 1159, "s": 1062, "text": "To annotate data points while plotting from pandas data frame, we can take the following steps −" }, { "code": null, "e": 1211, "s": 1159, "text": "Create df using DataFrame with x, y and index keys." }, { "code": null, "e": 1263, "s": 1211, "text": "Create df using DataFrame with x, y and index keys." }, { "code": null, "e": 1326, "s": 1263, "text": "Create a figure and a set of subplots using subplots() method." }, { "code": null, "e": 1389, "s": 1326, "text": "Create a figure and a set of subplots using subplots() method." }, { "code": null, "e": 1485, "s": 1389, "text": "Plot a series of data frame using plot() method, kind='scatter', ax=ax, c='red' and marker='x'." }, { "code": null, "e": 1581, "s": 1485, "text": "Plot a series of data frame using plot() method, kind='scatter', ax=ax, c='red' and marker='x'." }, { "code": null, "e": 1657, "s": 1581, "text": "To annotate the scatter point with the index value, iterate the data frame." }, { "code": null, "e": 1733, "s": 1657, "text": "To annotate the scatter point with the index value, iterate the data frame." }, { "code": null, "e": 1775, "s": 1733, "text": "To display the figure, use show() method." }, { "code": null, "e": 1817, "s": 1775, "text": "To display the figure, use show() method." }, { "code": null, "e": 2251, "s": 1817, "text": "import numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nimport string\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\ndf = pd.DataFrame({'x': np.random.rand(10), 'y': np.random.rand(10)}, index=list(string.ascii_lowercase[:10]))\nfig, ax = plt.subplots()\ndf.plot('x', 'y', kind='scatter', ax=ax, c='red', marker='x')\nfor k, v in df.iterrows():\n ax.annotate(k, v)\nplt.show()" } ]
7 Applications of Auto-Encoders every Data Scientist should know | by Satyam Kumar | Towards Data Science
Auto-Encoders are a popular type of unsupervised artificial neural network that takes un-labeled data and learns efficient codings about the structure of the data that can be used for another context. Auto-Encoders approximates the function that maps the data from full input space to lower dimension coordinates and further approximates to the same dimension of input space with minimum loss. For classification or regression tasks, auto-encoders can be used to extract features from the raw data to improve the robustness of the model. There are various other applications of an Auto-Encoder network, that can be used for some other context. We will 7 of such applications of auto-encoder in this article: Checklist:1) Dimensionality Reduction2) Feature Extraction3) Image Denoising4) Image Compression5) Image Search6) Anomaly Detection7) Missing Value Imputation Before diving into the applications of AutoEncoders, let's discuss briefly what exactly is Auto-Encoder network is. Autoencoder is an unsupervised neural network that tries to reconstruct the output layer as similar as the input layer. An autoencoder architecture has two parts: Encoder: Mapping from Input space to lower dimension space Decoder: Reconstructing from lower dimension space to Output space The autoencoder first compresses the input vector into lower dimensional space then tries to reconstruct the output by minimizing the reconstruction error. The autoencoder tries to reconstruct the output vector as similar as possible to the input layer. There are various types of autoencoders including regularized, concrete, and variational autoencoders. Refer to the Wikipedia page for autoencoders to know more about the variations of autoencoders in detail. Autoencoders train the network to explain the natural structure in the data into efficient lower-dimensional representation. It does this by using decoding and encoding strategy to minimize the reconstruction error. The input and the output dimension have 3000 dimensions, and the desired reduced dimension is 200. We can develop a 5-layer network where the encoder has 3000 and 1500 neurons a similar to the decoder network. The vector embeddings of the compressed input layer can be considered as a reduced dimensional embedding of the input layer. Autoencoders can be used as a feature extractor for classification or regression tasks. Autoencoders take un-labeled data and learn efficient codings about the structure of the data that can be used for supervised learning tasks. After training an autoencoder network using a sample of training data, we can ignore the decoder part of the autoencoder, and only use the encoder to convert raw input data of higher dimension to a lower dimension encoded space. This lower dimension of data can be used as a feature for supervised tasks. Follow my another article to get a step-by-step implementation of autoencoder as a feature extractor: towardsdatascience.com The real-world raw input data is often noisy in nature, and to train a robust supervised model requires cleaned and noiseless data. Autoencoders can be used to denoise the data. Image denoising is one of the popular applications where the autoencoders try to reconstruct the noiseless image from a noisy input image. The noisy input image is fed into the autoencoder as input and the output noiseless output is reconstructed by minimizing the reconstruction loss from the original target output (noiseless). Once the autoencoder weights are trained, they can be further used to denoise the raw image. Image compression is another application of an autoencoder network. The raw input image can be passed to the encoder network and obtained a compressed dimension of encoded data. The autoencoder network weights can be learned by reconstructing the image from the compressed encoding using a decoder network. Usually, autoencoders are not that good for data compression, rather basic compression algorithms work better. Autoencoders can be used to compress the database of images. The compressed embedding can be compared or searched with an encoded version of the search image. Anomaly detection is another useful application of an autoencoder network. An anomaly detection model can be used to detect a fraudulent transaction or any highly imbalanced supervised tasks. The idea is to train autoencoders on only sample data of one class (majority class). This way the network is capable of re-constructing the input with good or less reconstruction loss. Now, if a sample data of another target class is passed through the autoencoder network, it results in comparatively larger reconstruction loss. A threshold value of reconstruction loss (anomaly score) can be decided, larger than that can be considered an anomaly. Denoising autoencoders can be used to impute the missing values in the dataset. The idea is to train an autoencoder network by randomly placing missing values in the input data and trying to reconstruct the original raw data by minimizing the reconstruction loss. Once the autoencoder weights are trained the records having missing values can be passed through the autoencoder network to reconstruct the input data, that too with imputed missing features. In this article, we have discussed a brief overview of various applications of an autoencoder. For image reconstruction, we can use a variation of autoencoder called convolutional autoencoder that minimizes the reconstruction errors by learning the optimal filters. In my upcoming articles, I will implement each of the above-discussed applications. Loved the article? Become a Medium member to continue learning without limits. I’ll receive a small portion of your membership fee if you use the following link, with no extra cost to you. satyam-kumar.medium.com Thank You for Reading
[ { "code": null, "e": 566, "s": 172, "text": "Auto-Encoders are a popular type of unsupervised artificial neural network that takes un-labeled data and learns efficient codings about the structure of the data that can be used for another context. Auto-Encoders approximates the function that maps the data from full input space to lower dimension coordinates and further approximates to the same dimension of input space with minimum loss." }, { "code": null, "e": 880, "s": 566, "text": "For classification or regression tasks, auto-encoders can be used to extract features from the raw data to improve the robustness of the model. There are various other applications of an Auto-Encoder network, that can be used for some other context. We will 7 of such applications of auto-encoder in this article:" }, { "code": null, "e": 1039, "s": 880, "text": "Checklist:1) Dimensionality Reduction2) Feature Extraction3) Image Denoising4) Image Compression5) Image Search6) Anomaly Detection7) Missing Value Imputation" }, { "code": null, "e": 1155, "s": 1039, "text": "Before diving into the applications of AutoEncoders, let's discuss briefly what exactly is Auto-Encoder network is." }, { "code": null, "e": 1318, "s": 1155, "text": "Autoencoder is an unsupervised neural network that tries to reconstruct the output layer as similar as the input layer. An autoencoder architecture has two parts:" }, { "code": null, "e": 1377, "s": 1318, "text": "Encoder: Mapping from Input space to lower dimension space" }, { "code": null, "e": 1444, "s": 1377, "text": "Decoder: Reconstructing from lower dimension space to Output space" }, { "code": null, "e": 1698, "s": 1444, "text": "The autoencoder first compresses the input vector into lower dimensional space then tries to reconstruct the output by minimizing the reconstruction error. The autoencoder tries to reconstruct the output vector as similar as possible to the input layer." }, { "code": null, "e": 1907, "s": 1698, "text": "There are various types of autoencoders including regularized, concrete, and variational autoencoders. Refer to the Wikipedia page for autoencoders to know more about the variations of autoencoders in detail." }, { "code": null, "e": 2123, "s": 1907, "text": "Autoencoders train the network to explain the natural structure in the data into efficient lower-dimensional representation. It does this by using decoding and encoding strategy to minimize the reconstruction error." }, { "code": null, "e": 2333, "s": 2123, "text": "The input and the output dimension have 3000 dimensions, and the desired reduced dimension is 200. We can develop a 5-layer network where the encoder has 3000 and 1500 neurons a similar to the decoder network." }, { "code": null, "e": 2458, "s": 2333, "text": "The vector embeddings of the compressed input layer can be considered as a reduced dimensional embedding of the input layer." }, { "code": null, "e": 2688, "s": 2458, "text": "Autoencoders can be used as a feature extractor for classification or regression tasks. Autoencoders take un-labeled data and learn efficient codings about the structure of the data that can be used for supervised learning tasks." }, { "code": null, "e": 2993, "s": 2688, "text": "After training an autoencoder network using a sample of training data, we can ignore the decoder part of the autoencoder, and only use the encoder to convert raw input data of higher dimension to a lower dimension encoded space. This lower dimension of data can be used as a feature for supervised tasks." }, { "code": null, "e": 3095, "s": 2993, "text": "Follow my another article to get a step-by-step implementation of autoencoder as a feature extractor:" }, { "code": null, "e": 3118, "s": 3095, "text": "towardsdatascience.com" }, { "code": null, "e": 3296, "s": 3118, "text": "The real-world raw input data is often noisy in nature, and to train a robust supervised model requires cleaned and noiseless data. Autoencoders can be used to denoise the data." }, { "code": null, "e": 3435, "s": 3296, "text": "Image denoising is one of the popular applications where the autoencoders try to reconstruct the noiseless image from a noisy input image." }, { "code": null, "e": 3719, "s": 3435, "text": "The noisy input image is fed into the autoencoder as input and the output noiseless output is reconstructed by minimizing the reconstruction loss from the original target output (noiseless). Once the autoencoder weights are trained, they can be further used to denoise the raw image." }, { "code": null, "e": 4026, "s": 3719, "text": "Image compression is another application of an autoencoder network. The raw input image can be passed to the encoder network and obtained a compressed dimension of encoded data. The autoencoder network weights can be learned by reconstructing the image from the compressed encoding using a decoder network." }, { "code": null, "e": 4137, "s": 4026, "text": "Usually, autoencoders are not that good for data compression, rather basic compression algorithms work better." }, { "code": null, "e": 4296, "s": 4137, "text": "Autoencoders can be used to compress the database of images. The compressed embedding can be compared or searched with an encoded version of the search image." }, { "code": null, "e": 4488, "s": 4296, "text": "Anomaly detection is another useful application of an autoencoder network. An anomaly detection model can be used to detect a fraudulent transaction or any highly imbalanced supervised tasks." }, { "code": null, "e": 4818, "s": 4488, "text": "The idea is to train autoencoders on only sample data of one class (majority class). This way the network is capable of re-constructing the input with good or less reconstruction loss. Now, if a sample data of another target class is passed through the autoencoder network, it results in comparatively larger reconstruction loss." }, { "code": null, "e": 4938, "s": 4818, "text": "A threshold value of reconstruction loss (anomaly score) can be decided, larger than that can be considered an anomaly." }, { "code": null, "e": 5202, "s": 4938, "text": "Denoising autoencoders can be used to impute the missing values in the dataset. The idea is to train an autoencoder network by randomly placing missing values in the input data and trying to reconstruct the original raw data by minimizing the reconstruction loss." }, { "code": null, "e": 5394, "s": 5202, "text": "Once the autoencoder weights are trained the records having missing values can be passed through the autoencoder network to reconstruct the input data, that too with imputed missing features." }, { "code": null, "e": 5660, "s": 5394, "text": "In this article, we have discussed a brief overview of various applications of an autoencoder. For image reconstruction, we can use a variation of autoencoder called convolutional autoencoder that minimizes the reconstruction errors by learning the optimal filters." }, { "code": null, "e": 5744, "s": 5660, "text": "In my upcoming articles, I will implement each of the above-discussed applications." }, { "code": null, "e": 5933, "s": 5744, "text": "Loved the article? Become a Medium member to continue learning without limits. I’ll receive a small portion of your membership fee if you use the following link, with no extra cost to you." }, { "code": null, "e": 5957, "s": 5933, "text": "satyam-kumar.medium.com" } ]
Get distinct values from a column in MongoDB?
To get distinct values from a column, use distinct() in MongoDB. Let us first create a collection with documents − > db.demo128.insertOne({"Name":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e30583d68e7f832db1a7f5d") } > db.demo128.insertOne({"Name":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5e30584068e7f832db1a7f5e") } > db.demo128.insertOne({"Name":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5e30584368e7f832db1a7f5f") } > db.demo128.insertOne({"Name":"Bob"}); { "acknowledged" : true, "insertedId" : ObjectId("5e30584668e7f832db1a7f60") } > db.demo128.insertOne({"Name":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e30584c68e7f832db1a7f61") } Display all documents from a collection with the help of find() method − > db.demo128.find(); This will produce the following output − { "_id" : ObjectId("5e30583d68e7f832db1a7f5d"), "Name" : "Chris" } { "_id" : ObjectId("5e30584068e7f832db1a7f5e"), "Name" : "David" } { "_id" : ObjectId("5e30584368e7f832db1a7f5f"), "Name" : "David" } { "_id" : ObjectId("5e30584668e7f832db1a7f60"), "Name" : "Bob" } { "_id" : ObjectId("5e30584c68e7f832db1a7f61"), "Name" : "Chris" } Following is the query to get distinct values from a column in MongoDB − > db.demo128.distinct("Name"); This will produce the following output − [ "Chris", "David", "Bob" ]
[ { "code": null, "e": 1177, "s": 1062, "text": "To get distinct values from a column, use distinct() in MongoDB. Let us first create a collection with documents −" }, { "code": null, "e": 1810, "s": 1177, "text": "> db.demo128.insertOne({\"Name\":\"Chris\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e30583d68e7f832db1a7f5d\")\n}\n> db.demo128.insertOne({\"Name\":\"David\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e30584068e7f832db1a7f5e\")\n}\n> db.demo128.insertOne({\"Name\":\"David\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e30584368e7f832db1a7f5f\")\n}\n> db.demo128.insertOne({\"Name\":\"Bob\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e30584668e7f832db1a7f60\")\n}\n> db.demo128.insertOne({\"Name\":\"Chris\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e30584c68e7f832db1a7f61\")\n}" }, { "code": null, "e": 1883, "s": 1810, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1904, "s": 1883, "text": "> db.demo128.find();" }, { "code": null, "e": 1945, "s": 1904, "text": "This will produce the following output −" }, { "code": null, "e": 2278, "s": 1945, "text": "{ \"_id\" : ObjectId(\"5e30583d68e7f832db1a7f5d\"), \"Name\" : \"Chris\" }\n{ \"_id\" : ObjectId(\"5e30584068e7f832db1a7f5e\"), \"Name\" : \"David\" }\n{ \"_id\" : ObjectId(\"5e30584368e7f832db1a7f5f\"), \"Name\" : \"David\" }\n{ \"_id\" : ObjectId(\"5e30584668e7f832db1a7f60\"), \"Name\" : \"Bob\" }\n{ \"_id\" : ObjectId(\"5e30584c68e7f832db1a7f61\"), \"Name\" : \"Chris\" }" }, { "code": null, "e": 2351, "s": 2278, "text": "Following is the query to get distinct values from a column in MongoDB −" }, { "code": null, "e": 2382, "s": 2351, "text": "> db.demo128.distinct(\"Name\");" }, { "code": null, "e": 2423, "s": 2382, "text": "This will produce the following output −" }, { "code": null, "e": 2451, "s": 2423, "text": "[ \"Chris\", \"David\", \"Bob\" ]" } ]
Sum of array using pointer arithmetic in C
In this program, we need to find sum of array elements using pointer arithmetic. Here we use * which denotes the value stored at the memory address and this address will remain stored in the variable. Thus “int *ptr” means, ptr is a variable which contains an address and content of the address is an integer quantity. *p means it is a pointer variable. Using this and sum() we will find out sum of the elements of array. #include <stdio.h> void s(int* a, int len) { int i, s_of_arr = 0; for (i = 0; i < len; i++) s_of_arr = s_of_arr + *(a + i); printf( "sum of array is = %d" ,s_of_arr); } int main() { int arr[] = { 1,2,4,6,7,-5,-3 }; s(arr, 7); return 0; } Sum of array = 12 Begin Initialize array to hold the variables. Call function s to get the sum of the variables. Print the sum. End.
[ { "code": null, "e": 1143, "s": 1062, "text": "In this program, we need to find sum of array elements using pointer arithmetic." }, { "code": null, "e": 1381, "s": 1143, "text": "Here we use * which denotes the value stored at the memory address and this address will remain stored in the variable. Thus “int *ptr” means, ptr is a variable which contains an address and content of the address is an integer quantity." }, { "code": null, "e": 1484, "s": 1381, "text": "*p means it is a pointer variable. Using this and sum() we will find out sum of the elements of array." }, { "code": null, "e": 1746, "s": 1484, "text": "#include <stdio.h>\nvoid s(int* a, int len) {\n int i, s_of_arr = 0;\n for (i = 0; i < len; i++)\n s_of_arr = s_of_arr + *(a + i);\n printf( \"sum of array is = %d\" ,s_of_arr);\n}\nint main() {\n int arr[] = { 1,2,4,6,7,-5,-3 };\n s(arr, 7);\n return 0;\n}" }, { "code": null, "e": 1764, "s": 1746, "text": "Sum of array = 12" }, { "code": null, "e": 1888, "s": 1764, "text": "Begin\n Initialize array to hold the variables.\n Call function s to get the sum of the variables.\n Print the sum.\nEnd." } ]
Principal Component Analysis for Dimensionality Reduction | by Lorraine Li | Towards Data Science
In the modern age of technology, increasing amounts of data are produced and collected. In machine learning, however, too much data can be a bad thing. At a certain point, more features or dimensions can decrease a model’s accuracy since there is more data that needs to be generalized — this is known as the curse of dimensionality. Dimensionality reduction is way to reduce the complexity of a model and avoid overfitting. There are two main categories of dimensionality reduction: feature selection and feature extraction. Via feature selection, we select a subset of the original features, whereas in feature extraction, we derive information from the feature set to construct a new feature subspace. In this tutorial we will explore feature extraction. In practice, feature extraction is not only used to improve storage space or the computational efficiency of the learning algorithm, but can also improve the predictive performance by reducing the curse of dimensionality — especially if we are working with non-regularized models. Specifically, we will discuss the Principal Component Analysis (PCA) algorithm used to compress a dataset onto a lower-dimensional feature subspace with the goal of maintaining most of the relevant information. We will explore: The concepts and mathematics behind PCA How to execute PCA step-by-step from scratch using Python How to execute PCA using the Python library scikit-learn Let’s get started! This tutorial is adapted from Part 2 of Next Tech’s Python Machine Learning series, which takes you through machine learning and deep learning algorithms with Python from 0 to 100. It includes an in-browser sandboxed environment with all the necessary software and libraries pre-installed, and projects using public datasets. You can get started for free here! Principal Component Analysis (PCA) is an unsupervised linear transformation technique that is widely used across different fields, most prominently for feature extraction and dimensionality reduction. Other popular applications of PCA include exploratory data analyses and de-noising of signals in stock market trading, and the analysis of genome data and gene expression levels in the field of bioinformatics. PCA helps us to identify patterns in data based on the correlation between features. In a nutshell, PCA aims to find the directions of maximum variance in high-dimensional data and projects it onto a new subspace with equal or fewer dimensions than the original one. The orthogonal axes (principal components) of the new subspace can be interpreted as the directions of maximum variance given the constraint that the new feature axes are orthogonal to each other, as illustrated in the following figure: In the preceding figure, x1 and x2 are the original feature axes, and PC1 and PC2 are the principal components. If we use PCA for dimensionality reduction, we construct a d x k–dimensional transformation matrix W that allows us to map a sample vector x onto a new k–dimensional feature subspace that has fewer dimensions than the original d–dimensional feature space: As a result of transforming the original d-dimensional data onto this new k-dimensional subspace (typically k ≪ d), the first principal component will have the largest possible variance, and all consequent principal components will have the largest variance given the constraint that these components are uncorrelated (orthogonal) to the other principal components — even if the input features are correlated, the resulting principal components will be mutually orthogonal (uncorrelated). Note that the PCA directions are highly sensitive to data scaling, and we need to standardize the features prior to PCA if the features were measured on different scales and we want to assign equal importance to all features. Before looking at the PCA algorithm for dimensionality reduction in more detail, let’s summarize the approach in a few simple steps: Standardize the d-dimensional dataset.Construct the covariance matrix.Decompose the covariance matrix into its eigenvectors and eigenvalues.Sort the eigenvalues by decreasing order to rank the corresponding eigenvectors.Select k eigenvectors which correspond to the k largest eigenvalues, where k is the dimensionality of the new feature subspace (k ≤ d).Construct a projection matrix W from the “top” k eigenvectors.Transform the d-dimensional input dataset X using the projection matrix W to obtain the new k-dimensional feature subspace. Standardize the d-dimensional dataset. Construct the covariance matrix. Decompose the covariance matrix into its eigenvectors and eigenvalues. Sort the eigenvalues by decreasing order to rank the corresponding eigenvectors. Select k eigenvectors which correspond to the k largest eigenvalues, where k is the dimensionality of the new feature subspace (k ≤ d). Construct a projection matrix W from the “top” k eigenvectors. Transform the d-dimensional input dataset X using the projection matrix W to obtain the new k-dimensional feature subspace. Let’s perform a PCA step by step, using Python as a learning exercise. Then, we will see how to perform a PCA more conveniently using scikit-learn. We will be using the Wine dataset from The UCI Machine Learning Repository in our example. This dataset consists of 178 wine samples with 13 features describing their different chemical properties. You can find out more here. In this section we will tackle the first four steps of a PCA; later we will go over the last three. You can follow along with the code in this tutorial by using a Next Tech sandbox, which has all the necessary libraries pre-installed, or if you’d prefer, you can run the snippets in your own local environment. Once your sandbox loads, we will start by loading the Wine dataset directly from the repository: Next, we will process the Wine data into separate training and test sets — using a 70:30 split — and standardize it to unit variance: After completing the mandatory preprocessing, let’s advance to the second step: constructing the covariance matrix. The symmetric d x d-dimensional covariance matrix, where d is the number of dimensions in the dataset, stores the pairwise covariances between the different features. For example, the covariance between two features x_j and x_k on the population level can be calculated via the following equation: Here, μ_j and μ_k are the sample means of features j and k, respectively. Note that the sample means are zero if we standardized the dataset. A positive covariance between two features indicates that the features increase or decrease together, whereas a negative covariance indicates that the features vary in opposite directions. For example, the covariance matrix of three features can then be written as follows (note that Σ stands for the Greek uppercase letter sigma, which is not to be confused with the sum symbol): The eigenvectors of the covariance matrix represent the principal components (the directions of maximum variance), whereas the corresponding eigenvalues will define their magnitude. In the case of the Wine dataset, we would obtain 13 eigenvectors and eigenvalues from the 13 x 13-dimensional covariance matrix. Now, for our third step, let’s obtain the eigenpairs of the covariance matrix. An eigenvector v satisfies the following condition: Here, λ is a scalar: the eigenvalue. Since the manual computation of eigenvectors and eigenvalues is a somewhat tedious and elaborate task, we will use the linalg.eig function from NumPy to obtain the eigenpairs of the Wine covariance matrix: Using the numpy.cov function, we computed the covariance matrix of the standardized training dataset. Using the linalg.eig function, we performed the eigendecomposition, which yielded a vector (eigen_vals) consisting of 13 eigenvalues and the corresponding eigenvectors stored as columns in a 13 x 13-dimensional matrix (eigen_vecs). Since we want to reduce the dimensionality of our dataset by compressing it onto a new feature subspace, we only select the subset of the eigenvectors (principal components) that contains most of the information (variance). The eigenvalues define the magnitude of the eigenvectors, so we have to sort the eigenvalues by decreasing magnitude; we are interested in the top k eigenvectors based on the values of their corresponding eigenvalues. But before we collect those k most informative eigenvectors, let’s plot the variance explained ratios of the eigenvalues. The variance explained ratio of an eigenvalue λ_j is simply the fraction of an eigenvalue λ_j and the total sum of the eigenvalues: Using the NumPy cumsum function, we can then calculate the cumulative sum of explained variances, which we will then plot via matplotlib’s step function: The resulting plot indicates that the first principal component alone accounts for approximately 40% of the variance. Also, we can see that the first two principal components combined explain almost 60% of the variance in the dataset. After we have successfully decomposed the covariance matrix into eigenpairs, let’s now proceed with the last three steps of PCA to transform the Wine dataset onto the new principal component axes. We will sort the eigenpairs by descending order of the eigenvalues, construct a projection matrix from the selected eigenvectors, and use the projection matrix to transform the data onto the lower-dimensional subspace. We start by sorting the eigenpairs by decreasing order of the eigenvalues: Next, we collect the two eigenvectors that correspond to the two largest eigenvalues, to capture about 60% of the variance in this dataset. Note that we only chose two eigenvectors for the purpose of illustration, since we are going to plot the data via a two-dimensional scatter plot later in this subsection. In practice, the number of principal components has to be determined by a trade-off between computational efficiency and the performance of the classifier: [Out:]Matrix W: [[-0.13724218 0.50303478] [ 0.24724326 0.16487119] [-0.02545159 0.24456476] [ 0.20694508 -0.11352904] [-0.15436582 0.28974518] [-0.39376952 0.05080104] [-0.41735106 -0.02287338] [ 0.30572896 0.09048885] [-0.30668347 0.00835233] [ 0.07554066 0.54977581] [-0.32613263 -0.20716433] [-0.36861022 -0.24902536] [-0.29669651 0.38022942]] By executing the preceding code, we have created a 13 x 2-dimensional projection matrix W from the top two eigenvectors. Using the projection matrix, we can now transform a sample x (represented as a 1 x 13-dimensional row vector) onto the PCA subspace (the principal components one and two) obtaining x′, now a two-dimensional sample vector consisting of two new features: Similarly, we can transform the entire 124 x 13-dimensional training dataset onto the two principal components by calculating the matrix dot product: Lastly, let’s visualize the transformed Wine training set, now stored as an 124 x 2-dimensional matrix, in a two-dimensional scatterplot: As we can see in the resulting plot, the data is more spread along the x-axis — the first principal component — than the second principal component (y-axis), which is consistent with the explained variance ratio plot that we created previously. However, we can intuitively see that a linear classifier will likely be able to separate the classes well. Although we encoded the class label information for the purpose of illustration in the preceding scatter plot, we have to keep in mind that PCA is an unsupervised technique that does not use any class label information. Although the verbose approach in the previous subsection helped us to follow the inner workings of PCA, we will now discuss how to use the PCA class implemented in scikit-learn. The PCA class is another one of scikit-learn’s transformer classes, where we first fit the model using the training data before we transform both the training data and the test dataset using the same model parameters. Let’s use the PCA class on the Wine training dataset, classify the transformed samples via logistic regression: Now, using a custom plot_decision_regions function, we will visualize the decision regions: By executing the preceding code, we should now see the decision regions for the training data reduced to two principal component axes. For the sake of completeness, let’s plot the decision regions of the logistic regression on the transformed test dataset as well to see if it can separate the classes well: After we plotted the decision regions for the test set by executing the preceding code, we can see that logistic regression performs quite well on this small two-dimensional feature subspace and only misclassifies very few samples in the test dataset. If we are interested in the explained variance ratios of the different principal components, we can simply initialize the PCA class with the n_components parameter set to None, so all principal components are kept and the explained variance ratio can then be accessed via the explained_variance_ratio_ attribute: Note that we set n_components=None when we initialized the PCA class so that it will return all principal components in a sorted order instead of performing a dimensionality reduction. I hope you enjoyed this tutorial on principal component analysis for dimensionality reduction! We covered the mathematics behind the PCA algorithm, how to perform PCA step-by-step with Python, and how to implement PCA using scikit-learn. Other techniques for dimensionality reduction are Linear Discriminant Analysis (LDA) and Kernel PCA (used for non-linearly separable data). These other techniques and more topics to improve model performance, such as data preprocessing, model evaluation, hyperparameter tuning, and ensemble learning techniques are covered in Next Tech’s Python Machine Learning (Part 2) course. You can get started here for free!
[ { "code": null, "e": 381, "s": 47, "text": "In the modern age of technology, increasing amounts of data are produced and collected. In machine learning, however, too much data can be a bad thing. At a certain point, more features or dimensions can decrease a model’s accuracy since there is more data that needs to be generalized — this is known as the curse of dimensionality." }, { "code": null, "e": 752, "s": 381, "text": "Dimensionality reduction is way to reduce the complexity of a model and avoid overfitting. There are two main categories of dimensionality reduction: feature selection and feature extraction. Via feature selection, we select a subset of the original features, whereas in feature extraction, we derive information from the feature set to construct a new feature subspace." }, { "code": null, "e": 1086, "s": 752, "text": "In this tutorial we will explore feature extraction. In practice, feature extraction is not only used to improve storage space or the computational efficiency of the learning algorithm, but can also improve the predictive performance by reducing the curse of dimensionality — especially if we are working with non-regularized models." }, { "code": null, "e": 1314, "s": 1086, "text": "Specifically, we will discuss the Principal Component Analysis (PCA) algorithm used to compress a dataset onto a lower-dimensional feature subspace with the goal of maintaining most of the relevant information. We will explore:" }, { "code": null, "e": 1354, "s": 1314, "text": "The concepts and mathematics behind PCA" }, { "code": null, "e": 1412, "s": 1354, "text": "How to execute PCA step-by-step from scratch using Python" }, { "code": null, "e": 1469, "s": 1412, "text": "How to execute PCA using the Python library scikit-learn" }, { "code": null, "e": 1488, "s": 1469, "text": "Let’s get started!" }, { "code": null, "e": 1849, "s": 1488, "text": "This tutorial is adapted from Part 2 of Next Tech’s Python Machine Learning series, which takes you through machine learning and deep learning algorithms with Python from 0 to 100. It includes an in-browser sandboxed environment with all the necessary software and libraries pre-installed, and projects using public datasets. You can get started for free here!" }, { "code": null, "e": 2260, "s": 1849, "text": "Principal Component Analysis (PCA) is an unsupervised linear transformation technique that is widely used across different fields, most prominently for feature extraction and dimensionality reduction. Other popular applications of PCA include exploratory data analyses and de-noising of signals in stock market trading, and the analysis of genome data and gene expression levels in the field of bioinformatics." }, { "code": null, "e": 2527, "s": 2260, "text": "PCA helps us to identify patterns in data based on the correlation between features. In a nutshell, PCA aims to find the directions of maximum variance in high-dimensional data and projects it onto a new subspace with equal or fewer dimensions than the original one." }, { "code": null, "e": 2764, "s": 2527, "text": "The orthogonal axes (principal components) of the new subspace can be interpreted as the directions of maximum variance given the constraint that the new feature axes are orthogonal to each other, as illustrated in the following figure:" }, { "code": null, "e": 2876, "s": 2764, "text": "In the preceding figure, x1 and x2 are the original feature axes, and PC1 and PC2 are the principal components." }, { "code": null, "e": 3132, "s": 2876, "text": "If we use PCA for dimensionality reduction, we construct a d x k–dimensional transformation matrix W that allows us to map a sample vector x onto a new k–dimensional feature subspace that has fewer dimensions than the original d–dimensional feature space:" }, { "code": null, "e": 3621, "s": 3132, "text": "As a result of transforming the original d-dimensional data onto this new k-dimensional subspace (typically k ≪ d), the first principal component will have the largest possible variance, and all consequent principal components will have the largest variance given the constraint that these components are uncorrelated (orthogonal) to the other principal components — even if the input features are correlated, the resulting principal components will be mutually orthogonal (uncorrelated)." }, { "code": null, "e": 3847, "s": 3621, "text": "Note that the PCA directions are highly sensitive to data scaling, and we need to standardize the features prior to PCA if the features were measured on different scales and we want to assign equal importance to all features." }, { "code": null, "e": 3980, "s": 3847, "text": "Before looking at the PCA algorithm for dimensionality reduction in more detail, let’s summarize the approach in a few simple steps:" }, { "code": null, "e": 4521, "s": 3980, "text": "Standardize the d-dimensional dataset.Construct the covariance matrix.Decompose the covariance matrix into its eigenvectors and eigenvalues.Sort the eigenvalues by decreasing order to rank the corresponding eigenvectors.Select k eigenvectors which correspond to the k largest eigenvalues, where k is the dimensionality of the new feature subspace (k ≤ d).Construct a projection matrix W from the “top” k eigenvectors.Transform the d-dimensional input dataset X using the projection matrix W to obtain the new k-dimensional feature subspace." }, { "code": null, "e": 4560, "s": 4521, "text": "Standardize the d-dimensional dataset." }, { "code": null, "e": 4593, "s": 4560, "text": "Construct the covariance matrix." }, { "code": null, "e": 4664, "s": 4593, "text": "Decompose the covariance matrix into its eigenvectors and eigenvalues." }, { "code": null, "e": 4745, "s": 4664, "text": "Sort the eigenvalues by decreasing order to rank the corresponding eigenvectors." }, { "code": null, "e": 4881, "s": 4745, "text": "Select k eigenvectors which correspond to the k largest eigenvalues, where k is the dimensionality of the new feature subspace (k ≤ d)." }, { "code": null, "e": 4944, "s": 4881, "text": "Construct a projection matrix W from the “top” k eigenvectors." }, { "code": null, "e": 5068, "s": 4944, "text": "Transform the d-dimensional input dataset X using the projection matrix W to obtain the new k-dimensional feature subspace." }, { "code": null, "e": 5216, "s": 5068, "text": "Let’s perform a PCA step by step, using Python as a learning exercise. Then, we will see how to perform a PCA more conveniently using scikit-learn." }, { "code": null, "e": 5442, "s": 5216, "text": "We will be using the Wine dataset from The UCI Machine Learning Repository in our example. This dataset consists of 178 wine samples with 13 features describing their different chemical properties. You can find out more here." }, { "code": null, "e": 5753, "s": 5442, "text": "In this section we will tackle the first four steps of a PCA; later we will go over the last three. You can follow along with the code in this tutorial by using a Next Tech sandbox, which has all the necessary libraries pre-installed, or if you’d prefer, you can run the snippets in your own local environment." }, { "code": null, "e": 5850, "s": 5753, "text": "Once your sandbox loads, we will start by loading the Wine dataset directly from the repository:" }, { "code": null, "e": 5984, "s": 5850, "text": "Next, we will process the Wine data into separate training and test sets — using a 70:30 split — and standardize it to unit variance:" }, { "code": null, "e": 6398, "s": 5984, "text": "After completing the mandatory preprocessing, let’s advance to the second step: constructing the covariance matrix. The symmetric d x d-dimensional covariance matrix, where d is the number of dimensions in the dataset, stores the pairwise covariances between the different features. For example, the covariance between two features x_j and x_k on the population level can be calculated via the following equation:" }, { "code": null, "e": 6472, "s": 6398, "text": "Here, μ_j and μ_k are the sample means of features j and k, respectively." }, { "code": null, "e": 6921, "s": 6472, "text": "Note that the sample means are zero if we standardized the dataset. A positive covariance between two features indicates that the features increase or decrease together, whereas a negative covariance indicates that the features vary in opposite directions. For example, the covariance matrix of three features can then be written as follows (note that Σ stands for the Greek uppercase letter sigma, which is not to be confused with the sum symbol):" }, { "code": null, "e": 7232, "s": 6921, "text": "The eigenvectors of the covariance matrix represent the principal components (the directions of maximum variance), whereas the corresponding eigenvalues will define their magnitude. In the case of the Wine dataset, we would obtain 13 eigenvectors and eigenvalues from the 13 x 13-dimensional covariance matrix." }, { "code": null, "e": 7363, "s": 7232, "text": "Now, for our third step, let’s obtain the eigenpairs of the covariance matrix. An eigenvector v satisfies the following condition:" }, { "code": null, "e": 7606, "s": 7363, "text": "Here, λ is a scalar: the eigenvalue. Since the manual computation of eigenvectors and eigenvalues is a somewhat tedious and elaborate task, we will use the linalg.eig function from NumPy to obtain the eigenpairs of the Wine covariance matrix:" }, { "code": null, "e": 7940, "s": 7606, "text": "Using the numpy.cov function, we computed the covariance matrix of the standardized training dataset. Using the linalg.eig function, we performed the eigendecomposition, which yielded a vector (eigen_vals) consisting of 13 eigenvalues and the corresponding eigenvectors stored as columns in a 13 x 13-dimensional matrix (eigen_vecs)." }, { "code": null, "e": 8382, "s": 7940, "text": "Since we want to reduce the dimensionality of our dataset by compressing it onto a new feature subspace, we only select the subset of the eigenvectors (principal components) that contains most of the information (variance). The eigenvalues define the magnitude of the eigenvectors, so we have to sort the eigenvalues by decreasing magnitude; we are interested in the top k eigenvectors based on the values of their corresponding eigenvalues." }, { "code": null, "e": 8636, "s": 8382, "text": "But before we collect those k most informative eigenvectors, let’s plot the variance explained ratios of the eigenvalues. The variance explained ratio of an eigenvalue λ_j is simply the fraction of an eigenvalue λ_j and the total sum of the eigenvalues:" }, { "code": null, "e": 8790, "s": 8636, "text": "Using the NumPy cumsum function, we can then calculate the cumulative sum of explained variances, which we will then plot via matplotlib’s step function:" }, { "code": null, "e": 9025, "s": 8790, "text": "The resulting plot indicates that the first principal component alone accounts for approximately 40% of the variance. Also, we can see that the first two principal components combined explain almost 60% of the variance in the dataset." }, { "code": null, "e": 9222, "s": 9025, "text": "After we have successfully decomposed the covariance matrix into eigenpairs, let’s now proceed with the last three steps of PCA to transform the Wine dataset onto the new principal component axes." }, { "code": null, "e": 9441, "s": 9222, "text": "We will sort the eigenpairs by descending order of the eigenvalues, construct a projection matrix from the selected eigenvectors, and use the projection matrix to transform the data onto the lower-dimensional subspace." }, { "code": null, "e": 9516, "s": 9441, "text": "We start by sorting the eigenpairs by decreasing order of the eigenvalues:" }, { "code": null, "e": 9983, "s": 9516, "text": "Next, we collect the two eigenvectors that correspond to the two largest eigenvalues, to capture about 60% of the variance in this dataset. Note that we only chose two eigenvectors for the purpose of illustration, since we are going to plot the data via a two-dimensional scatter plot later in this subsection. In practice, the number of principal components has to be determined by a trade-off between computational efficiency and the performance of the classifier:" }, { "code": null, "e": 10339, "s": 9983, "text": "[Out:]Matrix W: [[-0.13724218 0.50303478] [ 0.24724326 0.16487119] [-0.02545159 0.24456476] [ 0.20694508 -0.11352904] [-0.15436582 0.28974518] [-0.39376952 0.05080104] [-0.41735106 -0.02287338] [ 0.30572896 0.09048885] [-0.30668347 0.00835233] [ 0.07554066 0.54977581] [-0.32613263 -0.20716433] [-0.36861022 -0.24902536] [-0.29669651 0.38022942]]" }, { "code": null, "e": 10460, "s": 10339, "text": "By executing the preceding code, we have created a 13 x 2-dimensional projection matrix W from the top two eigenvectors." }, { "code": null, "e": 10713, "s": 10460, "text": "Using the projection matrix, we can now transform a sample x (represented as a 1 x 13-dimensional row vector) onto the PCA subspace (the principal components one and two) obtaining x′, now a two-dimensional sample vector consisting of two new features:" }, { "code": null, "e": 10863, "s": 10713, "text": "Similarly, we can transform the entire 124 x 13-dimensional training dataset onto the two principal components by calculating the matrix dot product:" }, { "code": null, "e": 11001, "s": 10863, "text": "Lastly, let’s visualize the transformed Wine training set, now stored as an 124 x 2-dimensional matrix, in a two-dimensional scatterplot:" }, { "code": null, "e": 11353, "s": 11001, "text": "As we can see in the resulting plot, the data is more spread along the x-axis — the first principal component — than the second principal component (y-axis), which is consistent with the explained variance ratio plot that we created previously. However, we can intuitively see that a linear classifier will likely be able to separate the classes well." }, { "code": null, "e": 11573, "s": 11353, "text": "Although we encoded the class label information for the purpose of illustration in the preceding scatter plot, we have to keep in mind that PCA is an unsupervised technique that does not use any class label information." }, { "code": null, "e": 11969, "s": 11573, "text": "Although the verbose approach in the previous subsection helped us to follow the inner workings of PCA, we will now discuss how to use the PCA class implemented in scikit-learn. The PCA class is another one of scikit-learn’s transformer classes, where we first fit the model using the training data before we transform both the training data and the test dataset using the same model parameters." }, { "code": null, "e": 12081, "s": 11969, "text": "Let’s use the PCA class on the Wine training dataset, classify the transformed samples via logistic regression:" }, { "code": null, "e": 12173, "s": 12081, "text": "Now, using a custom plot_decision_regions function, we will visualize the decision regions:" }, { "code": null, "e": 12308, "s": 12173, "text": "By executing the preceding code, we should now see the decision regions for the training data reduced to two principal component axes." }, { "code": null, "e": 12481, "s": 12308, "text": "For the sake of completeness, let’s plot the decision regions of the logistic regression on the transformed test dataset as well to see if it can separate the classes well:" }, { "code": null, "e": 12733, "s": 12481, "text": "After we plotted the decision regions for the test set by executing the preceding code, we can see that logistic regression performs quite well on this small two-dimensional feature subspace and only misclassifies very few samples in the test dataset." }, { "code": null, "e": 13046, "s": 12733, "text": "If we are interested in the explained variance ratios of the different principal components, we can simply initialize the PCA class with the n_components parameter set to None, so all principal components are kept and the explained variance ratio can then be accessed via the explained_variance_ratio_ attribute:" }, { "code": null, "e": 13231, "s": 13046, "text": "Note that we set n_components=None when we initialized the PCA class so that it will return all principal components in a sorted order instead of performing a dimensionality reduction." }, { "code": null, "e": 13609, "s": 13231, "text": "I hope you enjoyed this tutorial on principal component analysis for dimensionality reduction! We covered the mathematics behind the PCA algorithm, how to perform PCA step-by-step with Python, and how to implement PCA using scikit-learn. Other techniques for dimensionality reduction are Linear Discriminant Analysis (LDA) and Kernel PCA (used for non-linearly separable data)." }, { "code": null, "e": 13848, "s": 13609, "text": "These other techniques and more topics to improve model performance, such as data preprocessing, model evaluation, hyperparameter tuning, and ensemble learning techniques are covered in Next Tech’s Python Machine Learning (Part 2) course." } ]
JavaScript | array.values() - GeeksforGeeks
18 Nov, 2021 The array.values() function is an inbuilt function in JavaScript which is used to returns a new array Iterator object that contains the values for each index in the array i.e, it prints all the elements of the array. Syntax: arr.values() Return values: It returns a new array iterator object i.e, elements of the given array. Examples: Input: A = ['a', 'b', 'c', 'd'] Output: a, b, c, d Here as we see that input array contain some elements and in output same elements get printed. Let’s see JavaScript program on array.values() function: JavaScript // Input array contain some elementsvar A = [ 'Ram', 'Z', 'k', 'geeksforgeeks' ]; // Here array.values() function is called.var iterator = A.values(); // All the elements of the array the array// is being printed.console.log(iterator.next().value);console.log(iterator.next().value);console.log(iterator.next().value);console.log(iterator.next().value); Output: > Ram, z, k, geeksforgeeks Application: This array.values() function in JavaScript is used to print the elements of the given array. Let’s see JavaScript program on array.values() function: JavaScript // Input array contain some elements.var array = [ 'a', 'gfg', 'c', 'n' ]; // Here array.values() function is called.var iterator = array.values(); // Here all the elements of the array is being printed.for (let elements of iterator) { console.log(elements);} Output: > a, gfg, c, n Supported Browser: Google Chrome 66 and above Microsoft Edge 12 and above Firefox 60 and above Opera 53 and above Safari 9 and above JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples. ysachin2314 javascript-array JavaScript Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Set the value of an input field in JavaScript Difference Between PUT and PATCH Request Form validation using HTML and JavaScript Node.js | fs.writeFileSync() Method How to Use the JavaScript Fetch API to Get Data? How to get character array from string in JavaScript? Create a Responsive Navbar using ReactJS
[ { "code": null, "e": 24540, "s": 24512, "text": "\n18 Nov, 2021" }, { "code": null, "e": 24767, "s": 24540, "text": "The array.values() function is an inbuilt function in JavaScript which is used to returns a new array Iterator object that contains the values for each index in the array i.e, it prints all the elements of the array. Syntax: " }, { "code": null, "e": 24780, "s": 24767, "text": "arr.values()" }, { "code": null, "e": 24880, "s": 24780, "text": "Return values: It returns a new array iterator object i.e, elements of the given array. Examples: " }, { "code": null, "e": 25027, "s": 24880, "text": "Input:\nA = ['a', 'b', 'c', 'd']\nOutput:\na, b, c, d\nHere as we see that input array contain some \nelements and in output same elements get printed." }, { "code": null, "e": 25086, "s": 25027, "text": "Let’s see JavaScript program on array.values() function: " }, { "code": null, "e": 25097, "s": 25086, "text": "JavaScript" }, { "code": "// Input array contain some elementsvar A = [ 'Ram', 'Z', 'k', 'geeksforgeeks' ]; // Here array.values() function is called.var iterator = A.values(); // All the elements of the array the array// is being printed.console.log(iterator.next().value);console.log(iterator.next().value);console.log(iterator.next().value);console.log(iterator.next().value);", "e": 25451, "s": 25097, "text": null }, { "code": null, "e": 25459, "s": 25451, "text": "Output:" }, { "code": null, "e": 25486, "s": 25459, "text": "> Ram, z, k, geeksforgeeks" }, { "code": null, "e": 25651, "s": 25486, "text": "Application: This array.values() function in JavaScript is used to print the elements of the given array. Let’s see JavaScript program on array.values() function: " }, { "code": null, "e": 25662, "s": 25651, "text": "JavaScript" }, { "code": "// Input array contain some elements.var array = [ 'a', 'gfg', 'c', 'n' ]; // Here array.values() function is called.var iterator = array.values(); // Here all the elements of the array is being printed.for (let elements of iterator) { console.log(elements);}", "e": 25923, "s": 25662, "text": null }, { "code": null, "e": 25931, "s": 25923, "text": "Output:" }, { "code": null, "e": 25946, "s": 25931, "text": "> a, gfg, c, n" }, { "code": null, "e": 25965, "s": 25946, "text": "Supported Browser:" }, { "code": null, "e": 25992, "s": 25965, "text": "Google Chrome 66 and above" }, { "code": null, "e": 26020, "s": 25992, "text": "Microsoft Edge 12 and above" }, { "code": null, "e": 26041, "s": 26020, "text": "Firefox 60 and above" }, { "code": null, "e": 26060, "s": 26041, "text": "Opera 53 and above" }, { "code": null, "e": 26080, "s": 26060, "text": "Safari 9 and above " }, { "code": null, "e": 26299, "s": 26080, "text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples." }, { "code": null, "e": 26313, "s": 26301, "text": "ysachin2314" }, { "code": null, "e": 26330, "s": 26313, "text": "javascript-array" }, { "code": null, "e": 26341, "s": 26330, "text": "JavaScript" }, { "code": null, "e": 26439, "s": 26341, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26448, "s": 26439, "text": "Comments" }, { "code": null, "e": 26461, "s": 26448, "text": "Old Comments" }, { "code": null, "e": 26506, "s": 26461, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 26567, "s": 26506, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 26639, "s": 26567, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 26685, "s": 26639, "text": "Set the value of an input field in JavaScript" }, { "code": null, "e": 26726, "s": 26685, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 26768, "s": 26726, "text": "Form validation using HTML and JavaScript" }, { "code": null, "e": 26804, "s": 26768, "text": "Node.js | fs.writeFileSync() Method" }, { "code": null, "e": 26853, "s": 26804, "text": "How to Use the JavaScript Fetch API to Get Data?" }, { "code": null, "e": 26907, "s": 26853, "text": "How to get character array from string in JavaScript?" } ]
Array of maps in C++ with Examples - GeeksforGeeks
27 Dec, 2021 What is an array? An array in any programming language is a data structure that is used to store elements or data items of similar data types at contiguous memory locations and elements can be accessed randomly using indices of an array. Arrays are efficient when we want to store a large number of elements that too of similar data types. What is a Map? In C++, a map is an associative container that is used to store elements in a mapped fashion. Internally, a map is implemented as a self-balancing binary tree. Each element of a map is treated as a pair. The first value is referred to as key and the second value is referred to as value. No two values can have the same key. Functions associated with Map: begin(): Returns an iterator to the first element in the map end(): Returns an iterator to the theoretical element that follows the last element in the map size(): Returns the number of elements in the map max_size(): Returns the maximum number of elements that the map can hold empty(): Returns whether the map is empty insert(key, Value): Adds a new element to the map erase(iterator position): Removes the element at the position pointed by the iterator erase(const x): Removes the key-value ‘x’ from the map clear(): Removes all the elements from the map Array of Maps C++ allows us a facility to create an array of maps. An array of maps is an array in which each element is a map on its own. Syntax: map<<dataType1, dataType2>> myContainer[N]; Here, N: The size of the array of mapsdataType1: The dataType for the keydataType2: The dataType for the value Example 1: Below is the C++ program to implement an array of maps. C++ // C++ program to demonstrate the// working of array of maps in C++#include <bits/stdc++.h>using namespace std; // Function to print map elements// specified at the index, "index"void print(map<int, bool>& myMap, int index){ cout << "The map elements stored at the index " << index << ": \n"; cout << "Key Value\n"; // Each element of the map is a pair // on its own for (auto pr : myMap) { // Each element of the map is a pair // on its own cout << pr.first << " " << pr.second << '\n'; } cout << '\n';} // Function to iterate over all the arrayvoid print(map<int, bool>* myContainer, int n){ // Iterating over myContainer elements // Each element is a map on its own for (int i = 0; i < n; i++) { print(myContainer[i], i); }} // Driver codeint main(){ // Declaring an array of maps // In map Key is of type int // Value is of type bool map<int, bool> myContainer[3]; // Mapping values to the map stored // at the index 0 myContainer[0][10] = true; myContainer[0][15] = false; myContainer[0][20] = true; myContainer[0][25] = false; // Mapping values to the map stored // at the index 1 myContainer[1][30] = true; myContainer[1][35] = false; myContainer[1][40] = true; myContainer[1][45] = false; // Mapping values to the map stored // at the index 2 myContainer[2][50] = true; myContainer[2][55] = false; myContainer[2][60] = true; myContainer[2][65] = false; // Calling print function to iterate // over myContainer elements print(myContainer, 3); return 0;} The map elements stored at the index 0: Key Value 10 1 15 0 20 1 25 0 The map elements stored at the index 1: Key Value 30 1 35 0 40 1 45 0 The map elements stored at the index 2: Key Value 50 1 55 0 60 1 65 0 Example 2: Below is the C++ program to implement array of maps. C++ // C++ program to demonstrate the// working of array of maps in C++ #include <bits/stdc++.h>using namespace std; // Function to print map elements specified // at the index, "index"void print(map<string, bool>& myMap, int index){ cout << "The map elements stored at the index " << index << ": \n"; cout << "Key Value\n"; // Each element of the map is a pair // on its own for (auto pr : myMap) { cout << pr.first << " " << pr.second << '\n'; } cout << '\n';} // Function to iterate over the map // corresponding to an indexvoid print(map<string, bool>* myContainer, int n){ for (int i = 0; i < n; i++) { print(myContainer[i], i); }} // Driver codeint main(){ // Declaring an array of maps // In map Key is of type string // Value is of type bool map<string, bool> myContainer[3]; // Mapping values to the map stored // at the index 0 myContainer[0]["Code"] = true; myContainer[0]["HTML"] = false; myContainer[0]["Java"] = true; myContainer[0]["Solo"] = false; // Mapping values to the map stored // at the index 1 myContainer[1]["PHP"] = true; myContainer[1]["CSS"] = false; myContainer[1]["C++"] = true; myContainer[1]["Lab"] = false; // Mapping values to the map stored // at the index 2 myContainer[2]["Swift"] = true; myContainer[2]["Cobol"] = false; myContainer[2]["Fizzy"] = true; myContainer[2]["Pizza"] = false; // Calling print function to print // myContainer elements print(myContainer, 3); return 0;} The map elements stored at the index 0: Key Value Code 1 HTML 0 Java 1 Solo 0 The map elements stored at the index 1: Key Value C++ 1 CSS 0 Lab 0 PHP 1 The map elements stored at the index 2: Key Value Cobol 0 Fizzy 1 Pizza 0 Swift 1 cpp-array cpp-map STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Operator Overloading in C++ Iterators in C++ STL Friend class and function in C++ Polymorphism in C++ Sorting a vector in C++ Convert string to char array in C++ List in C++ Standard Template Library (STL) Inline Functions in C++ std::string class in C++ Destructors in C++
[ { "code": null, "e": 24042, "s": 24014, "text": "\n27 Dec, 2021" }, { "code": null, "e": 24060, "s": 24042, "text": "What is an array?" }, { "code": null, "e": 24382, "s": 24060, "text": "An array in any programming language is a data structure that is used to store elements or data items of similar data types at contiguous memory locations and elements can be accessed randomly using indices of an array. Arrays are efficient when we want to store a large number of elements that too of similar data types." }, { "code": null, "e": 24397, "s": 24382, "text": "What is a Map?" }, { "code": null, "e": 24722, "s": 24397, "text": "In C++, a map is an associative container that is used to store elements in a mapped fashion. Internally, a map is implemented as a self-balancing binary tree. Each element of a map is treated as a pair. The first value is referred to as key and the second value is referred to as value. No two values can have the same key." }, { "code": null, "e": 24753, "s": 24722, "text": "Functions associated with Map:" }, { "code": null, "e": 24814, "s": 24753, "text": "begin(): Returns an iterator to the first element in the map" }, { "code": null, "e": 24909, "s": 24814, "text": "end(): Returns an iterator to the theoretical element that follows the last element in the map" }, { "code": null, "e": 24959, "s": 24909, "text": "size(): Returns the number of elements in the map" }, { "code": null, "e": 25032, "s": 24959, "text": "max_size(): Returns the maximum number of elements that the map can hold" }, { "code": null, "e": 25074, "s": 25032, "text": "empty(): Returns whether the map is empty" }, { "code": null, "e": 25124, "s": 25074, "text": "insert(key, Value): Adds a new element to the map" }, { "code": null, "e": 25210, "s": 25124, "text": "erase(iterator position): Removes the element at the position pointed by the iterator" }, { "code": null, "e": 25265, "s": 25210, "text": "erase(const x): Removes the key-value ‘x’ from the map" }, { "code": null, "e": 25312, "s": 25265, "text": "clear(): Removes all the elements from the map" }, { "code": null, "e": 25326, "s": 25312, "text": "Array of Maps" }, { "code": null, "e": 25452, "s": 25326, "text": "C++ allows us a facility to create an array of maps. An array of maps is an array in which each element is a map on its own. " }, { "code": null, "e": 25460, "s": 25452, "text": "Syntax:" }, { "code": null, "e": 25504, "s": 25460, "text": "map<<dataType1, dataType2>> myContainer[N];" }, { "code": null, "e": 25510, "s": 25504, "text": "Here," }, { "code": null, "e": 25615, "s": 25510, "text": "N: The size of the array of mapsdataType1: The dataType for the keydataType2: The dataType for the value" }, { "code": null, "e": 25682, "s": 25615, "text": "Example 1: Below is the C++ program to implement an array of maps." }, { "code": null, "e": 25686, "s": 25682, "text": "C++" }, { "code": "// C++ program to demonstrate the// working of array of maps in C++#include <bits/stdc++.h>using namespace std; // Function to print map elements// specified at the index, \"index\"void print(map<int, bool>& myMap, int index){ cout << \"The map elements stored at the index \" << index << \": \\n\"; cout << \"Key Value\\n\"; // Each element of the map is a pair // on its own for (auto pr : myMap) { // Each element of the map is a pair // on its own cout << pr.first << \" \" << pr.second << '\\n'; } cout << '\\n';} // Function to iterate over all the arrayvoid print(map<int, bool>* myContainer, int n){ // Iterating over myContainer elements // Each element is a map on its own for (int i = 0; i < n; i++) { print(myContainer[i], i); }} // Driver codeint main(){ // Declaring an array of maps // In map Key is of type int // Value is of type bool map<int, bool> myContainer[3]; // Mapping values to the map stored // at the index 0 myContainer[0][10] = true; myContainer[0][15] = false; myContainer[0][20] = true; myContainer[0][25] = false; // Mapping values to the map stored // at the index 1 myContainer[1][30] = true; myContainer[1][35] = false; myContainer[1][40] = true; myContainer[1][45] = false; // Mapping values to the map stored // at the index 2 myContainer[2][50] = true; myContainer[2][55] = false; myContainer[2][60] = true; myContainer[2][65] = false; // Calling print function to iterate // over myContainer elements print(myContainer, 3); return 0;}", "e": 27365, "s": 25686, "text": null }, { "code": null, "e": 27692, "s": 27365, "text": "The map elements stored at the index 0: \nKey Value\n10 1\n15 0\n20 1\n25 0\n\nThe map elements stored at the index 1: \nKey Value\n30 1\n35 0\n40 1\n45 0\n\nThe map elements stored at the index 2: \nKey Value\n50 1\n55 0\n60 1\n65 0\n" }, { "code": null, "e": 27756, "s": 27692, "text": "Example 2: Below is the C++ program to implement array of maps." }, { "code": null, "e": 27760, "s": 27756, "text": "C++" }, { "code": "// C++ program to demonstrate the// working of array of maps in C++ #include <bits/stdc++.h>using namespace std; // Function to print map elements specified // at the index, \"index\"void print(map<string, bool>& myMap, int index){ cout << \"The map elements stored at the index \" << index << \": \\n\"; cout << \"Key Value\\n\"; // Each element of the map is a pair // on its own for (auto pr : myMap) { cout << pr.first << \" \" << pr.second << '\\n'; } cout << '\\n';} // Function to iterate over the map // corresponding to an indexvoid print(map<string, bool>* myContainer, int n){ for (int i = 0; i < n; i++) { print(myContainer[i], i); }} // Driver codeint main(){ // Declaring an array of maps // In map Key is of type string // Value is of type bool map<string, bool> myContainer[3]; // Mapping values to the map stored // at the index 0 myContainer[0][\"Code\"] = true; myContainer[0][\"HTML\"] = false; myContainer[0][\"Java\"] = true; myContainer[0][\"Solo\"] = false; // Mapping values to the map stored // at the index 1 myContainer[1][\"PHP\"] = true; myContainer[1][\"CSS\"] = false; myContainer[1][\"C++\"] = true; myContainer[1][\"Lab\"] = false; // Mapping values to the map stored // at the index 2 myContainer[2][\"Swift\"] = true; myContainer[2][\"Cobol\"] = false; myContainer[2][\"Fizzy\"] = true; myContainer[2][\"Pizza\"] = false; // Calling print function to print // myContainer elements print(myContainer, 3); return 0;}", "e": 29383, "s": 27760, "text": null }, { "code": null, "e": 29698, "s": 29383, "text": "The map elements stored at the index 0: \nKey Value\nCode 1\nHTML 0\nJava 1\nSolo 0\n\nThe map elements stored at the index 1: \nKey Value\nC++ 1\nCSS 0\nLab 0\nPHP 1\n\nThe map elements stored at the index 2: \nKey Value\nCobol 0\nFizzy 1\nPizza 0\nSwift 1\n" }, { "code": null, "e": 29708, "s": 29698, "text": "cpp-array" }, { "code": null, "e": 29716, "s": 29708, "text": "cpp-map" }, { "code": null, "e": 29720, "s": 29716, "text": "STL" }, { "code": null, "e": 29724, "s": 29720, "text": "C++" }, { "code": null, "e": 29728, "s": 29724, "text": "STL" }, { "code": null, "e": 29732, "s": 29728, "text": "CPP" }, { "code": null, "e": 29830, "s": 29732, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29839, "s": 29830, "text": "Comments" }, { "code": null, "e": 29852, "s": 29839, "text": "Old Comments" }, { "code": null, "e": 29880, "s": 29852, "text": "Operator Overloading in C++" }, { "code": null, "e": 29901, "s": 29880, "text": "Iterators in C++ STL" }, { "code": null, "e": 29934, "s": 29901, "text": "Friend class and function in C++" }, { "code": null, "e": 29954, "s": 29934, "text": "Polymorphism in C++" }, { "code": null, "e": 29978, "s": 29954, "text": "Sorting a vector in C++" }, { "code": null, "e": 30014, "s": 29978, "text": "Convert string to char array in C++" }, { "code": null, "e": 30058, "s": 30014, "text": "List in C++ Standard Template Library (STL)" }, { "code": null, "e": 30082, "s": 30058, "text": "Inline Functions in C++" }, { "code": null, "e": 30107, "s": 30082, "text": "std::string class in C++" } ]
Create and Import modules in Python - GeeksforGeeks
29 Dec, 2019 In Python, a module is a self-contained Python file that contains Python statements and definitions, like a file named GFG.py, can be considered as a module named GFG which can be imported with the help of import statement. However, one might get confused about the difference between modules and packages. A package is a collection of modules in directories that give structure and hierarchy to the modules. Reusability: Working with modules makes the code reusability a reality. Simplicity: Module focuses on a small proportion of the problem, rather than focusing on the entire problem. Scoping: A separate namespace is defined by a module that helps to avoid collisions between identifiers. A module is simply a Python file with a .py extension that can be imported inside another Python program. The name of the Python file becomes the module name. The module contains definitions and implementation of classes, variables, and functions that can be used inside another program. Example: Let’s create a simple module named GFG. ''' GFG.py ''' # Python program to create# a module # Defining a functiondef Geeks(): print("GeeksforGeeks") # Defining a variablelocation = "Noida" The above example shows the creation of a simple module named GFG as the name of the above Python file is GFG.py. When this code is executed it does nothing because the function created is not invoked. To use the above created module, create a new Python file in the same directory and import GFG module using the import statement. Example: # Python program to demonstrate# modules import GFG # Use the function createdGFG.Geeks() # Print the variable declaredprint(GFG.location) Output: GeeksforGeeks Noida The above example shows a simple module with only functions and variables. Now let’s create a little bit complex module with classes, functions, and variables. Below is the implementation. Example: Open the above created GFG module and make the following changes. ''' GFG.py ''' # Python program to demonstrate # modules # Defining a functiondef Geeks(): print("GeeksforGeeks") # Defining a variablelocation = "Noida" # Defining a classclass Employee(): def __init__(self, name, position): self. name = name self.position = position def show(self): print("Employee name:", self.name) print("Employee position:", self.position) In this example, a class named employee has been declared with a method show() to print the details of the employee. Now open the Python script for importing and using this module. Example: # Python program to demonstrate# modules import GFG # Use the class createdemp = GFG.Employee("Nikhil", "Developer")emp.show() Output: Employee name: Nikhil Employee position: Developer All the object from a module can be imported as a variable. This prevents the usage of the module name as a prefix. Syntax: from module_name_ import * Example: We will use the above created GFG module. # Python program to demonstrate# modules from GFG import * # Calling the functionGeeks() # Printing the variableprint(location) # Calling classemp = Employee("Nikhil", "Developer")emp.show() Output: GeeksforGeeks Noida Employee name: Nikhil Employee position: Developer A module can be imported with another name, specified by the user. Example: # Python program to demonstrate# modules import GFG as g # Calling the functiong.Geeks() # Printing the variableprint(g.location) # Calling classemp = g.Employee("Nikhil", "Developer")emp.show() Output: GeeksforGeeks Noida Employee name: Nikhil Employee position: Developer python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25863, "s": 25835, "text": "\n29 Dec, 2019" }, { "code": null, "e": 26272, "s": 25863, "text": "In Python, a module is a self-contained Python file that contains Python statements and definitions, like a file named GFG.py, can be considered as a module named GFG which can be imported with the help of import statement. However, one might get confused about the difference between modules and packages. A package is a collection of modules in directories that give structure and hierarchy to the modules." }, { "code": null, "e": 26344, "s": 26272, "text": "Reusability: Working with modules makes the code reusability a reality." }, { "code": null, "e": 26453, "s": 26344, "text": "Simplicity: Module focuses on a small proportion of the problem, rather than focusing on the entire problem." }, { "code": null, "e": 26558, "s": 26453, "text": "Scoping: A separate namespace is defined by a module that helps to avoid collisions between identifiers." }, { "code": null, "e": 26846, "s": 26558, "text": "A module is simply a Python file with a .py extension that can be imported inside another Python program. The name of the Python file becomes the module name. The module contains definitions and implementation of classes, variables, and functions that can be used inside another program." }, { "code": null, "e": 26895, "s": 26846, "text": "Example: Let’s create a simple module named GFG." }, { "code": "''' GFG.py ''' # Python program to create# a module # Defining a functiondef Geeks(): print(\"GeeksforGeeks\") # Defining a variablelocation = \"Noida\"", "e": 27052, "s": 26895, "text": null }, { "code": null, "e": 27254, "s": 27052, "text": "The above example shows the creation of a simple module named GFG as the name of the above Python file is GFG.py. When this code is executed it does nothing because the function created is not invoked." }, { "code": null, "e": 27384, "s": 27254, "text": "To use the above created module, create a new Python file in the same directory and import GFG module using the import statement." }, { "code": null, "e": 27393, "s": 27384, "text": "Example:" }, { "code": "# Python program to demonstrate# modules import GFG # Use the function createdGFG.Geeks() # Print the variable declaredprint(GFG.location)", "e": 27537, "s": 27393, "text": null }, { "code": null, "e": 27545, "s": 27537, "text": "Output:" }, { "code": null, "e": 27566, "s": 27545, "text": "GeeksforGeeks\nNoida\n" }, { "code": null, "e": 27755, "s": 27566, "text": "The above example shows a simple module with only functions and variables. Now let’s create a little bit complex module with classes, functions, and variables. Below is the implementation." }, { "code": null, "e": 27830, "s": 27755, "text": "Example: Open the above created GFG module and make the following changes." }, { "code": "''' GFG.py ''' # Python program to demonstrate # modules # Defining a functiondef Geeks(): print(\"GeeksforGeeks\") # Defining a variablelocation = \"Noida\" # Defining a classclass Employee(): def __init__(self, name, position): self. name = name self.position = position def show(self): print(\"Employee name:\", self.name) print(\"Employee position:\", self.position)", "e": 28252, "s": 27830, "text": null }, { "code": null, "e": 28433, "s": 28252, "text": "In this example, a class named employee has been declared with a method show() to print the details of the employee. Now open the Python script for importing and using this module." }, { "code": null, "e": 28442, "s": 28433, "text": "Example:" }, { "code": "# Python program to demonstrate# modules import GFG # Use the class createdemp = GFG.Employee(\"Nikhil\", \"Developer\")emp.show()", "e": 28578, "s": 28442, "text": null }, { "code": null, "e": 28586, "s": 28578, "text": "Output:" }, { "code": null, "e": 28638, "s": 28586, "text": "Employee name: Nikhil\nEmployee position: Developer\n" }, { "code": null, "e": 28754, "s": 28638, "text": "All the object from a module can be imported as a variable. This prevents the usage of the module name as a prefix." }, { "code": null, "e": 28762, "s": 28754, "text": "Syntax:" }, { "code": null, "e": 28790, "s": 28762, "text": "from module_name_ import *\n" }, { "code": null, "e": 28841, "s": 28790, "text": "Example: We will use the above created GFG module." }, { "code": "# Python program to demonstrate# modules from GFG import * # Calling the functionGeeks() # Printing the variableprint(location) # Calling classemp = Employee(\"Nikhil\", \"Developer\")emp.show()", "e": 29043, "s": 28841, "text": null }, { "code": null, "e": 29051, "s": 29043, "text": "Output:" }, { "code": null, "e": 29123, "s": 29051, "text": "GeeksforGeeks\nNoida\nEmployee name: Nikhil\nEmployee position: Developer\n" }, { "code": null, "e": 29190, "s": 29123, "text": "A module can be imported with another name, specified by the user." }, { "code": null, "e": 29199, "s": 29190, "text": "Example:" }, { "code": "# Python program to demonstrate# modules import GFG as g # Calling the functiong.Geeks() # Printing the variableprint(g.location) # Calling classemp = g.Employee(\"Nikhil\", \"Developer\")emp.show()", "e": 29405, "s": 29199, "text": null }, { "code": null, "e": 29413, "s": 29405, "text": "Output:" }, { "code": null, "e": 29485, "s": 29413, "text": "GeeksforGeeks\nNoida\nEmployee name: Nikhil\nEmployee position: Developer\n" }, { "code": null, "e": 29500, "s": 29485, "text": "python-modules" }, { "code": null, "e": 29507, "s": 29500, "text": "Python" }, { "code": null, "e": 29605, "s": 29507, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29623, "s": 29605, "text": "Python Dictionary" }, { "code": null, "e": 29658, "s": 29623, "text": "Read a file line by line in Python" }, { "code": null, "e": 29690, "s": 29658, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29712, "s": 29690, "text": "Enumerate() in Python" }, { "code": null, "e": 29754, "s": 29712, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29784, "s": 29754, "text": "Iterate over a list in Python" }, { "code": null, "e": 29810, "s": 29784, "text": "Python String | replace()" }, { "code": null, "e": 29839, "s": 29810, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29883, "s": 29839, "text": "Reading and Writing to text files in Python" } ]
SQL Query for Finding Maximum Values in Rows
07 Apr, 2021 SQL stands for Structured Query Language and is used to create, maintain and retrieve the data from relational databases. Relational Database Management Systems (RDBMS) like MySQL, MS Access, Oracle, and SQL Server use SQL as their standard database language. Here we are going to see the SQL query for Finding Maximum Values in Rows. Let us understand it by creating a database named “CSEportal”. Creating Database : Syntax : CREATE DATABASE <DatabaseName>; Example : CREATE DATABASE CSEportal; Output : Query returned successfully in 3 secs 817 msec. Using the Database : Syntax : USE <DatabaseName>; Example : USE CSEportal; Using the above commands, we have successfully created our database named “CSEportal”, now we need to create a table(Relation) named “GeeksforGeeks” in this database. Creating table : Syntax : CREATE TABLE TableName (field1 dataType1 , field2 dataType2...fieldN dataTypeN); Example : CREATE TABLE GeeksforGeeks( sno int, Description VARCHAR(40), courses VARCHAR(40)); This will create an empty table, so let us populate our table with some records using the INSERT INTO command to perform the actual operations on the tables. Inserting records in the table : Syntax : INSERT INTO tablename (field1,field2,...fieldN) VALUES (value1,value2...valueN); Example : INSERT INTO GeeksforGeeks(sno,Description,Courses) VALUES(1,'Cse Portal','DBMS'); Similarly, we can fill our table using this INSERT INTO command. To see the created table, we can run the SELECT command which is shown below: SELECT * from GeeksforGeeks; Output : Our Table “GeeksforGeeks” Now we can move ahead to write our SQL query for finding maximum values in all the rows, This can be done using MAX(field) function in SQL. Let us try to retrieve the maximum value of the field “Description” as shown below: Select max(Description) as Maximum from GeeksforGeeks; Here we have used the ‘as ‘ keyword just to change the name of the resulting field as shown in the output below: Output : Here we have got ‘well explained’ as the output since it is the maximum value out of all the rows of the table. Let us try to apply this on the field holding some numeric values to get a more clear idea. Select max(sno) from GeeksforGeeks; Output : Clearly, 4 is the maximum value out of all the rows of the table, hence we have got 4 as our output. Also, here we have not used the ‘as’ keyword, so in the resulting field, we have got ‘max(sno)’ as its name. It is an optional step and can be done in the same manner as shown above. We can also retrieve maximum values of more than one field out of all the rows using a single query as shown below: Query: Select max(sno),max(description) from GeeksforGeeks; Output: max(sno) max(description) 4 well explained So here, we have retrieved the maximum value of two fields (out of all the rows) using a single query only. DBMS-SQL SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Apr, 2021" }, { "code": null, "e": 427, "s": 28, "text": "SQL stands for Structured Query Language and is used to create, maintain and retrieve the data from relational databases. Relational Database Management Systems (RDBMS) like MySQL, MS Access, Oracle, and SQL Server use SQL as their standard database language. Here we are going to see the SQL query for Finding Maximum Values in Rows. Let us understand it by creating a database named “CSEportal”. " }, { "code": null, "e": 447, "s": 427, "text": "Creating Database :" }, { "code": null, "e": 583, "s": 447, "text": "Syntax : \nCREATE DATABASE <DatabaseName>;\nExample :\nCREATE DATABASE CSEportal;\nOutput :\nQuery returned successfully in 3 secs 817 msec." }, { "code": null, "e": 604, "s": 583, "text": "Using the Database :" }, { "code": null, "e": 658, "s": 604, "text": "Syntax :\nUSE <DatabaseName>;\nExample :\nUSE CSEportal;" }, { "code": null, "e": 826, "s": 658, "text": "Using the above commands, we have successfully created our database named “CSEportal”, now we need to create a table(Relation) named “GeeksforGeeks” in this database. " }, { "code": null, "e": 843, "s": 826, "text": "Creating table :" }, { "code": null, "e": 1030, "s": 843, "text": "Syntax :\nCREATE TABLE TableName (field1 dataType1 , field2 dataType2...fieldN dataTypeN);\nExample : \nCREATE TABLE GeeksforGeeks(\nsno int, \nDescription VARCHAR(40), \ncourses VARCHAR(40));" }, { "code": null, "e": 1189, "s": 1030, "text": "This will create an empty table, so let us populate our table with some records using the INSERT INTO command to perform the actual operations on the tables. " }, { "code": null, "e": 1222, "s": 1189, "text": "Inserting records in the table :" }, { "code": null, "e": 1404, "s": 1222, "text": "Syntax :\nINSERT INTO tablename (field1,field2,...fieldN) VALUES (value1,value2...valueN);\nExample :\nINSERT INTO GeeksforGeeks(sno,Description,Courses) VALUES(1,'Cse Portal','DBMS');" }, { "code": null, "e": 1547, "s": 1404, "text": "Similarly, we can fill our table using this INSERT INTO command. To see the created table, we can run the SELECT command which is shown below:" }, { "code": null, "e": 1576, "s": 1547, "text": "SELECT * from GeeksforGeeks;" }, { "code": null, "e": 1585, "s": 1576, "text": "Output :" }, { "code": null, "e": 1611, "s": 1585, "text": "Our Table “GeeksforGeeks”" }, { "code": null, "e": 1835, "s": 1611, "text": "Now we can move ahead to write our SQL query for finding maximum values in all the rows, This can be done using MAX(field) function in SQL. Let us try to retrieve the maximum value of the field “Description” as shown below:" }, { "code": null, "e": 1890, "s": 1835, "text": "Select max(Description) as Maximum from GeeksforGeeks;" }, { "code": null, "e": 2003, "s": 1890, "text": "Here we have used the ‘as ‘ keyword just to change the name of the resulting field as shown in the output below:" }, { "code": null, "e": 2013, "s": 2003, "text": "Output : " }, { "code": null, "e": 2218, "s": 2013, "text": "Here we have got ‘well explained’ as the output since it is the maximum value out of all the rows of the table. Let us try to apply this on the field holding some numeric values to get a more clear idea. " }, { "code": null, "e": 2255, "s": 2218, "text": " Select max(sno) from GeeksforGeeks;" }, { "code": null, "e": 2265, "s": 2255, "text": "Output : " }, { "code": null, "e": 2665, "s": 2265, "text": "Clearly, 4 is the maximum value out of all the rows of the table, hence we have got 4 as our output. Also, here we have not used the ‘as’ keyword, so in the resulting field, we have got ‘max(sno)’ as its name. It is an optional step and can be done in the same manner as shown above. We can also retrieve maximum values of more than one field out of all the rows using a single query as shown below:" }, { "code": null, "e": 2792, "s": 2665, "text": "Query:\nSelect max(sno),max(description) from GeeksforGeeks;\n\nOutput:\nmax(sno) max(description)\n\n4 well explained" }, { "code": null, "e": 2900, "s": 2792, "text": "So here, we have retrieved the maximum value of two fields (out of all the rows) using a single query only." }, { "code": null, "e": 2909, "s": 2900, "text": "DBMS-SQL" }, { "code": null, "e": 2913, "s": 2909, "text": "SQL" }, { "code": null, "e": 2917, "s": 2913, "text": "SQL" } ]
Interpreter Design Pattern
22 Feb, 2018 Interpreter design pattern is one of the behavioral design pattern. Interpreter pattern is used to defines a grammatical representation for a language and provides an interpreter to deal with this grammar. This pattern involves implementing an expression interface which tells to interpret a particular context. This pattern is used in SQL parsing, symbol processing engine etc. This pattern performs upon a hierarchy of expressions. Each expression here is a terminal or non-terminal. The tree structure of Interpreter design pattern is somewhat similar to that defined by the composite design pattern with terminal expressions being leaf objects and non-terminal expressions being composites. The tree contains the expressions to be evaluated and is usually generated by a parser. The parser itself is not a part of the interpreter pattern. For Example :Here is the hierarchy of expressions for “+ – 9 8 7” : Implementing the Interpreter Pattern UML Diagram Interpreter Design Pattern Design components AbstractExpression (Expression): Declares an interpret() operation that all nodes (terminal and nonterminal) in the AST overrides. TerminalExpression (NumberExpression): Implements the interpret() operation for terminal expressions. NonterminalExpression (AdditionExpression, SubtractionExpression, and MultiplicationExpression): Implements the interpret() operation for all nonterminal expressions. Context (String): Contains information that is global to the interpreter. It is this String expression with the Postfix notation that has to be interpreted and parsed. Client (ExpressionParser): Builds (or is provided) the AST assembled from TerminalExpression and NonTerminalExpression. The Client invokes the interpret() operation. Let’s see an example of Interpreter Design Pattern. // Expression interface used to// check the interpreter.interface Expression{ boolean interpreter(String con);} // TerminalExpression class implementing// the above interface. This interpreter // just check if the data is same as the // interpreter data.class TerminalExpression implements Expression { String data; public TerminalExpression(String data) { this.data = data; } public boolean interpreter(String con) { if(con.contains(data)) { return true; } else { return false; } }}// OrExpression class implementing// the above interface. This interpreter // just returns the or condition of the // data is same as the interpreter data.class OrExpression implements Expression { Expression expr1; Expression expr2; public OrExpression(Expression expr1, Expression expr2) { this.expr1 = expr1; this.expr2 = expr2; } public boolean interpreter(String con) { return expr1.interpreter(con) || expr2.interpreter(con); }} // AndExpression class implementing// the above interface. This interpreter // just returns the And condition of the // data is same as the interpreter data.class AndExpression implements Expression { Expression expr1; Expression expr2; public AndExpression(Expression expr1, Expression expr2) { this.expr1 = expr1; this.expr2 = expr2; } public boolean interpreter(String con) { return expr1.interpreter(con) && expr2.interpreter(con); }} // Driver classclass InterpreterPattern{ public static void main(String[] args) { Expression person1 = new TerminalExpression("Kushagra"); Expression person2 = new TerminalExpression("Lokesh"); Expression isSingle = new OrExpression(person1, person2); Expression vikram = new TerminalExpression("Vikram"); Expression committed = new TerminalExpression("Committed"); Expression isCommitted = new AndExpression(vikram, committed); System.out.println(isSingle.interpreter("Kushagra")); System.out.println(isSingle.interpreter("Lokesh")); System.out.println(isSingle.interpreter("Achint")); System.out.println(isCommitted.interpreter("Committed, Vikram")); System.out.println(isCommitted.interpreter("Single, Vikram")); }} Output: true true false true false In the above code , We are creating an interface Expression and concrete classes implementing the Expression interface. A class TerminalExpression is defined which acts as a main interpreter and other classes OrExpression, AndExpression are used to create combinational expressions. Advantages It’s easy to change and extend the grammar. Because the pattern uses classes to represent grammar rules, you can use inheritance to change or extend the grammar. Existing expressions can be modified incrementally, and new expressions can be defined as variations on old ones. Implementing the grammar is easy, too. Classes defining nodes in the abstract syntax tree have similar implementations. These classes are easy to write, and often their generation can be automated with a compiler or parser generator. Disadvantages Complex grammars are hard to maintain. The Interpreter pattern defines at least one class for every rule in the grammar. Hence grammars containing many rules can be hard to manage and maintain. This article is contributed by Saket Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Design Pattern Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Factory method design pattern in Java Builder Design Pattern Introduction of Programming Paradigms Unified Modeling Language (UML) | An Introduction Unified Modeling Language (UML) | Sequence Diagrams Adapter Pattern MVC Design Pattern Monolithic vs Microservices architecture Unified Modeling Language (UML) | State Diagrams Unified Modeling Language (UML) | Activity Diagrams
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Feb, 2018" }, { "code": null, "e": 258, "s": 52, "text": "Interpreter design pattern is one of the behavioral design pattern. Interpreter pattern is used to defines a grammatical representation for a language and provides an interpreter to deal with this grammar." }, { "code": null, "e": 431, "s": 258, "text": "This pattern involves implementing an expression interface which tells to interpret a particular context. This pattern is used in SQL parsing, symbol processing engine etc." }, { "code": null, "e": 538, "s": 431, "text": "This pattern performs upon a hierarchy of expressions. Each expression here is a terminal or non-terminal." }, { "code": null, "e": 747, "s": 538, "text": "The tree structure of Interpreter design pattern is somewhat similar to that defined by the composite design pattern with terminal expressions being leaf objects and non-terminal expressions being composites." }, { "code": null, "e": 895, "s": 747, "text": "The tree contains the expressions to be evaluated and is usually generated by a parser. The parser itself is not a part of the interpreter pattern." }, { "code": null, "e": 963, "s": 895, "text": "For Example :Here is the hierarchy of expressions for “+ – 9 8 7” :" }, { "code": null, "e": 1000, "s": 963, "text": "Implementing the Interpreter Pattern" }, { "code": null, "e": 1039, "s": 1000, "text": "UML Diagram Interpreter Design Pattern" }, { "code": null, "e": 1057, "s": 1039, "text": "Design components" }, { "code": null, "e": 1188, "s": 1057, "text": "AbstractExpression (Expression): Declares an interpret() operation that all nodes (terminal and nonterminal) in the AST overrides." }, { "code": null, "e": 1290, "s": 1188, "text": "TerminalExpression (NumberExpression): Implements the interpret() operation for terminal expressions." }, { "code": null, "e": 1457, "s": 1290, "text": "NonterminalExpression (AdditionExpression, SubtractionExpression, and MultiplicationExpression): Implements the interpret() operation for all nonterminal expressions." }, { "code": null, "e": 1625, "s": 1457, "text": "Context (String): Contains information that is global to the interpreter. It is this String expression with the Postfix notation that has to be interpreted and parsed." }, { "code": null, "e": 1791, "s": 1625, "text": "Client (ExpressionParser): Builds (or is provided) the AST assembled from TerminalExpression and NonTerminalExpression. The Client invokes the interpret() operation." }, { "code": null, "e": 1843, "s": 1791, "text": "Let’s see an example of Interpreter Design Pattern." }, { "code": "// Expression interface used to// check the interpreter.interface Expression{ boolean interpreter(String con);} // TerminalExpression class implementing// the above interface. This interpreter // just check if the data is same as the // interpreter data.class TerminalExpression implements Expression { String data; public TerminalExpression(String data) { this.data = data; } public boolean interpreter(String con) { if(con.contains(data)) { return true; } else { return false; } }}// OrExpression class implementing// the above interface. This interpreter // just returns the or condition of the // data is same as the interpreter data.class OrExpression implements Expression { Expression expr1; Expression expr2; public OrExpression(Expression expr1, Expression expr2) { this.expr1 = expr1; this.expr2 = expr2; } public boolean interpreter(String con) { return expr1.interpreter(con) || expr2.interpreter(con); }} // AndExpression class implementing// the above interface. This interpreter // just returns the And condition of the // data is same as the interpreter data.class AndExpression implements Expression { Expression expr1; Expression expr2; public AndExpression(Expression expr1, Expression expr2) { this.expr1 = expr1; this.expr2 = expr2; } public boolean interpreter(String con) { return expr1.interpreter(con) && expr2.interpreter(con); }} // Driver classclass InterpreterPattern{ public static void main(String[] args) { Expression person1 = new TerminalExpression(\"Kushagra\"); Expression person2 = new TerminalExpression(\"Lokesh\"); Expression isSingle = new OrExpression(person1, person2); Expression vikram = new TerminalExpression(\"Vikram\"); Expression committed = new TerminalExpression(\"Committed\"); Expression isCommitted = new AndExpression(vikram, committed); System.out.println(isSingle.interpreter(\"Kushagra\")); System.out.println(isSingle.interpreter(\"Lokesh\")); System.out.println(isSingle.interpreter(\"Achint\")); System.out.println(isCommitted.interpreter(\"Committed, Vikram\")); System.out.println(isCommitted.interpreter(\"Single, Vikram\")); }}", "e": 4257, "s": 1843, "text": null }, { "code": null, "e": 4265, "s": 4257, "text": "Output:" }, { "code": null, "e": 4293, "s": 4265, "text": "true\ntrue\nfalse\ntrue\nfalse\n" }, { "code": null, "e": 4576, "s": 4293, "text": "In the above code , We are creating an interface Expression and concrete classes implementing the Expression interface. A class TerminalExpression is defined which acts as a main interpreter and other classes OrExpression, AndExpression are used to create combinational expressions." }, { "code": null, "e": 4587, "s": 4576, "text": "Advantages" }, { "code": null, "e": 4863, "s": 4587, "text": "It’s easy to change and extend the grammar. Because the pattern uses classes to represent grammar rules, you can use inheritance to change or extend the grammar. Existing expressions can be modified incrementally, and new expressions can be defined as variations on old ones." }, { "code": null, "e": 5097, "s": 4863, "text": "Implementing the grammar is easy, too. Classes defining nodes in the abstract syntax tree have similar implementations. These classes are easy to write, and often their generation can be automated with a compiler or parser generator." }, { "code": null, "e": 5111, "s": 5097, "text": "Disadvantages" }, { "code": null, "e": 5305, "s": 5111, "text": "Complex grammars are hard to maintain. The Interpreter pattern defines at least one class for every rule in the grammar. Hence grammars containing many rules can be hard to manage and maintain." }, { "code": null, "e": 5604, "s": 5305, "text": "This article is contributed by Saket Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 5729, "s": 5604, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 5744, "s": 5729, "text": "Design Pattern" }, { "code": null, "e": 5842, "s": 5744, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5880, "s": 5842, "text": "Factory method design pattern in Java" }, { "code": null, "e": 5903, "s": 5880, "text": "Builder Design Pattern" }, { "code": null, "e": 5941, "s": 5903, "text": "Introduction of Programming Paradigms" }, { "code": null, "e": 5991, "s": 5941, "text": "Unified Modeling Language (UML) | An Introduction" }, { "code": null, "e": 6043, "s": 5991, "text": "Unified Modeling Language (UML) | Sequence Diagrams" }, { "code": null, "e": 6059, "s": 6043, "text": "Adapter Pattern" }, { "code": null, "e": 6078, "s": 6059, "text": "MVC Design Pattern" }, { "code": null, "e": 6119, "s": 6078, "text": "Monolithic vs Microservices architecture" }, { "code": null, "e": 6168, "s": 6119, "text": "Unified Modeling Language (UML) | State Diagrams" } ]
Lodash _.pickBy() Method - GeeksforGeeks
09 Sep, 2020 Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc. The _.pickBy() method is used to return a copy of the object that composed of the object properties predicate returns truthy for. Syntax: _.pickBy( object, predicate ) Parameters: This method accepts two parameters as mentioned above and described below: object: This parameter holds the source object. predicate: This parameter holds the function that is invoked for every property. It is an optional value. Return Value: This method returns the new object. Example 1: Javascript // Requiring the lodash library const _ = require("lodash"); // The source objectvar obj = { Name: "GeeksforGeeks", password: 123456, username: "your_geeks"} // Using the _.pickBy() method console.log(_.pickBy(obj, _.isLength)); Output: {'password': 123456} Example 2: Javascript // Requiring the lodash library const _ = require("lodash"); // The source objectvar obj = { 'x': 1, 'y': '2', 'z': 3 }; // Using the _.pickBy() method console.log(_.pickBy(obj, _.isNumber)); Output: {'x': 1, 'z': 3} JavaScript-Lodash 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": 26545, "s": 26517, "text": "\n09 Sep, 2020" }, { "code": null, "e": 26685, "s": 26545, "text": "Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc." }, { "code": null, "e": 26815, "s": 26685, "text": "The _.pickBy() method is used to return a copy of the object that composed of the object properties predicate returns truthy for." }, { "code": null, "e": 26823, "s": 26815, "text": "Syntax:" }, { "code": null, "e": 26853, "s": 26823, "text": "_.pickBy( object, predicate )" }, { "code": null, "e": 26940, "s": 26853, "text": "Parameters: This method accepts two parameters as mentioned above and described below:" }, { "code": null, "e": 26988, "s": 26940, "text": "object: This parameter holds the source object." }, { "code": null, "e": 27094, "s": 26988, "text": "predicate: This parameter holds the function that is invoked for every property. It is an optional value." }, { "code": null, "e": 27144, "s": 27094, "text": "Return Value: This method returns the new object." }, { "code": null, "e": 27155, "s": 27144, "text": "Example 1:" }, { "code": null, "e": 27166, "s": 27155, "text": "Javascript" }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // The source objectvar obj = { Name: \"GeeksforGeeks\", password: 123456, username: \"your_geeks\"} // Using the _.pickBy() method console.log(_.pickBy(obj, _.isLength));", "e": 27412, "s": 27166, "text": null }, { "code": null, "e": 27420, "s": 27412, "text": "Output:" }, { "code": null, "e": 27441, "s": 27420, "text": "{'password': 123456}" }, { "code": null, "e": 27454, "s": 27441, "text": "Example 2: " }, { "code": null, "e": 27465, "s": 27454, "text": "Javascript" }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // The source objectvar obj = { 'x': 1, 'y': '2', 'z': 3 }; // Using the _.pickBy() method console.log(_.pickBy(obj, _.isNumber));", "e": 27662, "s": 27465, "text": null }, { "code": null, "e": 27670, "s": 27662, "text": "Output:" }, { "code": null, "e": 27687, "s": 27670, "text": "{'x': 1, 'z': 3}" }, { "code": null, "e": 27705, "s": 27687, "text": "JavaScript-Lodash" }, { "code": null, "e": 27716, "s": 27705, "text": "JavaScript" }, { "code": null, "e": 27733, "s": 27716, "text": "Web Technologies" }, { "code": null, "e": 27831, "s": 27733, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27871, "s": 27831, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27932, "s": 27871, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27973, "s": 27932, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 27995, "s": 27973, "text": "JavaScript | Promises" }, { "code": null, "e": 28049, "s": 27995, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 28089, "s": 28049, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28122, "s": 28089, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28165, "s": 28122, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28215, "s": 28165, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Number of intersections between two ranges - GeeksforGeeks
10 Sep, 2021 Given N ranges of type1 ranges and M ranges of type2.The task is to find the total number of intersections between all possible type1 and type2 range pairs. All start and end points of type1 and type2 ranges are given.Examples: Input : N = 2, M = 2 type1[ ] = { { 1, 3 }, { 5, 9 } } type2[ ] = { { 2, 8 }, { 9, 12 } } Output : 3 Range {2, 8} intersects with type1 ranges {1, 3} and {5, 9} Range {9, 12} intersects with {5, 9} only. So the total number of intersections is 3.Input : N = 3, M = 1 type1[ ] = { { 1, 8 }, { 5, 10 }, { 14, 28 } type2[ ] = { { 2, 8 } } Output : 2 Approach: Idea is to use inclusion-exclusion method to determine the total number of intersections. Total possible number of intersections are n * m. Now subtract those count of type1 ranges which do not intersect with ith type2 range. Those type1 ranges will not intersect with ith type2 range which ends before starts of ith type2 range and starts after the end of ith type2 range. This count can be determined by using binary search . The C++ inbuilt function upper_bound can be used directly. Below is the implementation of above approach: CPP Java Python3 C# Javascript // C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to return total// number of intersectionsint FindIntersection(pair<int, int> type1[], int n, pair<int, int> type2[], int m){ // Maximum possible number // of intersections int ans = n * m; vector<int> start, end; for (int i = 0; i < n; i++) { // Store all starting // points of type1 ranges start.push_back(type1[i].first); // Store all endpoints // of type1 ranges end.push_back(type1[i].second); } sort(start.begin(), start.end()); sort(end.begin(), end.end()); for (int i = 0; i < m; i++) { // Starting point of type2 ranges int L = type2[i].first; // Ending point of type2 ranges int R = type2[i].second; // Subtract those ranges which // are starting after R ans -= (start.end() - upper_bound(start.begin(), start.end(), R)); // Subtract those ranges which // are ending before L ans -= (upper_bound(end.begin(), end.end(), L - 1) - end.begin()); } return ans;} // Driver Codeint main(){ pair<int, int> type1[] = { { 1, 2 }, { 2, 3 }, { 4, 5 }, { 6, 7 } }; pair<int, int> type2[] = { { 1, 5 }, { 2, 3 }, { 4, 7 }, { 5, 7 } }; int n = sizeof(type1) / (sizeof(type1[0])); int m = sizeof(type2) / sizeof(type2[0]); cout << FindIntersection(type1, n, type2, m); return 0;} // Java implementation of above approachimport java.io.*;import java.util.*;class GFG{ static int upperBound(ArrayList<Integer> a, int low, int high, int element) { while (low < high) { int middle = low + (high - low) / 2; if (a.get(middle) > element) { high = middle; } else { low = middle + 1; } } return low; } // Function to return total // number of intersections static int FindIntersection(ArrayList<ArrayList<Integer>> type1, int n, ArrayList<ArrayList<Integer>> type2, int m ) { // Maximum possible number // of intersections int ans = n * m; ArrayList<Integer> start = new ArrayList<Integer>(); ArrayList<Integer> end = new ArrayList<Integer>(); for (int i = 0; i < n; i++) { // Store all starting // points of type1 ranges start.add(type1.get(i).get(0)); // Store all endpoints // of type1 ranges end.add(type1.get(i).get(1)); } Collections.sort(start); Collections.sort(end); for (int i = 0; i < m; i++) { // Starting point of type2 ranges int L = type2.get(i).get(0); // Ending point of type2 ranges int R = type2.get(i).get(1); // Subtract those ranges which // are starting after R ans -= start.size() - upperBound(start, 0, start.size(), R); // Subtract those ranges which // are ending before L ans -= upperBound(end, 0, end.size() , L - 1); } return ans; } // Driver Code public static void main (String[] args) { ArrayList<ArrayList<Integer>> type1 = new ArrayList<ArrayList<Integer>>(); type1.add(new ArrayList<Integer>(Arrays.asList(1,2))); type1.add(new ArrayList<Integer>(Arrays.asList(2,3))); type1.add(new ArrayList<Integer>(Arrays.asList(4,5))); type1.add(new ArrayList<Integer>(Arrays.asList(6,7))); ArrayList<ArrayList<Integer>> type2 = new ArrayList<ArrayList<Integer>>(); type2.add(new ArrayList<Integer>(Arrays.asList(1,5))); type2.add(new ArrayList<Integer>(Arrays.asList(2,3))); type2.add(new ArrayList<Integer>(Arrays.asList(4,7))); type2.add(new ArrayList<Integer>(Arrays.asList(5,7))); int n = type1.size(); int m = type2.size(); System.out.println(FindIntersection(type1, n, type2, m)); }} // This code is contributed by avanitrachhadiya2155 # Python3 implementation of above approachfrom bisect import bisect as upper_bound # Function to return total# number of intersectionsdef FindIntersection(type1, n, type2, m): # Maximum possible number # of intersections ans = n * m start = [] end = [] for i in range(n): # Store all starting # points of type1 ranges start.append(type1[i][0]) # Store all endpoints # of type1 ranges end.append(type1[i][1]) start = sorted(start) start = sorted(end) for i in range(m): # Starting point of type2 ranges L = type2[i][0] # Ending point of type2 ranges R = type2[i][1] # Subtract those ranges which # are starting after R ans -= (len(start)- upper_bound(start, R)) # Subtract those ranges which # are ending before L ans -= (upper_bound(end, L - 1)) return ans # Driver Codetype1 = [ [ 1, 2 ], [ 2, 3 ], [ 4, 5 ], [ 6, 7 ] ] type2 = [ [ 1, 5 ], [ 2, 3 ], [ 4, 7 ], [ 5, 7 ] ] n = len(type1)m = len(type2) print(FindIntersection(type1, n, type2, m)) # This code is contributed by Mohit Kumar // C# implementation of above approachusing System;using System.Collections.Generic;class GFG{ static int upperBound(List<int> a, int low, int high, int element) { while (low < high) { int middle = low + (high - low) / 2; if (a[middle] > element) { high = middle; } else { low = middle + 1; } } return low; } // Function to return total // number of intersections static int FindIntersection(List<List<int>> type1, int n, List<List<int>> type2, int m) { // Maximum possible number // of intersections int ans = n * m; List<int> start = new List<int>(); List<int> end = new List<int>(); for (int i = 0; i < n; i++) { // Store all starting // points of type1 ranges start.Add(type1[i][0]); // Store all endpoints // of type1 ranges end.Add(type1[i][1]); } start.Sort(); end.Sort(); for (int i = 0; i < m; i++) { // Starting point of type2 ranges int L = type2[i][0]; // Ending point of type2 ranges int R = type2[i][1]; // Subtract those ranges which // are starting after R ans -= start.Count - upperBound(start, 0, start.Count, R); // Subtract those ranges which // are ending before L ans -= upperBound(end, 0, end.Count , L - 1); } return ans; } // Driver Code static public void Main () { List<List<int>> type1 = new List<List<int>>(); type1.Add(new List<int>(){1,2}); type1.Add(new List<int>(){2,3}); type1.Add(new List<int>(){4,5}); type1.Add(new List<int>(){6,7}); List<List<int>> type2 = new List<List<int>>(); type2.Add(new List<int>(){1,5}); type2.Add(new List<int>(){2,3}); type2.Add(new List<int>(){4,7}); type2.Add(new List<int>(){5,7}); int n = type1.Count; int m = type2.Count; Console.WriteLine(FindIntersection(type1, n, type2, m)); }} // This code is contributed by rag2127 <script>// Javascript implementation of above approach function upperBound(a,low,high,element){ while (low < high) { let middle = low + Math.floor((high - low) / 2); if (a[middle] > element) { high = middle; } else { low = middle + 1; } } return low;} // Function to return total // number of intersectionsfunction FindIntersection(type1,n,type2,m){ // Maximum possible number // of intersections let ans = n * m; let start = []; let end = []; for (let i = 0; i < n; i++) { // Store all starting // points of type1 ranges start.push(type1[i][0]); // Store all endpoints // of type1 ranges end.push(type1[i][1]); } start.sort(function(a,b){return a-b;}); end.sort(function(a,b){return a-b;}); for (let i = 0; i < m; i++) { // Starting point of type2 ranges let L = type2[i][0]; // Ending point of type2 ranges let R = type2[i][1]; // Subtract those ranges which // are starting after R ans -= start.length - upperBound(start, 0, start.length, R); // Subtract those ranges which // are ending before L ans -= upperBound(end, 0, end.length , L - 1); } return ans;} // Driver Codelet type1 = [ [ 1, 2 ], [ 2, 3 ], [ 4, 5 ], [ 6, 7 ] ]; let type2 = [ [ 1, 5 ], [ 2, 3 ], [ 4, 7 ], [ 5, 7 ] ]; let n = type1.length;let m = type2.length; document.write(FindIntersection(type1, n, type2, m)); // This code is contributed by patel2127</script> 9 Time Complexity: O(M*log(N)) mohit kumar 29 avanitrachhadiya2155 rag2127 patel2127 akshaysingh98088 Geometric Mathematical Searching Searching Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Haversine formula to find distance between two points on a sphere Program to find slope of a line Equation of circle when three points on the circle are given Program to find line passing through 2 Points Maximum Manhattan distance between a distinct pair from N coordinates 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": 26561, "s": 26533, "text": "\n10 Sep, 2021" }, { "code": null, "e": 26790, "s": 26561, "text": "Given N ranges of type1 ranges and M ranges of type2.The task is to find the total number of intersections between all possible type1 and type2 range pairs. All start and end points of type1 and type2 ranges are given.Examples: " }, { "code": null, "e": 27139, "s": 26790, "text": "Input : N = 2, M = 2 type1[ ] = { { 1, 3 }, { 5, 9 } } type2[ ] = { { 2, 8 }, { 9, 12 } } Output : 3 Range {2, 8} intersects with type1 ranges {1, 3} and {5, 9} Range {9, 12} intersects with {5, 9} only. So the total number of intersections is 3.Input : N = 3, M = 1 type1[ ] = { { 1, 8 }, { 5, 10 }, { 14, 28 } type2[ ] = { { 2, 8 } } Output : 2 " }, { "code": null, "e": 27153, "s": 27141, "text": "Approach: " }, { "code": null, "e": 27243, "s": 27153, "text": "Idea is to use inclusion-exclusion method to determine the total number of intersections." }, { "code": null, "e": 27379, "s": 27243, "text": "Total possible number of intersections are n * m. Now subtract those count of type1 ranges which do not intersect with ith type2 range." }, { "code": null, "e": 27527, "s": 27379, "text": "Those type1 ranges will not intersect with ith type2 range which ends before starts of ith type2 range and starts after the end of ith type2 range." }, { "code": null, "e": 27640, "s": 27527, "text": "This count can be determined by using binary search . The C++ inbuilt function upper_bound can be used directly." }, { "code": null, "e": 27688, "s": 27640, "text": "Below is the implementation of above approach: " }, { "code": null, "e": 27692, "s": 27688, "text": "CPP" }, { "code": null, "e": 27697, "s": 27692, "text": "Java" }, { "code": null, "e": 27705, "s": 27697, "text": "Python3" }, { "code": null, "e": 27708, "s": 27705, "text": "C#" }, { "code": null, "e": 27719, "s": 27708, "text": "Javascript" }, { "code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to return total// number of intersectionsint FindIntersection(pair<int, int> type1[], int n, pair<int, int> type2[], int m){ // Maximum possible number // of intersections int ans = n * m; vector<int> start, end; for (int i = 0; i < n; i++) { // Store all starting // points of type1 ranges start.push_back(type1[i].first); // Store all endpoints // of type1 ranges end.push_back(type1[i].second); } sort(start.begin(), start.end()); sort(end.begin(), end.end()); for (int i = 0; i < m; i++) { // Starting point of type2 ranges int L = type2[i].first; // Ending point of type2 ranges int R = type2[i].second; // Subtract those ranges which // are starting after R ans -= (start.end() - upper_bound(start.begin(), start.end(), R)); // Subtract those ranges which // are ending before L ans -= (upper_bound(end.begin(), end.end(), L - 1) - end.begin()); } return ans;} // Driver Codeint main(){ pair<int, int> type1[] = { { 1, 2 }, { 2, 3 }, { 4, 5 }, { 6, 7 } }; pair<int, int> type2[] = { { 1, 5 }, { 2, 3 }, { 4, 7 }, { 5, 7 } }; int n = sizeof(type1) / (sizeof(type1[0])); int m = sizeof(type2) / sizeof(type2[0]); cout << FindIntersection(type1, n, type2, m); return 0;}", "e": 29215, "s": 27719, "text": null }, { "code": "// Java implementation of above approachimport java.io.*;import java.util.*;class GFG{ static int upperBound(ArrayList<Integer> a, int low, int high, int element) { while (low < high) { int middle = low + (high - low) / 2; if (a.get(middle) > element) { high = middle; } else { low = middle + 1; } } return low; } // Function to return total // number of intersections static int FindIntersection(ArrayList<ArrayList<Integer>> type1, int n, ArrayList<ArrayList<Integer>> type2, int m ) { // Maximum possible number // of intersections int ans = n * m; ArrayList<Integer> start = new ArrayList<Integer>(); ArrayList<Integer> end = new ArrayList<Integer>(); for (int i = 0; i < n; i++) { // Store all starting // points of type1 ranges start.add(type1.get(i).get(0)); // Store all endpoints // of type1 ranges end.add(type1.get(i).get(1)); } Collections.sort(start); Collections.sort(end); for (int i = 0; i < m; i++) { // Starting point of type2 ranges int L = type2.get(i).get(0); // Ending point of type2 ranges int R = type2.get(i).get(1); // Subtract those ranges which // are starting after R ans -= start.size() - upperBound(start, 0, start.size(), R); // Subtract those ranges which // are ending before L ans -= upperBound(end, 0, end.size() , L - 1); } return ans; } // Driver Code public static void main (String[] args) { ArrayList<ArrayList<Integer>> type1 = new ArrayList<ArrayList<Integer>>(); type1.add(new ArrayList<Integer>(Arrays.asList(1,2))); type1.add(new ArrayList<Integer>(Arrays.asList(2,3))); type1.add(new ArrayList<Integer>(Arrays.asList(4,5))); type1.add(new ArrayList<Integer>(Arrays.asList(6,7))); ArrayList<ArrayList<Integer>> type2 = new ArrayList<ArrayList<Integer>>(); type2.add(new ArrayList<Integer>(Arrays.asList(1,5))); type2.add(new ArrayList<Integer>(Arrays.asList(2,3))); type2.add(new ArrayList<Integer>(Arrays.asList(4,7))); type2.add(new ArrayList<Integer>(Arrays.asList(5,7))); int n = type1.size(); int m = type2.size(); System.out.println(FindIntersection(type1, n, type2, m)); }} // This code is contributed by avanitrachhadiya2155", "e": 31977, "s": 29215, "text": null }, { "code": "# Python3 implementation of above approachfrom bisect import bisect as upper_bound # Function to return total# number of intersectionsdef FindIntersection(type1, n, type2, m): # Maximum possible number # of intersections ans = n * m start = [] end = [] for i in range(n): # Store all starting # points of type1 ranges start.append(type1[i][0]) # Store all endpoints # of type1 ranges end.append(type1[i][1]) start = sorted(start) start = sorted(end) for i in range(m): # Starting point of type2 ranges L = type2[i][0] # Ending point of type2 ranges R = type2[i][1] # Subtract those ranges which # are starting after R ans -= (len(start)- upper_bound(start, R)) # Subtract those ranges which # are ending before L ans -= (upper_bound(end, L - 1)) return ans # Driver Codetype1 = [ [ 1, 2 ], [ 2, 3 ], [ 4, 5 ], [ 6, 7 ] ] type2 = [ [ 1, 5 ], [ 2, 3 ], [ 4, 7 ], [ 5, 7 ] ] n = len(type1)m = len(type2) print(FindIntersection(type1, n, type2, m)) # This code is contributed by Mohit Kumar", "e": 33143, "s": 31977, "text": null }, { "code": "// C# implementation of above approachusing System;using System.Collections.Generic;class GFG{ static int upperBound(List<int> a, int low, int high, int element) { while (low < high) { int middle = low + (high - low) / 2; if (a[middle] > element) { high = middle; } else { low = middle + 1; } } return low; } // Function to return total // number of intersections static int FindIntersection(List<List<int>> type1, int n, List<List<int>> type2, int m) { // Maximum possible number // of intersections int ans = n * m; List<int> start = new List<int>(); List<int> end = new List<int>(); for (int i = 0; i < n; i++) { // Store all starting // points of type1 ranges start.Add(type1[i][0]); // Store all endpoints // of type1 ranges end.Add(type1[i][1]); } start.Sort(); end.Sort(); for (int i = 0; i < m; i++) { // Starting point of type2 ranges int L = type2[i][0]; // Ending point of type2 ranges int R = type2[i][1]; // Subtract those ranges which // are starting after R ans -= start.Count - upperBound(start, 0, start.Count, R); // Subtract those ranges which // are ending before L ans -= upperBound(end, 0, end.Count , L - 1); } return ans; } // Driver Code static public void Main () { List<List<int>> type1 = new List<List<int>>(); type1.Add(new List<int>(){1,2}); type1.Add(new List<int>(){2,3}); type1.Add(new List<int>(){4,5}); type1.Add(new List<int>(){6,7}); List<List<int>> type2 = new List<List<int>>(); type2.Add(new List<int>(){1,5}); type2.Add(new List<int>(){2,3}); type2.Add(new List<int>(){4,7}); type2.Add(new List<int>(){5,7}); int n = type1.Count; int m = type2.Count; Console.WriteLine(FindIntersection(type1, n, type2, m)); }} // This code is contributed by rag2127", "e": 35145, "s": 33143, "text": null }, { "code": "<script>// Javascript implementation of above approach function upperBound(a,low,high,element){ while (low < high) { let middle = low + Math.floor((high - low) / 2); if (a[middle] > element) { high = middle; } else { low = middle + 1; } } return low;} // Function to return total // number of intersectionsfunction FindIntersection(type1,n,type2,m){ // Maximum possible number // of intersections let ans = n * m; let start = []; let end = []; for (let i = 0; i < n; i++) { // Store all starting // points of type1 ranges start.push(type1[i][0]); // Store all endpoints // of type1 ranges end.push(type1[i][1]); } start.sort(function(a,b){return a-b;}); end.sort(function(a,b){return a-b;}); for (let i = 0; i < m; i++) { // Starting point of type2 ranges let L = type2[i][0]; // Ending point of type2 ranges let R = type2[i][1]; // Subtract those ranges which // are starting after R ans -= start.length - upperBound(start, 0, start.length, R); // Subtract those ranges which // are ending before L ans -= upperBound(end, 0, end.length , L - 1); } return ans;} // Driver Codelet type1 = [ [ 1, 2 ], [ 2, 3 ], [ 4, 5 ], [ 6, 7 ] ]; let type2 = [ [ 1, 5 ], [ 2, 3 ], [ 4, 7 ], [ 5, 7 ] ]; let n = type1.length;let m = type2.length; document.write(FindIntersection(type1, n, type2, m)); // This code is contributed by patel2127</script>", "e": 36977, "s": 35145, "text": null }, { "code": null, "e": 36979, "s": 36977, "text": "9" }, { "code": null, "e": 37011, "s": 36981, "text": "Time Complexity: O(M*log(N)) " }, { "code": null, "e": 37026, "s": 37011, "text": "mohit kumar 29" }, { "code": null, "e": 37047, "s": 37026, "text": "avanitrachhadiya2155" }, { "code": null, "e": 37055, "s": 37047, "text": "rag2127" }, { "code": null, "e": 37065, "s": 37055, "text": "patel2127" }, { "code": null, "e": 37082, "s": 37065, "text": "akshaysingh98088" }, { "code": null, "e": 37092, "s": 37082, "text": "Geometric" }, { "code": null, "e": 37105, "s": 37092, "text": "Mathematical" }, { "code": null, "e": 37115, "s": 37105, "text": "Searching" }, { "code": null, "e": 37125, "s": 37115, "text": "Searching" }, { "code": null, "e": 37138, "s": 37125, "text": "Mathematical" }, { "code": null, "e": 37148, "s": 37138, "text": "Geometric" }, { "code": null, "e": 37246, "s": 37148, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37312, "s": 37246, "text": "Haversine formula to find distance between two points on a sphere" }, { "code": null, "e": 37344, "s": 37312, "text": "Program to find slope of a line" }, { "code": null, "e": 37405, "s": 37344, "text": "Equation of circle when three points on the circle are given" }, { "code": null, "e": 37451, "s": 37405, "text": "Program to find line passing through 2 Points" }, { "code": null, "e": 37521, "s": 37451, "text": "Maximum Manhattan distance between a distinct pair from N coordinates" }, { "code": null, "e": 37551, "s": 37521, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 37611, "s": 37551, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 37626, "s": 37611, "text": "C++ Data Types" }, { "code": null, "e": 37669, "s": 37626, "text": "Set in C++ Standard Template Library (STL)" } ]
Python | Program to count duplicates in a list of tuples - GeeksforGeeks
11 Dec, 2018 Given a list of tuples, write a Python program to check if an element of the list has duplicates. If duplicate exist, print the number of occurrence of each duplicate tuple, otherwise print “No Duplicates”. Examples: Input : [(‘a’, ‘e’), (‘b’, ‘x’), (‘b’, ‘x’), (‘a’, ‘e’), (‘b’, ‘x’)]Output :(‘a’, ‘e’) – 2(‘b’, ‘x’) – 3 Input : [(0, 5), (6, 9), (0, 8)]Output : No Duplicates Let’s see the various ways we can count duplicates in a list of tuples. Approach #1 : Naive Approach This approach uses two loops to traverse the list elements and check if the first element and second element of each element matches any other tuple. # Python3 code to convert tuple # into stringdef count(listOfTuple): flag = False # To append Duplicate elements in list coll_list = [] coll_cnt = 0 for t in listOfTuple: # To check if Duplicate exist if t in coll_list: flag = True continue else: coll_cnt = 0 for b in listOfTuple: if b[0] == t[0] and b[1] == t[1]: coll_cnt = coll_cnt + 1 # To print count if Duplicate of element exist if(coll_cnt > 1): print(t, "-", coll_cnt) coll_list.append(t) if flag == False: print("No Duplicates") # Driver codeprint("Test Case 1:")listOfTuple = [('a', 'e'), ('b', 'x'), ('b', 'x'), ('a', 'e'), ('b', 'x')] count(listOfTuple) print("Test Case 2:")listOfTuple = [(0, 5), (6, 9), (0, 8)]count(listOfTuple) Test Case 1: ('a', 'e') - 2 ('b', 'x') - 3 Test Case 2: No Duplicates Time complexity – O(n)2 Approach #2 : Using Counter Counter is a container included in the collections module. It is an unordered collection where elements and their respective count are stored as dictionary. # Python3 code to convert tuple # into stringimport collections def count(listOfTuple): flag = False val = collections.Counter(listOfTuple) uniqueList = list(set(listOfTuple)) for i in uniqueList: if val[i]>= 2: flag = True print(i, "-", val[i]) if flag == False: print("Duplicate doesn't exist") # Driver codelistOfTuple = [('a', 'e'), ('b', 'x'), ('b', 'x'), ('a', 'e'), ('b', 'x')] count(listOfTuple) ('b', 'x') - 3 ('a', 'e') - 2 Time complexity – O(n) Approach #3 : Using another dict You can make a dictionary, say count_map, and store the count of each tuple as the value. # Python3 code to convert tuple # into stringdef count(listOfTuple): count_map = {} for i in listOfTuple: count_map[i] = count_map.get(i, 0) +1 print(count_map) # Driver codeprint("Test Case 1:")listOfTuple = [('a', 'e'), ('b', 'x'), ('b', 'x'), ('a', 'e'), ('b', 'x')] count(listOfTuple) Test Case 1: {('a', 'e'): 2, ('b', 'x'): 3} Time complexity – O(n) Python list-programs Python tuple-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 26305, "s": 26277, "text": "\n11 Dec, 2018" }, { "code": null, "e": 26512, "s": 26305, "text": "Given a list of tuples, write a Python program to check if an element of the list has duplicates. If duplicate exist, print the number of occurrence of each duplicate tuple, otherwise print “No Duplicates”." }, { "code": null, "e": 26522, "s": 26512, "text": "Examples:" }, { "code": null, "e": 26627, "s": 26522, "text": "Input : [(‘a’, ‘e’), (‘b’, ‘x’), (‘b’, ‘x’), (‘a’, ‘e’), (‘b’, ‘x’)]Output :(‘a’, ‘e’) – 2(‘b’, ‘x’) – 3" }, { "code": null, "e": 26682, "s": 26627, "text": "Input : [(0, 5), (6, 9), (0, 8)]Output : No Duplicates" }, { "code": null, "e": 26754, "s": 26682, "text": "Let’s see the various ways we can count duplicates in a list of tuples." }, { "code": null, "e": 26783, "s": 26754, "text": "Approach #1 : Naive Approach" }, { "code": null, "e": 26933, "s": 26783, "text": "This approach uses two loops to traverse the list elements and check if the first element and second element of each element matches any other tuple." }, { "code": "# Python3 code to convert tuple # into stringdef count(listOfTuple): flag = False # To append Duplicate elements in list coll_list = [] coll_cnt = 0 for t in listOfTuple: # To check if Duplicate exist if t in coll_list: flag = True continue else: coll_cnt = 0 for b in listOfTuple: if b[0] == t[0] and b[1] == t[1]: coll_cnt = coll_cnt + 1 # To print count if Duplicate of element exist if(coll_cnt > 1): print(t, \"-\", coll_cnt) coll_list.append(t) if flag == False: print(\"No Duplicates\") # Driver codeprint(\"Test Case 1:\")listOfTuple = [('a', 'e'), ('b', 'x'), ('b', 'x'), ('a', 'e'), ('b', 'x')] count(listOfTuple) print(\"Test Case 2:\")listOfTuple = [(0, 5), (6, 9), (0, 8)]count(listOfTuple)", "e": 27890, "s": 26933, "text": null }, { "code": null, "e": 27962, "s": 27890, "text": "Test Case 1:\n('a', 'e') - 2\n('b', 'x') - 3\n\nTest Case 2:\nNo Duplicates\n" }, { "code": null, "e": 27986, "s": 27962, "text": "Time complexity – O(n)2" }, { "code": null, "e": 28015, "s": 27986, "text": " Approach #2 : Using Counter" }, { "code": null, "e": 28172, "s": 28015, "text": "Counter is a container included in the collections module. It is an unordered collection where elements and their respective count are stored as dictionary." }, { "code": "# Python3 code to convert tuple # into stringimport collections def count(listOfTuple): flag = False val = collections.Counter(listOfTuple) uniqueList = list(set(listOfTuple)) for i in uniqueList: if val[i]>= 2: flag = True print(i, \"-\", val[i]) if flag == False: print(\"Duplicate doesn't exist\") # Driver codelistOfTuple = [('a', 'e'), ('b', 'x'), ('b', 'x'), ('a', 'e'), ('b', 'x')] count(listOfTuple)", "e": 28670, "s": 28172, "text": null }, { "code": null, "e": 28701, "s": 28670, "text": "('b', 'x') - 3\n('a', 'e') - 2\n" }, { "code": null, "e": 28757, "s": 28701, "text": "Time complexity – O(n) Approach #3 : Using another dict" }, { "code": null, "e": 28847, "s": 28757, "text": "You can make a dictionary, say count_map, and store the count of each tuple as the value." }, { "code": "# Python3 code to convert tuple # into stringdef count(listOfTuple): count_map = {} for i in listOfTuple: count_map[i] = count_map.get(i, 0) +1 print(count_map) # Driver codeprint(\"Test Case 1:\")listOfTuple = [('a', 'e'), ('b', 'x'), ('b', 'x'), ('a', 'e'), ('b', 'x')] count(listOfTuple)", "e": 29176, "s": 28847, "text": null }, { "code": null, "e": 29221, "s": 29176, "text": "Test Case 1:\n{('a', 'e'): 2, ('b', 'x'): 3}\n" }, { "code": null, "e": 29244, "s": 29221, "text": "Time complexity – O(n)" }, { "code": null, "e": 29265, "s": 29244, "text": "Python list-programs" }, { "code": null, "e": 29287, "s": 29265, "text": "Python tuple-programs" }, { "code": null, "e": 29294, "s": 29287, "text": "Python" }, { "code": null, "e": 29310, "s": 29294, "text": "Python Programs" }, { "code": null, "e": 29408, "s": 29310, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29426, "s": 29408, "text": "Python Dictionary" }, { "code": null, "e": 29458, "s": 29426, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29480, "s": 29458, "text": "Enumerate() in Python" }, { "code": null, "e": 29522, "s": 29480, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29548, "s": 29522, "text": "Python String | replace()" }, { "code": null, "e": 29570, "s": 29548, "text": "Defaultdict in Python" }, { "code": null, "e": 29609, "s": 29570, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 29655, "s": 29609, "text": "Python | Split string into list of characters" }, { "code": null, "e": 29693, "s": 29655, "text": "Python | Convert a list to dictionary" } ]
Print all the duplicates in the input string - GeeksforGeeks
23 Nov, 2021 Write an efficient program to print all the duplicates and their counts in the input string Method 1: Using hashingAlgorithm: Let input string be “geeksforgeeks” 1: Construct character count array from the input string.count[‘e’] = 4 count[‘g’] = 2 count[‘k’] = 2 ......2: Print all the indexes from the constructed array which have values greater than 1.Solution C++14 C Java Python C# PHP Javascript // C++ program to count all duplicates// from string using hashing#include <iostream>using namespace std;# define NO_OF_CHARS 256 class gfg{ public : /* Fills count array with frequency of characters */ void fillCharCounts(char *str, int *count) { int i; for (i = 0; *(str + i); i++) count[*(str + i)]++; } /* Print duplicates present in the passed string */ void printDups(char *str) { // Create an array of size 256 and fill // count of every character in it int *count = (int *)calloc(NO_OF_CHARS, sizeof(int)); fillCharCounts(str, count); // Print characters having count more than 0 int i; for (i = 0; i < NO_OF_CHARS; i++) if(count[i] > 1) printf("%c, count = %d \n", i, count[i]); free(count); }}; /* Driver code*/int main(){ gfg g ; char str[] = "test string"; g.printDups(str); //getchar(); return 0;} // This code is contributed by SoM15242 // C program to count all duplicates// from string using hashing# include <stdio.h># include <stdlib.h># define NO_OF_CHARS 256 /* Fills count array with frequency of characters */void fillCharCounts(char *str, int *count){ int i; for (i = 0; *(str+i); i++) count[*(str+i)]++;} /* Print duplicates present in the passed string */void printDups(char *str){ // Create an array of size 256 and // fill count of every character in it int *count = (int *)calloc(NO_OF_CHARS, sizeof(int)); fillCharCounts(str, count); // Print characters having count more than 0 int i; for (i = 0; i < NO_OF_CHARS; i++) if(count[i] > 1) printf("%c, count = %d \n", i, count[i]); free(count);} /* Driver program to test to print printDups*/int main(){ char str[] = "test string"; printDups(str); getchar(); return 0;} // Java program to count all// duplicates from string using// hashing public class GFG { static final int NO_OF_CHARS = 256; /* Fills count array with frequency of characters */ static void fillCharCounts(String str, int[] count) { for (int i = 0; i < str.length(); i++) count[str.charAt(i)]++; } /* Print duplicates present in the passed string */ static void printDups(String str) { // Create an array of size // 256 and fill count of // every character in it int count[] = new int[NO_OF_CHARS]; fillCharCounts(str, count); for (int i = 0; i < NO_OF_CHARS; i++) if (count[i] > 1) System.out.println((char)(i) + ", count = " + count[i]); } // Driver Method public static void main(String[] args) { String str = "test string"; printDups(str); }} # Python program to count all# duplicates from string using hashingNO_OF_CHARS = 256 # Fills count array with# frequency of charactersdef fillCharCounts(string, count): for i in string: count[ord(i)] += 1 return count # Print duplicates present# in the passed stringdef printDups(string): # Create an array of size 256 # and fill count of every character in it count = [0] * NO_OF_CHARS count = fillCharCounts(string,count) # Utility Variable k = 0 # Print characters having # count more than 0 for i in count: if int(i) > 1: print chr(k) + ", count = " + str(i) k += 1 # Driver program to test the above functionstring = "test string"print printDups(string) # This code is contributed by Bhavya Jain // C# program to count all duplicates// from string using hashingusing System; class GFG{ static int NO_OF_CHARS = 256; /* Fills count array with frequency of characters */ static void fillCharCounts(String str, int[] count) { for (int i = 0; i < str.Length; i++) count[str[i]]++; } /* Print duplicates present in the passed string */ static void printDups(String str) { // Create an array of size 256 and // fill count of every character in it int []count = new int[NO_OF_CHARS]; fillCharCounts(str, count); for (int i = 0; i < NO_OF_CHARS; i++) if(count[i] > 1) Console.WriteLine((char)i + ", " + "count = " + count[i]); } // Driver Method public static void Main() { String str = "test string"; printDups(str); }} // This code is contributed by Sam007 <?php// PHP program to count// all duplicates from// string using hashingfunction fillCharCounts($str, $count){ for ($i = 0; $i < strlen($str); $i++) $count[ord($str[$i])]++; for ($i = 0; $i < 256; $i++) if($count[$i] > 1) echo chr($i) . ", " ."count = " . ($count[$i]) . "\n";} // Print duplicates present// in the passed stringfunction printDups($str){ // Create an array of size // 256 and fill count of // every character in it $count = array(); for ($i = 0; $i < 256; $i++) $count[$i] = 0; fillCharCounts($str, $count); } // Driver Code$str = "test string";printDups($str); // This code is contributed by Sam007?> <script> // Javascript program to count all duplicates // from string using hashing let NO_OF_CHARS = 256; /* Print duplicates present in the passed string */ function printDups(str) { // Create an array of size 256 and // fill count of every character in it let count = new Array(NO_OF_CHARS); count.fill(0); for (let i = 0; i < str.length; i++) count[str[i].charCodeAt()]++; for (let i = 0; i < NO_OF_CHARS; i++) { if(count[i] > 1) { document.write(String.fromCharCode(i) + ", " + "count = " + count[i] + "</br>"); } } } let str = "test string"; printDups(str); </script> s, count = 2 t, count = 3 Time Complexity: O(n), where n = length of the string passed Space Complexity: O(NO_OF_CHARS) Note: Hashing involves the use of an array of fixed size each time no matter whatever the string is. For example, str = “aaaaaaaaaa”. An array of size 256 is used for str, only 1 block out of total size (256) will be utilized to store the number of occurrences of ‘a’ in str (i.e count[‘a’] = 10). Rest 256 – 1 = 255 blocks remain unused. Thus, Space Complexity is potentially high for such cases. So, to avoid any discrepancies and to improve Space Complexity, maps are generally preferred over long-sized arrays. Method 2: Using Maps Approach: The approach is the same as discussed in Method 1, but, using a map to store the count. Solution: C++ Java Python3 C# Javascript // C++ program to count all duplicates// from string using maps#include <bits/stdc++.h>using namespace std;void printDups(string str){ map<char, int> count; for (int i = 0; i < str.length(); i++) { count[str[i]]++; } for (auto it : count) { if (it.second > 1) cout << it.first << ", count = " << it.second << "\n"; }}/* Driver code*/int main(){ string str = "test string"; printDups(str); return 0;}// This code is contributed by yashbeersingh42 // Java program to count all duplicates// from string using mapsimport java.util.*; class GFG { static void printDups(String str) { HashMap<Character, Integer> count = new HashMap<>(); /*Store duplicates present in the passed string */ for (int i = 0; i < str.length(); i++) { if (!count.containsKey(str.charAt(i))) count.put(str.charAt(i), 1); else count.put(str.charAt(i), count.get(str.charAt(i)) + 1); } /*Print duplicates in sorted order*/ for (Map.Entry mapElement : count.entrySet()) { char key = (char)mapElement.getKey(); int value = ((int)mapElement.getValue()); if (value > 1) System.out.println(key + ", count = " + value); } } // Driver code public static void main(String[] args) { String str = "test string"; printDups(str); }}// This code is contributed by yashbeersingh42 # Python 3 program to count all duplicates# from string using mapsfrom collections import defaultdict def printDups(st): count = defaultdict(int) for i in range(len(st)): count[st[i]] += 1 for it in count: if (count[it] > 1): print(it, ", count = ", count[it]) # Driver codeif __name__ == "__main__": st = "test string" printDups(st) # This code is contributed by ukasp. // C# program to count all duplicates// from string using mapsusing System;using System.Collections.Generic;using System.Linq; class GFG{ static void printDups(String str){ Dictionary<char, int> count = new Dictionary<char, int>(); for(int i = 0; i < str.Length; i++) { if (count.ContainsKey(str[i])) count[str[i]]++; else count[str[i]] = 1; } foreach(var it in count.OrderBy(key => key.Value)) { if (it.Value > 1) Console.WriteLine(it.Key + ", count = " + it.Value); }} // Driver codestatic public void Main(){ String str = "test string"; printDups(str);}} // This code is contributed by shubhamsingh10 <script>//Javascript Implementation// to count all duplicates// from string using maps function printDups(str){ var count = {}; for (var i = 0; i < str.length; i++) { count[str[i]] = 0; } for (var i = 0; i < str.length; i++) { count[str[i]]++; } for (var it in count) { if (count[it] > 1) document.write(it + ", count = " + count[it] + "<br>"); }}/* Driver code*/var str = "test string";printDups(str); // This code is contributed by shubhamsingh10</script> s, count = 2 t, count = 3 Time Complexity: O(N log N), where N = length of the string passed and it generally takes logN time for an element insertion in a map. Space Complexity: O(K), where K = size of the map (0<=K<=input_string_length). Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. YouTubeGeeksforGeeks506K subscribersPrint all the duplicates in the input string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:33•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=KYVR5U7rwAE" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> C++ // C++ program to count all duplicates// from string using maps#include <bits/stdc++.h>using namespace std;void printDups(string str){ unordered_map<char, int> count; for (int i = 0; i < str.length(); i++) { count[str[i]]++; //increase the count of characters by 1 } for (auto it : count) { //iterating through the unordered map if (it.second > 1) //if the count of characters is greater then 1 then duplicate found cout << it.first << ", count = " << it.second << "\n"; }}/* Driver code*/int main(){ string str = "test string"; printDups(str); return 0;} s, count = 2 t, count = 3 Time Complexity: O(N), where N = length of the string passed and it takes O(1) time to insert and access any element in an unordered map Space Complexity: O(K), where K = size of the map (0<=K<=input_string_length). Sam007 manoprakash6 SoumikMondal saxenakg yashbeersingh42 decode2207 ukasp SHUBHAMSINGH10 rupeshsk30 singghakshay String Duplicates Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Array of Strings in C++ (5 Different Ways to Create) Convert string to char array in C++ Longest Palindromic Substring | Set 1 Caesar Cipher in Cryptography Check whether two strings are anagram of each other Length of the longest substring without repeating characters Top 50 String Coding Problems for Interviews Remove duplicates from a given string How to split a string in C/C++, Python and Java? Reverse words in a given string
[ { "code": null, "e": 26495, "s": 26467, "text": "\n23 Nov, 2021" }, { "code": null, "e": 26588, "s": 26495, "text": "Write an efficient program to print all the duplicates and their counts in the input string " }, { "code": null, "e": 26861, "s": 26588, "text": "Method 1: Using hashingAlgorithm: Let input string be “geeksforgeeks” 1: Construct character count array from the input string.count[‘e’] = 4 count[‘g’] = 2 count[‘k’] = 2 ......2: Print all the indexes from the constructed array which have values greater than 1.Solution " }, { "code": null, "e": 26867, "s": 26861, "text": "C++14" }, { "code": null, "e": 26869, "s": 26867, "text": "C" }, { "code": null, "e": 26874, "s": 26869, "text": "Java" }, { "code": null, "e": 26881, "s": 26874, "text": "Python" }, { "code": null, "e": 26884, "s": 26881, "text": "C#" }, { "code": null, "e": 26888, "s": 26884, "text": "PHP" }, { "code": null, "e": 26899, "s": 26888, "text": "Javascript" }, { "code": "// C++ program to count all duplicates// from string using hashing#include <iostream>using namespace std;# define NO_OF_CHARS 256 class gfg{ public : /* Fills count array with frequency of characters */ void fillCharCounts(char *str, int *count) { int i; for (i = 0; *(str + i); i++) count[*(str + i)]++; } /* Print duplicates present in the passed string */ void printDups(char *str) { // Create an array of size 256 and fill // count of every character in it int *count = (int *)calloc(NO_OF_CHARS, sizeof(int)); fillCharCounts(str, count); // Print characters having count more than 0 int i; for (i = 0; i < NO_OF_CHARS; i++) if(count[i] > 1) printf(\"%c, count = %d \\n\", i, count[i]); free(count); }}; /* Driver code*/int main(){ gfg g ; char str[] = \"test string\"; g.printDups(str); //getchar(); return 0;} // This code is contributed by SoM15242", "e": 27947, "s": 26899, "text": null }, { "code": "// C program to count all duplicates// from string using hashing# include <stdio.h># include <stdlib.h># define NO_OF_CHARS 256 /* Fills count array with frequency of characters */void fillCharCounts(char *str, int *count){ int i; for (i = 0; *(str+i); i++) count[*(str+i)]++;} /* Print duplicates present in the passed string */void printDups(char *str){ // Create an array of size 256 and // fill count of every character in it int *count = (int *)calloc(NO_OF_CHARS, sizeof(int)); fillCharCounts(str, count); // Print characters having count more than 0 int i; for (i = 0; i < NO_OF_CHARS; i++) if(count[i] > 1) printf(\"%c, count = %d \\n\", i, count[i]); free(count);} /* Driver program to test to print printDups*/int main(){ char str[] = \"test string\"; printDups(str); getchar(); return 0;}", "e": 28821, "s": 27947, "text": null }, { "code": "// Java program to count all// duplicates from string using// hashing public class GFG { static final int NO_OF_CHARS = 256; /* Fills count array with frequency of characters */ static void fillCharCounts(String str, int[] count) { for (int i = 0; i < str.length(); i++) count[str.charAt(i)]++; } /* Print duplicates present in the passed string */ static void printDups(String str) { // Create an array of size // 256 and fill count of // every character in it int count[] = new int[NO_OF_CHARS]; fillCharCounts(str, count); for (int i = 0; i < NO_OF_CHARS; i++) if (count[i] > 1) System.out.println((char)(i) + \", count = \" + count[i]); } // Driver Method public static void main(String[] args) { String str = \"test string\"; printDups(str); }}", "e": 29780, "s": 28821, "text": null }, { "code": "# Python program to count all# duplicates from string using hashingNO_OF_CHARS = 256 # Fills count array with# frequency of charactersdef fillCharCounts(string, count): for i in string: count[ord(i)] += 1 return count # Print duplicates present# in the passed stringdef printDups(string): # Create an array of size 256 # and fill count of every character in it count = [0] * NO_OF_CHARS count = fillCharCounts(string,count) # Utility Variable k = 0 # Print characters having # count more than 0 for i in count: if int(i) > 1: print chr(k) + \", count = \" + str(i) k += 1 # Driver program to test the above functionstring = \"test string\"print printDups(string) # This code is contributed by Bhavya Jain", "e": 30553, "s": 29780, "text": null }, { "code": "// C# program to count all duplicates// from string using hashingusing System; class GFG{ static int NO_OF_CHARS = 256; /* Fills count array with frequency of characters */ static void fillCharCounts(String str, int[] count) { for (int i = 0; i < str.Length; i++) count[str[i]]++; } /* Print duplicates present in the passed string */ static void printDups(String str) { // Create an array of size 256 and // fill count of every character in it int []count = new int[NO_OF_CHARS]; fillCharCounts(str, count); for (int i = 0; i < NO_OF_CHARS; i++) if(count[i] > 1) Console.WriteLine((char)i + \", \" + \"count = \" + count[i]); } // Driver Method public static void Main() { String str = \"test string\"; printDups(str); }} // This code is contributed by Sam007", "e": 31544, "s": 30553, "text": null }, { "code": "<?php// PHP program to count// all duplicates from// string using hashingfunction fillCharCounts($str, $count){ for ($i = 0; $i < strlen($str); $i++) $count[ord($str[$i])]++; for ($i = 0; $i < 256; $i++) if($count[$i] > 1) echo chr($i) . \", \" .\"count = \" . ($count[$i]) . \"\\n\";} // Print duplicates present// in the passed stringfunction printDups($str){ // Create an array of size // 256 and fill count of // every character in it $count = array(); for ($i = 0; $i < 256; $i++) $count[$i] = 0; fillCharCounts($str, $count); } // Driver Code$str = \"test string\";printDups($str); // This code is contributed by Sam007?>", "e": 32257, "s": 31544, "text": null }, { "code": "<script> // Javascript program to count all duplicates // from string using hashing let NO_OF_CHARS = 256; /* Print duplicates present in the passed string */ function printDups(str) { // Create an array of size 256 and // fill count of every character in it let count = new Array(NO_OF_CHARS); count.fill(0); for (let i = 0; i < str.length; i++) count[str[i].charCodeAt()]++; for (let i = 0; i < NO_OF_CHARS; i++) { if(count[i] > 1) { document.write(String.fromCharCode(i) + \", \" + \"count = \" + count[i] + \"</br>\"); } } } let str = \"test string\"; printDups(str); </script>", "e": 33054, "s": 32257, "text": null }, { "code": null, "e": 33082, "s": 33054, "text": "s, count = 2 \nt, count = 3 " }, { "code": null, "e": 33143, "s": 33082, "text": "Time Complexity: O(n), where n = length of the string passed" }, { "code": null, "e": 33176, "s": 33143, "text": "Space Complexity: O(NO_OF_CHARS)" }, { "code": null, "e": 33278, "s": 33176, "text": "Note: Hashing involves the use of an array of fixed size each time no matter whatever the string is. " }, { "code": null, "e": 33312, "s": 33278, "text": "For example, str = “aaaaaaaaaa”. " }, { "code": null, "e": 33477, "s": 33312, "text": "An array of size 256 is used for str, only 1 block out of total size (256) will be utilized to store the number of occurrences of ‘a’ in str (i.e count[‘a’] = 10). " }, { "code": null, "e": 33519, "s": 33477, "text": "Rest 256 – 1 = 255 blocks remain unused. " }, { "code": null, "e": 33696, "s": 33519, "text": "Thus, Space Complexity is potentially high for such cases. So, to avoid any discrepancies and to improve Space Complexity, maps are generally preferred over long-sized arrays. " }, { "code": null, "e": 33717, "s": 33696, "text": "Method 2: Using Maps" }, { "code": null, "e": 33815, "s": 33717, "text": "Approach: The approach is the same as discussed in Method 1, but, using a map to store the count." }, { "code": null, "e": 33825, "s": 33815, "text": "Solution:" }, { "code": null, "e": 33829, "s": 33825, "text": "C++" }, { "code": null, "e": 33834, "s": 33829, "text": "Java" }, { "code": null, "e": 33842, "s": 33834, "text": "Python3" }, { "code": null, "e": 33845, "s": 33842, "text": "C#" }, { "code": null, "e": 33856, "s": 33845, "text": "Javascript" }, { "code": "// C++ program to count all duplicates// from string using maps#include <bits/stdc++.h>using namespace std;void printDups(string str){ map<char, int> count; for (int i = 0; i < str.length(); i++) { count[str[i]]++; } for (auto it : count) { if (it.second > 1) cout << it.first << \", count = \" << it.second << \"\\n\"; }}/* Driver code*/int main(){ string str = \"test string\"; printDups(str); return 0;}// This code is contributed by yashbeersingh42", "e": 34368, "s": 33856, "text": null }, { "code": "// Java program to count all duplicates// from string using mapsimport java.util.*; class GFG { static void printDups(String str) { HashMap<Character, Integer> count = new HashMap<>(); /*Store duplicates present in the passed string */ for (int i = 0; i < str.length(); i++) { if (!count.containsKey(str.charAt(i))) count.put(str.charAt(i), 1); else count.put(str.charAt(i), count.get(str.charAt(i)) + 1); } /*Print duplicates in sorted order*/ for (Map.Entry mapElement : count.entrySet()) { char key = (char)mapElement.getKey(); int value = ((int)mapElement.getValue()); if (value > 1) System.out.println(key + \", count = \" + value); } } // Driver code public static void main(String[] args) { String str = \"test string\"; printDups(str); }}// This code is contributed by yashbeersingh42", "e": 35410, "s": 34368, "text": null }, { "code": "# Python 3 program to count all duplicates# from string using mapsfrom collections import defaultdict def printDups(st): count = defaultdict(int) for i in range(len(st)): count[st[i]] += 1 for it in count: if (count[it] > 1): print(it, \", count = \", count[it]) # Driver codeif __name__ == \"__main__\": st = \"test string\" printDups(st) # This code is contributed by ukasp.", "e": 35828, "s": 35410, "text": null }, { "code": "// C# program to count all duplicates// from string using mapsusing System;using System.Collections.Generic;using System.Linq; class GFG{ static void printDups(String str){ Dictionary<char, int> count = new Dictionary<char, int>(); for(int i = 0; i < str.Length; i++) { if (count.ContainsKey(str[i])) count[str[i]]++; else count[str[i]] = 1; } foreach(var it in count.OrderBy(key => key.Value)) { if (it.Value > 1) Console.WriteLine(it.Key + \", count = \" + it.Value); }} // Driver codestatic public void Main(){ String str = \"test string\"; printDups(str);}} // This code is contributed by shubhamsingh10", "e": 36600, "s": 35828, "text": null }, { "code": "<script>//Javascript Implementation// to count all duplicates// from string using maps function printDups(str){ var count = {}; for (var i = 0; i < str.length; i++) { count[str[i]] = 0; } for (var i = 0; i < str.length; i++) { count[str[i]]++; } for (var it in count) { if (count[it] > 1) document.write(it + \", count = \" + count[it] + \"<br>\"); }}/* Driver code*/var str = \"test string\";printDups(str); // This code is contributed by shubhamsingh10</script>", "e": 37118, "s": 36600, "text": null }, { "code": null, "e": 37144, "s": 37118, "text": "s, count = 2\nt, count = 3" }, { "code": null, "e": 37279, "s": 37144, "text": "Time Complexity: O(N log N), where N = length of the string passed and it generally takes logN time for an element insertion in a map." }, { "code": null, "e": 37358, "s": 37279, "text": "Space Complexity: O(K), where K = size of the map (0<=K<=input_string_length)." }, { "code": null, "e": 37484, "s": 37358, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 38327, "s": 37484, "text": "YouTubeGeeksforGeeks506K subscribersPrint all the duplicates in the input string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:33•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=KYVR5U7rwAE\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 38331, "s": 38327, "text": "C++" }, { "code": "// C++ program to count all duplicates// from string using maps#include <bits/stdc++.h>using namespace std;void printDups(string str){ unordered_map<char, int> count; for (int i = 0; i < str.length(); i++) { count[str[i]]++; //increase the count of characters by 1 } for (auto it : count) { //iterating through the unordered map if (it.second > 1) //if the count of characters is greater then 1 then duplicate found cout << it.first << \", count = \" << it.second << \"\\n\"; }}/* Driver code*/int main(){ string str = \"test string\"; printDups(str); return 0;}", "e": 38959, "s": 38331, "text": null }, { "code": null, "e": 38985, "s": 38959, "text": "s, count = 2\nt, count = 3" }, { "code": null, "e": 39002, "s": 38985, "text": "Time Complexity:" }, { "code": null, "e": 39122, "s": 39002, "text": "O(N), where N = length of the string passed and it takes O(1) time to insert and access any element in an unordered map" }, { "code": null, "e": 39140, "s": 39122, "text": "Space Complexity:" }, { "code": null, "e": 39202, "s": 39140, "text": " O(K), where K = size of the map (0<=K<=input_string_length)." }, { "code": null, "e": 39209, "s": 39202, "text": "Sam007" }, { "code": null, "e": 39222, "s": 39209, "text": "manoprakash6" }, { "code": null, "e": 39235, "s": 39222, "text": "SoumikMondal" }, { "code": null, "e": 39244, "s": 39235, "text": "saxenakg" }, { "code": null, "e": 39260, "s": 39244, "text": "yashbeersingh42" }, { "code": null, "e": 39271, "s": 39260, "text": "decode2207" }, { "code": null, "e": 39277, "s": 39271, "text": "ukasp" }, { "code": null, "e": 39292, "s": 39277, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 39303, "s": 39292, "text": "rupeshsk30" }, { "code": null, "e": 39316, "s": 39303, "text": "singghakshay" }, { "code": null, "e": 39334, "s": 39316, "text": "String Duplicates" }, { "code": null, "e": 39342, "s": 39334, "text": "Strings" }, { "code": null, "e": 39350, "s": 39342, "text": "Strings" }, { "code": null, "e": 39448, "s": 39350, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39501, "s": 39448, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 39537, "s": 39501, "text": "Convert string to char array in C++" }, { "code": null, "e": 39575, "s": 39537, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 39605, "s": 39575, "text": "Caesar Cipher in Cryptography" }, { "code": null, "e": 39657, "s": 39605, "text": "Check whether two strings are anagram of each other" }, { "code": null, "e": 39718, "s": 39657, "text": "Length of the longest substring without repeating characters" }, { "code": null, "e": 39763, "s": 39718, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 39801, "s": 39763, "text": "Remove duplicates from a given string" }, { "code": null, "e": 39850, "s": 39801, "text": "How to split a string in C/C++, Python and Java?" } ]
Program to print a pattern of numbers - GeeksforGeeks
28 Jun, 2021 The idea of pattern based programs is to understand the concept of nesting of for loops and how and where to place the alphabets / numbers / stars to make the desired pattern.Write to program to print the pattern of numbers in the following manner using for loop 1 232 34543 4567654 567898765 In almost all types of pattern programs, two things that you must take care: No. of linesIf the pattern is increasing or decreasing per line? No. of lines If the pattern is increasing or decreasing per line? Implementation C++ C Java Python3 C# PHP Javascript // C++ program to illustrate the above// given pattern of numbers.#include<bits/stdc++.h>using namespace std; int main(){ int n = 5, i, j, num = 1, gap; gap = n - 1; for ( j = 1 ; j <= n ; j++ ) { num = j; for ( i = 1 ; i <= gap ; i++ ) cout << " "; gap --; for ( i = 1 ; i <= j ; i++ ) { cout << num; num++; } num--; num--; for ( i = 1 ; i < j ; i++) { cout << num; num--; } cout << "\n"; } return 0;} //This code is contributed by Shivi_Aggarwal // C program to illustrate the above// given pattern of numbers.#include<stdio.h> int main(){ int n = 5, i, j, num = 1, gap; gap = n - 1; for ( j = 1 ; j <= n ; j++ ) { num = j; for ( i = 1 ; i <= gap ; i++ ) printf(" "); gap --; for ( i = 1 ; i <= j ; i++ ) { printf("%d", num); num++; } num--; num--; for ( i = 1 ; i < j ; i++) { printf("%d", num); num--; } printf("\n"); } return 0;} // Java Program to illustrate the// above given pattern of numbersimport java.io.*; class GFG { public static void main(String args[]) { int n = 5, i, j, num = 1, gap; gap = n - 1; for ( j = 1 ; j <= n ; j++ ) { num = j; for ( i = 1 ; i <= gap ; i++ ) System.out.print(" "); gap --; for ( i = 1 ; i <= j ; i++ ) { System.out.print(num); num++; } num--; num--; for ( i = 1 ; i < j ; i++) { System.out.print(num); num--; } System.out.println(); } }} // This code is contributed// by Nikita tiwari. # Python Program to illustrate the# above given pattern of numbers. n = 5num = 1gap = n - 1for j in range(1, n + 1) : num = j for i in range(1, gap + 1) : print(" ", end="") gap = gap - 1 for i in range(1, j + 1) : print(num, end="") num = num + 1 num = num - 2 for i in range(1, j) : print(num, end="") num = num - 1 print() # This code is contributed# by Nikita tiwari. // C# Program to illustrate the// above given pattern of numbersusing System; class GFG { public static void Main() { int n = 5, i, j, num = 1, gap; gap = n - 1; for (j = 1; j <= n; j++) { num = j; for (i = 1; i <= gap; i++) Console.Write(" "); gap--; for (i = 1; i <= j; i++) { Console.Write(num); num++; } num--; num--; for (i = 1; i < j; i++) { Console.Write(num); num--; } Console.WriteLine(); } }} // This code is contributed// by vt_m. <?php//php program to illustrate the above// given pattern of numbers. $n = 5;$num = 1;$gap = $n - 1; for ($j = 1; $j <= $n; $j++){ $num = $j; for ($i = 1; $i <= $gap; $i++) printf(" "); $gap --; for ($i = 1; $i <= $j; $i++) { printf($num); $num++; } $num--; $num--; for ($i = 1; $i < $j; $i++) { printf($num); $num--; } printf("\n"); } // This code is contributed by mits?> <script> // JavaScript program to illustrate the above // given pattern of numbers. var n = 5, i, j, num = 1, gap; gap = n - 1; for (j = 1; j <= n; j++) { num = j; for (i = 1; i <= gap; i++) document.write(" "); gap--; for (i = 1; i <= j; i++) { document.write(num); num++; } num--; num--; for (i = 1; i < j; i++) { document.write(num); num--; } document.write("<br>"); } // This code is contributed by rdtank. </script> Output: 1 232 34543 4567654 567898765 Program for Pyramid PatternPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above Mithun Kumar Shivi_Aggarwal rdtank pattern-printing C Language C++ School Programming pattern-printing CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multidimensional Arrays in C / C++ rand() and srand() in C/C++ fork() in C Left Shift and Right Shift Operators in C/C++ Core Dump (Segmentation fault) in C/C++ Vector in C++ STL Initialize a vector in C++ (6 different ways) Inheritance in C++ Map in C++ Standard Template Library (STL) C++ Classes and Objects
[ { "code": null, "e": 24428, "s": 24400, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24693, "s": 24428, "text": "The idea of pattern based programs is to understand the concept of nesting of for loops and how and where to place the alphabets / numbers / stars to make the desired pattern.Write to program to print the pattern of numbers in the following manner using for loop " }, { "code": null, "e": 24733, "s": 24693, "text": " 1\n 232\n 34543\n 4567654\n567898765" }, { "code": null, "e": 24812, "s": 24733, "text": "In almost all types of pattern programs, two things that you must take care: " }, { "code": null, "e": 24877, "s": 24812, "text": "No. of linesIf the pattern is increasing or decreasing per line?" }, { "code": null, "e": 24890, "s": 24877, "text": "No. of lines" }, { "code": null, "e": 24943, "s": 24890, "text": "If the pattern is increasing or decreasing per line?" }, { "code": null, "e": 24960, "s": 24943, "text": "Implementation " }, { "code": null, "e": 24964, "s": 24960, "text": "C++" }, { "code": null, "e": 24966, "s": 24964, "text": "C" }, { "code": null, "e": 24971, "s": 24966, "text": "Java" }, { "code": null, "e": 24979, "s": 24971, "text": "Python3" }, { "code": null, "e": 24982, "s": 24979, "text": "C#" }, { "code": null, "e": 24986, "s": 24982, "text": "PHP" }, { "code": null, "e": 24997, "s": 24986, "text": "Javascript" }, { "code": "// C++ program to illustrate the above// given pattern of numbers.#include<bits/stdc++.h>using namespace std; int main(){ int n = 5, i, j, num = 1, gap; gap = n - 1; for ( j = 1 ; j <= n ; j++ ) { num = j; for ( i = 1 ; i <= gap ; i++ ) cout << \" \"; gap --; for ( i = 1 ; i <= j ; i++ ) { cout << num; num++; } num--; num--; for ( i = 1 ; i < j ; i++) { cout << num; num--; } cout << \"\\n\"; } return 0;} //This code is contributed by Shivi_Aggarwal", "e": 25604, "s": 24997, "text": null }, { "code": "// C program to illustrate the above// given pattern of numbers.#include<stdio.h> int main(){ int n = 5, i, j, num = 1, gap; gap = n - 1; for ( j = 1 ; j <= n ; j++ ) { num = j; for ( i = 1 ; i <= gap ; i++ ) printf(\" \"); gap --; for ( i = 1 ; i <= j ; i++ ) { printf(\"%d\", num); num++; } num--; num--; for ( i = 1 ; i < j ; i++) { printf(\"%d\", num); num--; } printf(\"\\n\"); } return 0;}", "e": 26209, "s": 25604, "text": null }, { "code": "// Java Program to illustrate the// above given pattern of numbersimport java.io.*; class GFG { public static void main(String args[]) { int n = 5, i, j, num = 1, gap; gap = n - 1; for ( j = 1 ; j <= n ; j++ ) { num = j; for ( i = 1 ; i <= gap ; i++ ) System.out.print(\" \"); gap --; for ( i = 1 ; i <= j ; i++ ) { System.out.print(num); num++; } num--; num--; for ( i = 1 ; i < j ; i++) { System.out.print(num); num--; } System.out.println(); } }} // This code is contributed// by Nikita tiwari.", "e": 26932, "s": 26209, "text": null }, { "code": "# Python Program to illustrate the# above given pattern of numbers. n = 5num = 1gap = n - 1for j in range(1, n + 1) : num = j for i in range(1, gap + 1) : print(\" \", end=\"\") gap = gap - 1 for i in range(1, j + 1) : print(num, end=\"\") num = num + 1 num = num - 2 for i in range(1, j) : print(num, end=\"\") num = num - 1 print() # This code is contributed# by Nikita tiwari.", "e": 27379, "s": 26932, "text": null }, { "code": "// C# Program to illustrate the// above given pattern of numbersusing System; class GFG { public static void Main() { int n = 5, i, j, num = 1, gap; gap = n - 1; for (j = 1; j <= n; j++) { num = j; for (i = 1; i <= gap; i++) Console.Write(\" \"); gap--; for (i = 1; i <= j; i++) { Console.Write(num); num++; } num--; num--; for (i = 1; i < j; i++) { Console.Write(num); num--; } Console.WriteLine(); } }} // This code is contributed// by vt_m.", "e": 28050, "s": 27379, "text": null }, { "code": "<?php//php program to illustrate the above// given pattern of numbers. $n = 5;$num = 1;$gap = $n - 1; for ($j = 1; $j <= $n; $j++){ $num = $j; for ($i = 1; $i <= $gap; $i++) printf(\" \"); $gap --; for ($i = 1; $i <= $j; $i++) { printf($num); $num++; } $num--; $num--; for ($i = 1; $i < $j; $i++) { printf($num); $num--; } printf(\"\\n\"); } // This code is contributed by mits?>", "e": 28499, "s": 28050, "text": null }, { "code": "<script> // JavaScript program to illustrate the above // given pattern of numbers. var n = 5, i, j, num = 1, gap; gap = n - 1; for (j = 1; j <= n; j++) { num = j; for (i = 1; i <= gap; i++) document.write(\" \"); gap--; for (i = 1; i <= j; i++) { document.write(num); num++; } num--; num--; for (i = 1; i < j; i++) { document.write(num); num--; } document.write(\"<br>\"); } // This code is contributed by rdtank. </script>", "e": 29102, "s": 28499, "text": null }, { "code": null, "e": 29112, "s": 29102, "text": "Output: " }, { "code": null, "e": 29152, "s": 29112, "text": " 1\n 232\n 34543\n 4567654\n567898765" }, { "code": null, "e": 29304, "s": 29152, "text": "Program for Pyramid PatternPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 29317, "s": 29304, "text": "Mithun Kumar" }, { "code": null, "e": 29332, "s": 29317, "text": "Shivi_Aggarwal" }, { "code": null, "e": 29339, "s": 29332, "text": "rdtank" }, { "code": null, "e": 29356, "s": 29339, "text": "pattern-printing" }, { "code": null, "e": 29367, "s": 29356, "text": "C Language" }, { "code": null, "e": 29371, "s": 29367, "text": "C++" }, { "code": null, "e": 29390, "s": 29371, "text": "School Programming" }, { "code": null, "e": 29407, "s": 29390, "text": "pattern-printing" }, { "code": null, "e": 29411, "s": 29407, "text": "CPP" }, { "code": null, "e": 29509, "s": 29411, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29544, "s": 29509, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 29572, "s": 29544, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 29584, "s": 29572, "text": "fork() in C" }, { "code": null, "e": 29630, "s": 29584, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 29670, "s": 29630, "text": "Core Dump (Segmentation fault) in C/C++" }, { "code": null, "e": 29688, "s": 29670, "text": "Vector in C++ STL" }, { "code": null, "e": 29734, "s": 29688, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 29753, "s": 29734, "text": "Inheritance in C++" }, { "code": null, "e": 29796, "s": 29753, "text": "Map in C++ Standard Template Library (STL)" } ]
GATE | GATE-CS-2014-(Set-2) | Question 65 - GeeksforGeeks
28 Jun, 2021 An IP machine Q has a path to another IP machine H via three IP routers R1, R2, and R3. Q—R1—R2—R3—H H acts as an HTTP server, and Q connects to H via HTTP and downloads a file. Session layer encryption is used, with DES as the shared key encryption protocol. Consider the following four pieces of information: [I1] The URL of the file downloaded by Q [I2] The TCP port numbers at Q and H [I3] The IP addresses of Q and H [I4] The link layer addresses of Q and H Which of I1, I2, I3, and I4 can an intruder learn through sniffing at R2 alone? (A) Only I1 and I2(B) Only I1(C) Only I2 and I3(D) Only I3 and I4Answer: (C)Explanation: An Intruder can’t learn [I1] through sniffing at R2 because URLs and Download are functioned at Application layer of OSI Model. An Intruder can learn [I2] through sniffing at R2 because Port Numbers are encapsulated in the payload field of IP Datagram. An Intruder can learn [I3] through sniffing at R2 because IP Addresses and Routers are functioned at network layer of OSI Model. An Intruder can’t learn [I4] through sniffing at R2 because it is related to Data Link Layer of OSI Model. Quiz of this Question GATE-CS-2014-(Set-2) GATE-GATE-CS-2014-(Set-2) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | GATE CS 2019 | Question 27 GATE | GATE-IT-2004 | Question 66 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE-CS-2006 | Question 49 GATE | GATE-CS-2016 (Set 2) | Question 48 GATE | GATE-CS-2004 | Question 3 GATE | GATE-CS-2000 | Question 43 GATE | GATE-CS-2017 (Set 2) | Question 42 GATE | GATE CS 2010 | Question 24 GATE | Gate IT 2007 | Question 30
[ { "code": null, "e": 24668, "s": 24640, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24756, "s": 24668, "text": "An IP machine Q has a path to another IP machine H via three IP routers R1, R2, and R3." }, { "code": null, "e": 24770, "s": 24756, "text": "Q—R1—R2—R3—H " }, { "code": null, "e": 24980, "s": 24770, "text": "H acts as an HTTP server, and Q connects to H via HTTP and downloads a file. Session layer encryption is used, with DES as the shared key encryption protocol. Consider the following four pieces of information:" }, { "code": null, "e": 25133, "s": 24980, "text": "[I1] The URL of the file downloaded by Q\n[I2] The TCP port numbers at Q and H\n[I3] The IP addresses of Q and H\n[I4] The link layer addresses of Q and H " }, { "code": null, "e": 25213, "s": 25133, "text": "Which of I1, I2, I3, and I4 can an intruder learn through sniffing at R2 alone?" }, { "code": null, "e": 25302, "s": 25213, "text": "(A) Only I1 and I2(B) Only I1(C) Only I2 and I3(D) Only I3 and I4Answer: (C)Explanation:" }, { "code": null, "e": 25798, "s": 25302, "text": "An Intruder can’t learn [I1] through sniffing at R2 because \nURLs and Download are functioned at Application layer of OSI Model.\n\nAn Intruder can learn [I2] through sniffing at R2 because\nPort Numbers are encapsulated in the payload field of IP Datagram.\n\nAn Intruder can learn [I3] through sniffing at R2 because IP \nAddresses and Routers are functioned at network layer of OSI Model.\n\nAn Intruder can’t learn [I4] through sniffing at R2 because \nit is related to Data Link Layer of OSI Model.\n" }, { "code": null, "e": 25820, "s": 25798, "text": "Quiz of this Question" }, { "code": null, "e": 25841, "s": 25820, "text": "GATE-CS-2014-(Set-2)" }, { "code": null, "e": 25867, "s": 25841, "text": "GATE-GATE-CS-2014-(Set-2)" }, { "code": null, "e": 25872, "s": 25867, "text": "GATE" }, { "code": null, "e": 25970, "s": 25872, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26004, "s": 25970, "text": "GATE | GATE CS 2019 | Question 27" }, { "code": null, "e": 26038, "s": 26004, "text": "GATE | GATE-IT-2004 | Question 66" }, { "code": null, "e": 26080, "s": 26038, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 26114, "s": 26080, "text": "GATE | GATE-CS-2006 | Question 49" }, { "code": null, "e": 26156, "s": 26114, "text": "GATE | GATE-CS-2016 (Set 2) | Question 48" }, { "code": null, "e": 26189, "s": 26156, "text": "GATE | GATE-CS-2004 | Question 3" }, { "code": null, "e": 26223, "s": 26189, "text": "GATE | GATE-CS-2000 | Question 43" }, { "code": null, "e": 26265, "s": 26223, "text": "GATE | GATE-CS-2017 (Set 2) | Question 42" }, { "code": null, "e": 26299, "s": 26265, "text": "GATE | GATE CS 2010 | Question 24" } ]
Adding millisecond to date in SAP HANA
Try using ADD_SECONDS function as below: SELECT ADD_SECONDS (TO_TIMESTAMP('2017-07-15 02:17:15'), 0.1) FROM TEST This will add seconds as fraction value as requested. Below is syntax and example: ADD_SECONDS Syntax ADD_SECONDS (t, n) Description Computes the time t plus n seconds. Example: SELECT ADD_SECONDS (TO_TIMESTAMP ('2012-01-01 23:30:45'), 60*30) "add seconds" FROM DUMMY; add seconds 2012-01-02 00:00:45.0 To know more about ADD_SECONDS function, you can also refer this link: datetime function in SAP HANA To know more about SQL functions in SAP HANA system, you can also refer our HANA tutorial: SAP HANA SQL Functions
[ { "code": null, "e": 1103, "s": 1062, "text": "Try using ADD_SECONDS function as below:" }, { "code": null, "e": 1175, "s": 1103, "text": "SELECT ADD_SECONDS (TO_TIMESTAMP('2017-07-15 02:17:15'), 0.1) FROM TEST" }, { "code": null, "e": 1258, "s": 1175, "text": "This will add seconds as fraction value as requested. Below is syntax and example:" }, { "code": null, "e": 1271, "s": 1258, "text": "ADD_SECONDS\n" }, { "code": null, "e": 1278, "s": 1271, "text": "Syntax" }, { "code": null, "e": 1297, "s": 1278, "text": "ADD_SECONDS (t, n)" }, { "code": null, "e": 1309, "s": 1297, "text": "Description" }, { "code": null, "e": 1345, "s": 1309, "text": "Computes the time t plus n seconds." }, { "code": null, "e": 1354, "s": 1345, "text": "Example:" }, { "code": null, "e": 1446, "s": 1354, "text": "SELECT ADD_SECONDS (TO_TIMESTAMP ('2012-01-01 23:30:45'), 60*30) \"add seconds\" FROM DUMMY;\n" }, { "code": null, "e": 1458, "s": 1446, "text": "add seconds" }, { "code": null, "e": 1480, "s": 1458, "text": "2012-01-02 00:00:45.0" }, { "code": null, "e": 1551, "s": 1480, "text": "To know more about ADD_SECONDS function, you can also refer this link:" }, { "code": null, "e": 1581, "s": 1551, "text": "datetime function in SAP HANA" }, { "code": null, "e": 1672, "s": 1581, "text": "To know more about SQL functions in SAP HANA system, you can also refer our HANA tutorial:" }, { "code": null, "e": 1695, "s": 1672, "text": "SAP HANA SQL Functions" } ]
Apex - Objects
An instance of class is called Object. In terms of Salesforce, object can be of class or you can create an object of sObject as well. You can create an object of class as you might have done in Java or other object-oriented programming language. Following is an example Class called MyClass − // Sample Class Example public class MyClass { Integer myInteger = 10; public void myMethod (Integer multiplier) { Integer multiplicationResult; multiplicationResult = multiplier*myInteger; System.debug('Multiplication is '+multiplicationResult); } } This is an instance class, i.e., to call or access the variables or methods of this class, you must create an instance of this class and then you can perform all the operations. // Object Creation // Creating an object of class MyClass objClass = new MyClass(); // Calling Class method using Class instance objClass.myMethod(100); sObjects are the objects of Salesforce in which you store the data. For example, Account, Contact, etc., are custom objects. You can create object instances of these sObjects. Following is an example of sObject initialization and shows how you can access the field of that particular object using dot notation and assign the values to fields. // Execute the below code in Developer console by simply pasting it // Standard Object Initialization for Account sObject Account objAccount = new Account(); // Object initialization objAccount.Name = 'Testr Account'; // Assigning the value to field Name of Account objAccount.Description = 'Test Account'; insert objAccount; // Creating record using DML System.debug('Records Has been created '+objAccount); // Custom sObject initialization and assignment of values to field APEX_Customer_c objCustomer = new APEX_Customer_c (); objCustomer.Name = 'ABC Customer'; objCustomer.APEX_Customer_Decscription_c = 'Test Description'; insert objCustomer; System.debug('Records Has been created '+objCustomer); Static methods and variables are initialized only once when a class is loaded. Static variables are not transmitted as part of the view state for a Visualforce page. Following is an example of Static method as well as Static variable. // Sample Class Example with Static Method public class MyStaticClass { Static Integer myInteger = 10; public static void myMethod (Integer multiplier) { Integer multiplicationResult; multiplicationResult = multiplier * myInteger; System.debug('Multiplication is '+multiplicationResult); } } // Calling the Class Method using Class Name and not using the instance object MyStaticClass.myMethod(100); Static Variable Use Static variables will be instantiated only once when class is loaded and this phenomenon can be used to avoid the trigger recursion. Static variable value will be same within the same execution context and any class, trigger or code which is executing can refer to it and prevent the recursion. 14 Lectures 2 hours Vijay Thapa 7 Lectures 2 hours Uplatz 29 Lectures 6 hours Ramnarayan Ramakrishnan 49 Lectures 3 hours Ali Saleh Ali 10 Lectures 4 hours Soham Ghosh 48 Lectures 4.5 hours GUHARAJANM Print Add Notes Bookmark this page
[ { "code": null, "e": 2186, "s": 2052, "text": "An instance of class is called Object. In terms of Salesforce, object can be of class or you can create an object of sObject as well." }, { "code": null, "e": 2298, "s": 2186, "text": "You can create an object of class as you might have done in Java or other object-oriented programming language." }, { "code": null, "e": 2345, "s": 2298, "text": "Following is an example Class called MyClass −" }, { "code": null, "e": 2627, "s": 2345, "text": "// Sample Class Example\npublic class MyClass {\n Integer myInteger = 10;\n \n public void myMethod (Integer multiplier) {\n Integer multiplicationResult;\n multiplicationResult = multiplier*myInteger;\n System.debug('Multiplication is '+multiplicationResult);\n }\n}" }, { "code": null, "e": 2805, "s": 2627, "text": "This is an instance class, i.e., to call or access the variables or methods of this class, you must create an instance of this class and then you can perform all the operations." }, { "code": null, "e": 2959, "s": 2805, "text": "// Object Creation\n// Creating an object of class\nMyClass objClass = new MyClass();\n\n// Calling Class method using Class instance\nobjClass.myMethod(100);" }, { "code": null, "e": 3135, "s": 2959, "text": "sObjects are the objects of Salesforce in which you store the data. For example, Account, Contact, etc., are custom objects. You can create object instances of these sObjects." }, { "code": null, "e": 3302, "s": 3135, "text": "Following is an example of sObject initialization and shows how you can access the field of that particular object using dot notation and assign the values to fields." }, { "code": null, "e": 4006, "s": 3302, "text": "// Execute the below code in Developer console by simply pasting it\n// Standard Object Initialization for Account sObject\nAccount objAccount = new Account(); // Object initialization\nobjAccount.Name = 'Testr Account'; // Assigning the value to field Name of Account\nobjAccount.Description = 'Test Account';\ninsert objAccount; // Creating record using DML\nSystem.debug('Records Has been created '+objAccount);\n\n// Custom sObject initialization and assignment of values to field\nAPEX_Customer_c objCustomer = new APEX_Customer_c ();\nobjCustomer.Name = 'ABC Customer';\nobjCustomer.APEX_Customer_Decscription_c = 'Test Description';\ninsert objCustomer;\nSystem.debug('Records Has been created '+objCustomer);" }, { "code": null, "e": 4172, "s": 4006, "text": "Static methods and variables are initialized only once when a class is loaded. Static variables are not transmitted as part of the view state for a Visualforce page." }, { "code": null, "e": 4241, "s": 4172, "text": "Following is an example of Static method as well as Static variable." }, { "code": null, "e": 4673, "s": 4241, "text": "// Sample Class Example with Static Method\npublic class MyStaticClass {\n Static Integer myInteger = 10;\n \n public static void myMethod (Integer multiplier) {\n Integer multiplicationResult;\n multiplicationResult = multiplier * myInteger;\n System.debug('Multiplication is '+multiplicationResult);\n }\n}\n\n// Calling the Class Method using Class Name and not using the instance object\nMyStaticClass.myMethod(100);" }, { "code": null, "e": 4693, "s": 4673, "text": "Static Variable Use" }, { "code": null, "e": 4988, "s": 4693, "text": "Static variables will be instantiated only once when class is loaded and this phenomenon can be used to avoid the trigger recursion. Static variable value will be same within the same execution context and any class, trigger or code which is executing can refer to it and prevent the recursion." }, { "code": null, "e": 5021, "s": 4988, "text": "\n 14 Lectures \n 2 hours \n" }, { "code": null, "e": 5034, "s": 5021, "text": " Vijay Thapa" }, { "code": null, "e": 5066, "s": 5034, "text": "\n 7 Lectures \n 2 hours \n" }, { "code": null, "e": 5074, "s": 5066, "text": " Uplatz" }, { "code": null, "e": 5107, "s": 5074, "text": "\n 29 Lectures \n 6 hours \n" }, { "code": null, "e": 5132, "s": 5107, "text": " Ramnarayan Ramakrishnan" }, { "code": null, "e": 5165, "s": 5132, "text": "\n 49 Lectures \n 3 hours \n" }, { "code": null, "e": 5180, "s": 5165, "text": " Ali Saleh Ali" }, { "code": null, "e": 5213, "s": 5180, "text": "\n 10 Lectures \n 4 hours \n" }, { "code": null, "e": 5226, "s": 5213, "text": " Soham Ghosh" }, { "code": null, "e": 5261, "s": 5226, "text": "\n 48 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5273, "s": 5261, "text": " GUHARAJANM" }, { "code": null, "e": 5280, "s": 5273, "text": " Print" }, { "code": null, "e": 5291, "s": 5280, "text": " Add Notes" } ]
Constructor Chaining In Java programming
Constructor chaining refers to calling a constructor from other constructor. It is of two types. Within same Class − Use this() keyword to refer to current class constructor. Make sure that this() is the first statement of the constructor and there should be at least one constructor without using this() statement. Within same Class − Use this() keyword to refer to current class constructor. Make sure that this() is the first statement of the constructor and there should be at least one constructor without using this() statement. From super/base Class − Use super() keyword to refer to parent class constructor. Make sure that super() is the first statement of the constructor. From super/base Class − Use super() keyword to refer to parent class constructor. Make sure that super() is the first statement of the constructor. Live Demo class A { public int a; public A() { this(-1); } public A(int a) { this.a = a; } public String toString() { return "[ a= " + this.a + "]"; } } class B extends A { public int b; public B() { this(-1,-1); } public B(int a, int b) { super(a); this.b = b; } public String toString() { return "[ a= " + this.a + ", b = " + b + "]"; } } public class Tester { public static void main(String args[]) { A a = new A(10); System.out.println(a); B b = new B(11,12); System.out.println(b); A a1 = new A(); System.out.println(a1); B b1 = new B(); System.out.println(b1); } } [ a= 10] [ a= 11, b = 12] [ a= -1] [ a= -1, b = -1]
[ { "code": null, "e": 1159, "s": 1062, "text": "Constructor chaining refers to calling a constructor from other constructor. It is of two types." }, { "code": null, "e": 1378, "s": 1159, "text": "Within same Class − Use this() keyword to refer to current class constructor. Make sure that this() is the first statement of the constructor and there should be at least one constructor without using this() statement." }, { "code": null, "e": 1597, "s": 1378, "text": "Within same Class − Use this() keyword to refer to current class constructor. Make sure that this() is the first statement of the constructor and there should be at least one constructor without using this() statement." }, { "code": null, "e": 1745, "s": 1597, "text": "From super/base Class − Use super() keyword to refer to parent class constructor. Make sure that super() is the first statement of the constructor." }, { "code": null, "e": 1893, "s": 1745, "text": "From super/base Class − Use super() keyword to refer to parent class constructor. Make sure that super() is the first statement of the constructor." }, { "code": null, "e": 1904, "s": 1893, "text": " Live Demo" }, { "code": null, "e": 2603, "s": 1904, "text": "class A {\n public int a;\n public A() {\n this(-1);\n }\n public A(int a) {\n this.a = a;\n }\n public String toString() {\n return \"[ a= \" + this.a + \"]\";\n }\n}\nclass B extends A {\n public int b;\n public B() {\n this(-1,-1);\n }\n public B(int a, int b) {\n super(a);\n this.b = b;\n }\n public String toString() {\n return \"[ a= \" + this.a + \", b = \" + b + \"]\";\n }\n}\npublic class Tester {\n public static void main(String args[]) {\n A a = new A(10);\n System.out.println(a);\n B b = new B(11,12);\n System.out.println(b);\n A a1 = new A();\n System.out.println(a1);\n B b1 = new B();\n System.out.println(b1);\n }\n}" }, { "code": null, "e": 2655, "s": 2603, "text": "[ a= 10]\n[ a= 11, b = 12]\n[ a= -1]\n[ a= -1, b = -1]" } ]
Python - Functions
A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing. As you already know, Python gives you many built-in functions like print(), etc. but you can also create your own functions. These functions are called user-defined functions. You can define functions to provide the required functionality. Here are simple rules to define a function in Python. Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ). Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ). Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses. Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses. The first statement of a function can be an optional statement - the documentation string of the function or docstring. The first statement of a function can be an optional statement - the documentation string of the function or docstring. The code block within every function starts with a colon (:) and is indented. The code block within every function starts with a colon (:) and is indented. The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None. The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None. def functionname( parameters ): "function_docstring" function_suite return [expression] By default, parameters have a positional behavior and you need to inform them in the same order that they were defined. The following function takes a string as input parameter and prints it on standard screen. def printme( str ): "This prints a passed string into this function" print str return Defining a function only gives it a name, specifies the parameters that are to be included in the function and structures the blocks of code. Once the basic structure of a function is finalized, you can execute it by calling it from another function or directly from the Python prompt. Following is the example to call printme() function − #!/usr/bin/python # Function definition is here def printme( str ): "This prints a passed string into this function" print str return; # Now you can call printme function printme("I'm first call to user defined function!") printme("Again second call to the same function") When the above code is executed, it produces the following result − I'm first call to user defined function! Again second call to the same function All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function. For example − #!/usr/bin/python # Function definition is here def changeme( mylist ): "This changes a passed list into this function" mylist.append([1,2,3,4]); print "Values inside the function: ", mylist return # Now you can call changeme function mylist = [10,20,30]; changeme( mylist ); print "Values outside the function: ", mylist Here, we are maintaining reference of the passed object and appending values in the same object. So, this would produce the following result − Values inside the function: [10, 20, 30, [1, 2, 3, 4]] Values outside the function: [10, 20, 30, [1, 2, 3, 4]] There is one more example where argument is being passed by reference and the reference is being overwritten inside the called function. #!/usr/bin/python # Function definition is here def changeme( mylist ): "This changes a passed list into this function" mylist = [1,2,3,4]; # This would assig new reference in mylist print "Values inside the function: ", mylist return # Now you can call changeme function mylist = [10,20,30]; changeme( mylist ); print "Values outside the function: ", mylist The parameter mylist is local to the function changeme. Changing mylist within the function does not affect mylist. The function accomplishes nothing and finally this would produce the following result − Values inside the function: [1, 2, 3, 4] Values outside the function: [10, 20, 30] You can call a function by using the following types of formal arguments − Required arguments Keyword arguments Default arguments Variable-length arguments Required arguments are the arguments passed to a function in correct positional order. Here, the number of arguments in the function call should match exactly with the function definition. To call the function printme(), you definitely need to pass one argument, otherwise it gives a syntax error as follows − #!/usr/bin/python # Function definition is here def printme( str ): "This prints a passed string into this function" print str return; # Now you can call printme function printme() When the above code is executed, it produces the following result − Traceback (most recent call last): File "test.py", line 11, in <module> printme(); TypeError: printme() takes exactly 1 argument (0 given) Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name. This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters. You can also make keyword calls to the printme() function in the following ways − #!/usr/bin/python # Function definition is here def printme( str ): "This prints a passed string into this function" print str return; # Now you can call printme function printme( str = "My string") When the above code is executed, it produces the following result − My string The following example gives more clear picture. Note that the order of parameters does not matter. #!/usr/bin/python # Function definition is here def printinfo( name, age ): "This prints a passed info into this function" print "Name: ", name print "Age ", age return; # Now you can call printinfo function printinfo( age=50, name="miki" ) When the above code is executed, it produces the following result − Name: miki Age 50 A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument. The following example gives an idea on default arguments, it prints default age if it is not passed − #!/usr/bin/python # Function definition is here def printinfo( name, age = 35 ): "This prints a passed info into this function" print "Name: ", name print "Age ", age return; # Now you can call printinfo function printinfo( age=50, name="miki" ) printinfo( name="miki" ) When the above code is executed, it produces the following result − Name: miki Age 50 Name: miki Age 35 You may need to process a function for more arguments than you specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments. Syntax for a function with non-keyword variable arguments is this − def functionname([formal_args,] *var_args_tuple ): "function_docstring" function_suite return [expression] An asterisk (*) is placed before the variable name that holds the values of all nonkeyword variable arguments. This tuple remains empty if no additional arguments are specified during the function call. Following is a simple example − #!/usr/bin/python # Function definition is here def printinfo( arg1, *vartuple ): "This prints a variable passed arguments" print "Output is: " print arg1 for var in vartuple: print var return; # Now you can call printinfo function printinfo( 10 ) printinfo( 70, 60, 50 ) When the above code is executed, it produces the following result − Output is: 10 Output is: 70 60 50 These functions are called anonymous because they are not declared in the standard manner by using the def keyword. You can use the lambda keyword to create small anonymous functions. Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions. Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions. An anonymous function cannot be a direct call to print because lambda requires an expression An anonymous function cannot be a direct call to print because lambda requires an expression Lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace. Lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace. Although it appears that lambda's are a one-line version of a function, they are not equivalent to inline statements in C or C++, whose purpose is by passing function stack allocation during invocation for performance reasons. Although it appears that lambda's are a one-line version of a function, they are not equivalent to inline statements in C or C++, whose purpose is by passing function stack allocation during invocation for performance reasons. The syntax of lambda functions contains only a single statement, which is as follows − lambda [arg1 [,arg2,.....argn]]:expression Following is the example to show how lambda form of function works − #!/usr/bin/python # Function definition is here sum = lambda arg1, arg2: arg1 + arg2; # Now you can call sum as a function print "Value of total : ", sum( 10, 20 ) print "Value of total : ", sum( 20, 20 ) When the above code is executed, it produces the following result − Value of total : 30 Value of total : 40 The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None. All the above examples are not returning any value. You can return a value from a function as follows − #!/usr/bin/python # Function definition is here def sum( arg1, arg2 ): # Add both the parameters and return them." total = arg1 + arg2 print "Inside the function : ", total return total; # Now you can call sum function total = sum( 10, 20 ); print "Outside the function : ", total When the above code is executed, it produces the following result − Inside the function : 30 Outside the function : 30 All variables in a program may not be accessible at all locations in that program. This depends on where you have declared a variable. The scope of a variable determines the portion of the program where you can access a particular identifier. There are two basic scopes of variables in Python − Global variables Local variables Variables that are defined inside a function body have a local scope, and those defined outside have a global scope. This means that local variables can be accessed only inside the function in which they are declared, whereas global variables can be accessed throughout the program body by all functions. When you call a function, the variables declared inside it are brought into scope. Following is a simple example − #!/usr/bin/python total = 0; # This is global variable. # Function definition is here def sum( arg1, arg2 ): # Add both the parameters and return them." total = arg1 + arg2; # Here total is local variable. print "Inside the function local total : ", total return total; # Now you can call sum function sum( 10, 20 ); print "Outside the function global total : ", total When the above code is executed, it produces the following result − Inside the function local total : 30 Outside the function global total : 0 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2436, "s": 2244, "text": "A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing." }, { "code": null, "e": 2612, "s": 2436, "text": "As you already know, Python gives you many built-in functions like print(), etc. but you can also create your own functions. These functions are called user-defined functions." }, { "code": null, "e": 2730, "s": 2612, "text": "You can define functions to provide the required functionality. Here are simple rules to define a function in Python." }, { "code": null, "e": 2828, "s": 2730, "text": "Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) )." }, { "code": null, "e": 2926, "s": 2828, "text": "Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) )." }, { "code": null, "e": 3060, "s": 2926, "text": "Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses." }, { "code": null, "e": 3194, "s": 3060, "text": "Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses." }, { "code": null, "e": 3314, "s": 3194, "text": "The first statement of a function can be an optional statement - the documentation string of the function or docstring." }, { "code": null, "e": 3434, "s": 3314, "text": "The first statement of a function can be an optional statement - the documentation string of the function or docstring." }, { "code": null, "e": 3512, "s": 3434, "text": "The code block within every function starts with a colon (:) and is indented." }, { "code": null, "e": 3590, "s": 3512, "text": "The code block within every function starts with a colon (:) and is indented." }, { "code": null, "e": 3760, "s": 3590, "text": "The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None." }, { "code": null, "e": 3930, "s": 3760, "text": "The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None." }, { "code": null, "e": 4028, "s": 3930, "text": "def functionname( parameters ):\n \"function_docstring\"\n function_suite\n return [expression]\n" }, { "code": null, "e": 4148, "s": 4028, "text": "By default, parameters have a positional behavior and you need to inform them in the same order that they were defined." }, { "code": null, "e": 4239, "s": 4148, "text": "The following function takes a string as input parameter and prints it on standard screen." }, { "code": null, "e": 4334, "s": 4239, "text": "def printme( str ):\n \"This prints a passed string into this function\"\n print str\n return" }, { "code": null, "e": 4476, "s": 4334, "text": "Defining a function only gives it a name, specifies the parameters that are to be included in the function and structures the blocks of code." }, { "code": null, "e": 4674, "s": 4476, "text": "Once the basic structure of a function is finalized, you can execute it by calling it from another function or directly from the Python prompt. Following is the example to call printme() function −" }, { "code": null, "e": 4958, "s": 4674, "text": "#!/usr/bin/python\n\n# Function definition is here\ndef printme( str ):\n \"This prints a passed string into this function\"\n print str\n return;\n\n# Now you can call printme function\nprintme(\"I'm first call to user defined function!\")\nprintme(\"Again second call to the same function\")" }, { "code": null, "e": 5026, "s": 4958, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 5107, "s": 5026, "text": "I'm first call to user defined function!\nAgain second call to the same function\n" }, { "code": null, "e": 5320, "s": 5107, "text": "All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function. For example −" }, { "code": null, "e": 5656, "s": 5320, "text": "#!/usr/bin/python\n\n# Function definition is here\ndef changeme( mylist ):\n \"This changes a passed list into this function\"\n mylist.append([1,2,3,4]);\n print \"Values inside the function: \", mylist\n return\n\n# Now you can call changeme function\nmylist = [10,20,30];\nchangeme( mylist );\nprint \"Values outside the function: \", mylist" }, { "code": null, "e": 5799, "s": 5656, "text": "Here, we are maintaining reference of the passed object and appending values in the same object. So, this would produce the following result −" }, { "code": null, "e": 5913, "s": 5799, "text": "Values inside the function: [10, 20, 30, [1, 2, 3, 4]]\nValues outside the function: [10, 20, 30, [1, 2, 3, 4]]\n" }, { "code": null, "e": 6050, "s": 5913, "text": "There is one more example where argument is being passed by reference and the reference is being overwritten inside the called function." }, { "code": null, "e": 6423, "s": 6050, "text": "#!/usr/bin/python\n\n# Function definition is here\ndef changeme( mylist ):\n \"This changes a passed list into this function\"\n mylist = [1,2,3,4]; # This would assig new reference in mylist\n print \"Values inside the function: \", mylist\n return\n\n# Now you can call changeme function\nmylist = [10,20,30];\nchangeme( mylist );\nprint \"Values outside the function: \", mylist" }, { "code": null, "e": 6627, "s": 6423, "text": "The parameter mylist is local to the function changeme. Changing mylist within the function does not affect mylist. The function accomplishes nothing and finally this would produce the following result −" }, { "code": null, "e": 6713, "s": 6627, "text": "Values inside the function: [1, 2, 3, 4]\nValues outside the function: [10, 20, 30]\n" }, { "code": null, "e": 6788, "s": 6713, "text": "You can call a function by using the following types of formal arguments −" }, { "code": null, "e": 6807, "s": 6788, "text": "Required arguments" }, { "code": null, "e": 6825, "s": 6807, "text": "Keyword arguments" }, { "code": null, "e": 6843, "s": 6825, "text": "Default arguments" }, { "code": null, "e": 6869, "s": 6843, "text": "Variable-length arguments" }, { "code": null, "e": 7058, "s": 6869, "text": "Required arguments are the arguments passed to a function in correct positional order. Here, the number of arguments in the function call should match exactly with the function definition." }, { "code": null, "e": 7179, "s": 7058, "text": "To call the function printme(), you definitely need to pass one argument, otherwise it gives a syntax error as follows −" }, { "code": null, "e": 7371, "s": 7179, "text": "#!/usr/bin/python\n\n# Function definition is here\ndef printme( str ):\n \"This prints a passed string into this function\"\n print str\n return;\n\n# Now you can call printme function\nprintme()" }, { "code": null, "e": 7440, "s": 7371, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 7589, "s": 7440, "text": "Traceback (most recent call last):\n File \"test.py\", line 11, in <module>\n printme();\nTypeError: printme() takes exactly 1 argument (0 given)\n" }, { "code": null, "e": 7752, "s": 7589, "text": "Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name." }, { "code": null, "e": 8000, "s": 7752, "text": "This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters. You can also make keyword calls to the printme() function in the following ways −" }, { "code": null, "e": 8210, "s": 8000, "text": "#!/usr/bin/python\n\n# Function definition is here\ndef printme( str ):\n \"This prints a passed string into this function\"\n print str\n return;\n\n# Now you can call printme function\nprintme( str = \"My string\")" }, { "code": null, "e": 8279, "s": 8210, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 8290, "s": 8279, "text": "My string\n" }, { "code": null, "e": 8389, "s": 8290, "text": "The following example gives more clear picture. Note that the order of parameters does not matter." }, { "code": null, "e": 8644, "s": 8389, "text": "#!/usr/bin/python\n\n# Function definition is here\ndef printinfo( name, age ):\n \"This prints a passed info into this function\"\n print \"Name: \", name\n print \"Age \", age\n return;\n\n# Now you can call printinfo function\nprintinfo( age=50, name=\"miki\" )" }, { "code": null, "e": 8713, "s": 8644, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 8734, "s": 8713, "text": "Name: miki\nAge 50\n" }, { "code": null, "e": 8966, "s": 8734, "text": "A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument. The following example gives an idea on default arguments, it prints default age if it is not passed −" }, { "code": null, "e": 9251, "s": 8966, "text": "#!/usr/bin/python\n\n# Function definition is here\ndef printinfo( name, age = 35 ):\n \"This prints a passed info into this function\"\n print \"Name: \", name\n print \"Age \", age\n return;\n\n# Now you can call printinfo function\nprintinfo( age=50, name=\"miki\" )\nprintinfo( name=\"miki\" )" }, { "code": null, "e": 9320, "s": 9251, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 9361, "s": 9320, "text": "Name: miki\nAge 50\nName: miki\nAge 35\n" }, { "code": null, "e": 9601, "s": 9361, "text": "You may need to process a function for more arguments than you specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments." }, { "code": null, "e": 9669, "s": 9601, "text": "Syntax for a function with non-keyword variable arguments is this −" }, { "code": null, "e": 9786, "s": 9669, "text": "def functionname([formal_args,] *var_args_tuple ):\n \"function_docstring\"\n function_suite\n return [expression]\n" }, { "code": null, "e": 10021, "s": 9786, "text": "An asterisk (*) is placed before the variable name that holds the values of all nonkeyword variable arguments. This tuple remains empty if no additional arguments are specified during the function call. Following is a simple example −" }, { "code": null, "e": 10316, "s": 10021, "text": "#!/usr/bin/python\n\n# Function definition is here\ndef printinfo( arg1, *vartuple ):\n \"This prints a variable passed arguments\"\n print \"Output is: \"\n print arg1\n for var in vartuple:\n print var\n return;\n\n# Now you can call printinfo function\nprintinfo( 10 )\nprintinfo( 70, 60, 50 )" }, { "code": null, "e": 10385, "s": 10316, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 10420, "s": 10385, "text": "Output is:\n10\nOutput is:\n70\n60\n50\n" }, { "code": null, "e": 10604, "s": 10420, "text": "These functions are called anonymous because they are not declared in the standard manner by using the def keyword. You can use the lambda keyword to create small anonymous functions." }, { "code": null, "e": 10760, "s": 10604, "text": "Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions." }, { "code": null, "e": 10916, "s": 10760, "text": "Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions." }, { "code": null, "e": 11009, "s": 10916, "text": "An anonymous function cannot be a direct call to print because lambda requires an expression" }, { "code": null, "e": 11102, "s": 11009, "text": "An anonymous function cannot be a direct call to print because lambda requires an expression" }, { "code": null, "e": 11254, "s": 11102, "text": "Lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace." }, { "code": null, "e": 11406, "s": 11254, "text": "Lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace." }, { "code": null, "e": 11633, "s": 11406, "text": "Although it appears that lambda's are a one-line version of a function, they are not equivalent to inline statements in C or C++, whose purpose is by passing function stack allocation during invocation for performance reasons." }, { "code": null, "e": 11860, "s": 11633, "text": "Although it appears that lambda's are a one-line version of a function, they are not equivalent to inline statements in C or C++, whose purpose is by passing function stack allocation during invocation for performance reasons." }, { "code": null, "e": 11947, "s": 11860, "text": "The syntax of lambda functions contains only a single statement, which is as follows −" }, { "code": null, "e": 11991, "s": 11947, "text": "lambda [arg1 [,arg2,.....argn]]:expression\n" }, { "code": null, "e": 12060, "s": 11991, "text": "Following is the example to show how lambda form of function works −" }, { "code": null, "e": 12267, "s": 12060, "text": "#!/usr/bin/python\n\n# Function definition is here\nsum = lambda arg1, arg2: arg1 + arg2;\n\n# Now you can call sum as a function\nprint \"Value of total : \", sum( 10, 20 )\nprint \"Value of total : \", sum( 20, 20 )" }, { "code": null, "e": 12336, "s": 12267, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 12379, "s": 12336, "text": "Value of total : 30\nValue of total : 40\n" }, { "code": null, "e": 12549, "s": 12379, "text": "The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None." }, { "code": null, "e": 12653, "s": 12549, "text": "All the above examples are not returning any value. You can return a value from a function as follows −" }, { "code": null, "e": 12949, "s": 12653, "text": "#!/usr/bin/python\n\n# Function definition is here\ndef sum( arg1, arg2 ):\n # Add both the parameters and return them.\"\n total = arg1 + arg2\n print \"Inside the function : \", total\n return total;\n\n# Now you can call sum function\ntotal = sum( 10, 20 );\nprint \"Outside the function : \", total " }, { "code": null, "e": 13018, "s": 12949, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 13072, "s": 13018, "text": "Inside the function : 30\nOutside the function : 30\n" }, { "code": null, "e": 13207, "s": 13072, "text": "All variables in a program may not be accessible at all locations in that program. This depends on where you have declared a variable." }, { "code": null, "e": 13368, "s": 13207, "text": "The scope of a variable determines the portion of the program where you can access a particular identifier. There are two basic scopes of variables in Python −" }, { "code": null, "e": 13385, "s": 13368, "text": "Global variables" }, { "code": null, "e": 13401, "s": 13385, "text": "Local variables" }, { "code": null, "e": 13518, "s": 13401, "text": "Variables that are defined inside a function body have a local scope, and those defined outside have a global scope." }, { "code": null, "e": 13821, "s": 13518, "text": "This means that local variables can be accessed only inside the function in which they are declared, whereas global variables can be accessed throughout the program body by all functions. When you call a function, the variables declared inside it are brought into scope. Following is a simple example −" }, { "code": null, "e": 14205, "s": 13821, "text": "#!/usr/bin/python\n\ntotal = 0; # This is global variable.\n# Function definition is here\ndef sum( arg1, arg2 ):\n # Add both the parameters and return them.\"\n total = arg1 + arg2; # Here total is local variable.\n print \"Inside the function local total : \", total\n return total;\n\n# Now you can call sum function\nsum( 10, 20 );\nprint \"Outside the function global total : \", total " }, { "code": null, "e": 14274, "s": 14205, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 14352, "s": 14274, "text": "Inside the function local total : 30\nOutside the function global total : 0\n" }, { "code": null, "e": 14389, "s": 14352, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 14405, "s": 14389, "text": " Malhar Lathkar" }, { "code": null, "e": 14438, "s": 14405, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 14457, "s": 14438, "text": " Arnab Chakraborty" }, { "code": null, "e": 14492, "s": 14457, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 14514, "s": 14492, "text": " In28Minutes Official" }, { "code": null, "e": 14548, "s": 14514, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 14576, "s": 14548, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 14611, "s": 14576, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 14625, "s": 14611, "text": " Lets Kode It" }, { "code": null, "e": 14658, "s": 14625, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 14675, "s": 14658, "text": " Abhilash Nelson" }, { "code": null, "e": 14682, "s": 14675, "text": " Print" }, { "code": null, "e": 14693, "s": 14682, "text": " Add Notes" } ]
How to search for files using the wildcard character (*) in PowerShell?
You can also search for files with a specific name or using the wildcard (*) character. Below command will search for the files (including hidden files) starting with “Bac”. Get-ChildItem D:\Temp -Recurse -Force -Include Bac* PS C:\WINDOWS\system32> Get-ChildItem D:\Temp -Recurse -Force -Include Bac* Directory: D:\Temp\GPO_backup\{C9C3DB4C-2E51-4201-B3C3-7C0F1ACECBE9} Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 24-11-2018 11:34 6215 Backup.xml When you use the wildcard character (*) at both the ends, file name containing that string will be displayed. For example, the below command will display all the files which contain the word “tmp”. Get-ChildItem D:\Temp\ -Recurse -Force -Include *tmp* PS C:\WINDOWS\system32> Get-ChildItem D:\Temp\ -Recurse -Force -Include *tmp* Directory: D:\Temp\GPO_backup\{C9C3DB4C-2E51-4201-B3C3-7C0F1ACECBE9}\DomainSysvol\GPO\Machine\microsoft\windows nt\SecEdit Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 24-11-2018 11:34 16028 GptTmpl.inf
[ { "code": null, "e": 1150, "s": 1062, "text": "You can also search for files with a specific name or using the wildcard (*) character." }, { "code": null, "e": 1236, "s": 1150, "text": "Below command will search for the files (including hidden files) starting with “Bac”." }, { "code": null, "e": 1288, "s": 1236, "text": "Get-ChildItem D:\\Temp -Recurse -Force -Include Bac*" }, { "code": null, "e": 1605, "s": 1288, "text": "PS C:\\WINDOWS\\system32> Get-ChildItem D:\\Temp -Recurse -Force -Include Bac*\n Directory: D:\\Temp\\GPO_backup\\{C9C3DB4C-2E51-4201-B3C3-7C0F1ACECBE9}\nMode LastWriteTime Length Name\n---- ------------- ------ ----\n-a---- 24-11-2018 11:34 6215 Backup.xml" }, { "code": null, "e": 1803, "s": 1605, "text": "When you use the wildcard character (*) at both the ends, file name containing that string will be displayed. For example, the below command will display all the files which contain the word “tmp”." }, { "code": null, "e": 1858, "s": 1803, "text": "Get-ChildItem D:\\Temp\\ -Recurse -Force -Include *tmp*\n" }, { "code": null, "e": 2236, "s": 1858, "text": "PS C:\\WINDOWS\\system32> Get-ChildItem D:\\Temp\\ -Recurse -Force -Include *tmp*\n Directory: D:\\Temp\\GPO_backup\\{C9C3DB4C-2E51-4201-B3C3-7C0F1ACECBE9}\\DomainSysvol\\GPO\\Machine\\microsoft\\windows\n nt\\SecEdit\nMode LastWriteTime Length Name\n---- ------------- ------ ----\n-a---- 24-11-2018 11:34 16028 GptTmpl.inf" } ]
Python PIL | ImageDraw.Draw.multiline_textsize() - GeeksforGeeks
17 Sep, 2019 PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageDraw module provide simple 2D graphics for Image objects. You can use this module to create new images, annotate or retouch existing images, and to generate graphics on the fly for web use. ImageDraw.Draw.multiline_textsize() Return the size of the given string, in pixels. Syntax:ImageDraw.Draw.multiline_textsize(text, font=None, spacing=0) Parameters:text – Text to be measured.font – An ImageFont instance.spacing – The number of pixels between lines. Return Type:returns an image with text. Image Used: Code : Using ImageDraw.Draw.multiline_textsize # Importing Image and ImageFont, ImageDraw module from PIL package from PIL import Image, ImageFont, ImageDraw # creating a image object image = Image.open(r'C:\Users\System-Pc\Desktop\rose.jpg') draw = ImageDraw.Draw(image) #specified font sizefont = ImageFont.truetype(r'C:\Users\System-Pc\Desktop\arial.ttf',30) text =u"""\ALWAYS BE HAPPY(LAUGHING IS THE \n BEST MEDICINE)""" # drawing text sizedraw.text((20,18), text,font = None,spacing=0) image.show() Output: Image-Processing Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Box Plot in Python using Matplotlib Bar Plot in Matplotlib Python | Get dictionary keys as a list Python | Convert set into a list Ways to filter Pandas DataFrame by column values Python - Call function from another file loops in python Multithreading in Python | Set 2 (Synchronization) Python Dictionary keys() method Python Lambda Functions
[ { "code": null, "e": 23901, "s": 23873, "text": "\n17 Sep, 2019" }, { "code": null, "e": 24205, "s": 23901, "text": "PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageDraw module provide simple 2D graphics for Image objects. You can use this module to create new images, annotate or retouch existing images, and to generate graphics on the fly for web use." }, { "code": null, "e": 24289, "s": 24205, "text": "ImageDraw.Draw.multiline_textsize() Return the size of the given string, in pixels." }, { "code": null, "e": 24358, "s": 24289, "text": "Syntax:ImageDraw.Draw.multiline_textsize(text, font=None, spacing=0)" }, { "code": null, "e": 24471, "s": 24358, "text": "Parameters:text – Text to be measured.font – An ImageFont instance.spacing – The number of pixels between lines." }, { "code": null, "e": 24511, "s": 24471, "text": "Return Type:returns an image with text." }, { "code": null, "e": 24523, "s": 24511, "text": "Image Used:" }, { "code": null, "e": 24570, "s": 24523, "text": "Code : Using ImageDraw.Draw.multiline_textsize" }, { "code": " # Importing Image and ImageFont, ImageDraw module from PIL package from PIL import Image, ImageFont, ImageDraw # creating a image object image = Image.open(r'C:\\Users\\System-Pc\\Desktop\\rose.jpg') draw = ImageDraw.Draw(image) #specified font sizefont = ImageFont.truetype(r'C:\\Users\\System-Pc\\Desktop\\arial.ttf',30) text =u\"\"\"\\ALWAYS BE HAPPY(LAUGHING IS THE \\n BEST MEDICINE)\"\"\" # drawing text sizedraw.text((20,18), text,font = None,spacing=0) image.show() ", "e": 25048, "s": 24570, "text": null }, { "code": null, "e": 25056, "s": 25048, "text": "Output:" }, { "code": null, "e": 25073, "s": 25056, "text": "Image-Processing" }, { "code": null, "e": 25080, "s": 25073, "text": "Python" }, { "code": null, "e": 25178, "s": 25080, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25187, "s": 25178, "text": "Comments" }, { "code": null, "e": 25200, "s": 25187, "text": "Old Comments" }, { "code": null, "e": 25236, "s": 25200, "text": "Box Plot in Python using Matplotlib" }, { "code": null, "e": 25259, "s": 25236, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 25298, "s": 25259, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 25331, "s": 25298, "text": "Python | Convert set into a list" }, { "code": null, "e": 25380, "s": 25331, "text": "Ways to filter Pandas DataFrame by column values" }, { "code": null, "e": 25421, "s": 25380, "text": "Python - Call function from another file" }, { "code": null, "e": 25437, "s": 25421, "text": "loops in python" }, { "code": null, "e": 25488, "s": 25437, "text": "Multithreading in Python | Set 2 (Synchronization)" }, { "code": null, "e": 25520, "s": 25488, "text": "Python Dictionary keys() method" } ]
Count all possible walks from a source to a destination with exactly k edges - GeeksforGeeks
26 Jan, 2022 Given a directed graph and two vertices ‘u’ and ‘v’ in it, count all possible walks from ‘u’ to ‘v’ with exactly k edges on the walk. The graph is given adjacency matrix representation where the value of graph[i][j] as 1 indicates that there is an edge from vertex i to vertex j and a value 0 indicates no edge from i to j. For example, consider the following graph. Let source ‘u’ be vertex 0, destination ‘v’ be 3 and k be 2. The output should be 2 as there are two walks from 0 to 3 with exactly 2 edges. The walks are {0, 2, 3} and {0, 1, 3} Simple Approach: Create a recursive function that takes the current vertex, destination vertex, and the count of the vertex. Call the recursive function with all adjacent vertices of a current vertex with the value of k as k-1. When the value of k is 0, then check whether the current vertex is the destination or not. If destination, then the output answer is 1. The following is the implementation of this simple solution. C++ Java Python3 C# PHP Javascript // C++ program to count walks from u to// v with exactly k edges#include <iostream>using namespace std; // Number of vertices in the graph#define V 4 // A naive recursive function to count// walks from u to v with k edgesint countwalks(int graph[][V], int u, int v, int k){ // Base cases if (k == 0 && u == v) return 1; if (k == 1 && graph[u][v]) return 1; if (k <= 0) return 0; // Initialize result int count = 0; // Go to all adjacents of u and recur for (int i = 0; i < V; i++) if (graph[u][i] == 1) // Check if is adjacent of u count += countwalks(graph, i, v, k - 1); return count;} // driver program to test above functionint main(){ /* Let us create the graph shown in above diagram*/ int graph[V][V] = { { 0, 1, 1, 1 }, { 0, 0, 0, 1 }, { 0, 0, 0, 1 }, { 0, 0, 0, 0 } }; int u = 0, v = 3, k = 2; cout << countwalks(graph, u, v, k); return 0;} // Java program to count walks from u to v with exactly k edgesimport java.util.*;import java.lang.*;import java.io.*; class KPaths { static final int V = 4; // Number of vertices // A naive recursive function to count walks from u // to v with k edges int countwalks(int graph[][], int u, int v, int k) { // Base cases if (k == 0 && u == v) return 1; if (k == 1 && graph[u][v] == 1) return 1; if (k <= 0) return 0; // Initialize result int count = 0; // Go to all adjacents of u and recur for (int i = 0; i < V; i++) if (graph[u][i] == 1) // Check if is adjacent of u count += countwalks(graph, i, v, k - 1); return count; } // Driver method public static void main(String[] args) throws java.lang.Exception { /* Let us create the graph shown in above diagram*/ int graph[][] = new int[][] { { 0, 1, 1, 1 }, { 0, 0, 0, 1 }, { 0, 0, 0, 1 }, { 0, 0, 0, 0 } }; int u = 0, v = 3, k = 2; KPaths p = new KPaths(); System.out.println(p.countwalks(graph, u, v, k)); }} // Contributed by Aakash Hasija # Python3 program to count walks from# u to v with exactly k edges # Number of vertices in the graphV = 4 # A naive recursive function to count# walks from u to v with k edgesdef countwalks(graph, u, v, k): # Base cases if (k == 0 and u == v): return 1 if (k == 1 and graph[u][v]): return 1 if (k <= 0): return 0 # Initialize result count = 0 # Go to all adjacents of u and recur for i in range(0, V): # Check if is adjacent of u if (graph[u][i] == 1): count += countwalks(graph, i, v, k-1) return count # Driver Code # Let us create the graph shown in above diagramgraph = [[0, 1, 1, 1, ], [0, 0, 0, 1, ], [0, 0, 0, 1, ], [0, 0, 0, 0] ] u = 0; v = 3; k = 2print(countwalks(graph, u, v, k)) # This code is contributed by Smitha Dinesh Semwal. // C# program to count walks from u to// v with exactly k edgesusing System; class GFG { // Number of vertices static int V = 4; // A naive recursive function to // count walks from u to v with // k edges static int countwalks(int[, ] graph, int u, int v, int k) { // Base cases if (k == 0 && u == v) return 1; if (k == 1 && graph[u, v] == 1) return 1; if (k <= 0) return 0; // Initialize result int count = 0; // Go to all adjacents of u and recur for (int i = 0; i < V; i++) // Check if is adjacent of u if (graph[u, i] == 1) count += countwalks(graph, i, v, k - 1); return count; } // Driver method public static void Main() { /* Let us create the graph shown in above diagram*/ int[, ] graph = new int[, ] { { 0, 1, 1, 1 }, { 0, 0, 0, 1 }, { 0, 0, 0, 1 }, { 0, 0, 0, 0 } }; int u = 0, v = 3, k = 2; Console.Write( countwalks(graph, u, v, k)); }} // This code is contributed by nitin mittal. <?php// PHP program to count walks from u// to v with exactly k edges // Number of vertices in the graph$V = 4; // A naive recursive function to count// walks from u to v with k edgesfunction countwalks( $graph, $u, $v, $k){ global $V; // Base cases if ($k == 0 and $u == $v) return 1; if ($k == 1 and $graph[$u][$v]) return 1; if ($k <= 0) return 0; // Initialize result $count = 0; // Go to all adjacents of u and recur for ( $i = 0; $i < $V; $i++) // Check if is adjacent of u if ($graph[$u][$i] == 1) $count += countwalks($graph, $i, $v, $k - 1); return $count;} // Driver Code /* Let us create the graph shown in above diagram*/ $graph = array(array(0, 1, 1, 1), array(0, 0, 0, 1), array(0, 0, 0, 1), array(0, 0, 0, 0)); $u = 0; $v = 3; $k = 2; echo countwalks($graph, $u, $v, $k); // This code is contributed by anuj_67.?> <script>// Javascript program to count walks from u to// v with exactly k edges // Number of vertices in the graphvar V = 4 // A naive recursive function to count// walks from u to v with k edgesfunction countwalks(graph, u, v, k){ // Base cases if (k == 0 && u == v) return 1; if (k == 1 && graph[u][v]) return 1; if (k <= 0) return 0; // Initialize result var count = 0; // Go to all adjacents of u and recur for (var i = 0; i < V; i++) if (graph[u][i] == 1) // Check if is adjacent of u count += countwalks(graph, i, v, k - 1); return count;} // driver program to test above function/* Let us create the graph shown in above diagram*/var graph = [[0, 1, 1, 1, ], [0, 0, 0, 1, ], [0, 0, 0, 1, ], [0, 0, 0, 0] ];var u = 0, v = 3, k = 2;document.write(countwalks(graph, u, v, k));// This code contributed by shubhamsingh10</script> Output: 2 Complexity Analysis: Time Complexity: O(Vk). The worst-case time complexity of the above function is O(Vk) where V is the number of vertices in the given graph. We can simply analyze the time complexity by drawing a recursion tree. The worst occurs for a complete graph. In the worst case, every internal node of the recursion tree would have exactly n children. Auxiliary Space: O(V). To store the stack space and the visited array O(V) space is needed. Efficient Approach: The solution can be optimized using Dynamic Programming. The idea is to build a 3D table where the first dimension is the source, the second dimension is the destination, the third dimension is the number of edges from source to destination, and the value is the count of walks. Like others, Dynamic Programming problems, fill the 3D table in a bottom-up manner. C++ Java Python3 C# Javascript // C++ program to count walks from// u to v with exactly k edges#include <iostream>using namespace std; // Number of vertices in the graph#define V 4 // A Dynamic programming based function to count walks from u// to v with k edgesint countwalks(int graph[][V], int u, int v, int k){ // Table to be filled up using DP. // The value count[i][j][e] will // store count of possible walks from // i to j with exactly k edges int count[V][V][k + 1]; // Loop for number of edges from 0 to k for (int e = 0; e <= k; e++) { for (int i = 0; i < V; i++) // for source { for (int j = 0; j < V; j++) // for destination { // initialize value count[i][j][e] = 0; // from base cases if (e == 0 && i == j) count[i][j][e] = 1; if (e == 1 && graph[i][j]) count[i][j][e] = 1; // go to adjacent only when the // number of edges is more than 1 if (e > 1) { for (int a = 0; a < V; a++) // adjacent of source i if (graph[i][a]) count[i][j][e] += count[a][j][e - 1]; } } } } return count[u][v][k];} // driver program to test above functionint main(){ /* Let us create the graph shown in above diagram*/ int graph[V][V] = { { 0, 1, 1, 1 }, { 0, 0, 0, 1 }, { 0, 0, 0, 1 }, { 0, 0, 0, 0 } }; int u = 0, v = 3, k = 2; cout << countwalks(graph, u, v, k); return 0;} // Java program to count walks from// u to v with exactly k edgesimport java.util.*;import java.lang.*;import java.io.*; class KPaths { static final int V = 4; // Number of vertices // A Dynamic programming based function to count walks from u // to v with k edges int countwalks(int graph[][], int u, int v, int k) { // Table to be filled up using DP. The value count[i][j][e] // will/ store count of possible walks from i to j with // exactly k edges int count[][][] = new int[V][V][k + 1]; // Loop for number of edges from 0 to k for (int e = 0; e <= k; e++) { for (int i = 0; i < V; i++) // for source { for (int j = 0; j < V; j++) // for destination { // initialize value count[i][j][e] = 0; // from base cases if (e == 0 && i == j) count[i][j][e] = 1; if (e == 1 && graph[i][j] != 0) count[i][j][e] = 1; // go to adjacent only when number of edges // is more than 1 if (e > 1) { for (int a = 0; a < V; a++) // adjacent of i if (graph[i][a] != 0) count[i][j][e] += count[a][j][e - 1]; } } } } return count[u][v][k]; } // Driver method public static void main(String[] args) throws java.lang.Exception { /* Let us create the graph shown in above diagram*/ int graph[][] = new int[][] { { 0, 1, 1, 1 }, { 0, 0, 0, 1 }, { 0, 0, 0, 1 }, { 0, 0, 0, 0 } }; int u = 0, v = 3, k = 2; KPaths p = new KPaths(); System.out.println(p.countwalks(graph, u, v, k)); }} // Contributed by Aakash Hasija # Python3 program to count walks from# u to v with exactly k edges # Number of verticesV = 4 # A Dynamic programming based function# to count walks from u to v with k edges def countwalks(graph, u, v, k): # Table to be filled up using DP. # The value count[i][j][e] will/ # store count of possible walks # from i to j with exactly k edges count = [[[0 for k in range(k + 1)] for i in range(V)] for j in range(V)] # Loop for number of edges from 0 to k for e in range(0, k + 1): # For Source for i in range(V): # For Destination for j in range(V): # Initialize value # count[i][j][e] = 0 # From base cases if (e == 0 and i == j): count[i][j][e] = 1 if (e == 1 and graph[i][j] != 0): count[i][j][e] = 1 # Go to adjacent only when number # of edges is more than 1 if (e > 1): for a in range(V): # Adjacent of i if (graph[i][a] != 0): count[i][j][e] += count[a][j][e - 1] return count[u][v][k] # Driver codeif __name__ == '__main__': # Let us create the graph shown # in above diagram graph = [[0, 1, 1, 1], [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 0]] u = 0 v = 3 k = 2 print(countwalks(graph, u, v, k)) # This code is contributed by Rajput-Ji // C# program to count walks from u to v// with exactly k edgesusing System; class GFG { static int V = 4; // Number of vertices // A Dynamic programming based function // to count walks from u to v with k edges static int countwalks(int[, ] graph, int u, int v, int k) { // Table to be filled up using DP. The // value count[i][j][e] will/ store // count of possible walks from i to // j with exactly k edges int[,, ] count = new int[V, V, k + 1]; // Loop for number of edges from 0 to k for (int e = 0; e <= k; e++) { // for source for (int i = 0; i < V; i++) { // for destination for (int j = 0; j < V; j++) { // initialize value count[i, j, e] = 0; // from base cases if (e == 0 && i == j) count[i, j, e] = 1; if (e == 1 && graph[i, j] != 0) count[i, j, e] = 1; // go to adjacent only when // number of edges // is more than 1 if (e > 1) { // adjacent of i for (int a = 0; a < V; a++) if (graph[i, a] != 0) count[i, j, e] += count[a, j, e - 1]; } } } } return count[u, v, k]; } // Driver method public static void Main() { /* Let us create the graph shown in above diagram*/ int[, ] graph = { { 0, 1, 1, 1 }, { 0, 0, 0, 1 }, { 0, 0, 0, 1 }, { 0, 0, 0, 0 } }; int u = 0, v = 3, k = 2; Console.WriteLine( countwalks(graph, u, v, k)); }} // This is Code Contributed by anuj_67. <script> // Javascript program to count walks from// u to v with exactly k edges // Number of vertices in the graphvar V = 4 // A Dynamic programming based function to count walks from u// to v with k edgesfunction countwalks(graph, u, v, k){ // Table to be filled up using DP. // The value count[i][j][e] will // store count of possible walks from // i to j with exactly k edges var count = new Array(V); for (var i = 0; i <V; i++) { count[i] = new Array(V); for (var j = 0; j < V; j++) { count[i][j] = new Array(V); for (var e = 0; e <= k; e++) { count[i][j][e] = 0; } } } // Loop for number of edges from 0 to k for (var e = 0; e <= k; e++) { for (var i = 0; i < V; i++) // for source { for (var j = 0; j < V; j++) // for destination { // initialize value count[i][j][e] = 0; // from base cases if (e == 0 && i == j) count[i][j][e] = 1; if (e == 1 && graph[i][j]) count[i][j][e] = 1; // go to adjacent only when the // number of edges is more than 1 if (e > 1) { for (var a = 0; a < V; a++) // adjacent of source i if (graph[i][a]) count[i][j][e] += count[a][j][e - 1]; } } } } return count[u][v][k];} // driver program to test above function/* Let us create the graph shown in above diagram*/var graph = [ [ 0, 1, 1, 1 ], [ 0, 0, 0, 1 ], [ 0, 0, 0, 1 ], [ 0, 0, 0, 0 ] ];var u = 0, v = 3, k = 2;document.write(countwalks(graph, u, v, k)); // This code is contributed by ShubhamSingh10</script> Output: 2 Complexity Analysis: Time Complexity: O(V3). Three nested loops are needed to fill the DP table, so the time complexity is O(V3/sup>). Auxiliary Space: O(V3). To store the DP table O(V3) space is needed. We can also use Divide and Conquer to solve the above problem in O(V3Logk) time. The count of walks of length k from u to v is the [u][v]’th entry in (graph[V][V])k. We can calculate the power by doing O(Logk) multiplication by using the divide and conquer technique to calculate power. A multiplication between two matrices of size V x V takes O(V3) time. 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 Rajput-Ji SHUBHAMSINGH10 arpansheetal kk773572498 DFS Divide and Conquer Dynamic Programming Graph Dynamic Programming Divide and Conquer DFS Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Program for Tower of Hanoi Divide and Conquer Algorithm | Introduction Median of two sorted arrays of different sizes Write a program to calculate pow(x,n) Count number of occurrences (or frequency) in a sorted array 0-1 Knapsack Problem | DP-10 Program for Fibonacci numbers Largest Sum Contiguous Subarray Longest Common Subsequence | DP-4 Longest Increasing Subsequence | DP-3
[ { "code": null, "e": 24741, "s": 24713, "text": "\n26 Jan, 2022" }, { "code": null, "e": 25065, "s": 24741, "text": "Given a directed graph and two vertices ‘u’ and ‘v’ in it, count all possible walks from ‘u’ to ‘v’ with exactly k edges on the walk. The graph is given adjacency matrix representation where the value of graph[i][j] as 1 indicates that there is an edge from vertex i to vertex j and a value 0 indicates no edge from i to j." }, { "code": null, "e": 25287, "s": 25065, "text": "For example, consider the following graph. Let source ‘u’ be vertex 0, destination ‘v’ be 3 and k be 2. The output should be 2 as there are two walks from 0 to 3 with exactly 2 edges. The walks are {0, 2, 3} and {0, 1, 3}" }, { "code": null, "e": 25653, "s": 25289, "text": "Simple Approach: Create a recursive function that takes the current vertex, destination vertex, and the count of the vertex. Call the recursive function with all adjacent vertices of a current vertex with the value of k as k-1. When the value of k is 0, then check whether the current vertex is the destination or not. If destination, then the output answer is 1." }, { "code": null, "e": 25716, "s": 25653, "text": "The following is the implementation of this simple solution. " }, { "code": null, "e": 25720, "s": 25716, "text": "C++" }, { "code": null, "e": 25725, "s": 25720, "text": "Java" }, { "code": null, "e": 25733, "s": 25725, "text": "Python3" }, { "code": null, "e": 25736, "s": 25733, "text": "C#" }, { "code": null, "e": 25740, "s": 25736, "text": "PHP" }, { "code": null, "e": 25751, "s": 25740, "text": "Javascript" }, { "code": "// C++ program to count walks from u to// v with exactly k edges#include <iostream>using namespace std; // Number of vertices in the graph#define V 4 // A naive recursive function to count// walks from u to v with k edgesint countwalks(int graph[][V], int u, int v, int k){ // Base cases if (k == 0 && u == v) return 1; if (k == 1 && graph[u][v]) return 1; if (k <= 0) return 0; // Initialize result int count = 0; // Go to all adjacents of u and recur for (int i = 0; i < V; i++) if (graph[u][i] == 1) // Check if is adjacent of u count += countwalks(graph, i, v, k - 1); return count;} // driver program to test above functionint main(){ /* Let us create the graph shown in above diagram*/ int graph[V][V] = { { 0, 1, 1, 1 }, { 0, 0, 0, 1 }, { 0, 0, 0, 1 }, { 0, 0, 0, 0 } }; int u = 0, v = 3, k = 2; cout << countwalks(graph, u, v, k); return 0;}", "e": 26760, "s": 25751, "text": null }, { "code": "// Java program to count walks from u to v with exactly k edgesimport java.util.*;import java.lang.*;import java.io.*; class KPaths { static final int V = 4; // Number of vertices // A naive recursive function to count walks from u // to v with k edges int countwalks(int graph[][], int u, int v, int k) { // Base cases if (k == 0 && u == v) return 1; if (k == 1 && graph[u][v] == 1) return 1; if (k <= 0) return 0; // Initialize result int count = 0; // Go to all adjacents of u and recur for (int i = 0; i < V; i++) if (graph[u][i] == 1) // Check if is adjacent of u count += countwalks(graph, i, v, k - 1); return count; } // Driver method public static void main(String[] args) throws java.lang.Exception { /* Let us create the graph shown in above diagram*/ int graph[][] = new int[][] { { 0, 1, 1, 1 }, { 0, 0, 0, 1 }, { 0, 0, 0, 1 }, { 0, 0, 0, 0 } }; int u = 0, v = 3, k = 2; KPaths p = new KPaths(); System.out.println(p.countwalks(graph, u, v, k)); }} // Contributed by Aakash Hasija", "e": 28063, "s": 26760, "text": null }, { "code": "# Python3 program to count walks from# u to v with exactly k edges # Number of vertices in the graphV = 4 # A naive recursive function to count# walks from u to v with k edgesdef countwalks(graph, u, v, k): # Base cases if (k == 0 and u == v): return 1 if (k == 1 and graph[u][v]): return 1 if (k <= 0): return 0 # Initialize result count = 0 # Go to all adjacents of u and recur for i in range(0, V): # Check if is adjacent of u if (graph[u][i] == 1): count += countwalks(graph, i, v, k-1) return count # Driver Code # Let us create the graph shown in above diagramgraph = [[0, 1, 1, 1, ], [0, 0, 0, 1, ], [0, 0, 0, 1, ], [0, 0, 0, 0] ] u = 0; v = 3; k = 2print(countwalks(graph, u, v, k)) # This code is contributed by Smitha Dinesh Semwal.", "e": 28940, "s": 28063, "text": null }, { "code": "// C# program to count walks from u to// v with exactly k edgesusing System; class GFG { // Number of vertices static int V = 4; // A naive recursive function to // count walks from u to v with // k edges static int countwalks(int[, ] graph, int u, int v, int k) { // Base cases if (k == 0 && u == v) return 1; if (k == 1 && graph[u, v] == 1) return 1; if (k <= 0) return 0; // Initialize result int count = 0; // Go to all adjacents of u and recur for (int i = 0; i < V; i++) // Check if is adjacent of u if (graph[u, i] == 1) count += countwalks(graph, i, v, k - 1); return count; } // Driver method public static void Main() { /* Let us create the graph shown in above diagram*/ int[, ] graph = new int[, ] { { 0, 1, 1, 1 }, { 0, 0, 0, 1 }, { 0, 0, 0, 1 }, { 0, 0, 0, 0 } }; int u = 0, v = 3, k = 2; Console.Write( countwalks(graph, u, v, k)); }} // This code is contributed by nitin mittal.", "e": 30211, "s": 28940, "text": null }, { "code": "<?php// PHP program to count walks from u// to v with exactly k edges // Number of vertices in the graph$V = 4; // A naive recursive function to count// walks from u to v with k edgesfunction countwalks( $graph, $u, $v, $k){ global $V; // Base cases if ($k == 0 and $u == $v) return 1; if ($k == 1 and $graph[$u][$v]) return 1; if ($k <= 0) return 0; // Initialize result $count = 0; // Go to all adjacents of u and recur for ( $i = 0; $i < $V; $i++) // Check if is adjacent of u if ($graph[$u][$i] == 1) $count += countwalks($graph, $i, $v, $k - 1); return $count;} // Driver Code /* Let us create the graph shown in above diagram*/ $graph = array(array(0, 1, 1, 1), array(0, 0, 0, 1), array(0, 0, 0, 1), array(0, 0, 0, 0)); $u = 0; $v = 3; $k = 2; echo countwalks($graph, $u, $v, $k); // This code is contributed by anuj_67.?>", "e": 31266, "s": 30211, "text": null }, { "code": "<script>// Javascript program to count walks from u to// v with exactly k edges // Number of vertices in the graphvar V = 4 // A naive recursive function to count// walks from u to v with k edgesfunction countwalks(graph, u, v, k){ // Base cases if (k == 0 && u == v) return 1; if (k == 1 && graph[u][v]) return 1; if (k <= 0) return 0; // Initialize result var count = 0; // Go to all adjacents of u and recur for (var i = 0; i < V; i++) if (graph[u][i] == 1) // Check if is adjacent of u count += countwalks(graph, i, v, k - 1); return count;} // driver program to test above function/* Let us create the graph shown in above diagram*/var graph = [[0, 1, 1, 1, ], [0, 0, 0, 1, ], [0, 0, 0, 1, ], [0, 0, 0, 0] ];var u = 0, v = 3, k = 2;document.write(countwalks(graph, u, v, k));// This code contributed by shubhamsingh10</script>", "e": 32197, "s": 31266, "text": null }, { "code": null, "e": 32206, "s": 32197, "text": "Output: " }, { "code": null, "e": 32208, "s": 32206, "text": "2" }, { "code": null, "e": 32230, "s": 32208, "text": "Complexity Analysis: " }, { "code": null, "e": 32572, "s": 32230, "text": "Time Complexity: O(Vk). The worst-case time complexity of the above function is O(Vk) where V is the number of vertices in the given graph. We can simply analyze the time complexity by drawing a recursion tree. The worst occurs for a complete graph. In the worst case, every internal node of the recursion tree would have exactly n children." }, { "code": null, "e": 32664, "s": 32572, "text": "Auxiliary Space: O(V). To store the stack space and the visited array O(V) space is needed." }, { "code": null, "e": 33048, "s": 32664, "text": "Efficient Approach: The solution can be optimized using Dynamic Programming. The idea is to build a 3D table where the first dimension is the source, the second dimension is the destination, the third dimension is the number of edges from source to destination, and the value is the count of walks. Like others, Dynamic Programming problems, fill the 3D table in a bottom-up manner. " }, { "code": null, "e": 33052, "s": 33048, "text": "C++" }, { "code": null, "e": 33057, "s": 33052, "text": "Java" }, { "code": null, "e": 33065, "s": 33057, "text": "Python3" }, { "code": null, "e": 33068, "s": 33065, "text": "C#" }, { "code": null, "e": 33079, "s": 33068, "text": "Javascript" }, { "code": "// C++ program to count walks from// u to v with exactly k edges#include <iostream>using namespace std; // Number of vertices in the graph#define V 4 // A Dynamic programming based function to count walks from u// to v with k edgesint countwalks(int graph[][V], int u, int v, int k){ // Table to be filled up using DP. // The value count[i][j][e] will // store count of possible walks from // i to j with exactly k edges int count[V][V][k + 1]; // Loop for number of edges from 0 to k for (int e = 0; e <= k; e++) { for (int i = 0; i < V; i++) // for source { for (int j = 0; j < V; j++) // for destination { // initialize value count[i][j][e] = 0; // from base cases if (e == 0 && i == j) count[i][j][e] = 1; if (e == 1 && graph[i][j]) count[i][j][e] = 1; // go to adjacent only when the // number of edges is more than 1 if (e > 1) { for (int a = 0; a < V; a++) // adjacent of source i if (graph[i][a]) count[i][j][e] += count[a][j][e - 1]; } } } } return count[u][v][k];} // driver program to test above functionint main(){ /* Let us create the graph shown in above diagram*/ int graph[V][V] = { { 0, 1, 1, 1 }, { 0, 0, 0, 1 }, { 0, 0, 0, 1 }, { 0, 0, 0, 0 } }; int u = 0, v = 3, k = 2; cout << countwalks(graph, u, v, k); return 0;}", "e": 34732, "s": 33079, "text": null }, { "code": "// Java program to count walks from// u to v with exactly k edgesimport java.util.*;import java.lang.*;import java.io.*; class KPaths { static final int V = 4; // Number of vertices // A Dynamic programming based function to count walks from u // to v with k edges int countwalks(int graph[][], int u, int v, int k) { // Table to be filled up using DP. The value count[i][j][e] // will/ store count of possible walks from i to j with // exactly k edges int count[][][] = new int[V][V][k + 1]; // Loop for number of edges from 0 to k for (int e = 0; e <= k; e++) { for (int i = 0; i < V; i++) // for source { for (int j = 0; j < V; j++) // for destination { // initialize value count[i][j][e] = 0; // from base cases if (e == 0 && i == j) count[i][j][e] = 1; if (e == 1 && graph[i][j] != 0) count[i][j][e] = 1; // go to adjacent only when number of edges // is more than 1 if (e > 1) { for (int a = 0; a < V; a++) // adjacent of i if (graph[i][a] != 0) count[i][j][e] += count[a][j][e - 1]; } } } } return count[u][v][k]; } // Driver method public static void main(String[] args) throws java.lang.Exception { /* Let us create the graph shown in above diagram*/ int graph[][] = new int[][] { { 0, 1, 1, 1 }, { 0, 0, 0, 1 }, { 0, 0, 0, 1 }, { 0, 0, 0, 0 } }; int u = 0, v = 3, k = 2; KPaths p = new KPaths(); System.out.println(p.countwalks(graph, u, v, k)); }} // Contributed by Aakash Hasija", "e": 36742, "s": 34732, "text": null }, { "code": "# Python3 program to count walks from# u to v with exactly k edges # Number of verticesV = 4 # A Dynamic programming based function# to count walks from u to v with k edges def countwalks(graph, u, v, k): # Table to be filled up using DP. # The value count[i][j][e] will/ # store count of possible walks # from i to j with exactly k edges count = [[[0 for k in range(k + 1)] for i in range(V)] for j in range(V)] # Loop for number of edges from 0 to k for e in range(0, k + 1): # For Source for i in range(V): # For Destination for j in range(V): # Initialize value # count[i][j][e] = 0 # From base cases if (e == 0 and i == j): count[i][j][e] = 1 if (e == 1 and graph[i][j] != 0): count[i][j][e] = 1 # Go to adjacent only when number # of edges is more than 1 if (e > 1): for a in range(V): # Adjacent of i if (graph[i][a] != 0): count[i][j][e] += count[a][j][e - 1] return count[u][v][k] # Driver codeif __name__ == '__main__': # Let us create the graph shown # in above diagram graph = [[0, 1, 1, 1], [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 0]] u = 0 v = 3 k = 2 print(countwalks(graph, u, v, k)) # This code is contributed by Rajput-Ji", "e": 38301, "s": 36742, "text": null }, { "code": "// C# program to count walks from u to v// with exactly k edgesusing System; class GFG { static int V = 4; // Number of vertices // A Dynamic programming based function // to count walks from u to v with k edges static int countwalks(int[, ] graph, int u, int v, int k) { // Table to be filled up using DP. The // value count[i][j][e] will/ store // count of possible walks from i to // j with exactly k edges int[,, ] count = new int[V, V, k + 1]; // Loop for number of edges from 0 to k for (int e = 0; e <= k; e++) { // for source for (int i = 0; i < V; i++) { // for destination for (int j = 0; j < V; j++) { // initialize value count[i, j, e] = 0; // from base cases if (e == 0 && i == j) count[i, j, e] = 1; if (e == 1 && graph[i, j] != 0) count[i, j, e] = 1; // go to adjacent only when // number of edges // is more than 1 if (e > 1) { // adjacent of i for (int a = 0; a < V; a++) if (graph[i, a] != 0) count[i, j, e] += count[a, j, e - 1]; } } } } return count[u, v, k]; } // Driver method public static void Main() { /* Let us create the graph shown in above diagram*/ int[, ] graph = { { 0, 1, 1, 1 }, { 0, 0, 0, 1 }, { 0, 0, 0, 1 }, { 0, 0, 0, 0 } }; int u = 0, v = 3, k = 2; Console.WriteLine( countwalks(graph, u, v, k)); }} // This is Code Contributed by anuj_67.", "e": 40258, "s": 38301, "text": null }, { "code": "<script> // Javascript program to count walks from// u to v with exactly k edges // Number of vertices in the graphvar V = 4 // A Dynamic programming based function to count walks from u// to v with k edgesfunction countwalks(graph, u, v, k){ // Table to be filled up using DP. // The value count[i][j][e] will // store count of possible walks from // i to j with exactly k edges var count = new Array(V); for (var i = 0; i <V; i++) { count[i] = new Array(V); for (var j = 0; j < V; j++) { count[i][j] = new Array(V); for (var e = 0; e <= k; e++) { count[i][j][e] = 0; } } } // Loop for number of edges from 0 to k for (var e = 0; e <= k; e++) { for (var i = 0; i < V; i++) // for source { for (var j = 0; j < V; j++) // for destination { // initialize value count[i][j][e] = 0; // from base cases if (e == 0 && i == j) count[i][j][e] = 1; if (e == 1 && graph[i][j]) count[i][j][e] = 1; // go to adjacent only when the // number of edges is more than 1 if (e > 1) { for (var a = 0; a < V; a++) // adjacent of source i if (graph[i][a]) count[i][j][e] += count[a][j][e - 1]; } } } } return count[u][v][k];} // driver program to test above function/* Let us create the graph shown in above diagram*/var graph = [ [ 0, 1, 1, 1 ], [ 0, 0, 0, 1 ], [ 0, 0, 0, 1 ], [ 0, 0, 0, 0 ] ];var u = 0, v = 3, k = 2;document.write(countwalks(graph, u, v, k)); // This code is contributed by ShubhamSingh10</script>", "e": 42105, "s": 40258, "text": null }, { "code": null, "e": 42114, "s": 42105, "text": "Output: " }, { "code": null, "e": 42116, "s": 42114, "text": "2" }, { "code": null, "e": 42138, "s": 42116, "text": "Complexity Analysis: " }, { "code": null, "e": 42252, "s": 42138, "text": "Time Complexity: O(V3). Three nested loops are needed to fill the DP table, so the time complexity is O(V3/sup>)." }, { "code": null, "e": 42321, "s": 42252, "text": "Auxiliary Space: O(V3). To store the DP table O(V3) space is needed." }, { "code": null, "e": 42804, "s": 42321, "text": "We can also use Divide and Conquer to solve the above problem in O(V3Logk) time. The count of walks of length k from u to v is the [u][v]’th entry in (graph[V][V])k. We can calculate the power by doing O(Logk) multiplication by using the divide and conquer technique to calculate power. A multiplication between two matrices of size V x V takes O(V3) time. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 42817, "s": 42804, "text": "nitin mittal" }, { "code": null, "e": 42822, "s": 42817, "text": "vt_m" }, { "code": null, "e": 42833, "s": 42822, "text": "andrew1234" }, { "code": null, "e": 42843, "s": 42833, "text": "Rajput-Ji" }, { "code": null, "e": 42858, "s": 42843, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 42871, "s": 42858, "text": "arpansheetal" }, { "code": null, "e": 42883, "s": 42871, "text": "kk773572498" }, { "code": null, "e": 42887, "s": 42883, "text": "DFS" }, { "code": null, "e": 42906, "s": 42887, "text": "Divide and Conquer" }, { "code": null, "e": 42926, "s": 42906, "text": "Dynamic Programming" }, { "code": null, "e": 42932, "s": 42926, "text": "Graph" }, { "code": null, "e": 42952, "s": 42932, "text": "Dynamic Programming" }, { "code": null, "e": 42971, "s": 42952, "text": "Divide and Conquer" }, { "code": null, "e": 42975, "s": 42971, "text": "DFS" }, { "code": null, "e": 42981, "s": 42975, "text": "Graph" }, { "code": null, "e": 43079, "s": 42981, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 43088, "s": 43079, "text": "Comments" }, { "code": null, "e": 43101, "s": 43088, "text": "Old Comments" }, { "code": null, "e": 43128, "s": 43101, "text": "Program for Tower of Hanoi" }, { "code": null, "e": 43172, "s": 43128, "text": "Divide and Conquer Algorithm | Introduction" }, { "code": null, "e": 43219, "s": 43172, "text": "Median of two sorted arrays of different sizes" }, { "code": null, "e": 43257, "s": 43219, "text": "Write a program to calculate pow(x,n)" }, { "code": null, "e": 43318, "s": 43257, "text": "Count number of occurrences (or frequency) in a sorted array" }, { "code": null, "e": 43347, "s": 43318, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 43377, "s": 43347, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 43409, "s": 43377, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 43443, "s": 43409, "text": "Longest Common Subsequence | DP-4" } ]
Tryit Editor v3.7
Tryit: two classes
[]
Statistical Machine Learning: Gradient Boosting & AdaBoost from Scratch | by Andrew Rothman | Towards Data Science
Boosting is a family of ensemble Machine Learning techniques for both discrete and continuous random variable targets. Boosting models take the form of Non-Parametric Additive models and are most typically specified with additive components being “weak learners”. From an empirical risk decomposition perspective, where it can be easily shown the Mean Squared Error (MSE) of any arbitrary statistical estimator is the additive sum of the squared bias and sampling variance of said sampling estimator... ... a “weak learner” is a statistical estimator with high squared-bias but low sampling variance. Weak learners have the benefit of ease of model fitting from a computational perspective. Examples of weak learners include single decision and regression trees constrained to only a few layers of depth, possible even one layer (refereed to as “decision/regression stumps”). The motivation of Boosting is to recover an additive ensemble of weak leaners that together can specify an arbitrarily complex model. In this piece, we will specify the theoretically framework and full mathematical derivation for Gradient Boosting and AdaBoost. We will also provide a full computational simulation of these methods from scratch, without use of Boosting computational packages. The Table of Contents for this piece are as follows: With Gradient Boosting, the model estimation procedure can be viewed as performing Gradient Descent in function-space over a space of proposal weak-learners (hence the name “Gradient Boosting”). Let’s jump into the mathematical specification and fitting procedure: To understand the fitting procedure for Gradient Boosting Models, it is helpful to first recall the Taylor Expansion. Let’s next discuss AdaBoost, which is in-fact a special case of the more general Gradient Boosting Model With the information and notation outlined in section 3.1, let’s dive into the fitting procedure for AdaBoost There is a slight alternative view of Boosting from a Non-Parametric Additive Model perspective. This is a view quite well understood in the Mathematical Statistics and Statistical Learning community, but one I rarely ever see covered in the Computer Science arm of the Machine Learning community. I think it’s a perspective worth understanding, and provides a more robust view of Boosting as a family of procedures. There are a class of Statistical Models known as Non-Parametric Additive Models. This class of estimators is enormous, and are highly flexible. In a certain sense, these class of models is too flexible. As an an analyst leveraging a statistical model from this class, there are so many hyperparameters and design choices to choose from, specifying a the “right” model can be overwhelming. For a given prediction problem, there is some underlying Non-Parametric Additive model that “works best” so-to-speak in a global sense. This “best” model we will refer to as the “true NPA model”. Given our sample data, we would like to do our best to specify and recover this “true NPA model”. But how can go about doing so in a structured and practical manner? The parameters space over which we need to search is enormous! Let’s make an analogy for a moment. Imagine instead we had a Machine Learning problem for which we are leveraging Linear Regression. We have 100 features to choose from, and we know there is some true combination of features that provides the “best subset selection” Linear Regression Model. But we would have to test 2100 different models to recover the “best one”, which is a search space in the hundreds of trillions. Instead of attempting to search over that entire space, we could instead leverage a greedy algorithm like Forward-Selection where we will choose and add one variable to the final model at a time making our choices based on a greedy myopic heuristic. With this approach, we only need to test a few thousand models instead of hundreds of trillions. We know this Forward-Selection procedure is unlikely to recover the exact solution to the “best subset selection” problem; but it will recover a model that will likely work very well for our purposes. The Forward-Selection scenario above is very similar to leveraging Boosting as a fitting procedure for Non-Parametric Additive models in a Machine Learning context. We would like to recover an estimate to the “true NPA model”, however the size of the search space is overwhelming. Boosting in this sense can be viewed as a family of greedy algorithmic procedures for estimating the solution to the “true NPA model” problem, similar to estimating the best subset-selection problem with Forward Selection. Below is a fully working example (built from scratch) of fitting a Gradient Boosted Model on a continuous target, and an AdaBoost Model on a binary categorical target. First, let’s load our needed libraries: #################### ## load libraries ## #################### import numpy as np import pandas as pd np.random.seed(123456789) from sklearn.tree import DecisionTreeRegressor from sklearn.tree import DecisionTreeClassifier Next, a function to simulate a dataset with a purposely complex model specification: ############################ ## Toy Dataset Simulation ## ############################ def simulate_df(n=100, seed=123456, binary_flag=False): np.random.seed(seed) ## specify dataframe df = pd.DataFrame() ## specify variables L1 through L6 L1_split = 0.52 L2_split = 0.23 L3_split = 0.38 df['L1'] = np.random.choice([0, 1], size=n, replace=True, p=[L1_split, (1-L1_split)]) df['L2'] = np.random.choice([0, 1], size=n, replace=True, p=[L2_split, (1-L2_split)]) df['L3'] = np.random.choice([0, 1], size=n, replace=True, p=[L3_split, (1-L3_split)]) df['L4'] = np.random.normal(0, 1, df.shape[0]) df['L5'] = np.random.normal(0, 0.75, df.shape[0]) df['L6'] = np.random.normal(0, 2, df.shape[0]) theta_0 = 5.5 theta_1 = 1.28 theta_2 = 0.42 theta_3 = 2.32 theta_4 = -3.15 theta_5 = 3.12 theta_6 = -4.29 theta_7 = -1.23 theta_8 = -10.18 theta_9 = 2.21 theta_10 = 10.3 if(binary_flag): Z = theta_0 + (theta_1*df['L1']) + (theta_2*df['L2']) + (theta_3*df['L3']) + (theta_4*df['L4']) + (theta_5*df['L5']) + (theta_6*df['L6']) + (theta_7*df['L2']*df['L4']) + (theta_8*df['L3']*df['L6']) + (theta_9*df['L5']*df['L5']) + (theta_10*np.sin(df['L5'])) p = 1 / (1 + np.exp(-Z)) df['Y'] = np.random.binomial(1, p) df.loc[df['Y']==0, 'Y'] = -1 else: df['Y'] = theta_0 + (theta_1*df['L1']) + (theta_2*df['L2']) + (theta_3*df['L3']) + (theta_4*df['L4']) + (theta_5*df['L5']) + (theta_6*df['L6']) + (theta_7*df['L2']*df['L4']) + (theta_8*df['L3']*df['L6']) + (theta_9*df['L5']*df['L5']) + (theta_10*np.sin(df['L5'])) + np.random.normal(0, 0.1, df.shape[0]) return(df) Let’s recover a simulated dataset with a continuous outcome target Y, and fit a Gradient Boosting Model. Note, we will print the empirical realization of the Global Loss function with each weak learner added to the model. We will consider the model to have converged when the empirical loss < 1. ############################################### ## Gradient Boosting with Continuous Outcome ## ############################################### ## simulate the dataset with continuous outcome Y df = simulate_df(n=1000, seed=123456) df['Y_original'] = df['Y'] ## fit Gradient Boosting Model with depth-3 Regression Trees as Weak Learners ## continue fitting model until loss function < 1 alpha = 100000 current_loss = sum((df['Y'])**2) while(current_loss > 1): model = DecisionTreeRegressor(random_state=0, max_depth=3) model.fit(df[['L1', 'L2', 'L3','L4', 'L5', 'L6']], df['Y']) df['Y_hat'] = model.predict(df[['L1', 'L2', 'L3','L4', 'L5', 'L6']]) df['Y_hat_squared'] = df['Y_hat']**2 df['Y_hat_scaled'] = np.sqrt(df['Y_hat_squared'] / df['Y_hat_squared'].sum()) * np.sign(df['Y_hat']) loss_not_lowered_flag = True while(loss_not_lowered_flag): new_loss = sum((df['Y'] - (alpha*df['Y_hat_scaled']))**2) if(new_loss < current_loss): loss_not_lowered_flag = False current_loss = new_loss print('Current Loss: ' + str(current_loss)) df['Y'] = df['Y'] - (alpha*df['Y_hat_scaled']) else: alpha = 0.99*alpha del model print('model converged') Let’s now recover a simulated dataset with a binary categorical outcome target Y, and fit an AdaBoost Model. Note, we will print the empirical realization of the Global Loss function with each weak learner added to the model. We will consider the model to have converged when all n=1000 training points are correctly classified by the ensemble model. ###################################################### ## AdaBoost with Binary Categorical Outcome {-1, 1} ## ###################################################### ## simulate the dataset with continuous outcome Y df = simulate_df(n=1000, seed=123456, binary_flag=True) df = df.rename(columns={'Y':'Y_original'}) df['w'] = df.shape[0]*[1/df.shape[0]] df['Y'] = 0 ## fit AdaBoost Model with depth-2 Decision Trees as Weak Learners ## continue fitting model until all n-1000 observations predicted correctly count = True while(count): model = DecisionTreeClassifier(random_state=0, max_depth=2) model.fit(df[['L1', 'L2', 'L3','L4', 'L5', 'L6']], df['Y_original'], sample_weight=df['w']) df['Y_hat'] = model.predict(df[['L1', 'L2', 'L3','L4', 'L5', 'L6']]) df.loc[df['Y_hat']==df['Y_original'], 'w'] = 0 epsilon = sum(df['w']) alpha = 0.5*(np.log((1-epsilon)/epsilon)) df['Y'] = df['Y'] + (alpha*df['Y_hat']) current_loss = sum(np.exp(-df['Y_original']*df['Y'])) psi = np.exp(-df['Y_original']*df['Y']) df['w'] = psi / current_loss print('Current Loss: ' + str(current_loss)) df['Y_final'] = 1 df.loc[df['Y']<0, 'Y_final'] = -1 if(df.loc[df['Y_original']!=df['Y_final'], :].shape[0] == 0): print('results converged, all datapoints correctly classified') break pd.crosstab(df['Y_original'], df['Y_final']) For the complete code/notebook for the above computational simulation, please see the following github link. I hope the above is insightful. As I’ve mentioned in some of my previous pieces, it’s my opinion not enough folks take the time to go through these types of exercises. For me, this type of theory-based insight leaves me more comfortable using methods in practice. A personal goal of mine is to encourage others in the field to take a similar approach. I will continue to write similar pieces in the future. Please subscribe and follow me here on Medium and on LinkedIn for updates!
[ { "code": null, "e": 675, "s": 172, "text": "Boosting is a family of ensemble Machine Learning techniques for both discrete and continuous random variable targets. Boosting models take the form of Non-Parametric Additive models and are most typically specified with additive components being “weak learners”. From an empirical risk decomposition perspective, where it can be easily shown the Mean Squared Error (MSE) of any arbitrary statistical estimator is the additive sum of the squared bias and sampling variance of said sampling estimator..." }, { "code": null, "e": 1048, "s": 675, "text": "... a “weak learner” is a statistical estimator with high squared-bias but low sampling variance. Weak learners have the benefit of ease of model fitting from a computational perspective. Examples of weak learners include single decision and regression trees constrained to only a few layers of depth, possible even one layer (refereed to as “decision/regression stumps”)." }, { "code": null, "e": 1442, "s": 1048, "text": "The motivation of Boosting is to recover an additive ensemble of weak leaners that together can specify an arbitrarily complex model. In this piece, we will specify the theoretically framework and full mathematical derivation for Gradient Boosting and AdaBoost. We will also provide a full computational simulation of these methods from scratch, without use of Boosting computational packages." }, { "code": null, "e": 1495, "s": 1442, "text": "The Table of Contents for this piece are as follows:" }, { "code": null, "e": 1760, "s": 1495, "text": "With Gradient Boosting, the model estimation procedure can be viewed as performing Gradient Descent in function-space over a space of proposal weak-learners (hence the name “Gradient Boosting”). Let’s jump into the mathematical specification and fitting procedure:" }, { "code": null, "e": 1878, "s": 1760, "text": "To understand the fitting procedure for Gradient Boosting Models, it is helpful to first recall the Taylor Expansion." }, { "code": null, "e": 1983, "s": 1878, "text": "Let’s next discuss AdaBoost, which is in-fact a special case of the more general Gradient Boosting Model" }, { "code": null, "e": 2093, "s": 1983, "text": "With the information and notation outlined in section 3.1, let’s dive into the fitting procedure for AdaBoost" }, { "code": null, "e": 2510, "s": 2093, "text": "There is a slight alternative view of Boosting from a Non-Parametric Additive Model perspective. This is a view quite well understood in the Mathematical Statistics and Statistical Learning community, but one I rarely ever see covered in the Computer Science arm of the Machine Learning community. I think it’s a perspective worth understanding, and provides a more robust view of Boosting as a family of procedures." }, { "code": null, "e": 2899, "s": 2510, "text": "There are a class of Statistical Models known as Non-Parametric Additive Models. This class of estimators is enormous, and are highly flexible. In a certain sense, these class of models is too flexible. As an an analyst leveraging a statistical model from this class, there are so many hyperparameters and design choices to choose from, specifying a the “right” model can be overwhelming." }, { "code": null, "e": 3324, "s": 2899, "text": "For a given prediction problem, there is some underlying Non-Parametric Additive model that “works best” so-to-speak in a global sense. This “best” model we will refer to as the “true NPA model”. Given our sample data, we would like to do our best to specify and recover this “true NPA model”. But how can go about doing so in a structured and practical manner? The parameters space over which we need to search is enormous!" }, { "code": null, "e": 4293, "s": 3324, "text": "Let’s make an analogy for a moment. Imagine instead we had a Machine Learning problem for which we are leveraging Linear Regression. We have 100 features to choose from, and we know there is some true combination of features that provides the “best subset selection” Linear Regression Model. But we would have to test 2100 different models to recover the “best one”, which is a search space in the hundreds of trillions. Instead of attempting to search over that entire space, we could instead leverage a greedy algorithm like Forward-Selection where we will choose and add one variable to the final model at a time making our choices based on a greedy myopic heuristic. With this approach, we only need to test a few thousand models instead of hundreds of trillions. We know this Forward-Selection procedure is unlikely to recover the exact solution to the “best subset selection” problem; but it will recover a model that will likely work very well for our purposes." }, { "code": null, "e": 4797, "s": 4293, "text": "The Forward-Selection scenario above is very similar to leveraging Boosting as a fitting procedure for Non-Parametric Additive models in a Machine Learning context. We would like to recover an estimate to the “true NPA model”, however the size of the search space is overwhelming. Boosting in this sense can be viewed as a family of greedy algorithmic procedures for estimating the solution to the “true NPA model” problem, similar to estimating the best subset-selection problem with Forward Selection." }, { "code": null, "e": 4965, "s": 4797, "text": "Below is a fully working example (built from scratch) of fitting a Gradient Boosted Model on a continuous target, and an AdaBoost Model on a binary categorical target." }, { "code": null, "e": 5005, "s": 4965, "text": "First, let’s load our needed libraries:" }, { "code": null, "e": 5228, "s": 5005, "text": "####################\n## load libraries ##\n####################\nimport numpy as np\nimport pandas as pd\nnp.random.seed(123456789)\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.tree import DecisionTreeClassifier" }, { "code": null, "e": 5313, "s": 5228, "text": "Next, a function to simulate a dataset with a purposely complex model specification:" }, { "code": null, "e": 7023, "s": 5313, "text": "############################\n## Toy Dataset Simulation ##\n############################\ndef simulate_df(n=100, seed=123456, binary_flag=False):\n np.random.seed(seed)\n \n ## specify dataframe\n df = pd.DataFrame()\n\n ## specify variables L1 through L6\n L1_split = 0.52\n L2_split = 0.23\n L3_split = 0.38\n df['L1'] = np.random.choice([0, 1], size=n, replace=True, p=[L1_split, (1-L1_split)])\n df['L2'] = np.random.choice([0, 1], size=n, replace=True, p=[L2_split, (1-L2_split)])\n df['L3'] = np.random.choice([0, 1], size=n, replace=True, p=[L3_split, (1-L3_split)])\n df['L4'] = np.random.normal(0, 1, df.shape[0])\n df['L5'] = np.random.normal(0, 0.75, df.shape[0])\n df['L6'] = np.random.normal(0, 2, df.shape[0])\n \n theta_0 = 5.5\n theta_1 = 1.28\n theta_2 = 0.42\n theta_3 = 2.32\n theta_4 = -3.15\n theta_5 = 3.12\n theta_6 = -4.29\n theta_7 = -1.23\n theta_8 = -10.18\n theta_9 = 2.21\n theta_10 = 10.3\n \n if(binary_flag):\n Z = theta_0 + (theta_1*df['L1']) + (theta_2*df['L2']) + (theta_3*df['L3']) + (theta_4*df['L4']) + (theta_5*df['L5']) + (theta_6*df['L6']) + (theta_7*df['L2']*df['L4']) + (theta_8*df['L3']*df['L6']) + (theta_9*df['L5']*df['L5']) + (theta_10*np.sin(df['L5']))\n p = 1 / (1 + np.exp(-Z))\n df['Y'] = np.random.binomial(1, p)\n df.loc[df['Y']==0, 'Y'] = -1\n else:\n df['Y'] = theta_0 + (theta_1*df['L1']) + (theta_2*df['L2']) + (theta_3*df['L3']) + (theta_4*df['L4']) + (theta_5*df['L5']) + (theta_6*df['L6']) + (theta_7*df['L2']*df['L4']) + (theta_8*df['L3']*df['L6']) + (theta_9*df['L5']*df['L5']) + (theta_10*np.sin(df['L5'])) + np.random.normal(0, 0.1, df.shape[0])\n\n return(df)" }, { "code": null, "e": 7319, "s": 7023, "text": "Let’s recover a simulated dataset with a continuous outcome target Y, and fit a Gradient Boosting Model. Note, we will print the empirical realization of the Global Loss function with each weak learner added to the model. We will consider the model to have converged when the empirical loss < 1." }, { "code": null, "e": 8574, "s": 7319, "text": "###############################################\n## Gradient Boosting with Continuous Outcome ##\n###############################################\n\n## simulate the dataset with continuous outcome Y\ndf = simulate_df(n=1000, seed=123456)\ndf['Y_original'] = df['Y']\n\n## fit Gradient Boosting Model with depth-3 Regression Trees as Weak Learners\n## continue fitting model until loss function < 1\nalpha = 100000\ncurrent_loss = sum((df['Y'])**2)\nwhile(current_loss > 1):\n model = DecisionTreeRegressor(random_state=0, max_depth=3)\n model.fit(df[['L1', 'L2', 'L3','L4', 'L5', 'L6']], df['Y'])\n df['Y_hat'] = model.predict(df[['L1', 'L2', 'L3','L4', 'L5', 'L6']])\n df['Y_hat_squared'] = df['Y_hat']**2\n df['Y_hat_scaled'] = np.sqrt(df['Y_hat_squared'] / df['Y_hat_squared'].sum()) * np.sign(df['Y_hat'])\n loss_not_lowered_flag = True\n while(loss_not_lowered_flag):\n new_loss = sum((df['Y'] - (alpha*df['Y_hat_scaled']))**2)\n if(new_loss < current_loss):\n loss_not_lowered_flag = False\n current_loss = new_loss\n print('Current Loss: ' + str(current_loss))\n df['Y'] = df['Y'] - (alpha*df['Y_hat_scaled'])\n else:\n alpha = 0.99*alpha\n del model\nprint('model converged')" }, { "code": null, "e": 8925, "s": 8574, "text": "Let’s now recover a simulated dataset with a binary categorical outcome target Y, and fit an AdaBoost Model. Note, we will print the empirical realization of the Global Loss function with each weak learner added to the model. We will consider the model to have converged when all n=1000 training points are correctly classified by the ensemble model." }, { "code": null, "e": 10282, "s": 8925, "text": "######################################################\n## AdaBoost with Binary Categorical Outcome {-1, 1} ##\n######################################################\n\n## simulate the dataset with continuous outcome Y\ndf = simulate_df(n=1000, seed=123456, binary_flag=True)\ndf = df.rename(columns={'Y':'Y_original'})\ndf['w'] = df.shape[0]*[1/df.shape[0]]\ndf['Y'] = 0\n\n## fit AdaBoost Model with depth-2 Decision Trees as Weak Learners\n## continue fitting model until all n-1000 observations predicted correctly\ncount = True\nwhile(count):\n model = DecisionTreeClassifier(random_state=0, max_depth=2)\n model.fit(df[['L1', 'L2', 'L3','L4', 'L5', 'L6']], df['Y_original'], sample_weight=df['w'])\n df['Y_hat'] = model.predict(df[['L1', 'L2', 'L3','L4', 'L5', 'L6']])\n df.loc[df['Y_hat']==df['Y_original'], 'w'] = 0\n epsilon = sum(df['w'])\n alpha = 0.5*(np.log((1-epsilon)/epsilon))\n \n df['Y'] = df['Y'] + (alpha*df['Y_hat'])\n \n current_loss = sum(np.exp(-df['Y_original']*df['Y']))\n psi = np.exp(-df['Y_original']*df['Y'])\n df['w'] = psi / current_loss\n \n print('Current Loss: ' + str(current_loss))\n \n df['Y_final'] = 1\n df.loc[df['Y']<0, 'Y_final'] = -1\n \n if(df.loc[df['Y_original']!=df['Y_final'], :].shape[0] == 0):\n print('results converged, all datapoints correctly classified')\n break" }, { "code": null, "e": 10327, "s": 10282, "text": "pd.crosstab(df['Y_original'], df['Y_final'])" }, { "code": null, "e": 10436, "s": 10327, "text": "For the complete code/notebook for the above computational simulation, please see the following github link." } ]
How to Extract Key from Python Dictionary using Value | by Abhijith Chandradas | Towards Data Science
It is straight-forward to extract value if we have key, like unlocking a lock with a key. However, the vice versa is not as simple, like “unkeying the key with a lock”, maybe! Sometimes extracting keys become important especially when the key and value has a one-to-one relationship. That is, when either of them is unique and hence can act as the key. Before getting into the various methods, first we will create a dictionary for the purpose of illustration. currency_dict is the dictionary with currency abbreviations as keys and currency names as value. currency_dict={'USD':'Dollar', 'EUR':'Euro', 'GBP':'Pound', 'INR':'Rupee'} If you have the key, getting the value by simply adding the key within square brackets.For example, currency_dict[‘GBP’] will return ‘Pound’. Step 1: Convert dictionary keys and values into lists.Step 2: Find the matching index from value list.Step 3: Use the index to find the appropriate key from key list. key_list=list(currency_dict.keys())val_list=list(currency_dict.values())ind=val_list.index(val)key_list[ind]Output: 'GBP' All the three steps can be combined in a single step as below: list(currency_dict.keys())[list(currency_dict.values()).index(val)] Method 1 can be slightly modified using a for loop as below:Step 1: Convert dictionary keys and values into lists.Step 2: Iterate through all values in value list to find the required valueStep 3: Return the corresponding key from the key list. def return_key(val): for i in range(len(currency_dict)): if val_list[i]==val: return key_list[i] return("Key Not Found")return_key("Rupee")Output: 'INR' items() keep dictionary elements as key-value pair.Step 1: Iterate through all key-value pairs in item().Step 2: Find the value which match the required valueStep 3: Return the key from the key-value pair. def return_key(val): for key, value in currency_dict.items(): if value==val: return key return('Key Not Found')return_key('Dollar')Output: 'USD' Getting the keys from after converting into a DataFrame is in my opinion the simplest and easy to understand method. However it is not the most efficient one, which in my opinion would be the one-liner in Method 1. A dictionary can be converted into a pandas DataFrame as below: df=pd.DataFrame({'abbr':list(currency_dict.keys()), 'curr':list(currency_dict.values())}) All keys are in the column ‘abbr’ and all values are in ‘curr’ column of DataFrame ‘df’. Now finding the value is very easy, just return the value from ‘abbr’ column from the row where value of ‘curr’ column is the required value. df.abbr[df.curr==val]Output: 2 GBP Much simpler than how it sounds! Note that the output contains index as well. The output is not in string format but it is a pandas Series object type. The series object can be converted to string using many options, few are as follows: df.abbr[df.curr==val].unique()[0]df.abbr[df.curr==val].mode()[0]df.abbr[df.curr==val].sum()Output : 'GBP' The code for this article is available in my GitHub Repo. You can check out my YouTube video if you are more interested in the visual format I hope you like the article, I would highly recommend signing up for Medium Membership to read more articles by me or stories by thousands of other authors on variety of topics. Your membership fee directly supports me and other writers you read. You’ll also get full access to every story on Medium.
[ { "code": null, "e": 347, "s": 171, "text": "It is straight-forward to extract value if we have key, like unlocking a lock with a key. However, the vice versa is not as simple, like “unkeying the key with a lock”, maybe!" }, { "code": null, "e": 524, "s": 347, "text": "Sometimes extracting keys become important especially when the key and value has a one-to-one relationship. That is, when either of them is unique and hence can act as the key." }, { "code": null, "e": 729, "s": 524, "text": "Before getting into the various methods, first we will create a dictionary for the purpose of illustration. currency_dict is the dictionary with currency abbreviations as keys and currency names as value." }, { "code": null, "e": 841, "s": 729, "text": "currency_dict={'USD':'Dollar', 'EUR':'Euro', 'GBP':'Pound', 'INR':'Rupee'}" }, { "code": null, "e": 983, "s": 841, "text": "If you have the key, getting the value by simply adding the key within square brackets.For example, currency_dict[‘GBP’] will return ‘Pound’." }, { "code": null, "e": 1150, "s": 983, "text": "Step 1: Convert dictionary keys and values into lists.Step 2: Find the matching index from value list.Step 3: Use the index to find the appropriate key from key list." }, { "code": null, "e": 1272, "s": 1150, "text": "key_list=list(currency_dict.keys())val_list=list(currency_dict.values())ind=val_list.index(val)key_list[ind]Output: 'GBP'" }, { "code": null, "e": 1335, "s": 1272, "text": "All the three steps can be combined in a single step as below:" }, { "code": null, "e": 1403, "s": 1335, "text": "list(currency_dict.keys())[list(currency_dict.values()).index(val)]" }, { "code": null, "e": 1648, "s": 1403, "text": "Method 1 can be slightly modified using a for loop as below:Step 1: Convert dictionary keys and values into lists.Step 2: Iterate through all values in value list to find the required valueStep 3: Return the corresponding key from the key list." }, { "code": null, "e": 1825, "s": 1648, "text": "def return_key(val): for i in range(len(currency_dict)): if val_list[i]==val: return key_list[i] return(\"Key Not Found\")return_key(\"Rupee\")Output: 'INR'" }, { "code": null, "e": 2031, "s": 1825, "text": "items() keep dictionary elements as key-value pair.Step 1: Iterate through all key-value pairs in item().Step 2: Find the value which match the required valueStep 3: Return the key from the key-value pair." }, { "code": null, "e": 2200, "s": 2031, "text": "def return_key(val): for key, value in currency_dict.items(): if value==val: return key return('Key Not Found')return_key('Dollar')Output: 'USD'" }, { "code": null, "e": 2479, "s": 2200, "text": "Getting the keys from after converting into a DataFrame is in my opinion the simplest and easy to understand method. However it is not the most efficient one, which in my opinion would be the one-liner in Method 1. A dictionary can be converted into a pandas DataFrame as below:" }, { "code": null, "e": 2585, "s": 2479, "text": "df=pd.DataFrame({'abbr':list(currency_dict.keys()), 'curr':list(currency_dict.values())})" }, { "code": null, "e": 2816, "s": 2585, "text": "All keys are in the column ‘abbr’ and all values are in ‘curr’ column of DataFrame ‘df’. Now finding the value is very easy, just return the value from ‘abbr’ column from the row where value of ‘curr’ column is the required value." }, { "code": null, "e": 2854, "s": 2816, "text": "df.abbr[df.curr==val]Output: 2 GBP" }, { "code": null, "e": 3006, "s": 2854, "text": "Much simpler than how it sounds! Note that the output contains index as well. The output is not in string format but it is a pandas Series object type." }, { "code": null, "e": 3091, "s": 3006, "text": "The series object can be converted to string using many options, few are as follows:" }, { "code": null, "e": 3197, "s": 3091, "text": "df.abbr[df.curr==val].unique()[0]df.abbr[df.curr==val].mode()[0]df.abbr[df.curr==val].sum()Output : 'GBP'" }, { "code": null, "e": 3255, "s": 3197, "text": "The code for this article is available in my GitHub Repo." }, { "code": null, "e": 3338, "s": 3255, "text": "You can check out my YouTube video if you are more interested in the visual format" } ]
Python Tkinter - Message - GeeksforGeeks
26 Mar, 2020 Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using Tkinter is an easy task. Note: For more information, refer to Python GUI – tkinter The Message widget is used to show the message to the user regarding the behavior of the python application. The message text contains more than one line. Syntax:The syntax to use the message is given below. w = Message( master, options) Parameters: master: This parameter is used to represents the parent window. options:There are many options which are available and they can be used as key-value pairs separated by commas. Options:Following are commonly used Option can be used with this widget :- anchor: This option is used to decide the exact position of the text within the space .Its default value is CENTER. bg: This option used to represent the normal background color. bitmap: This option used to display a monochrome image. bd: This option used to represent the size of the border and the default value is 2 pixels. cursor: By using this option, the mouse cursor will change to that pattern when it is over type. font: This option used to represent the font used for the text. fg: This option used to represent the color used to render the text. height: This option used to represent the number of lines of text on the message. image: This option used to display a graphic image on the widget. justify: This option used to control how the text is justified: CENTER, LEFT, or RIGHT. padx: This option used to represent how much space to leave to the left and right of the widget and text. It’s default value is 1 pixel. pady: This option used to represent how much space to leave above and below the widget. It’s default value is 1 pixel. relief: The type of the border of the widget. It’s default value is set to FLAT. text: This option used use newlines (“\n”) to display multiple lines of text. variable: This option used to represents the associated variable that tracks the state of the widget. width: This option used to represents the width of the widget. and also represented in the number of characters that are represented in the form of texts. wraplength: This option will be broken text into the number of pieces. Example: from tkinter import * root = Tk()root.geometry("300x200") w = Label(root, text ='GeeksForGeeks', font = "50") w.pack() msg = Message( root, text = "A computer science portal for geeks") msg.pack() root.mainloop() Output: Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace()
[ { "code": null, "e": 41554, "s": 41526, "text": "\n26 Mar, 2020" }, { "code": null, "e": 41906, "s": 41554, "text": "Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using Tkinter is an easy task." }, { "code": null, "e": 41964, "s": 41906, "text": "Note: For more information, refer to Python GUI – tkinter" }, { "code": null, "e": 42119, "s": 41964, "text": "The Message widget is used to show the message to the user regarding the behavior of the python application. The message text contains more than one line." }, { "code": null, "e": 42172, "s": 42119, "text": "Syntax:The syntax to use the message is given below." }, { "code": null, "e": 42202, "s": 42172, "text": "w = Message( master, options)" }, { "code": null, "e": 42214, "s": 42202, "text": "Parameters:" }, { "code": null, "e": 42278, "s": 42214, "text": "master: This parameter is used to represents the parent window." }, { "code": null, "e": 42390, "s": 42278, "text": "options:There are many options which are available and they can be used as key-value pairs separated by commas." }, { "code": null, "e": 42465, "s": 42390, "text": "Options:Following are commonly used Option can be used with this widget :-" }, { "code": null, "e": 42581, "s": 42465, "text": "anchor: This option is used to decide the exact position of the text within the space .Its default value is CENTER." }, { "code": null, "e": 42644, "s": 42581, "text": "bg: This option used to represent the normal background color." }, { "code": null, "e": 42700, "s": 42644, "text": "bitmap: This option used to display a monochrome image." }, { "code": null, "e": 42792, "s": 42700, "text": "bd: This option used to represent the size of the border and the default value is 2 pixels." }, { "code": null, "e": 42889, "s": 42792, "text": "cursor: By using this option, the mouse cursor will change to that pattern when it is over type." }, { "code": null, "e": 42953, "s": 42889, "text": "font: This option used to represent the font used for the text." }, { "code": null, "e": 43022, "s": 42953, "text": "fg: This option used to represent the color used to render the text." }, { "code": null, "e": 43104, "s": 43022, "text": "height: This option used to represent the number of lines of text on the message." }, { "code": null, "e": 43170, "s": 43104, "text": "image: This option used to display a graphic image on the widget." }, { "code": null, "e": 43258, "s": 43170, "text": "justify: This option used to control how the text is justified: CENTER, LEFT, or RIGHT." }, { "code": null, "e": 43395, "s": 43258, "text": "padx: This option used to represent how much space to leave to the left and right of the widget and text. It’s default value is 1 pixel." }, { "code": null, "e": 43514, "s": 43395, "text": "pady: This option used to represent how much space to leave above and below the widget. It’s default value is 1 pixel." }, { "code": null, "e": 43595, "s": 43514, "text": "relief: The type of the border of the widget. It’s default value is set to FLAT." }, { "code": null, "e": 43673, "s": 43595, "text": "text: This option used use newlines (“\\n”) to display multiple lines of text." }, { "code": null, "e": 43775, "s": 43673, "text": "variable: This option used to represents the associated variable that tracks the state of the widget." }, { "code": null, "e": 43930, "s": 43775, "text": "width: This option used to represents the width of the widget. and also represented in the number of characters that are represented in the form of texts." }, { "code": null, "e": 44001, "s": 43930, "text": "wraplength: This option will be broken text into the number of pieces." }, { "code": null, "e": 44010, "s": 44001, "text": "Example:" }, { "code": "from tkinter import * root = Tk()root.geometry(\"300x200\") w = Label(root, text ='GeeksForGeeks', font = \"50\") w.pack() msg = Message( root, text = \"A computer science portal for geeks\") msg.pack() root.mainloop() ", "e": 44237, "s": 44010, "text": null }, { "code": null, "e": 44245, "s": 44237, "text": "Output:" }, { "code": null, "e": 44260, "s": 44245, "text": "Python-tkinter" }, { "code": null, "e": 44267, "s": 44260, "text": "Python" }, { "code": null, "e": 44365, "s": 44267, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 44393, "s": 44365, "text": "Read JSON file using Python" }, { "code": null, "e": 44443, "s": 44393, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 44465, "s": 44443, "text": "Python map() function" }, { "code": null, "e": 44509, "s": 44465, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 44544, "s": 44509, "text": "Read a file line by line in Python" }, { "code": null, "e": 44566, "s": 44544, "text": "Enumerate() in Python" }, { "code": null, "e": 44598, "s": 44566, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 44628, "s": 44598, "text": "Iterate over a list in Python" }, { "code": null, "e": 44670, "s": 44628, "text": "Different ways to create Pandas Dataframe" } ]
How to remove empty rows from R dataframe? - GeeksforGeeks
26 Mar, 2021 A dataframe can contain empty rows and here with empty rows we don’t mean NA, NaN or 0, it literally means empty with absolutely no data. Such rows are obviously wasting space and making data frame unnecessarily large. This article will discuss how can this be done. To remove rows with empty cells we have a syntax in the R language, which makes it easier for the user to remove as many numbers of empty rows in the data frame automatically. Syntax: data <- data[!apply(data == “”, 1, all),] Approach Create dataframe Select empty rows Remove those rows Copy the resultant dataframe Display dataframe Example 1: R gfg <- data.frame(a=c('i','','iii','iv','','vi','','viii','','x'), b=c('I','','III','IV','','VI','','VIII','','X'), c=c('1','','3','4','','6','','8','','10'), d=c('a','','c','d','','f','','h','','j')) print('Original dataframe:-')gfg gfg <- gfg[!apply(gfg == "", 1, all),]print('Modified dataframe:-')gfg Output: Example 2: R gfg <- data.frame( A=c('a','','c','','e'), B=c('5','','5','','5'), C=c('1','','1','','1'), D=c('3','','3','','3'), E=c('#','','#','','#'), F=c('@','','@','','@'), H=c('8','','8','','8')) print('Original dataframe:-')gfg gfg <- gfg[!apply(gfg == "", 1, all),]print('Modified dataframe:-')gfg Output: Picked R DataFrame-Programs R-DataFrame R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? How to filter R dataframe by multiple conditions? Replace Specific Characters in String in R Convert Matrix to Dataframe in R
[ { "code": null, "e": 25242, "s": 25214, "text": "\n26 Mar, 2021" }, { "code": null, "e": 25509, "s": 25242, "text": "A dataframe can contain empty rows and here with empty rows we don’t mean NA, NaN or 0, it literally means empty with absolutely no data. Such rows are obviously wasting space and making data frame unnecessarily large. This article will discuss how can this be done." }, { "code": null, "e": 25685, "s": 25509, "text": "To remove rows with empty cells we have a syntax in the R language, which makes it easier for the user to remove as many numbers of empty rows in the data frame automatically." }, { "code": null, "e": 25693, "s": 25685, "text": "Syntax:" }, { "code": null, "e": 25735, "s": 25693, "text": "data <- data[!apply(data == “”, 1, all),]" }, { "code": null, "e": 25744, "s": 25735, "text": "Approach" }, { "code": null, "e": 25761, "s": 25744, "text": "Create dataframe" }, { "code": null, "e": 25779, "s": 25761, "text": "Select empty rows" }, { "code": null, "e": 25797, "s": 25779, "text": "Remove those rows" }, { "code": null, "e": 25826, "s": 25797, "text": "Copy the resultant dataframe" }, { "code": null, "e": 25844, "s": 25826, "text": "Display dataframe" }, { "code": null, "e": 25855, "s": 25844, "text": "Example 1:" }, { "code": null, "e": 25857, "s": 25855, "text": "R" }, { "code": "gfg <- data.frame(a=c('i','','iii','iv','','vi','','viii','','x'), b=c('I','','III','IV','','VI','','VIII','','X'), c=c('1','','3','4','','6','','8','','10'), d=c('a','','c','d','','f','','h','','j')) print('Original dataframe:-')gfg gfg <- gfg[!apply(gfg == \"\", 1, all),]print('Modified dataframe:-')gfg", "e": 26217, "s": 25857, "text": null }, { "code": null, "e": 26225, "s": 26217, "text": "Output:" }, { "code": null, "e": 26236, "s": 26225, "text": "Example 2:" }, { "code": null, "e": 26238, "s": 26236, "text": "R" }, { "code": "gfg <- data.frame( A=c('a','','c','','e'), B=c('5','','5','','5'), C=c('1','','1','','1'), D=c('3','','3','','3'), E=c('#','','#','','#'), F=c('@','','@','','@'), H=c('8','','8','','8')) print('Original dataframe:-')gfg gfg <- gfg[!apply(gfg == \"\", 1, all),]print('Modified dataframe:-')gfg", "e": 26658, "s": 26238, "text": null }, { "code": null, "e": 26666, "s": 26658, "text": "Output:" }, { "code": null, "e": 26673, "s": 26666, "text": "Picked" }, { "code": null, "e": 26694, "s": 26673, "text": "R DataFrame-Programs" }, { "code": null, "e": 26706, "s": 26694, "text": "R-DataFrame" }, { "code": null, "e": 26717, "s": 26706, "text": "R Language" }, { "code": null, "e": 26728, "s": 26717, "text": "R Programs" }, { "code": null, "e": 26826, "s": 26728, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26878, "s": 26826, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 26916, "s": 26878, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 26951, "s": 26916, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 27009, "s": 26951, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 27058, "s": 27009, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 27116, "s": 27058, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 27165, "s": 27116, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 27215, "s": 27165, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 27258, "s": 27215, "text": "Replace Specific Characters in String in R" } ]
Linear Regression in Python. The math behind Linear Regression and... | by Indhumathy Chelliah | Towards Data Science
Linear Regression is a machine learning algorithm based on supervised learning. Linear Regression is a predictive model that is used for finding the linear relationship between a dependent variable and one or more independent variables. Here,dependent variable/target variable(Y) should be continuous variable. Let’s learn the math behind simple linear regression and the Python way of implementation using ski-kit learn Let’s looks at our dataset first. I have taken a simple dataset for an easy explanation. Years of Experience vs Salary. We want to predict the salary of the person based on their years of experience? Dataset In the given dataset, we have Exp vs Salary. Now, we want to predict the salary for 3.5 years of experience? Let’s see how to predict that? c →y-intercept → What is the value of y when x is zero?The regression line cuts the y-axis at the y-intercept. Y → Predicted Y value for the given X value Let’s calculate m and c. m is also known as regression co-efficient. It tells whether there is a positive correlation between the dependent and independent variables. A positive correlation means when the independent variable increases, the mean of the dependent variable also increases. The Regression coefficient is defined as the covariance of x and y divided by the variance of the independent variable, x. Variance → How far each number in the dataset is from the mean.x̄ → mean of xȳ → mean of y Covariance →It’s a measure of the relationship between two variables. I have done all the math calculations in an excel sheet which can be downloaded from my GitHub link. Covariance =( Σ [ (xi — x̅ )(yi — ȳ) ])/n=529.0740741 Variance =(Σ [ (xi — x̅ )2])/n= 1.509876543 m= Covariance /Variance =529.0740741/1.509876543=350.4088307 m=350.4088307 Now to calculate intercept c y=mx+cc=y-mxApply mean y (ȳ) and mean x (x̅)in the equation and calculate c c= 1683.33333-(350.4088307*2.7111)c=733.3360589 After calculating m and c, now we can do predictions. Let’s predict the salary of a person having 3.5 years of experience. y=mx+cm=350.4088307c=733.3360589 y predict = (350.4088307 * 3.5) + 733.3360589 = 1959.766966 The predicted y value for x=3.5 is 1959.766966 To evaluate how good our regression model is, we can use the following metrics. The error or residual is the difference between the actual value and the predicted value. The sum of all errors can cancel out since it can contain negative signs and give zero. So, we square all the errors and sum it up. The line which gives us the least sum of squared errors is the best fit. The line of best fit always goes through x̅ and ȳ. In Linear Regression, the line of best fit is calculated by minimizing the error(the distance between data points and the line). Sum of Squares Errors is also known as Residual error or Residual sum of squares SSR is also known as Regression Error or Explained Error.It is the sum of the differences between the predicted value and the mean of the dependent variable ȳ SST/Total Error = Sum of squared errors + Regression Error. Total Error or Variability of the data set is equal to the variability explained by the regression line (Regression Error) plus the unexplained variability (SSE) known as error or residuals. Explained Error or Variability → SSRUnexplained Error → SSE MSE is the average of the squared difference between the actual and predicted values of the data points. RMSE is a measure of how spread out these residuals are. In other words, it tells you how concentrated the data is around the line of best fit.RMSE is calculated by taking the square root of MSE. Interpretation of RMSE:RMSE is interpreted as the standard deviation of unexplained variance(MSE).RMSE contains the same units as the dependent variable.Lower values of RMSE indicates a better fit. Before building the model, have to identify good predictors. The coefficient of Correlation (r) is used to determine the strength of the relationship between two variables. It will help to identify good predictors. Formula: The value of r range from -1 to 1. -1 indicates a negative correlation which means when x increases y decreases. +1 indicates a positive correlation which means both x and y travels in the same direction.0 or close to 0 means no correlation. The coefficient of determination → This metric is used after building the model, to check how reliable the model is. R2 →It is equal to the variance explained by regression (Regression Error or SSR) divided by Total variance in y (SST) R2 → It describes how much of the total variance in y is explained by our model.If Error(unexplained error or SSE)<Variance (SST) means the model is good.The best fit is the line in which unexplained error (SSE) is minimized. R2 values range from 0 to 1. 0 → indicates Poor model1 or close to 1 → indicates the Best model The code used can be downloaded as a Jupyter notebook in my GitHub link. import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as sns df=pd.read_csv("exp1.csv")df df.describe() Scatterplot plt.scatter(df.Exp,df.Salary,color='red') [We can find linear relationship between x and y] Histogram df.hist() Finding the Coefficient of Correlation (r) df.corr() r value 0.98 indicates a strong relationship. We can plot correlation using the heatmap sns.heatmap(df.corr(),annot=True,vmin=-1,vmax=-1) Finding missing values df.isna().sum() [No Missing values are there] x=df.iloc[:,0:1]x.head(1)y=df.iloc[:,1:]y.head(1 plt.scatter(x, y)plt.title('Experience Vs Salary')plt.xlabel('Years of Experience')plt.ylabel('Salary')plt.show() from sklearn.linear_model import LinearRegressionlin_reg=LinearRegression()lin_reg.fit(x,y) Visualize the model plt.scatter(x,y)plt.plot(x,lin_reg.predict(x),color='green')plt.title("Regression Model")plt.xlabel("YOE")plt.ylabel("Salary") 7. Predict the salary for 3.5 years of experience using the model ypredict=lin_reg.predict(np.array([[3.5]]))ypredict#Output:array([[1959.76696648]]) 8. m (slope) and c(intercept) values lin_reg.coef_#Output:array([[350.40883074]])lin_reg.intercept_#Output:array([733.33605887]) ypredict=lin_reg.predict(x)ypredict from sklearn.metrics import mean_squared_error,r2_score,explained_variance_scoreprint ("Coefficient of determination :",r2_score(y,ypredict))print ("MSE: ",mean_squared_error(y,ypredict))print("RMSE: ",np.sqrt(mean_squared_error(y,ypredict)))#Output:Coefficient of determination : 0.9729038186936964MSE: 5163.327882256747RMSE: 71.85630022661024 We get the same values using math calculation and python implementation.If it's a large dataset, we have to split the data for training and testing. GitHub Link Code, dataset, excel sheet used in this story is available in my GitHub Link In this story, we have taken the simple dataset and learned the math behind simple linear regression and python way of implementation using scikit learn.We can also implement linear regression using statsmodel. towardsdatascience.com towardsdatascience.com towardsdatascience.com towardsdatascience.com pub.towardsai.net betterprogramming.pub Watch this space for more articles on Python and DataScience. If you like to read more of my tutorials, follow me on Medium, LinkedIn, Twitter. Become Medium Member by clicking here:
[ { "code": null, "e": 483, "s": 172, "text": "Linear Regression is a machine learning algorithm based on supervised learning. Linear Regression is a predictive model that is used for finding the linear relationship between a dependent variable and one or more independent variables. Here,dependent variable/target variable(Y) should be continuous variable." }, { "code": null, "e": 593, "s": 483, "text": "Let’s learn the math behind simple linear regression and the Python way of implementation using ski-kit learn" }, { "code": null, "e": 713, "s": 593, "text": "Let’s looks at our dataset first. I have taken a simple dataset for an easy explanation. Years of Experience vs Salary." }, { "code": null, "e": 793, "s": 713, "text": "We want to predict the salary of the person based on their years of experience?" }, { "code": null, "e": 801, "s": 793, "text": "Dataset" }, { "code": null, "e": 941, "s": 801, "text": "In the given dataset, we have Exp vs Salary. Now, we want to predict the salary for 3.5 years of experience? Let’s see how to predict that?" }, { "code": null, "e": 1052, "s": 941, "text": "c →y-intercept → What is the value of y when x is zero?The regression line cuts the y-axis at the y-intercept." }, { "code": null, "e": 1096, "s": 1052, "text": "Y → Predicted Y value for the given X value" }, { "code": null, "e": 1121, "s": 1096, "text": "Let’s calculate m and c." }, { "code": null, "e": 1384, "s": 1121, "text": "m is also known as regression co-efficient. It tells whether there is a positive correlation between the dependent and independent variables. A positive correlation means when the independent variable increases, the mean of the dependent variable also increases." }, { "code": null, "e": 1507, "s": 1384, "text": "The Regression coefficient is defined as the covariance of x and y divided by the variance of the independent variable, x." }, { "code": null, "e": 1599, "s": 1507, "text": "Variance → How far each number in the dataset is from the mean.x̄ → mean of xȳ → mean of y" }, { "code": null, "e": 1669, "s": 1599, "text": "Covariance →It’s a measure of the relationship between two variables." }, { "code": null, "e": 1770, "s": 1669, "text": "I have done all the math calculations in an excel sheet which can be downloaded from my GitHub link." }, { "code": null, "e": 1825, "s": 1770, "text": "Covariance =( Σ [ (xi — x̅ )(yi — ȳ) ])/n=529.0740741" }, { "code": null, "e": 1869, "s": 1825, "text": "Variance =(Σ [ (xi — x̅ )2])/n= 1.509876543" }, { "code": null, "e": 1930, "s": 1869, "text": "m= Covariance /Variance =529.0740741/1.509876543=350.4088307" }, { "code": null, "e": 1944, "s": 1930, "text": "m=350.4088307" }, { "code": null, "e": 1973, "s": 1944, "text": "Now to calculate intercept c" }, { "code": null, "e": 2050, "s": 1973, "text": "y=mx+cc=y-mxApply mean y (ȳ) and mean x (x̅)in the equation and calculate c" }, { "code": null, "e": 2098, "s": 2050, "text": "c= 1683.33333-(350.4088307*2.7111)c=733.3360589" }, { "code": null, "e": 2152, "s": 2098, "text": "After calculating m and c, now we can do predictions." }, { "code": null, "e": 2221, "s": 2152, "text": "Let’s predict the salary of a person having 3.5 years of experience." }, { "code": null, "e": 2254, "s": 2221, "text": "y=mx+cm=350.4088307c=733.3360589" }, { "code": null, "e": 2314, "s": 2254, "text": "y predict = (350.4088307 * 3.5) + 733.3360589 = 1959.766966" }, { "code": null, "e": 2361, "s": 2314, "text": "The predicted y value for x=3.5 is 1959.766966" }, { "code": null, "e": 2441, "s": 2361, "text": "To evaluate how good our regression model is, we can use the following metrics." }, { "code": null, "e": 2736, "s": 2441, "text": "The error or residual is the difference between the actual value and the predicted value. The sum of all errors can cancel out since it can contain negative signs and give zero. So, we square all the errors and sum it up. The line which gives us the least sum of squared errors is the best fit." }, { "code": null, "e": 2788, "s": 2736, "text": "The line of best fit always goes through x̅ and ȳ." }, { "code": null, "e": 2917, "s": 2788, "text": "In Linear Regression, the line of best fit is calculated by minimizing the error(the distance between data points and the line)." }, { "code": null, "e": 2998, "s": 2917, "text": "Sum of Squares Errors is also known as Residual error or Residual sum of squares" }, { "code": null, "e": 3158, "s": 2998, "text": "SSR is also known as Regression Error or Explained Error.It is the sum of the differences between the predicted value and the mean of the dependent variable ȳ" }, { "code": null, "e": 3218, "s": 3158, "text": "SST/Total Error = Sum of squared errors + Regression Error." }, { "code": null, "e": 3409, "s": 3218, "text": "Total Error or Variability of the data set is equal to the variability explained by the regression line (Regression Error) plus the unexplained variability (SSE) known as error or residuals." }, { "code": null, "e": 3469, "s": 3409, "text": "Explained Error or Variability → SSRUnexplained Error → SSE" }, { "code": null, "e": 3574, "s": 3469, "text": "MSE is the average of the squared difference between the actual and predicted values of the data points." }, { "code": null, "e": 3770, "s": 3574, "text": "RMSE is a measure of how spread out these residuals are. In other words, it tells you how concentrated the data is around the line of best fit.RMSE is calculated by taking the square root of MSE." }, { "code": null, "e": 3968, "s": 3770, "text": "Interpretation of RMSE:RMSE is interpreted as the standard deviation of unexplained variance(MSE).RMSE contains the same units as the dependent variable.Lower values of RMSE indicates a better fit." }, { "code": null, "e": 4183, "s": 3968, "text": "Before building the model, have to identify good predictors. The coefficient of Correlation (r) is used to determine the strength of the relationship between two variables. It will help to identify good predictors." }, { "code": null, "e": 4192, "s": 4183, "text": "Formula:" }, { "code": null, "e": 4434, "s": 4192, "text": "The value of r range from -1 to 1. -1 indicates a negative correlation which means when x increases y decreases. +1 indicates a positive correlation which means both x and y travels in the same direction.0 or close to 0 means no correlation." }, { "code": null, "e": 4551, "s": 4434, "text": "The coefficient of determination → This metric is used after building the model, to check how reliable the model is." }, { "code": null, "e": 4670, "s": 4551, "text": "R2 →It is equal to the variance explained by regression (Regression Error or SSR) divided by Total variance in y (SST)" }, { "code": null, "e": 4896, "s": 4670, "text": "R2 → It describes how much of the total variance in y is explained by our model.If Error(unexplained error or SSE)<Variance (SST) means the model is good.The best fit is the line in which unexplained error (SSE) is minimized." }, { "code": null, "e": 4925, "s": 4896, "text": "R2 values range from 0 to 1." }, { "code": null, "e": 4992, "s": 4925, "text": "0 → indicates Poor model1 or close to 1 → indicates the Best model" }, { "code": null, "e": 5065, "s": 4992, "text": "The code used can be downloaded as a Jupyter notebook in my GitHub link." }, { "code": null, "e": 5155, "s": 5065, "text": "import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as sns" }, { "code": null, "e": 5184, "s": 5155, "text": "df=pd.read_csv(\"exp1.csv\")df" }, { "code": null, "e": 5198, "s": 5184, "text": "df.describe()" }, { "code": null, "e": 5210, "s": 5198, "text": "Scatterplot" }, { "code": null, "e": 5252, "s": 5210, "text": "plt.scatter(df.Exp,df.Salary,color='red')" }, { "code": null, "e": 5302, "s": 5252, "text": "[We can find linear relationship between x and y]" }, { "code": null, "e": 5312, "s": 5302, "text": "Histogram" }, { "code": null, "e": 5322, "s": 5312, "text": "df.hist()" }, { "code": null, "e": 5365, "s": 5322, "text": "Finding the Coefficient of Correlation (r)" }, { "code": null, "e": 5375, "s": 5365, "text": "df.corr()" }, { "code": null, "e": 5421, "s": 5375, "text": "r value 0.98 indicates a strong relationship." }, { "code": null, "e": 5463, "s": 5421, "text": "We can plot correlation using the heatmap" }, { "code": null, "e": 5513, "s": 5463, "text": "sns.heatmap(df.corr(),annot=True,vmin=-1,vmax=-1)" }, { "code": null, "e": 5536, "s": 5513, "text": "Finding missing values" }, { "code": null, "e": 5552, "s": 5536, "text": "df.isna().sum()" }, { "code": null, "e": 5582, "s": 5552, "text": "[No Missing values are there]" }, { "code": null, "e": 5631, "s": 5582, "text": "x=df.iloc[:,0:1]x.head(1)y=df.iloc[:,1:]y.head(1" }, { "code": null, "e": 5745, "s": 5631, "text": "plt.scatter(x, y)plt.title('Experience Vs Salary')plt.xlabel('Years of Experience')plt.ylabel('Salary')plt.show()" }, { "code": null, "e": 5837, "s": 5745, "text": "from sklearn.linear_model import LinearRegressionlin_reg=LinearRegression()lin_reg.fit(x,y)" }, { "code": null, "e": 5857, "s": 5837, "text": "Visualize the model" }, { "code": null, "e": 5984, "s": 5857, "text": "plt.scatter(x,y)plt.plot(x,lin_reg.predict(x),color='green')plt.title(\"Regression Model\")plt.xlabel(\"YOE\")plt.ylabel(\"Salary\")" }, { "code": null, "e": 6050, "s": 5984, "text": "7. Predict the salary for 3.5 years of experience using the model" }, { "code": null, "e": 6134, "s": 6050, "text": "ypredict=lin_reg.predict(np.array([[3.5]]))ypredict#Output:array([[1959.76696648]])" }, { "code": null, "e": 6171, "s": 6134, "text": "8. m (slope) and c(intercept) values" }, { "code": null, "e": 6263, "s": 6171, "text": "lin_reg.coef_#Output:array([[350.40883074]])lin_reg.intercept_#Output:array([733.33605887])" }, { "code": null, "e": 6299, "s": 6263, "text": "ypredict=lin_reg.predict(x)ypredict" }, { "code": null, "e": 6646, "s": 6299, "text": "from sklearn.metrics import mean_squared_error,r2_score,explained_variance_scoreprint (\"Coefficient of determination :\",r2_score(y,ypredict))print (\"MSE: \",mean_squared_error(y,ypredict))print(\"RMSE: \",np.sqrt(mean_squared_error(y,ypredict)))#Output:Coefficient of determination : 0.9729038186936964MSE: 5163.327882256747RMSE: 71.85630022661024" }, { "code": null, "e": 6795, "s": 6646, "text": "We get the same values using math calculation and python implementation.If it's a large dataset, we have to split the data for training and testing." }, { "code": null, "e": 6807, "s": 6795, "text": "GitHub Link" }, { "code": null, "e": 6884, "s": 6807, "text": "Code, dataset, excel sheet used in this story is available in my GitHub Link" }, { "code": null, "e": 7095, "s": 6884, "text": "In this story, we have taken the simple dataset and learned the math behind simple linear regression and python way of implementation using scikit learn.We can also implement linear regression using statsmodel." }, { "code": null, "e": 7118, "s": 7095, "text": "towardsdatascience.com" }, { "code": null, "e": 7141, "s": 7118, "text": "towardsdatascience.com" }, { "code": null, "e": 7164, "s": 7141, "text": "towardsdatascience.com" }, { "code": null, "e": 7187, "s": 7164, "text": "towardsdatascience.com" }, { "code": null, "e": 7205, "s": 7187, "text": "pub.towardsai.net" }, { "code": null, "e": 7227, "s": 7205, "text": "betterprogramming.pub" }, { "code": null, "e": 7371, "s": 7227, "text": "Watch this space for more articles on Python and DataScience. If you like to read more of my tutorials, follow me on Medium, LinkedIn, Twitter." } ]
Making a cone with VPython - GeeksforGeeks
08 Jun, 2020 VPython makes it easy to create navigable 3D displays and animations, even for those with limited programming experience. Because it is based on Python, it also has much to offer for experienced programmers and researchers. VPython allows users to create objects such as spheres and cones in 3D space and displays these objects in a window. This makes it easy to create simple visualizations, allowing programmers to focus more on the computational aspect of their programs. The simplicity of VPython has made it a tool for the illustration of simple physics, especially in the educational environment. Installation : pip install vpython A cone is a geometrical object in three-dimensional space that tapers smoothly from a flat circular base to a point called the apex or vertex. We can generate a cone in VPython using the cone() method. Syntax : cone(parameters) Parameters : pos : It is the position of the center of the base of the cone. Assign a vector containing 3 values, example pos = vector(0, 0, 0) axis : It is the axis of alignment of the cone. Assign a vector containing 3 values, example axis = vector(1, 2, 1) up : It is the orientation of the cone. Assign a vector containing 3 values, example up = vector(0, 1, 0) color : It is the color of the cone. Assign a vector containing 3 values, example color = vector(1, 1, 1) will give the color white opacity : It is the opacity of the cone. Assign a floating value in which 1 is the most opaque and 0 the least opaque, example opacity = 0.5 shininess : It is the shininess of the cone. Assign a floating value in which 1 is the most shiny and 0 the least shiny, example shininess = 0.6 emissive : It is the emissivity of the cone. Assign a boolean value in which True is emissive and False is not emissive, example emissivity = False texture : It is the texture of the cone. Assign the required texture from the textures class, example texture = textures.stucco length : It is the length of the cone. Assign a floating value, the default length is 1, example length = 10 radius : It is the radius of the base of the cone. Assign a floating value, the default height is 1, example radius = 5 size : It is the size of the cone. Assign a vector containing 3 values representing the length, height and width respectively, example size = vector(1, 1, 1) All the parameters are optional. Example 1 :A cone with no parameters, all the parameters will have the default value. # import the modulefrom vpython import * cone() Output : Example 2 :A cone using the parameters color, opacity, shininess and emissivity. # import the modulefrom vpython import * cone(color = vector(0, 1, 1), opacity = 0.5, shininess = 1, emissive = False) Output : Example 3 :Displaying 2 cones to visualize the attributes pos, length and radius. # import the modulefrom vpython import * # the first conecone(pos = vector(-2, 2, 0), length = 3, radius = 1, color = vector(1, 0, 0)) # the second conecone(pos = vector(0.4, 0.2, 0.6), color = vector(1, 1, 0)) Output : Example 4 :A cone using the parameters texture, axis and up. # import the modulefrom vpython import * cone(texture = textures.stucco, axis = vector(-1, 4, 0), up = vector(1, 2, 2)) Output : Python vpython-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Selecting rows in pandas DataFrame based on conditions Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Split string into list of characters
[ { "code": null, "e": 24292, "s": 24264, "text": "\n08 Jun, 2020" }, { "code": null, "e": 24895, "s": 24292, "text": "VPython makes it easy to create navigable 3D displays and animations, even for those with limited programming experience. Because it is based on Python, it also has much to offer for experienced programmers and researchers. VPython allows users to create objects such as spheres and cones in 3D space and displays these objects in a window. This makes it easy to create simple visualizations, allowing programmers to focus more on the computational aspect of their programs. The simplicity of VPython has made it a tool for the illustration of simple physics, especially in the educational environment." }, { "code": null, "e": 24910, "s": 24895, "text": "Installation :" }, { "code": null, "e": 24930, "s": 24910, "text": "pip install vpython" }, { "code": null, "e": 25132, "s": 24930, "text": "A cone is a geometrical object in three-dimensional space that tapers smoothly from a flat circular base to a point called the apex or vertex. We can generate a cone in VPython using the cone() method." }, { "code": null, "e": 25158, "s": 25132, "text": "Syntax : cone(parameters)" }, { "code": null, "e": 25171, "s": 25158, "text": "Parameters :" }, { "code": null, "e": 25302, "s": 25171, "text": "pos : It is the position of the center of the base of the cone. Assign a vector containing 3 values, example pos = vector(0, 0, 0)" }, { "code": null, "e": 25418, "s": 25302, "text": "axis : It is the axis of alignment of the cone. Assign a vector containing 3 values, example axis = vector(1, 2, 1)" }, { "code": null, "e": 25524, "s": 25418, "text": "up : It is the orientation of the cone. Assign a vector containing 3 values, example up = vector(0, 1, 0)" }, { "code": null, "e": 25656, "s": 25524, "text": "color : It is the color of the cone. Assign a vector containing 3 values, example color = vector(1, 1, 1) will give the color white" }, { "code": null, "e": 25797, "s": 25656, "text": "opacity : It is the opacity of the cone. Assign a floating value in which 1 is the most opaque and 0 the least opaque, example opacity = 0.5" }, { "code": null, "e": 25942, "s": 25797, "text": "shininess : It is the shininess of the cone. Assign a floating value in which 1 is the most shiny and 0 the least shiny, example shininess = 0.6" }, { "code": null, "e": 26090, "s": 25942, "text": "emissive : It is the emissivity of the cone. Assign a boolean value in which True is emissive and False is not emissive, example emissivity = False" }, { "code": null, "e": 26218, "s": 26090, "text": "texture : It is the texture of the cone. Assign the required texture from the textures class, example texture = textures.stucco" }, { "code": null, "e": 26327, "s": 26218, "text": "length : It is the length of the cone. Assign a floating value, the default length is 1, example length = 10" }, { "code": null, "e": 26447, "s": 26327, "text": "radius : It is the radius of the base of the cone. Assign a floating value, the default height is 1, example radius = 5" }, { "code": null, "e": 26605, "s": 26447, "text": "size : It is the size of the cone. Assign a vector containing 3 values representing the length, height and width respectively, example size = vector(1, 1, 1)" }, { "code": null, "e": 26638, "s": 26605, "text": "All the parameters are optional." }, { "code": null, "e": 26724, "s": 26638, "text": "Example 1 :A cone with no parameters, all the parameters will have the default value." }, { "code": "# import the modulefrom vpython import * cone()", "e": 26772, "s": 26724, "text": null }, { "code": null, "e": 26781, "s": 26772, "text": "Output :" }, { "code": null, "e": 26862, "s": 26781, "text": "Example 2 :A cone using the parameters color, opacity, shininess and emissivity." }, { "code": "# import the modulefrom vpython import * cone(color = vector(0, 1, 1), opacity = 0.5, shininess = 1, emissive = False)", "e": 26996, "s": 26862, "text": null }, { "code": null, "e": 27005, "s": 26996, "text": "Output :" }, { "code": null, "e": 27087, "s": 27005, "text": "Example 3 :Displaying 2 cones to visualize the attributes pos, length and radius." }, { "code": "# import the modulefrom vpython import * # the first conecone(pos = vector(-2, 2, 0), length = 3, radius = 1, color = vector(1, 0, 0)) # the second conecone(pos = vector(0.4, 0.2, 0.6), color = vector(1, 1, 0))", "e": 27317, "s": 27087, "text": null }, { "code": null, "e": 27326, "s": 27317, "text": "Output :" }, { "code": null, "e": 27387, "s": 27326, "text": "Example 4 :A cone using the parameters texture, axis and up." }, { "code": "# import the modulefrom vpython import * cone(texture = textures.stucco, axis = vector(-1, 4, 0), up = vector(1, 2, 2))", "e": 27515, "s": 27387, "text": null }, { "code": null, "e": 27524, "s": 27515, "text": "Output :" }, { "code": null, "e": 27546, "s": 27524, "text": "Python vpython-module" }, { "code": null, "e": 27553, "s": 27546, "text": "Python" }, { "code": null, "e": 27651, "s": 27553, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27683, "s": 27651, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27739, "s": 27683, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27781, "s": 27739, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27823, "s": 27781, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27878, "s": 27823, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 27900, "s": 27878, "text": "Defaultdict in Python" }, { "code": null, "e": 27939, "s": 27900, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27970, "s": 27939, "text": "Python | os.path.join() method" }, { "code": null, "e": 27999, "s": 27970, "text": "Create a directory in Python" } ]
BigInteger remainder() Method in Java - GeeksforGeeks
04 Dec, 2018 The java.math.BigInteger.remainder(BigInteger big) method returns a BigInteger whose value is equal to (this BigInteger % big(BigInteger passed as parameter)).The remainder operation finds the remainder after division of this BigInteger by another BigInteger passed as parameter. Syntax: public BigInteger remainder(BigInteger big) Parameter: The function accepts a single mandatory parameter big which specifies the BigInteger Object by which we want to divide this bigInteger object. Returns: The method returns the BigInteger which is equal to this BigInteger % big(BigInteger passed as parameter). ExceptionThe method throws an ArithmeticException – when big = 0 Examples: Input: BigInteger1=321456, BigInteger2=31711 Output: 4346 Explanation: BigInteger1.remainder(BigInteger2)=4346. The divide operation between 321456 and 31711 returns 4346 as remainder. Input: BigInteger1=59185482345, BigInteger2=59185482345 Output: 0 Explanation: BigInteger1.remainder(BigInteger2)=0. The divide operation between 59185482345 and 59185482345 returns 0 as remainder. Example 1: Below programs illustrate remainder() method of BigInteger class // Java program to demonstrate remainder() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Creating 2 BigInteger objects BigInteger b1, b2; b1 = new BigInteger("321456"); b2 = new BigInteger("31711"); // apply remainder() method BigInteger result = b1.remainder(b2); // print result System.out.println("Result of remainder " + "operation between " + b1 + " and " + b2 + " equal to " + result); }} Result of remainder operation between 321456 and 31711 equal to 4346 Example 2: when both are equal in value. // Java program to demonstrate remainder() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Creating 2 BigInteger objects BigInteger b1, b2; b1 = new BigInteger("3515219485"); b2 = new BigInteger("3515219485"); // apply remainder() method BigInteger result = b1.remainder(b2); // print result System.out.println("Result of remainder " + "operation between " + b1 + " and " + b2 + " equal to " + result); }} Result of remainder operation between 3515219485 and 3515219485 equal to 0 Example 3: program showing exception when BigInteger passed as parameter is equal to zero. // Java program to demonstrate remainder() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Creating 2 BigInteger objects BigInteger b1, b2; b1 = new BigInteger("3515219485"); b2 = new BigInteger("0"); // apply remainder() method BigInteger result = b1.remainder(b2); // print result System.out.println("Result of remainder "+ "operation between " + b1 + " and " + b2 + " equal to " + result); }} Output: Exception in thread "main" java.lang.ArithmeticException: BigInteger divide by zero at java.math.MutableBigInteger.divideKnuth(MutableBigInteger.java:1179) at java.math.MutableBigInteger.divideKnuth(MutableBigInteger.java:1163) at java.math.BigInteger.remainderKnuth(BigInteger.java:2167) at java.math.BigInteger.remainder(BigInteger.java:2155) at GFG.main(GFG.java:16) Reference:BigInteger remainder() Docs java-basics Java-BigInteger Java-Functions java-math Java-math-package Java Java-BigInteger Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Different ways of Reading a text file in Java Constructors in Java Stream In Java Generics in Java Exceptions in Java Comparator Interface in Java with Examples HashMap get() Method in Java Functional Interfaces in Java StringBuilder Class in Java with Examples Strings in Java
[ { "code": null, "e": 23948, "s": 23920, "text": "\n04 Dec, 2018" }, { "code": null, "e": 24228, "s": 23948, "text": "The java.math.BigInteger.remainder(BigInteger big) method returns a BigInteger whose value is equal to (this BigInteger % big(BigInteger passed as parameter)).The remainder operation finds the remainder after division of this BigInteger by another BigInteger passed as parameter." }, { "code": null, "e": 24236, "s": 24228, "text": "Syntax:" }, { "code": null, "e": 24280, "s": 24236, "text": "public BigInteger remainder(BigInteger big)" }, { "code": null, "e": 24434, "s": 24280, "text": "Parameter: The function accepts a single mandatory parameter big which specifies the BigInteger Object by which we want to divide this bigInteger object." }, { "code": null, "e": 24550, "s": 24434, "text": "Returns: The method returns the BigInteger which is equal to this BigInteger % big(BigInteger passed as parameter)." }, { "code": null, "e": 24615, "s": 24550, "text": "ExceptionThe method throws an ArithmeticException – when big = 0" }, { "code": null, "e": 24625, "s": 24615, "text": "Examples:" }, { "code": null, "e": 25012, "s": 24625, "text": "Input: BigInteger1=321456, BigInteger2=31711\nOutput: 4346\nExplanation: BigInteger1.remainder(BigInteger2)=4346. The divide operation \nbetween 321456 and 31711 returns 4346 as remainder.\n\nInput: BigInteger1=59185482345, BigInteger2=59185482345\nOutput: 0\nExplanation: BigInteger1.remainder(BigInteger2)=0. The divide operation between \n59185482345 and 59185482345 returns 0 as remainder.\n" }, { "code": null, "e": 25088, "s": 25012, "text": "Example 1: Below programs illustrate remainder() method of BigInteger class" }, { "code": "// Java program to demonstrate remainder() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Creating 2 BigInteger objects BigInteger b1, b2; b1 = new BigInteger(\"321456\"); b2 = new BigInteger(\"31711\"); // apply remainder() method BigInteger result = b1.remainder(b2); // print result System.out.println(\"Result of remainder \" + \"operation between \" + b1 + \" and \" + b2 + \" equal to \" + result); }}", "e": 25679, "s": 25088, "text": null }, { "code": null, "e": 25749, "s": 25679, "text": "Result of remainder operation between 321456 and 31711 equal to 4346\n" }, { "code": null, "e": 25790, "s": 25749, "text": "Example 2: when both are equal in value." }, { "code": "// Java program to demonstrate remainder() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Creating 2 BigInteger objects BigInteger b1, b2; b1 = new BigInteger(\"3515219485\"); b2 = new BigInteger(\"3515219485\"); // apply remainder() method BigInteger result = b1.remainder(b2); // print result System.out.println(\"Result of remainder \" + \"operation between \" + b1 + \" and \" + b2 + \" equal to \" + result); }}", "e": 26390, "s": 25790, "text": null }, { "code": null, "e": 26466, "s": 26390, "text": "Result of remainder operation between 3515219485 and 3515219485 equal to 0\n" }, { "code": null, "e": 26557, "s": 26466, "text": "Example 3: program showing exception when BigInteger passed as parameter is equal to zero." }, { "code": "// Java program to demonstrate remainder() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Creating 2 BigInteger objects BigInteger b1, b2; b1 = new BigInteger(\"3515219485\"); b2 = new BigInteger(\"0\"); // apply remainder() method BigInteger result = b1.remainder(b2); // print result System.out.println(\"Result of remainder \"+ \"operation between \" + b1 + \" and \" + b2 + \" equal to \" + result); }}", "e": 27140, "s": 26557, "text": null }, { "code": null, "e": 27539, "s": 27140, "text": "Output:\nException in thread \"main\" java.lang.ArithmeticException: BigInteger divide by zero\n at java.math.MutableBigInteger.divideKnuth(MutableBigInteger.java:1179)\n at java.math.MutableBigInteger.divideKnuth(MutableBigInteger.java:1163)\n at java.math.BigInteger.remainderKnuth(BigInteger.java:2167)\n at java.math.BigInteger.remainder(BigInteger.java:2155)\n at GFG.main(GFG.java:16)\n" }, { "code": null, "e": 27577, "s": 27539, "text": "Reference:BigInteger remainder() Docs" }, { "code": null, "e": 27589, "s": 27577, "text": "java-basics" }, { "code": null, "e": 27605, "s": 27589, "text": "Java-BigInteger" }, { "code": null, "e": 27620, "s": 27605, "text": "Java-Functions" }, { "code": null, "e": 27630, "s": 27620, "text": "java-math" }, { "code": null, "e": 27648, "s": 27630, "text": "Java-math-package" }, { "code": null, "e": 27653, "s": 27648, "text": "Java" }, { "code": null, "e": 27669, "s": 27653, "text": "Java-BigInteger" }, { "code": null, "e": 27674, "s": 27669, "text": "Java" }, { "code": null, "e": 27772, "s": 27674, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27781, "s": 27772, "text": "Comments" }, { "code": null, "e": 27794, "s": 27781, "text": "Old Comments" }, { "code": null, "e": 27840, "s": 27794, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 27861, "s": 27840, "text": "Constructors in Java" }, { "code": null, "e": 27876, "s": 27861, "text": "Stream In Java" }, { "code": null, "e": 27893, "s": 27876, "text": "Generics in Java" }, { "code": null, "e": 27912, "s": 27893, "text": "Exceptions in Java" }, { "code": null, "e": 27955, "s": 27912, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 27984, "s": 27955, "text": "HashMap get() Method in Java" }, { "code": null, "e": 28014, "s": 27984, "text": "Functional Interfaces in Java" }, { "code": null, "e": 28056, "s": 28014, "text": "StringBuilder Class in Java with Examples" } ]
Print colored message with different fonts and sizes in C
29 Oct, 2018 In C/C++ we can use graphics.h header file for creation of programs which uses graphical functions like creating different objects, setting the color of text, printing messages in different fonts and size, changing the background of our output console and much more.Here we will create a program which will print message (“geeks”) in colored form in different font style and size. listed below are some function used : setcolor(): It will set the cursor color and hence anything written on the output screen will be of the color as per setcolor().function prototype :setcolor(int) setcolor(int) settexttyle(): It set the text font style, its orientation(horizontal/ vertical) and size of font.Function prototype :settextstyle(int style, int orientation, int size); settextstyle(int style, int orientation, int size); outtextxy() : It will print message passed to it at some certain coordinate (x,y).function prototype :settextstyle(int style, int orientation, int size); settextstyle(int style, int orientation, int size); More functions:TextHeight():textheight();TextWidth():textwidth();SetUserCharSize():-setusercharsize(x1,y1,x2,y2); textheight(); TextWidth(): textwidth(); SetUserCharSize():- setusercharsize(x1,y1,x2,y2); Note: Given program will not run on IDE, try it on your compiler // C program to print// message as colored characters#include<stdio.h>#include<graphics.h>#include<dos.h> // function for printing// message as colored charactervoid printMsg(){ // auto detection int gdriver = DETECT,gmode,i; // initialize graphics mode initgraph(&gdriver,&gmode,"C:\\Turboc3\\BGI"); for (i=3; i<7; i++) { // setcolor of cursor setcolor(i); // set text style as // settextstyle(font, orientation, size) settextstyle(i,0,i); // print text at coordinate x,y; outtextxy(100,20*i,"Geeks"); delay(500); } delay(2000);} // driver programint main(){ printMsg(); return 0;} Output: This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. PremDhadkar C Language School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n29 Oct, 2018" }, { "code": null, "e": 471, "s": 52, "text": "In C/C++ we can use graphics.h header file for creation of programs which uses graphical functions like creating different objects, setting the color of text, printing messages in different fonts and size, changing the background of our output console and much more.Here we will create a program which will print message (“geeks”) in colored form in different font style and size. listed below are some function used :" }, { "code": null, "e": 633, "s": 471, "text": "setcolor(): It will set the cursor color and hence anything written on the output screen will be of the color as per setcolor().function prototype :setcolor(int)" }, { "code": null, "e": 647, "s": 633, "text": "setcolor(int)" }, { "code": null, "e": 817, "s": 647, "text": "settexttyle(): It set the text font style, its orientation(horizontal/ vertical) and size of font.Function prototype :settextstyle(int style, int orientation, int size);" }, { "code": null, "e": 869, "s": 817, "text": "settextstyle(int style, int orientation, int size);" }, { "code": null, "e": 1023, "s": 869, "text": "outtextxy() : It will print message passed to it at some certain coordinate (x,y).function prototype :settextstyle(int style, int orientation, int size);" }, { "code": null, "e": 1075, "s": 1023, "text": "settextstyle(int style, int orientation, int size);" }, { "code": null, "e": 1189, "s": 1075, "text": "More functions:TextHeight():textheight();TextWidth():textwidth();SetUserCharSize():-setusercharsize(x1,y1,x2,y2);" }, { "code": null, "e": 1203, "s": 1189, "text": "textheight();" }, { "code": null, "e": 1216, "s": 1203, "text": "TextWidth():" }, { "code": null, "e": 1229, "s": 1216, "text": "textwidth();" }, { "code": null, "e": 1249, "s": 1229, "text": "SetUserCharSize():-" }, { "code": null, "e": 1279, "s": 1249, "text": "setusercharsize(x1,y1,x2,y2);" }, { "code": null, "e": 1344, "s": 1279, "text": "Note: Given program will not run on IDE, try it on your compiler" }, { "code": "// C program to print// message as colored characters#include<stdio.h>#include<graphics.h>#include<dos.h> // function for printing// message as colored charactervoid printMsg(){ // auto detection int gdriver = DETECT,gmode,i; // initialize graphics mode initgraph(&gdriver,&gmode,\"C:\\\\Turboc3\\\\BGI\"); for (i=3; i<7; i++) { // setcolor of cursor setcolor(i); // set text style as // settextstyle(font, orientation, size) settextstyle(i,0,i); // print text at coordinate x,y; outtextxy(100,20*i,\"Geeks\"); delay(500); } delay(2000);} // driver programint main(){ printMsg(); return 0;}", "e": 2050, "s": 1344, "text": null }, { "code": null, "e": 2058, "s": 2050, "text": "Output:" }, { "code": null, "e": 2375, "s": 2060, "text": "This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 2500, "s": 2375, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 2512, "s": 2500, "text": "PremDhadkar" }, { "code": null, "e": 2523, "s": 2512, "text": "C Language" }, { "code": null, "e": 2542, "s": 2523, "text": "School Programming" } ]
Count of sub-strings that are divisible by K
07 Jul, 2022 Given an integer K and a numeric string str (all the characters are from the range [‘0’, ‘9’]). The task is to count the number of sub-strings of str that are divisible by K. Examples: Input: str = “33445”, K = 11 Output: 3 Sub-strings that are divisible by 11 are “33”, “44” and “3344” Input: str = “334455”, K = 11 Output: 6 Approach: Initialize count = 0. Take all the sub-strings of str and check whether they are divisible by K or not. If yes, then update count = count + 1. Print the count in the end. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count of sub-strings// of str that are divisible by kint countSubStr(string str, int len, int k){ int count = 0; for (int i = 0; i < len; i++) { int n = 0; // Take all sub-strings starting from i for (int j = i; j < len; j++) { n = n * 10 + (str[j] - '0'); // If current sub-string is divisible by k if (n % k == 0) count++; } } // Return the required count return count;} // Driver codeint main(){ string str = "33445"; int len = str.length(); int k = 11; cout << countSubStr(str, len, k); return 0;} // Java implementation of above approachclass GFG{ // Function to return the count of sub-strings // of str that are divisible by k static int countSubStr(String str, int len, int k) { int count = 0; for (int i = 0; i < len; i++) { int n = 0; // Take all sub-strings starting from i for (int j = i; j < len; j++) { n = n * 10 + (str.charAt(j) - '0'); // If current sub-string is divisible by k if (n % k == 0) count++; } } // Return the required count return count; } // Driver code public static void main(String []args) { String str = "33445"; int len = str.length(); int k = 11; System.out.println(countSubStr(str, len, k)); }} // This code is contributed by Ryuga # Python 3 implementation of the approach # Function to return the count of sub-strings# of str that are divisible by kdef countSubStr(str, l, k): count = 0 for i in range(l): n = 0 # Take all sub-strings starting from i for j in range(i, l, 1): n = n * 10 + (ord(str[j]) - ord('0')) # If current sub-string is divisible by k if (n % k == 0): count += 1 # Return the required count return count # Driver codeif __name__ == '__main__': str = "33445" l = len(str) k = 11 print(countSubStr(str, l, k)) # This code is contributed by# Sanjit_Prasad // C# implementation of above approachusing System; class GFG{ // Function to return the count of sub-strings // of str that are divisible by k static int countSubStr(String str, int len, int k) { int count = 0; for (int i = 0; i < len; i++) { int n = 0; // Take all sub-strings starting from i for (int j = i; j < len; j++) { n = n * 10 + (str[j] - '0'); // If current sub-string is divisible by k if (n % k == 0) count++; } } // Return the required count return count; } // Driver code public static void Main() { String str = "33445"; int len = str.Length; int k = 11; Console.WriteLine(countSubStr(str, len, k)); }} // This code is contributed by Code_Mech <?php// PHP implementation of the approach // Function to return the count of sub-strings// of str that are divisible by kfunction countSubStr($str, $len, $k){ $count = 0; for ($i = 0; $i < $len; $i++) { $n = 0; // Take all sub-strings starting from i for ($j = $i; $j < $len; $j++) { $n = $n * 10 + ($str[$j] - '0'); // If current sub-string is // divisible by k if ($n % $k == 0) $count++; } } // Return the required count return $count;} // Driver code$str = "33445";$len = strlen($str);$k = 11;echo countSubStr($str, $len, $k); // This code is contributed// by Shivi_Aggarwal?> <script> // Javascript implementation of above approach // Function to return the count of sub-strings// of str that are divisible by kfunction countSubStr(str, len, k){ let count = 0; for(let i = 0; i < len; i++) { let n = 0; // Take all sub-strings starting from i for(let j = i; j < len; j++) { n = n * 10 + (str[j].charCodeAt() - '0'.charCodeAt()); // If current sub-string is // divisible by k if (n % k == 0) count++; } } // Return the required count return count;} // Driver codelet str = "33445";let len = str.length;let k = 11; document.write(countSubStr(str, len, k)); // This code is contributed by mukesh07 </script> 3 Efficient approach : The idea is to use a hashMap to store the remainders of each suffix of the string so that any suffix if it is already present int the hashMap then the substring between them is divisible by k. Below is the implementation of the above approach. Java // Java Program for above approachimport java.util.*;public class Main{ // Program to count number of substrings public static int Divisible(String s, int k) { // To count substrings int num_of_substrings = 0; // To store the remainders int rem[] = new int[k]; rem[0] = 1; StringBuffer curr = new StringBuffer(); // Iterate from s.length() - 1 to 0 for (int i = s.length() - 1; i >= 0; i--) { // to Calculate suffix string curr.insert(0, s.charAt(i)); // convert to number long num = Long.parseLong(curr. toString()); num_of_substrings += rem[(int)num % k]; // Keep track of visited remainders rem[(int)num % k]++; } // Return number of substrings return num_of_substrings; } // Driver Code public static void main(String args[]) { String s = "111111"; int k = 11; // Function Call System.out.println("Number of sub strings : " + Divisible(s, k)); }} Number of sub strings : 9 Time Complexity: O(n2)Auxiliary Space: O(k) ankthon Sanjit_Prasad Code_Mech Shivi_Aggarwal hemanthswarna1506 mukesh07 akshaysingh98088 sagar0719kumar jayanth_mkv cpp-strings divisibility C++ Programs Strings cpp-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": "\n07 Jul, 2022" }, { "code": null, "e": 227, "s": 52, "text": "Given an integer K and a numeric string str (all the characters are from the range [‘0’, ‘9’]). The task is to count the number of sub-strings of str that are divisible by K." }, { "code": null, "e": 238, "s": 227, "text": "Examples: " }, { "code": null, "e": 340, "s": 238, "text": "Input: str = “33445”, K = 11 Output: 3 Sub-strings that are divisible by 11 are “33”, “44” and “3344”" }, { "code": null, "e": 381, "s": 340, "text": "Input: str = “334455”, K = 11 Output: 6 " }, { "code": null, "e": 562, "s": 381, "text": "Approach: Initialize count = 0. Take all the sub-strings of str and check whether they are divisible by K or not. If yes, then update count = count + 1. Print the count in the end." }, { "code": null, "e": 615, "s": 562, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 619, "s": 615, "text": "C++" }, { "code": null, "e": 624, "s": 619, "text": "Java" }, { "code": null, "e": 632, "s": 624, "text": "Python3" }, { "code": null, "e": 635, "s": 632, "text": "C#" }, { "code": null, "e": 639, "s": 635, "text": "PHP" }, { "code": null, "e": 650, "s": 639, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count of sub-strings// of str that are divisible by kint countSubStr(string str, int len, int k){ int count = 0; for (int i = 0; i < len; i++) { int n = 0; // Take all sub-strings starting from i for (int j = i; j < len; j++) { n = n * 10 + (str[j] - '0'); // If current sub-string is divisible by k if (n % k == 0) count++; } } // Return the required count return count;} // Driver codeint main(){ string str = \"33445\"; int len = str.length(); int k = 11; cout << countSubStr(str, len, k); return 0;}", "e": 1381, "s": 650, "text": null }, { "code": "// Java implementation of above approachclass GFG{ // Function to return the count of sub-strings // of str that are divisible by k static int countSubStr(String str, int len, int k) { int count = 0; for (int i = 0; i < len; i++) { int n = 0; // Take all sub-strings starting from i for (int j = i; j < len; j++) { n = n * 10 + (str.charAt(j) - '0'); // If current sub-string is divisible by k if (n % k == 0) count++; } } // Return the required count return count; } // Driver code public static void main(String []args) { String str = \"33445\"; int len = str.length(); int k = 11; System.out.println(countSubStr(str, len, k)); }} // This code is contributed by Ryuga", "e": 2287, "s": 1381, "text": null }, { "code": "# Python 3 implementation of the approach # Function to return the count of sub-strings# of str that are divisible by kdef countSubStr(str, l, k): count = 0 for i in range(l): n = 0 # Take all sub-strings starting from i for j in range(i, l, 1): n = n * 10 + (ord(str[j]) - ord('0')) # If current sub-string is divisible by k if (n % k == 0): count += 1 # Return the required count return count # Driver codeif __name__ == '__main__': str = \"33445\" l = len(str) k = 11 print(countSubStr(str, l, k)) # This code is contributed by# Sanjit_Prasad", "e": 2932, "s": 2287, "text": null }, { "code": "// C# implementation of above approachusing System; class GFG{ // Function to return the count of sub-strings // of str that are divisible by k static int countSubStr(String str, int len, int k) { int count = 0; for (int i = 0; i < len; i++) { int n = 0; // Take all sub-strings starting from i for (int j = i; j < len; j++) { n = n * 10 + (str[j] - '0'); // If current sub-string is divisible by k if (n % k == 0) count++; } } // Return the required count return count; } // Driver code public static void Main() { String str = \"33445\"; int len = str.Length; int k = 11; Console.WriteLine(countSubStr(str, len, k)); }} // This code is contributed by Code_Mech", "e": 3831, "s": 2932, "text": null }, { "code": "<?php// PHP implementation of the approach // Function to return the count of sub-strings// of str that are divisible by kfunction countSubStr($str, $len, $k){ $count = 0; for ($i = 0; $i < $len; $i++) { $n = 0; // Take all sub-strings starting from i for ($j = $i; $j < $len; $j++) { $n = $n * 10 + ($str[$j] - '0'); // If current sub-string is // divisible by k if ($n % $k == 0) $count++; } } // Return the required count return $count;} // Driver code$str = \"33445\";$len = strlen($str);$k = 11;echo countSubStr($str, $len, $k); // This code is contributed// by Shivi_Aggarwal?>", "e": 4529, "s": 3831, "text": null }, { "code": "<script> // Javascript implementation of above approach // Function to return the count of sub-strings// of str that are divisible by kfunction countSubStr(str, len, k){ let count = 0; for(let i = 0; i < len; i++) { let n = 0; // Take all sub-strings starting from i for(let j = i; j < len; j++) { n = n * 10 + (str[j].charCodeAt() - '0'.charCodeAt()); // If current sub-string is // divisible by k if (n % k == 0) count++; } } // Return the required count return count;} // Driver codelet str = \"33445\";let len = str.length;let k = 11; document.write(countSubStr(str, len, k)); // This code is contributed by mukesh07 </script>", "e": 5310, "s": 4529, "text": null }, { "code": null, "e": 5312, "s": 5310, "text": "3" }, { "code": null, "e": 5333, "s": 5312, "text": "Efficient approach :" }, { "code": null, "e": 5526, "s": 5333, "text": "The idea is to use a hashMap to store the remainders of each suffix of the string so that any suffix if it is already present int the hashMap then the substring between them is divisible by k." }, { "code": null, "e": 5577, "s": 5526, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 5582, "s": 5577, "text": "Java" }, { "code": "// Java Program for above approachimport java.util.*;public class Main{ // Program to count number of substrings public static int Divisible(String s, int k) { // To count substrings int num_of_substrings = 0; // To store the remainders int rem[] = new int[k]; rem[0] = 1; StringBuffer curr = new StringBuffer(); // Iterate from s.length() - 1 to 0 for (int i = s.length() - 1; i >= 0; i--) { // to Calculate suffix string curr.insert(0, s.charAt(i)); // convert to number long num = Long.parseLong(curr. toString()); num_of_substrings += rem[(int)num % k]; // Keep track of visited remainders rem[(int)num % k]++; } // Return number of substrings return num_of_substrings; } // Driver Code public static void main(String args[]) { String s = \"111111\"; int k = 11; // Function Call System.out.println(\"Number of sub strings : \" + Divisible(s, k)); }}", "e": 6663, "s": 5582, "text": null }, { "code": null, "e": 6689, "s": 6663, "text": "Number of sub strings : 9" }, { "code": null, "e": 6733, "s": 6689, "text": "Time Complexity: O(n2)Auxiliary Space: O(k)" }, { "code": null, "e": 6741, "s": 6733, "text": "ankthon" }, { "code": null, "e": 6755, "s": 6741, "text": "Sanjit_Prasad" }, { "code": null, "e": 6765, "s": 6755, "text": "Code_Mech" }, { "code": null, "e": 6780, "s": 6765, "text": "Shivi_Aggarwal" }, { "code": null, "e": 6798, "s": 6780, "text": "hemanthswarna1506" }, { "code": null, "e": 6807, "s": 6798, "text": "mukesh07" }, { "code": null, "e": 6824, "s": 6807, "text": "akshaysingh98088" }, { "code": null, "e": 6839, "s": 6824, "text": "sagar0719kumar" }, { "code": null, "e": 6851, "s": 6839, "text": "jayanth_mkv" }, { "code": null, "e": 6863, "s": 6851, "text": "cpp-strings" }, { "code": null, "e": 6876, "s": 6863, "text": "divisibility" }, { "code": null, "e": 6889, "s": 6876, "text": "C++ Programs" }, { "code": null, "e": 6897, "s": 6889, "text": "Strings" }, { "code": null, "e": 6909, "s": 6897, "text": "cpp-strings" }, { "code": null, "e": 6917, "s": 6909, "text": "Strings" } ]
JavaScript | Rest parameter
28 Sep, 2021 Rest parameter is an improved way to handle function parameter, allowing us to more easily handle various input as parameters in a function. The rest parameter syntax allows us to represent an indefinite number of arguments as an array. With the help of a rest parameter a function can be called with any number of arguments, no matter how it was defined. Rest parameter is added in ES2015 or ES6 which improved the ability to handle parameter.Note: In order to run the code in this article make use of the console provided by the browser or use an online tool like repl.it.Syntax: function functionname(...parameters) //... is the rest parameter (triple dots) { statement; } Note: When ... is at the end of function parameter, it is the rest parameter. It stores n number of parameters as an array. Let’s see how the rest parameter works: Javascript // Without rest parameterfunction fun(a, b){ return a + b;}console.log(fun(1, 2)); // 3console.log(fun(1, 2, 3, 4, 5)); // 3 Output: In the above code, no error will be thrown even when we are passing arguments more than the parameters, but only the first two arguments will be evaluated. It’s different in the case with rest parameter. With the use of the rest parameter, we can gather any number of arguments into an array and do what we want with them. Javascript code demonstrating addition of numbers using rest parameter. Javascript // es6 rest parameterfunction fun(...input){ let sum = 0; for(let i of input){ sum+=i; } return sum;}console.log(fun(1,2)); //3console.log(fun(1,2,3)); //6console.log(fun(1,2,3,4,5)); //15 Output: We were able to get the sum of all the elements that we enter in the argument when we call the fun() function. We get the sum of all the elements in the array by making use of the for..of loop which is used to traverse the iterable elements inside an array. Note: The rest parameter have to be the last argument, as its job is to collect all the remaining arguments into an array. So having a function definition like the code below doesn’t make any sense and will throw an error. javascript // non-sense codefunction fun(a,...b,c){ //code return;} Let’s make use of the rest parameter with some other arguments inside a function,like this: javascript // rest with function and other argumentsfunction fun(a,b,...c){ console.log(`${a} ${b}`); //Mukul Latiyan console.log(c); //[ 'Lionel', 'Messi', 'Barcelona' ] console.log(c[0]); //Lionel console.log(c.length); //3 console.log(c.indexOf('Lionel')); //0}fun('Mukul','Latiyan','Lionel','Messi','Barcelona'); Output: In the above code sample, we passed the rest parameter as the third parameter and then we basically called the function fun() with five arguments and the first two were treated normally and the rest were all collected by the rest parameter and hence we get ‘Lionel’ when we tried to access c[0] and it is also important to note that the rest parameter gives an array in return and we can make use of the array methods that the javascript provides us. immukul amansingla javascript-operators JavaScript Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n28 Sep, 2021" }, { "code": null, "e": 637, "s": 53, "text": "Rest parameter is an improved way to handle function parameter, allowing us to more easily handle various input as parameters in a function. The rest parameter syntax allows us to represent an indefinite number of arguments as an array. With the help of a rest parameter a function can be called with any number of arguments, no matter how it was defined. Rest parameter is added in ES2015 or ES6 which improved the ability to handle parameter.Note: In order to run the code in this article make use of the console provided by the browser or use an online tool like repl.it.Syntax: " }, { "code": null, "e": 733, "s": 637, "text": "function functionname(...parameters) //... is the rest parameter (triple dots)\n{\nstatement;\n}" }, { "code": null, "e": 899, "s": 733, "text": "Note: When ... is at the end of function parameter, it is the rest parameter. It stores n number of parameters as an array. Let’s see how the rest parameter works: " }, { "code": null, "e": 910, "s": 899, "text": "Javascript" }, { "code": "// Without rest parameterfunction fun(a, b){ return a + b;}console.log(fun(1, 2)); // 3console.log(fun(1, 2, 3, 4, 5)); // 3 ", "e": 1053, "s": 910, "text": null }, { "code": null, "e": 1063, "s": 1053, "text": "Output: " }, { "code": null, "e": 1460, "s": 1063, "text": "In the above code, no error will be thrown even when we are passing arguments more than the parameters, but only the first two arguments will be evaluated. It’s different in the case with rest parameter. With the use of the rest parameter, we can gather any number of arguments into an array and do what we want with them. Javascript code demonstrating addition of numbers using rest parameter. " }, { "code": null, "e": 1471, "s": 1460, "text": "Javascript" }, { "code": "// es6 rest parameterfunction fun(...input){ let sum = 0; for(let i of input){ sum+=i; } return sum;}console.log(fun(1,2)); //3console.log(fun(1,2,3)); //6console.log(fun(1,2,3,4,5)); //15 ", "e": 1695, "s": 1471, "text": null }, { "code": null, "e": 1705, "s": 1695, "text": "Output: " }, { "code": null, "e": 2188, "s": 1705, "text": "We were able to get the sum of all the elements that we enter in the argument when we call the fun() function. We get the sum of all the elements in the array by making use of the for..of loop which is used to traverse the iterable elements inside an array. Note: The rest parameter have to be the last argument, as its job is to collect all the remaining arguments into an array. So having a function definition like the code below doesn’t make any sense and will throw an error. " }, { "code": null, "e": 2199, "s": 2188, "text": "javascript" }, { "code": "// non-sense codefunction fun(a,...b,c){ //code return;}", "e": 2264, "s": 2199, "text": null }, { "code": null, "e": 2358, "s": 2264, "text": "Let’s make use of the rest parameter with some other arguments inside a function,like this: " }, { "code": null, "e": 2369, "s": 2358, "text": "javascript" }, { "code": "// rest with function and other argumentsfunction fun(a,b,...c){ console.log(`${a} ${b}`); //Mukul Latiyan console.log(c); //[ 'Lionel', 'Messi', 'Barcelona' ] console.log(c[0]); //Lionel console.log(c.length); //3 console.log(c.indexOf('Lionel')); //0}fun('Mukul','Latiyan','Lionel','Messi','Barcelona');", "e": 2691, "s": 2369, "text": null }, { "code": null, "e": 2701, "s": 2691, "text": "Output: " }, { "code": null, "e": 3153, "s": 2701, "text": "In the above code sample, we passed the rest parameter as the third parameter and then we basically called the function fun() with five arguments and the first two were treated normally and the rest were all collected by the rest parameter and hence we get ‘Lionel’ when we tried to access c[0] and it is also important to note that the rest parameter gives an array in return and we can make use of the array methods that the javascript provides us. " }, { "code": null, "e": 3161, "s": 3153, "text": "immukul" }, { "code": null, "e": 3172, "s": 3161, "text": "amansingla" }, { "code": null, "e": 3193, "s": 3172, "text": "javascript-operators" }, { "code": null, "e": 3204, "s": 3193, "text": "JavaScript" } ]
How to make a glass/blur effect overlay using HTML and CSS ?
13 Jun, 2022 To give a background blur effect on an overlay, the CSS’s backdrop-filter: blur() property is used with ::before pseudo-element. The “backdrop-filter: blur()” property gives the blur effect on the box or any element where it is desired and “before” is used to add the blurred background without applying any extra markup. HTML Code: In this section, we will use HTML code to design the basic structure of the web page. HTML <!DOCTYPE html><html> <head> <meta charset="utf-8"> <title> How to make a CSS glass/blur effect work for an overlay? </title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> </head> <body> <section> <div class="layout"> <h1>GeeksforGeeks</h1> <p class="py-2"> It is a computer science portal for geeks. It is a platform where you can learn and practice programming problems. It contains programming content, web technology content, and some other domain content also. </p> <button class="btn btn-danger"> Button </button> </div> </section></body> </html> CSS Code: In this section, we will use some CSS properties to make a glass/blur effect overlay using HTML and CSS. CSS /* CSS code */body { margin: 0; padding: 0; } section { display: flex; background: #001923; justify-content: center; align-items: center; width: 100%; min-height: 100vh; } section .layout { position: relative; width: 100%; max-width: 600px; padding: 50px; box-shadow: 0 10px 20px rgba(0, 0, 0, .1); background: rgba(255, 255, 255, 0.1); backdrop-filter: blur(20px); border: 1px solid rgba(255, 255, 255, 0.25); border-radius: 10px; } section .layout::before { content: ''; position: absolute; top: 0; bottom: 0; left: 0; right: 0; } section .layout h1 { position: relative; text-align: center; color: rgb(36, 168, 36); } section .layout p { position: relative; color: #fff; } section .layout button { position: relative; } Combined Code: In this section, we will combine the above two sections of code (HTML and CSS code) to make a glass/blur effect overlay. HTML <!DOCTYPE html><html> <head> <meta charset="utf-8"> <title> How to make a CSS glass/blur effect work for an overlay? </title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <style> body { margin: 0; padding: 0; } section { display: flex; background: #001923; justify-content: center; align-items: center; width: 100%; min-height: 100vh; } section .layout { position: relative; width: 100%; max-width: 600px; padding: 50px; box-shadow: 0 10px 20px rgba(0, 0, 0, .1); background: rgba(255, 255, 255, 0.1); backdrop-filter: blur(20px); border: 1px solid rgba(255, 255, 255, 0.25); border-radius: 10px; } section .layout::before { content: ''; position: absolute; top: 0; bottom: 0; left: 0; right: 0; } section .layout h1 { position: relative; text-align: center; color: rgb(36, 168, 36); } section .layout p { position: relative; color: #fff; } section .layout button { position: relative; } </style></head> <body> <section> <div class="layout"> <h1>GeeksforGeeks</h1> <p class="py-2"> It is a computer science portal for geeks. It is a platform where you can learn and practice programming problems. It contains programming content, web technology content, and some other domain content also. </p> <button class="btn btn-danger"> Button </button> </div> </section></body> </html> Output: HTML is the foundation of web pages and is used for webpage development by structuring websites and web apps. You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples. CSS is the foundation of web pages and is used for webpage development by styling websites and web apps. You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples. gulshankumarar231 sanjyotpanure CSS-Misc HTML-Misc Picked CSS HTML Web Technologies Web technologies Questions HTML 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 Tribute Page using HTML & CSS Build a Survey Form using HTML and CSS Form validation using jQuery Design a web page using HTML and CSS REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? HTTP headers | Content-Type
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Jun, 2022" }, { "code": null, "e": 350, "s": 28, "text": "To give a background blur effect on an overlay, the CSS’s backdrop-filter: blur() property is used with ::before pseudo-element. The “backdrop-filter: blur()” property gives the blur effect on the box or any element where it is desired and “before” is used to add the blurred background without applying any extra markup." }, { "code": null, "e": 447, "s": 350, "text": "HTML Code: In this section, we will use HTML code to design the basic structure of the web page." }, { "code": null, "e": 452, "s": 447, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\"> <title> How to make a CSS glass/blur effect work for an overlay? </title> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> </head> <body> <section> <div class=\"layout\"> <h1>GeeksforGeeks</h1> <p class=\"py-2\"> It is a computer science portal for geeks. It is a platform where you can learn and practice programming problems. It contains programming content, web technology content, and some other domain content also. </p> <button class=\"btn btn-danger\"> Button </button> </div> </section></body> </html>", "e": 1288, "s": 452, "text": null }, { "code": null, "e": 1403, "s": 1288, "text": "CSS Code: In this section, we will use some CSS properties to make a glass/blur effect overlay using HTML and CSS." }, { "code": null, "e": 1407, "s": 1403, "text": "CSS" }, { "code": "/* CSS code */body { margin: 0; padding: 0; } section { display: flex; background: #001923; justify-content: center; align-items: center; width: 100%; min-height: 100vh; } section .layout { position: relative; width: 100%; max-width: 600px; padding: 50px; box-shadow: 0 10px 20px rgba(0, 0, 0, .1); background: rgba(255, 255, 255, 0.1); backdrop-filter: blur(20px); border: 1px solid rgba(255, 255, 255, 0.25); border-radius: 10px; } section .layout::before { content: ''; position: absolute; top: 0; bottom: 0; left: 0; right: 0; } section .layout h1 { position: relative; text-align: center; color: rgb(36, 168, 36); } section .layout p { position: relative; color: #fff; } section .layout button { position: relative; }", "e": 2546, "s": 1407, "text": null }, { "code": null, "e": 2682, "s": 2546, "text": "Combined Code: In this section, we will combine the above two sections of code (HTML and CSS code) to make a glass/blur effect overlay." }, { "code": null, "e": 2687, "s": 2682, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\"> <title> How to make a CSS glass/blur effect work for an overlay? </title> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <style> body { margin: 0; padding: 0; } section { display: flex; background: #001923; justify-content: center; align-items: center; width: 100%; min-height: 100vh; } section .layout { position: relative; width: 100%; max-width: 600px; padding: 50px; box-shadow: 0 10px 20px rgba(0, 0, 0, .1); background: rgba(255, 255, 255, 0.1); backdrop-filter: blur(20px); border: 1px solid rgba(255, 255, 255, 0.25); border-radius: 10px; } section .layout::before { content: ''; position: absolute; top: 0; bottom: 0; left: 0; right: 0; } section .layout h1 { position: relative; text-align: center; color: rgb(36, 168, 36); } section .layout p { position: relative; color: #fff; } section .layout button { position: relative; } </style></head> <body> <section> <div class=\"layout\"> <h1>GeeksforGeeks</h1> <p class=\"py-2\"> It is a computer science portal for geeks. It is a platform where you can learn and practice programming problems. It contains programming content, web technology content, and some other domain content also. </p> <button class=\"btn btn-danger\"> Button </button> </div> </section></body> </html>", "e": 4664, "s": 2687, "text": null }, { "code": null, "e": 4673, "s": 4664, "text": "Output: " }, { "code": null, "e": 4874, "s": 4675, "text": "HTML is the foundation of web pages and is used for webpage development by structuring websites and web apps. You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples." }, { "code": null, "e": 5065, "s": 4874, "text": "CSS is the foundation of web pages and is used for webpage development by styling websites and web apps. You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples." }, { "code": null, "e": 5083, "s": 5065, "text": "gulshankumarar231" }, { "code": null, "e": 5097, "s": 5083, "text": "sanjyotpanure" }, { "code": null, "e": 5106, "s": 5097, "text": "CSS-Misc" }, { "code": null, "e": 5116, "s": 5106, "text": "HTML-Misc" }, { "code": null, "e": 5123, "s": 5116, "text": "Picked" }, { "code": null, "e": 5127, "s": 5123, "text": "CSS" }, { "code": null, "e": 5132, "s": 5127, "text": "HTML" }, { "code": null, "e": 5149, "s": 5132, "text": "Web Technologies" }, { "code": null, "e": 5176, "s": 5149, "text": "Web technologies Questions" }, { "code": null, "e": 5181, "s": 5176, "text": "HTML" }, { "code": null, "e": 5279, "s": 5181, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5318, "s": 5279, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 5357, "s": 5318, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 5396, "s": 5357, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 5425, "s": 5396, "text": "Form validation using jQuery" }, { "code": null, "e": 5462, "s": 5425, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 5486, "s": 5462, "text": "REST API (Introduction)" }, { "code": null, "e": 5539, "s": 5486, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 5599, "s": 5539, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 5660, "s": 5599, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Python – Central Limit Theorem
29 May, 2021 The definition: The sample mean will approximately be normally distributed for large sample sizes, regardless of the distribution from which we are sampling. Suppose we are sampling from a population with a finite mean and a finite standard-deviation(sigma). Then Mean and standard deviation of the sampling distribution of the sample mean can be given as: Where represents the sampling distribution of the sample mean of size n each, and are the mean and standard deviation of the population respectively. The distribution of the sample tends towards the normal distribution as the sample size increases.Code: Python implementation of the Central Limit Theorem python3 import numpyimport matplotlib.pyplot as plt # number of samplenum = [1, 10, 50, 100] # list of sample meansmeans = [] # Generating 1, 10, 30, 100 random numbers from -40 to 40# taking their mean and appending it to list means.for j in num: # Generating seed so that we can get same result # every time the loop is run... numpy.random.seed(1) x = [numpy.mean( numpy.random.randint( -40, 40, j)) for _i in range(1000)] means.append(x)k = 0 # plotting all the means in one figurefig, ax = plt.subplots(2, 2, figsize =(8, 8))for i in range(0, 2): for j in range(0, 2): # Histogram for each x stored in means ax[i, j].hist(means[k], 10, density = True) ax[i, j].set_title(label = num[k]) k = k + 1 plt.show() Output: It is evident from the graphs that as we keep on increasing the sample size from 1 to 100 the histogram tends to take the shape of a normal distribution.Rule of thumb: Of course, the term “large” is relative. Roughly, the more “abnormal” the basic distribution, the larger n must be for normal approximations to work well. The rule of thumb is that a sample size n of at least 30 will suffice.Why is this important? The answer to this question is very simple, as we can often use well developed statistical inference procedures that are based on a normal distribution such as 68-95-99.7 rule and many others, even if we are sampling from a population that is not normal, provided we have a large sample size. redstormthecoder Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Linear Regression Reinforcement learning ML | Monte Carlo Tree Search (MCTS) Search Algorithms in AI Supervised and Unsupervised learning Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function Python Dictionary How to get column names in Pandas dataframe
[ { "code": null, "e": 52, "s": 24, "text": "\n29 May, 2021" }, { "code": null, "e": 69, "s": 52, "text": "The definition: " }, { "code": null, "e": 213, "s": 69, "text": "The sample mean will approximately be normally distributed for large sample sizes, regardless of the distribution from which we are sampling. " }, { "code": null, "e": 721, "s": 215, "text": "Suppose we are sampling from a population with a finite mean and a finite standard-deviation(sigma). Then Mean and standard deviation of the sampling distribution of the sample mean can be given as: Where represents the sampling distribution of the sample mean of size n each, and are the mean and standard deviation of the population respectively. The distribution of the sample tends towards the normal distribution as the sample size increases.Code: Python implementation of the Central Limit Theorem " }, { "code": null, "e": 729, "s": 721, "text": "python3" }, { "code": "import numpyimport matplotlib.pyplot as plt # number of samplenum = [1, 10, 50, 100] # list of sample meansmeans = [] # Generating 1, 10, 30, 100 random numbers from -40 to 40# taking their mean and appending it to list means.for j in num: # Generating seed so that we can get same result # every time the loop is run... numpy.random.seed(1) x = [numpy.mean( numpy.random.randint( -40, 40, j)) for _i in range(1000)] means.append(x)k = 0 # plotting all the means in one figurefig, ax = plt.subplots(2, 2, figsize =(8, 8))for i in range(0, 2): for j in range(0, 2): # Histogram for each x stored in means ax[i, j].hist(means[k], 10, density = True) ax[i, j].set_title(label = num[k]) k = k + 1 plt.show()", "e": 1498, "s": 729, "text": null }, { "code": null, "e": 1508, "s": 1498, "text": "Output: " }, { "code": null, "e": 2218, "s": 1508, "text": "It is evident from the graphs that as we keep on increasing the sample size from 1 to 100 the histogram tends to take the shape of a normal distribution.Rule of thumb: Of course, the term “large” is relative. Roughly, the more “abnormal” the basic distribution, the larger n must be for normal approximations to work well. The rule of thumb is that a sample size n of at least 30 will suffice.Why is this important? The answer to this question is very simple, as we can often use well developed statistical inference procedures that are based on a normal distribution such as 68-95-99.7 rule and many others, even if we are sampling from a population that is not normal, provided we have a large sample size. " }, { "code": null, "e": 2235, "s": 2218, "text": "redstormthecoder" }, { "code": null, "e": 2252, "s": 2235, "text": "Machine Learning" }, { "code": null, "e": 2259, "s": 2252, "text": "Python" }, { "code": null, "e": 2276, "s": 2259, "text": "Machine Learning" }, { "code": null, "e": 2374, "s": 2276, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2397, "s": 2374, "text": "ML | Linear Regression" }, { "code": null, "e": 2420, "s": 2397, "text": "Reinforcement learning" }, { "code": null, "e": 2456, "s": 2420, "text": "ML | Monte Carlo Tree Search (MCTS)" }, { "code": null, "e": 2480, "s": 2456, "text": "Search Algorithms in AI" }, { "code": null, "e": 2517, "s": 2480, "text": "Supervised and Unsupervised learning" }, { "code": null, "e": 2545, "s": 2517, "text": "Read JSON file using Python" }, { "code": null, "e": 2595, "s": 2545, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 2617, "s": 2595, "text": "Python map() function" }, { "code": null, "e": 2635, "s": 2617, "text": "Python Dictionary" } ]
Sorted() function in Python
29 Dec, 2021 Python sorted() function returns a sorted list from the iterable object. Sorted() sorts any sequence (list, tuple) and always returns a list with the elements in a sorted manner, without modifying the original sequence. Syntax: sorted(iterable, key, reverse) Parameters: sorted takes three parameters from which two are optional. Iterable : sequence (list, tuple, string) or collection (dictionary, set, frozenset) or any other iterator that needs to be sorted. Key(optional) : A function that would server as a key or a basis of sort comparison. Reverse(optional) : If set true, then the iterable would be sorted in reverse (descending) order, by default it is set as false. Python3 x = [2, 8, 1, 4, 6, 3, 7] print("Sorted List returned :"),print(sorted(x)) print("\nReverse sort :"),print(sorted(x, reverse=True)) print("\nOriginal list not modified :"),print(x) Output: Sorted List returned : [1, 2, 3, 4, 6, 7, 8] Reverse sort : [8, 7, 6, 4, 3, 2, 1] Original list not modified : [2, 8, 1, 4, 6, 3, 7] Python3 # Listx = ['q', 'w', 'r', 'e', 't', 'y']print(sorted(x)) # Tuplex = ('q', 'w', 'e', 'r', 't', 'y')print(sorted(x)) # String-sorted based on ASCII translationsx = "python"print(sorted(x)) # Dictionaryx = {'q': 1, 'w': 2, 'e': 3, 'r': 4, 't': 5, 'y': 6}print(sorted(x)) # Setx = {'q', 'w', 'e', 'r', 't', 'y'}print(sorted(x)) # Frozen Setx = frozenset(('q', 'w', 'e', 'r', 't', 'y'))print(sorted(x)) Output: ['e', 'q', 'r', 't', 'w', 'y'] ['e', 'q', 'r', 't', 'w', 'y'] ['h', 'n', 'o', 'p', 't', 'y'] ['e', 'q', 'r', 't', 'w', 'y'] ['e', 'q', 'r', 't', 'w', 'y'] ['e', 'q', 'r', 't', 'w', 'y'] Python3 # Python3 code to demonstrate# Reverse Sort a String# using join() + sorted() + reverse # initializing stringtest_string = "geekforgeeks" # printing original stringprint("The original string : " + str(test_string)) # using join() + sorted() + reverse# Sorting a stringres = ''.join(sorted(test_string, reverse = True)) # print resultprint("String after reverse sorting : " + str(res)) Output: The original string : geekforgeeks String after reverse sorting : srokkggfeeee Python3 # Python code to demonstrate# Reverse Sort a String# using sorted() + reduce() + lambda # import the moduleimport functools# initializing stringtest_string = "geekforgeeks" # printing original stringprint("The original string : " + str(test_string)) # using sorted() + reduce() + lambda# Reverse Sort a Stringres = functools.reduce(lambda x, y: x + y, sorted(test_string, reverse=True)) # print resultprint("String after reverse sorting : " + str(res)) Output: The original string : geekforgeeks String after reverse sorting : srokkggfeeee sorted() function has an optional parameter called ‘key’ which takes a function as its value. This key function transforms each element before sorting, it takes the value and returns 1 value which is then used within sort instead of the original value. For example, if we pass a list of strings in sorted(), it gets sorted alphabetically. But if we specify key = len, i.e. give len function as key, then the strings would be passed to len, and the value it returns, i.e. the length of strings will be sorted. This means that the strings would be sorted based on their lengths instead Python3 L = ["cccc", "b", "dd", "aaa"] print("Normal sort :", sorted(L)) print("Sort with len :", sorted(L, key=len)) Output: Normal sort : ['aaa', 'b', 'cccc', 'dd'] Sort with len : ['b', 'dd', 'aaa', 'cccc'] Key can also take user-defined functions as its value for the basis of sorting. Python3 # Sort a list of integers based on# their remainder on dividing from 7def func(x): return x % 7 L = [15, 3, 11, 7] print("Normal sort :", sorted(L))print("Sorted with key:", sorted(L, key=func)) Output: Normal sort : [3, 7, 11, 15] Sorted with key: [7, 15, 3, 11] This article is contributed by Harshit Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. kumar_satyam Spider_man Python-Library Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Enumerate() in Python Read a file line by line in Python Different ways to create Pandas Dataframe How to Install PIP on Windows ? Python String | replace() Introduction To PYTHON Python OOPs Concepts Python Classes and Objects *args and **kwargs in Python
[ { "code": null, "e": 52, "s": 24, "text": "\n29 Dec, 2021" }, { "code": null, "e": 125, "s": 52, "text": "Python sorted() function returns a sorted list from the iterable object." }, { "code": null, "e": 272, "s": 125, "text": "Sorted() sorts any sequence (list, tuple) and always returns a list with the elements in a sorted manner, without modifying the original sequence." }, { "code": null, "e": 311, "s": 272, "text": "Syntax: sorted(iterable, key, reverse)" }, { "code": null, "e": 383, "s": 311, "text": "Parameters: sorted takes three parameters from which two are optional. " }, { "code": null, "e": 515, "s": 383, "text": "Iterable : sequence (list, tuple, string) or collection (dictionary, set, frozenset) or any other iterator that needs to be sorted." }, { "code": null, "e": 600, "s": 515, "text": "Key(optional) : A function that would server as a key or a basis of sort comparison." }, { "code": null, "e": 729, "s": 600, "text": "Reverse(optional) : If set true, then the iterable would be sorted in reverse (descending) order, by default it is set as false." }, { "code": null, "e": 737, "s": 729, "text": "Python3" }, { "code": "x = [2, 8, 1, 4, 6, 3, 7] print(\"Sorted List returned :\"),print(sorted(x)) print(\"\\nReverse sort :\"),print(sorted(x, reverse=True)) print(\"\\nOriginal list not modified :\"),print(x)", "e": 918, "s": 737, "text": null }, { "code": null, "e": 926, "s": 918, "text": "Output:" }, { "code": null, "e": 1061, "s": 926, "text": "Sorted List returned : [1, 2, 3, 4, 6, 7, 8]\n\nReverse sort : [8, 7, 6, 4, 3, 2, 1]\n\nOriginal list not modified : [2, 8, 1, 4, 6, 3, 7]" }, { "code": null, "e": 1069, "s": 1061, "text": "Python3" }, { "code": "# Listx = ['q', 'w', 'r', 'e', 't', 'y']print(sorted(x)) # Tuplex = ('q', 'w', 'e', 'r', 't', 'y')print(sorted(x)) # String-sorted based on ASCII translationsx = \"python\"print(sorted(x)) # Dictionaryx = {'q': 1, 'w': 2, 'e': 3, 'r': 4, 't': 5, 'y': 6}print(sorted(x)) # Setx = {'q', 'w', 'e', 'r', 't', 'y'}print(sorted(x)) # Frozen Setx = frozenset(('q', 'w', 'e', 'r', 't', 'y'))print(sorted(x))", "e": 1467, "s": 1069, "text": null }, { "code": null, "e": 1475, "s": 1467, "text": "Output:" }, { "code": null, "e": 1661, "s": 1475, "text": "['e', 'q', 'r', 't', 'w', 'y']\n['e', 'q', 'r', 't', 'w', 'y']\n['h', 'n', 'o', 'p', 't', 'y']\n['e', 'q', 'r', 't', 'w', 'y']\n['e', 'q', 'r', 't', 'w', 'y']\n['e', 'q', 'r', 't', 'w', 'y']" }, { "code": null, "e": 1669, "s": 1661, "text": "Python3" }, { "code": "# Python3 code to demonstrate# Reverse Sort a String# using join() + sorted() + reverse # initializing stringtest_string = \"geekforgeeks\" # printing original stringprint(\"The original string : \" + str(test_string)) # using join() + sorted() + reverse# Sorting a stringres = ''.join(sorted(test_string, reverse = True)) # print resultprint(\"String after reverse sorting : \" + str(res))", "e": 2066, "s": 1669, "text": null }, { "code": null, "e": 2074, "s": 2066, "text": "Output:" }, { "code": null, "e": 2153, "s": 2074, "text": "The original string : geekforgeeks\nString after reverse sorting : srokkggfeeee" }, { "code": null, "e": 2161, "s": 2153, "text": "Python3" }, { "code": "# Python code to demonstrate# Reverse Sort a String# using sorted() + reduce() + lambda # import the moduleimport functools# initializing stringtest_string = \"geekforgeeks\" # printing original stringprint(\"The original string : \" + str(test_string)) # using sorted() + reduce() + lambda# Reverse Sort a Stringres = functools.reduce(lambda x, y: x + y, sorted(test_string, reverse=True)) # print resultprint(\"String after reverse sorting : \" + str(res))", "e": 2665, "s": 2161, "text": null }, { "code": null, "e": 2673, "s": 2665, "text": "Output:" }, { "code": null, "e": 2752, "s": 2673, "text": "The original string : geekforgeeks\nString after reverse sorting : srokkggfeeee" }, { "code": null, "e": 3336, "s": 2752, "text": "sorted() function has an optional parameter called ‘key’ which takes a function as its value. This key function transforms each element before sorting, it takes the value and returns 1 value which is then used within sort instead of the original value. For example, if we pass a list of strings in sorted(), it gets sorted alphabetically. But if we specify key = len, i.e. give len function as key, then the strings would be passed to len, and the value it returns, i.e. the length of strings will be sorted. This means that the strings would be sorted based on their lengths instead" }, { "code": null, "e": 3344, "s": 3336, "text": "Python3" }, { "code": "L = [\"cccc\", \"b\", \"dd\", \"aaa\"] print(\"Normal sort :\", sorted(L)) print(\"Sort with len :\", sorted(L, key=len))", "e": 3454, "s": 3344, "text": null }, { "code": null, "e": 3462, "s": 3454, "text": "Output:" }, { "code": null, "e": 3546, "s": 3462, "text": "Normal sort : ['aaa', 'b', 'cccc', 'dd']\nSort with len : ['b', 'dd', 'aaa', 'cccc']" }, { "code": null, "e": 3626, "s": 3546, "text": "Key can also take user-defined functions as its value for the basis of sorting." }, { "code": null, "e": 3634, "s": 3626, "text": "Python3" }, { "code": "# Sort a list of integers based on# their remainder on dividing from 7def func(x): return x % 7 L = [15, 3, 11, 7] print(\"Normal sort :\", sorted(L))print(\"Sorted with key:\", sorted(L, key=func))", "e": 3832, "s": 3634, "text": null }, { "code": null, "e": 3840, "s": 3832, "text": "Output:" }, { "code": null, "e": 3901, "s": 3840, "text": "Normal sort : [3, 7, 11, 15]\nSorted with key: [7, 15, 3, 11]" }, { "code": null, "e": 4200, "s": 3901, "text": "This article is contributed by Harshit Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 4325, "s": 4200, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 4338, "s": 4325, "text": "kumar_satyam" }, { "code": null, "e": 4349, "s": 4338, "text": "Spider_man" }, { "code": null, "e": 4364, "s": 4349, "text": "Python-Library" }, { "code": null, "e": 4371, "s": 4364, "text": "Python" }, { "code": null, "e": 4469, "s": 4371, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4487, "s": 4469, "text": "Python Dictionary" }, { "code": null, "e": 4509, "s": 4487, "text": "Enumerate() in Python" }, { "code": null, "e": 4544, "s": 4509, "text": "Read a file line by line in Python" }, { "code": null, "e": 4586, "s": 4544, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 4618, "s": 4586, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4644, "s": 4618, "text": "Python String | replace()" }, { "code": null, "e": 4667, "s": 4644, "text": "Introduction To PYTHON" }, { "code": null, "e": 4688, "s": 4667, "text": "Python OOPs Concepts" }, { "code": null, "e": 4715, "s": 4688, "text": "Python Classes and Objects" } ]
Minimize the maximum difference between the heights
05 Jul, 2022 Given heights of n towers and a value k. We need to either increase or decrease the height of every tower by k (only once) where k > 0. The task is to minimize the difference between the heights of the longest and the shortest tower after modifications and output this difference. Examples: Input : arr[] = {1, 15, 10}, k = 6Output : Maximum difference is 5.Explanation : We change 1 to 7, 15 to 9 and 10 to 4. Maximum difference is 5 (between 4 and 9). We can’t get a lower difference. Input : arr[] = {1, 5, 15, 10} k = 3 Output : Maximum difference is 8 arr[] = {4, 8, 12, 7} Input : arr[] = {4, 6} k = 10Output : Maximum difference is 2 arr[] = {14, 16} OR {-6, -4} Input : arr[] = {6, 10} k = 3Output : Maximum difference is 2 arr[] = {9, 7} Input : arr[] = {1, 10, 14, 14, 14, 15} k = 6 Output: Maximum difference is 5 arr[] = {7, 4, 8, 8, 8, 9} Input : arr[] = {1, 2, 3} k = 2 Output: Maximum difference is 2 arr[] = {3, 4, 5} Source: Adobe Interview Experience | Set 24 (On-Campus for MTS) First, we try to sort the array and make each height of the tower maximum. We do this by decreasing the height of all the towers towards the right by k and increasing all the height of the towers towards the left (by k). It is also possible that the tower you are trying to increase the height doesn’t have the maximum height. Therefore we only need to check whether it has the maximum height or not by comparing it with the last element on the right side which is a[n]-k. Since the array is sorted if the tower’s height is greater than the [n]-k then it’s the tallest tower available. Similar reasoning can also be applied to finding the shortest tower. Note:- We need not consider where a[i]<k because the height of the tower can’t be negative so we have to neglect that case. Below is the implementation of the above approach: C++ Java Python3 C# Javascript #include <bits/stdc++.h>using namespace std; // User function Templateint getMinDiff(int arr[], int n, int k){ sort(arr, arr + n); int ans = arr[n - 1] - arr[0]; // Maximum possible height difference int tempmin, tempmax; tempmin = arr[0]; tempmax = arr[n - 1]; for (int i = 1; i < n; i++) { if(arr[i] - k < 0) // if on subtracting k we got negative then continue continue; tempmin= min(arr[0] + k,arr[i] - k); // Minimum element when we // add k to whole array tempmax = max(arr[i - 1] + k, arr[n - 1] - k); // Maximum element when we // subtract k from whole array ans = min(ans, tempmax - tempmin); } return ans;} // Driver Code Startsint main(){ int k = 6, n = 6; int arr[n] = { 7, 4, 8, 8, 8, 9 }; int ans = getMinDiff(arr, n, k); cout << ans;} /*package whatever //do not write package name here */ import java.io.*;import java.util.*; // Driver codepublic class Main { public static void main(String[] args) { int[] arr = { 7, 4, 8, 8, 8, 9 }; int k = 6; int ans = getMinDiff(arr, arr.length, k); System.out.println(ans); } // User function Template for Java public static int getMinDiff(int[] arr, int n, int k) { Arrays.sort(arr); // Maximum possible height difference int ans = arr[n - 1] - arr[0]; int tempmin, tempmax; tempmin = arr[0]; tempmax = arr[n - 1]; for (int i = 1; i < n; i++) { // if on subtracting k we got negative then // continue if (arr[i] - k < 0) continue; // Minimum element when we add k to whole array tempmin = Math.min(arr[0] + k, arr[i] - k); // Maximum element when we subtract k from whole // array tempmax = Math.max(arr[i - 1] + k, arr[n - 1] - k); ans = Math.min(ans, tempmax - tempmin); } return ans; }} # User function Templatedef getMinDiff(arr, n, k): arr.sort() ans = arr[n - 1] - arr[0] # Maximum possible height difference tempmin = arr[0] tempmax = arr[n - 1] for i in range(1, n): tempmin = min(arr[0] + k, arr[i] - k) # Minimum element when we # add k to whole array # Maximum element when we tempmax = max(arr[i - 1] + k, arr[n - 1] - k) # subtract k from whole array ans = min(ans, tempmax - tempmin) return ans # Driver Code Startsk = 6n = 6arr = [7, 4, 8, 8, 8, 9]ans = getMinDiff(arr, n, k)print(ans) # This code is contributed by ninja_hattori. using System; public class GFG { static public int getMinDiff(int[] arr, int n, int k) { Array.Sort(arr); int ans = (arr[n - 1] + k) - (arr[0] + k); // Maximum possible height difference int tempmax = arr[n - 1] - k; // Maximum element when we // subtract k from whole array int tempmin = arr[0] + k; // Minimum element when we // add k to whole array int max, min; for (int i = 0; i < n - 1; i++) { if (tempmax > (arr[i] + k)) { max = tempmax; } else { max = arr[i] + k; } if (tempmin < (arr[i + 1] - k)) { min = tempmin; } else { min = arr[i + 1] - k; } if (ans > (max - min)) { ans = max - min; } } return ans; } static public void Main() { int[] arr = { 7, 4, 8, 8, 8, 9 }; int k = 6; int ans = getMinDiff(arr, arr.Length, k); Console.Write(ans); }} // This code is contributed by ninja_hattori. <script> // User function Templatefunction getMinDiff(arr,n,k){ arr.sort((a,b) => (a-b)) let ans = arr[n - 1] - arr[0]; // Maximum possible height difference let tempmin, tempmax; tempmin = arr[0]; tempmax = arr[n - 1]; for (let i = 1; i < n; i++) { tempmin= Math.min(arr[0] + k,arr[i] - k); // Minimum element when we // add k to whole array tempmax = Math.max(arr[i - 1] + k, arr[n - 1] - k); // Maximum element when we // subtract k from whole array ans = Math.min(ans, tempmax - tempmin); } return ans;} // Driver Code Startslet k = 6, n = 6;let arr = [ 7, 4, 8, 8, 8, 9 ];let ans = getMinDiff(arr, n, k);document.write(ans,"</br>"); //This code is contributed by shinjanpatra.</script> 5 Time Complexity: O(nlogn)Auxiliary Space: O(n) ukasp ihritik SHIKHAR AGRAWAL avanitrachhadiya2155 gautampraveen351 sudhanshublaze suyashsincever13 adityapawar666 lucky_002 swapnilakash21 kalrap615 u19cs070 shivanshchaudhary18 himanshu000choudhary mrigankvashist ninja_hattori shinjanpatra eni_g ayushrajput1410 naitikvarshneyintern hardikkoriintern Adobe Arrays Greedy Adobe Arrays Greedy Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n05 Jul, 2022" }, { "code": null, "e": 333, "s": 52, "text": "Given heights of n towers and a value k. We need to either increase or decrease the height of every tower by k (only once) where k > 0. The task is to minimize the difference between the heights of the longest and the shortest tower after modifications and output this difference." }, { "code": null, "e": 344, "s": 333, "text": "Examples: " }, { "code": null, "e": 542, "s": 344, "text": "Input : arr[] = {1, 15, 10}, k = 6Output : Maximum difference is 5.Explanation : We change 1 to 7, 15 to 9 and 10 to 4. Maximum difference is 5 (between 4 and 9). We can’t get a lower difference." }, { "code": null, "e": 646, "s": 542, "text": "Input : arr[] = {1, 5, 15, 10} k = 3 Output : Maximum difference is 8 arr[] = {4, 8, 12, 7}" }, { "code": null, "e": 746, "s": 646, "text": "Input : arr[] = {4, 6} k = 10Output : Maximum difference is 2 arr[] = {14, 16} OR {-6, -4}" }, { "code": null, "e": 832, "s": 746, "text": "Input : arr[] = {6, 10} k = 3Output : Maximum difference is 2 arr[] = {9, 7} " }, { "code": null, "e": 945, "s": 832, "text": "Input : arr[] = {1, 10, 14, 14, 14, 15} k = 6 Output: Maximum difference is 5 arr[] = {7, 4, 8, 8, 8, 9} " }, { "code": null, "e": 1035, "s": 945, "text": "Input : arr[] = {1, 2, 3} k = 2 Output: Maximum difference is 2 arr[] = {3, 4, 5} " }, { "code": null, "e": 1099, "s": 1035, "text": "Source: Adobe Interview Experience | Set 24 (On-Campus for MTS)" }, { "code": null, "e": 1756, "s": 1099, "text": "First, we try to sort the array and make each height of the tower maximum. We do this by decreasing the height of all the towers towards the right by k and increasing all the height of the towers towards the left (by k). It is also possible that the tower you are trying to increase the height doesn’t have the maximum height. Therefore we only need to check whether it has the maximum height or not by comparing it with the last element on the right side which is a[n]-k. Since the array is sorted if the tower’s height is greater than the [n]-k then it’s the tallest tower available. Similar reasoning can also be applied to finding the shortest tower. " }, { "code": null, "e": 1880, "s": 1756, "text": "Note:- We need not consider where a[i]<k because the height of the tower can’t be negative so we have to neglect that case." }, { "code": null, "e": 1931, "s": 1880, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1935, "s": 1931, "text": "C++" }, { "code": null, "e": 1940, "s": 1935, "text": "Java" }, { "code": null, "e": 1948, "s": 1940, "text": "Python3" }, { "code": null, "e": 1951, "s": 1948, "text": "C#" }, { "code": null, "e": 1962, "s": 1951, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; // User function Templateint getMinDiff(int arr[], int n, int k){ sort(arr, arr + n); int ans = arr[n - 1] - arr[0]; // Maximum possible height difference int tempmin, tempmax; tempmin = arr[0]; tempmax = arr[n - 1]; for (int i = 1; i < n; i++) { if(arr[i] - k < 0) // if on subtracting k we got negative then continue continue; tempmin= min(arr[0] + k,arr[i] - k); // Minimum element when we // add k to whole array tempmax = max(arr[i - 1] + k, arr[n - 1] - k); // Maximum element when we // subtract k from whole array ans = min(ans, tempmax - tempmin); } return ans;} // Driver Code Startsint main(){ int k = 6, n = 6; int arr[n] = { 7, 4, 8, 8, 8, 9 }; int ans = getMinDiff(arr, n, k); cout << ans;}", "e": 2894, "s": 1962, "text": null }, { "code": "/*package whatever //do not write package name here */ import java.io.*;import java.util.*; // Driver codepublic class Main { public static void main(String[] args) { int[] arr = { 7, 4, 8, 8, 8, 9 }; int k = 6; int ans = getMinDiff(arr, arr.length, k); System.out.println(ans); } // User function Template for Java public static int getMinDiff(int[] arr, int n, int k) { Arrays.sort(arr); // Maximum possible height difference int ans = arr[n - 1] - arr[0]; int tempmin, tempmax; tempmin = arr[0]; tempmax = arr[n - 1]; for (int i = 1; i < n; i++) { // if on subtracting k we got negative then // continue if (arr[i] - k < 0) continue; // Minimum element when we add k to whole array tempmin = Math.min(arr[0] + k, arr[i] - k); // Maximum element when we subtract k from whole // array tempmax = Math.max(arr[i - 1] + k, arr[n - 1] - k); ans = Math.min(ans, tempmax - tempmin); } return ans; }}", "e": 4049, "s": 2894, "text": null }, { "code": "# User function Templatedef getMinDiff(arr, n, k): arr.sort() ans = arr[n - 1] - arr[0] # Maximum possible height difference tempmin = arr[0] tempmax = arr[n - 1] for i in range(1, n): tempmin = min(arr[0] + k, arr[i] - k) # Minimum element when we # add k to whole array # Maximum element when we tempmax = max(arr[i - 1] + k, arr[n - 1] - k) # subtract k from whole array ans = min(ans, tempmax - tempmin) return ans # Driver Code Startsk = 6n = 6arr = [7, 4, 8, 8, 8, 9]ans = getMinDiff(arr, n, k)print(ans) # This code is contributed by ninja_hattori.", "e": 4703, "s": 4049, "text": null }, { "code": "using System; public class GFG { static public int getMinDiff(int[] arr, int n, int k) { Array.Sort(arr); int ans = (arr[n - 1] + k) - (arr[0] + k); // Maximum possible height difference int tempmax = arr[n - 1] - k; // Maximum element when we // subtract k from whole array int tempmin = arr[0] + k; // Minimum element when we // add k to whole array int max, min; for (int i = 0; i < n - 1; i++) { if (tempmax > (arr[i] + k)) { max = tempmax; } else { max = arr[i] + k; } if (tempmin < (arr[i + 1] - k)) { min = tempmin; } else { min = arr[i + 1] - k; } if (ans > (max - min)) { ans = max - min; } } return ans; } static public void Main() { int[] arr = { 7, 4, 8, 8, 8, 9 }; int k = 6; int ans = getMinDiff(arr, arr.Length, k); Console.Write(ans); }} // This code is contributed by ninja_hattori.", "e": 5675, "s": 4703, "text": null }, { "code": "<script> // User function Templatefunction getMinDiff(arr,n,k){ arr.sort((a,b) => (a-b)) let ans = arr[n - 1] - arr[0]; // Maximum possible height difference let tempmin, tempmax; tempmin = arr[0]; tempmax = arr[n - 1]; for (let i = 1; i < n; i++) { tempmin= Math.min(arr[0] + k,arr[i] - k); // Minimum element when we // add k to whole array tempmax = Math.max(arr[i - 1] + k, arr[n - 1] - k); // Maximum element when we // subtract k from whole array ans = Math.min(ans, tempmax - tempmin); } return ans;} // Driver Code Startslet k = 6, n = 6;let arr = [ 7, 4, 8, 8, 8, 9 ];let ans = getMinDiff(arr, n, k);document.write(ans,\"</br>\"); //This code is contributed by shinjanpatra.</script>", "e": 6522, "s": 5675, "text": null }, { "code": null, "e": 6524, "s": 6522, "text": "5" }, { "code": null, "e": 6571, "s": 6524, "text": "Time Complexity: O(nlogn)Auxiliary Space: O(n)" }, { "code": null, "e": 6577, "s": 6571, "text": "ukasp" }, { "code": null, "e": 6585, "s": 6577, "text": "ihritik" }, { "code": null, "e": 6601, "s": 6585, "text": "SHIKHAR AGRAWAL" }, { "code": null, "e": 6622, "s": 6601, "text": "avanitrachhadiya2155" }, { "code": null, "e": 6639, "s": 6622, "text": "gautampraveen351" }, { "code": null, "e": 6654, "s": 6639, "text": "sudhanshublaze" }, { "code": null, "e": 6671, "s": 6654, "text": "suyashsincever13" }, { "code": null, "e": 6686, "s": 6671, "text": "adityapawar666" }, { "code": null, "e": 6696, "s": 6686, "text": "lucky_002" }, { "code": null, "e": 6711, "s": 6696, "text": "swapnilakash21" }, { "code": null, "e": 6721, "s": 6711, "text": "kalrap615" }, { "code": null, "e": 6730, "s": 6721, "text": "u19cs070" }, { "code": null, "e": 6750, "s": 6730, "text": "shivanshchaudhary18" }, { "code": null, "e": 6771, "s": 6750, "text": "himanshu000choudhary" }, { "code": null, "e": 6786, "s": 6771, "text": "mrigankvashist" }, { "code": null, "e": 6800, "s": 6786, "text": "ninja_hattori" }, { "code": null, "e": 6813, "s": 6800, "text": "shinjanpatra" }, { "code": null, "e": 6819, "s": 6813, "text": "eni_g" }, { "code": null, "e": 6835, "s": 6819, "text": "ayushrajput1410" }, { "code": null, "e": 6856, "s": 6835, "text": "naitikvarshneyintern" }, { "code": null, "e": 6873, "s": 6856, "text": "hardikkoriintern" }, { "code": null, "e": 6879, "s": 6873, "text": "Adobe" }, { "code": null, "e": 6886, "s": 6879, "text": "Arrays" }, { "code": null, "e": 6893, "s": 6886, "text": "Greedy" }, { "code": null, "e": 6899, "s": 6893, "text": "Adobe" }, { "code": null, "e": 6906, "s": 6899, "text": "Arrays" }, { "code": null, "e": 6913, "s": 6906, "text": "Greedy" } ]
Lexicographically smallest string with given string as prefix
07 Oct, 2021 Given an array arr[] consisting of N strings and a string S if size M, the task is to find the lexicographically smallest string consisting of the string S as the prefix. If there doesn’t exist any string starting with prefix S then print “-1”. Examples: Input: arr[] = {“apple”, “appe”, “apl”, “aapl”, “appax”}, S = “app”Output: appaxExplanation:The lexicographical order of the strings consisting of “app” as the substring is {“aapl”, “apl”, “appax”, “appe”, “apple”}. The smallest lexicographic string containing is “appax”. Input: arr[] = {“can”, “man”, “va”}, S = “van”Output: -1 Approach: The given problem can be solved by sorting the given array of strings arr[] such that all the strings starting with prefixes S occur consecutively. Now traverse the given array of strings arr[] and when the first string whose prefix matches with S then print that string and break out of the loop. Otherwise, print “-1”. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the whether the// string temp starts with str or notbool is_prefix(string temp, string str){ // Base Case if (temp.length() < str.length()) return 0; else { // Check for the corresponding // characters in temp & str for (int i = 0; i < str.length(); i++) { if (str[i] != temp[i]) return 0; } return 1; }} // Function to find lexicographic smallest// string consisting of the string str// as prefixstring lexicographicallyString( string input[], int n, string str){ // Sort the given array string arr[] sort(input, input + n); for (int i = 0; i < n; i++) { string temp = input[i]; // If the i-th string contains // given string as a prefix, // then print the result if (is_prefix(temp, str)) { return temp; } } // If no string exists then // return "-1" return "-1";} // Driver Codeint main(){ string arr[] = { "apple", "appe", "apl", "aapl", "appax" }; string S = "app"; int N = 5; cout << lexicographicallyString( arr, N, S); return 0;} // Java program for the above approach import java.util.Arrays; class GFG { // Function to find the whether the // string temp starts with str or not static boolean is_prefix(String temp, String str) { // Base Case if (temp.length() < str.length()) return false; else { // Check for the corresponding // characters in temp & str for (int i = 0; i < str.length(); i++) { if (str.charAt(i) != temp.charAt(i)) return false; } return true; } } // Function to find lexicographic smallest // string consisting of the string str // as prefix static String lexicographicallyString(String[] input, int n, String str) { // Sort the given array string arr[] Arrays.sort(input); for (int i = 0; i < n; i++) { String temp = input[i]; // If the i-th string contains // given string as a prefix, // then print the result if (is_prefix(temp, str)) { return temp; } } // If no string exists then // return "-1" return "-1"; } // Driver Code public static void main(String args[]) { String[] arr = { "apple", "appe", "apl", "aapl", "appax" }; String S = "app"; int N = 5; System.out.println( lexicographicallyString(arr, N, S)); }} // This code is contributed by AnkThon # Python 3 program for the above approach # Function to find the whether the# string temp starts with str or notdef is_prefix(temp, str): # Base Case if (len(temp) < len(str)): return 0 else: # Check for the corresponding # characters in temp & str for i in range(len(str)): if (str[i] != temp[i]): return 0 return 1 # Function to find lexicographic smallest# string consisting of the string str# as prefixdef lexicographicallyString(input, n, str): # Sort the given array string arr[] input.sort() for i in range(n): temp = input[i] # If the i-th string contains # given string as a prefix, # then print the result if (is_prefix(temp, str)): return temp # If no string exists then # return "-1" return "-1" # Driver Codeif __name__ == '__main__': arr = ["apple", "appe", "apl", "aapl", "appax"] S = "app" N = 5 print(lexicographicallyString(arr, N, S)) # This code is contributed by ipg2016107. // C# program for the above approachusing System;class GFG { // Function to find the whether the // string temp starts with str or not static bool is_prefix(string temp, string str) { // Base Case if (temp.Length < str.Length) return false; else { // Check for the corresponding // characters in temp & str for (int i = 0; i < str.Length; i++) { if (str[i] != temp[i]) return false; } return true; } } // Function to find lexicographic smallest // string consisting of the string str // as prefix static string lexicographicallyString(string[] input, int n, string str) { // Sort the given array string arr[] Array.Sort(input); for (int i = 0; i < n; i++) { string temp = input[i]; // If the i-th string contains // given string as a prefix, // then print the result if (is_prefix(temp, str)) { return temp; } } // If no string exists then // return "-1" return "-1"; } // Driver Code public static void Main() { string[] arr = { "apple", "appe", "apl", "aapl", "appax" }; string S = "app"; int N = 5; Console.WriteLine( lexicographicallyString(arr, N, S)); }} // This code is contributed by ukasp. <script> // JavaScript Program to implement // the above approach // Function to find the whether the // string temp starts with str or not function is_prefix(temp, str) { // Base Case if (temp.length < str.length) return 0; else { // Check for the corresponding // characters in temp & str for (let i = 0; i < str.length; i++) { if (str[i] != temp[i]) return 0; } return 1; } } // Function to find lexicographic smallest // string consisting of the string str // as prefix function lexicographicallyString( input, n, str) { // Sort the given array string arr[] input = Array.from(input).sort(); for (let i = 0; i < n; i++) { let temp = input[i]; // If the i-th string contains // given string as a prefix, // then print the result if (is_prefix(temp, str)) { return temp; } } // If no string exists then // return "-1" return "-1"; } // Driver Code let arr = ["apple", "appe", "apl", "aapl", "appax"]; let S = "app"; let N = 5; document.write(lexicographicallyString( arr, N, S)); // This code is contributed by Potta Lokesh </script> appax Time Complexity: O(M*K*N*log N), where K is the maximum length of the string in the array arr[].Auxiliary Space: O(N) Another Approach: The above approach can also be optimized by using the Trie Data Structure by inserting all the given strings in the Trie and then check for the first string that exists in the Trie having prefix S. Time Complexity: O(M*N)Auxiliary Space: O(N) lokeshpotta20 ukasp ankthon ipg2016107 saurabh1990aror lexicographic-ordering prefix Trie Searching Sorting Strings Searching Strings Sorting Trie Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Oct, 2021" }, { "code": null, "e": 273, "s": 28, "text": "Given an array arr[] consisting of N strings and a string S if size M, the task is to find the lexicographically smallest string consisting of the string S as the prefix. If there doesn’t exist any string starting with prefix S then print “-1”." }, { "code": null, "e": 283, "s": 273, "text": "Examples:" }, { "code": null, "e": 556, "s": 283, "text": "Input: arr[] = {“apple”, “appe”, “apl”, “aapl”, “appax”}, S = “app”Output: appaxExplanation:The lexicographical order of the strings consisting of “app” as the substring is {“aapl”, “apl”, “appax”, “appe”, “apple”}. The smallest lexicographic string containing is “appax”." }, { "code": null, "e": 613, "s": 556, "text": "Input: arr[] = {“can”, “man”, “va”}, S = “van”Output: -1" }, { "code": null, "e": 944, "s": 613, "text": "Approach: The given problem can be solved by sorting the given array of strings arr[] such that all the strings starting with prefixes S occur consecutively. Now traverse the given array of strings arr[] and when the first string whose prefix matches with S then print that string and break out of the loop. Otherwise, print “-1”." }, { "code": null, "e": 995, "s": 944, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 999, "s": 995, "text": "C++" }, { "code": null, "e": 1004, "s": 999, "text": "Java" }, { "code": null, "e": 1012, "s": 1004, "text": "Python3" }, { "code": null, "e": 1015, "s": 1012, "text": "C#" }, { "code": null, "e": 1026, "s": 1015, "text": "Javascript" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the whether the// string temp starts with str or notbool is_prefix(string temp, string str){ // Base Case if (temp.length() < str.length()) return 0; else { // Check for the corresponding // characters in temp & str for (int i = 0; i < str.length(); i++) { if (str[i] != temp[i]) return 0; } return 1; }} // Function to find lexicographic smallest// string consisting of the string str// as prefixstring lexicographicallyString( string input[], int n, string str){ // Sort the given array string arr[] sort(input, input + n); for (int i = 0; i < n; i++) { string temp = input[i]; // If the i-th string contains // given string as a prefix, // then print the result if (is_prefix(temp, str)) { return temp; } } // If no string exists then // return \"-1\" return \"-1\";} // Driver Codeint main(){ string arr[] = { \"apple\", \"appe\", \"apl\", \"aapl\", \"appax\" }; string S = \"app\"; int N = 5; cout << lexicographicallyString( arr, N, S); return 0;}", "e": 2285, "s": 1026, "text": null }, { "code": "// Java program for the above approach import java.util.Arrays; class GFG { // Function to find the whether the // string temp starts with str or not static boolean is_prefix(String temp, String str) { // Base Case if (temp.length() < str.length()) return false; else { // Check for the corresponding // characters in temp & str for (int i = 0; i < str.length(); i++) { if (str.charAt(i) != temp.charAt(i)) return false; } return true; } } // Function to find lexicographic smallest // string consisting of the string str // as prefix static String lexicographicallyString(String[] input, int n, String str) { // Sort the given array string arr[] Arrays.sort(input); for (int i = 0; i < n; i++) { String temp = input[i]; // If the i-th string contains // given string as a prefix, // then print the result if (is_prefix(temp, str)) { return temp; } } // If no string exists then // return \"-1\" return \"-1\"; } // Driver Code public static void main(String args[]) { String[] arr = { \"apple\", \"appe\", \"apl\", \"aapl\", \"appax\" }; String S = \"app\"; int N = 5; System.out.println( lexicographicallyString(arr, N, S)); }} // This code is contributed by AnkThon", "e": 3832, "s": 2285, "text": null }, { "code": "# Python 3 program for the above approach # Function to find the whether the# string temp starts with str or notdef is_prefix(temp, str): # Base Case if (len(temp) < len(str)): return 0 else: # Check for the corresponding # characters in temp & str for i in range(len(str)): if (str[i] != temp[i]): return 0 return 1 # Function to find lexicographic smallest# string consisting of the string str# as prefixdef lexicographicallyString(input, n, str): # Sort the given array string arr[] input.sort() for i in range(n): temp = input[i] # If the i-th string contains # given string as a prefix, # then print the result if (is_prefix(temp, str)): return temp # If no string exists then # return \"-1\" return \"-1\" # Driver Codeif __name__ == '__main__': arr = [\"apple\", \"appe\", \"apl\", \"aapl\", \"appax\"] S = \"app\" N = 5 print(lexicographicallyString(arr, N, S)) # This code is contributed by ipg2016107.", "e": 4889, "s": 3832, "text": null }, { "code": "// C# program for the above approachusing System;class GFG { // Function to find the whether the // string temp starts with str or not static bool is_prefix(string temp, string str) { // Base Case if (temp.Length < str.Length) return false; else { // Check for the corresponding // characters in temp & str for (int i = 0; i < str.Length; i++) { if (str[i] != temp[i]) return false; } return true; } } // Function to find lexicographic smallest // string consisting of the string str // as prefix static string lexicographicallyString(string[] input, int n, string str) { // Sort the given array string arr[] Array.Sort(input); for (int i = 0; i < n; i++) { string temp = input[i]; // If the i-th string contains // given string as a prefix, // then print the result if (is_prefix(temp, str)) { return temp; } } // If no string exists then // return \"-1\" return \"-1\"; } // Driver Code public static void Main() { string[] arr = { \"apple\", \"appe\", \"apl\", \"aapl\", \"appax\" }; string S = \"app\"; int N = 5; Console.WriteLine( lexicographicallyString(arr, N, S)); }} // This code is contributed by ukasp.", "e": 6391, "s": 4889, "text": null }, { "code": "<script> // JavaScript Program to implement // the above approach // Function to find the whether the // string temp starts with str or not function is_prefix(temp, str) { // Base Case if (temp.length < str.length) return 0; else { // Check for the corresponding // characters in temp & str for (let i = 0; i < str.length; i++) { if (str[i] != temp[i]) return 0; } return 1; } } // Function to find lexicographic smallest // string consisting of the string str // as prefix function lexicographicallyString( input, n, str) { // Sort the given array string arr[] input = Array.from(input).sort(); for (let i = 0; i < n; i++) { let temp = input[i]; // If the i-th string contains // given string as a prefix, // then print the result if (is_prefix(temp, str)) { return temp; } } // If no string exists then // return \"-1\" return \"-1\"; } // Driver Code let arr = [\"apple\", \"appe\", \"apl\", \"aapl\", \"appax\"]; let S = \"app\"; let N = 5; document.write(lexicographicallyString( arr, N, S)); // This code is contributed by Potta Lokesh </script>", "e": 7994, "s": 6391, "text": null }, { "code": null, "e": 8000, "s": 7994, "text": "appax" }, { "code": null, "e": 8120, "s": 8002, "text": "Time Complexity: O(M*K*N*log N), where K is the maximum length of the string in the array arr[].Auxiliary Space: O(N)" }, { "code": null, "e": 8336, "s": 8120, "text": "Another Approach: The above approach can also be optimized by using the Trie Data Structure by inserting all the given strings in the Trie and then check for the first string that exists in the Trie having prefix S." }, { "code": null, "e": 8381, "s": 8336, "text": "Time Complexity: O(M*N)Auxiliary Space: O(N)" }, { "code": null, "e": 8395, "s": 8381, "text": "lokeshpotta20" }, { "code": null, "e": 8401, "s": 8395, "text": "ukasp" }, { "code": null, "e": 8409, "s": 8401, "text": "ankthon" }, { "code": null, "e": 8420, "s": 8409, "text": "ipg2016107" }, { "code": null, "e": 8436, "s": 8420, "text": "saurabh1990aror" }, { "code": null, "e": 8459, "s": 8436, "text": "lexicographic-ordering" }, { "code": null, "e": 8466, "s": 8459, "text": "prefix" }, { "code": null, "e": 8471, "s": 8466, "text": "Trie" }, { "code": null, "e": 8481, "s": 8471, "text": "Searching" }, { "code": null, "e": 8489, "s": 8481, "text": "Sorting" }, { "code": null, "e": 8497, "s": 8489, "text": "Strings" }, { "code": null, "e": 8507, "s": 8497, "text": "Searching" }, { "code": null, "e": 8515, "s": 8507, "text": "Strings" }, { "code": null, "e": 8523, "s": 8515, "text": "Sorting" }, { "code": null, "e": 8528, "s": 8523, "text": "Trie" } ]
Servlet With JDBC
20 Dec, 2021 Servlets are the Java programs that run on the Java-enabled web server or application server. They are used to handle the request obtained from the webserver, process the request, produce the response, then send a response back to the webserver. Properties of Servlets are as follows: Servlets work on the server-side. Servlets are capable of handling complex requests obtained from the webserver. Prerequisites: Basic Servlet knowledge. JDBC connection in Java. We can use any database to store the data, in this example, the PostgreSQL database management system is used. SQL Language – Insert, Delete, Update & Select statements. Eclipse IDE and Tomcat server. In this example, we will be creating a simple “Student Database Management system” in which, we can insert, update, delete and view the student details. Application Step 1: Create Table in PostgreSQL Create a Table studentdetails to store details of students. Add columns, stuid- to store student id, stuname – to store student name, email – to store email id of student and phonenum – to store phone number of student. And insert some data into the table. Table and columns Step 2: Create a Dynamic web project in Eclipse In Eclipse IDE, create a Dynamic web project as the below project structure. To connect with PostgreSQL DB, add “postgresql-42.2.18.jar” in the project under “WEB-INF/lib” folder. Project Structure Step 3: Create required JSP’s to get the details from the student Home.jsp This is the welcome page of the project. On this page, we will be displaying the different types of operations such as Insert, Delete and Select data on the Student details. HTML <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>Welcome Page</title></head><body> <h2 align="center">Welcome to Student database management system</h2> <br /> <table align="center"> <tr> <td>To insert your details into the Database:</td> <td><input type="button" value="Insert data" onclick="window.location.href='Insert.jsp'" /></td> </tr> <tr> <td>To delete your details from the Database:</td> <td><input type="button" value="Delete data" onclick="window.location.href='Delete.jsp'" /></td> </tr> <tr> <td>To view your details from the Database:</td> <td><input type="button" value="Select data" onclick="window.location.href='Select.jsp'" /></td> </tr> </table> </body> </html> Based on the student selection, the respective JSP page will be displayed. Insert.jsp This page takes the required values from the student – Student Id, Student Name, Email Id, and Phone number and submits the page to Insert servlet to store the values in DB. HTML <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>Insert Details</title></head><body> <h2>Fill in the details</h2> <form action="./InsertDetails" method="post"> <table> <tr> <td>ID:</td> <td><input type="text" name="id" maxlength="6" size="7" /></td> </tr> <tr> <td>Name:</td> <td><input type="text" name="name" maxlength="30" size="25" /></td> </tr> <tr> <td>Email Id:</td> <td><input type="text" name="email" maxlength="40" size="35" /></td> </tr> <tr> <td>Phone Number:</td> <td><input type="text" name="phnum" maxlength="10" size="11" /></td> </tr> <tr /> </table> <br /> <input type="submit" value="Insert Data" /> </form> <br /> <input type="button" value="Return to Home" onclick="window.location.href='Home.jsp'" /> </body> </html> Based on the action and method specified, it will map the respective servlet and go to the doPost method() in that servlet. Delete.jsp To delete the student information from DB, we need the ID of the student. This page takes the id from the student and submits the value to the Delete servlet. HTML <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>Delete Details</title></head><body> <form action="./DeleteDetails" method="post"> <table> <tr> <td>Enter ID:</td> <td><input type="text" name="id" maxlength="6" size="7" /></td> </tr> </table> <br /> <input type="submit" value="Delete Data" /> </form> <br /> <input type="button" value="Return to Home" onclick="window.location.href='Home.jsp'" /> </body> </html> Success.jsp To display the success message after insert, update and delete operations. HTML <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>Success Page</title></head><body> <form action="Home.jsp"> <h3> <%=request.getParameter("msg")%> Successful </h3> <br /> <input type="submit" value="Return to Home page" /> </form> </body></html> After successful insertion or deletion of the values, this page will display the success message to the UI. Select.jsp To populate the student information from DB, we need the ID of the student. This page takes the id provided and submits it to the Select servlet to fetch the details. HTML <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>Select Details</title></head><body> <form action="./SelectDetails" method="get"> <table> <tr> <td>Enter ID:</td> <td><input type="text" name="id" maxlength="6" size="7" /></td> </tr> </table> <br /> <input type="submit" value="View Data" /> </form> <br /> <input type="button" value="Return to Home" onclick="window.location.href='Home.jsp'" /> </body> </html> Result.jsp This page is to populate the student information in the UI. To display the result set of the student details based on the given id. HTML <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>Student Details - Result</title></head><body> <h2>Details</h2> <form> <input type="hidden" name="stid" value="<%=request.getParameter("id")%>"> <table> <tr> <td>ID:</td> <td><%=request.getParameter("id")%></td> </tr> <tr> <td>Name:</td> <td><%=request.getParameter("name")%></td> </tr> <tr> <td>Email Id:</td> <td><%=request.getParameter("email")%></td> </tr> <tr> <td>Phone Number:</td> <td><%=request.getParameter("phone")%></td> </tr> <tr /> </table> <br /> </form> <br /> <input type="button" value="Update data" onclick="update()" /> <br /> <input type="button" value="Return to Home" onclick="window.location.href='Home.jsp'" /> </body> <script language="javascript" type="text/javascript"> function update() { var sid = document.forms[0].elements['stid'].value; window.location.href = "Update.jsp?id=" + sid; }</script></html> Update.jsp Once the information is populated, if the student wants to update their details, this page takes the updated information from the student and submits it to the Update servlet. HTML <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>Update Details</title></head><body> <h2>Fill in your details</h2> <form action="./UpdateDetails" method="post"> <table> <tr> <td>ID:</td> <td><input type="text" name="id" value="<%=request.getParameter("id")%>" readonly="readonly"> </td> </tr> <tr> <td>Name:</td> <td><input type="text" name="name" maxlength="30" size="25" /></td> </tr> <tr> <td>Email Id:</td> <td><input type="text" name="email" maxlength="40" size="35" /></td> </tr> <tr> <td>Phone Number:</td> <td><input type="text" name="phnum" maxlength="10" size="11" /></td> </tr> <tr /> </table> <br /> <input type="submit" value="Update Data" /> </form> <br /> <input type="button" value="Return to Home" onclick="window.location.href='Home.jsp'" /> </body></html> We are making the ID value as read-only so that it won’t be changed and the information will be updated with respect to the ID value. Step 4: Create DBUtil.java To establish a JDBC connection with PostgreSQL, we need to specify the driver, URL, username, and password objects of the PostgreSQL. In order to reuse these objects in all the servlets to make a connection with the DB, we can provide these values in separate class like below. Java public class DbUtil { public static String url = "jdbc:postgresql://localhost/postgres"; public static String user = "root"; public static String password = "root"; public static String driver = "org.postgresql.Driver"; } Instead of using a java class, we can specify these values in the properties file also. Step 5: Create respective servlet classes Servlet classes and JSP pages can be mapped through the web.xml(deployment descriptor) or by using annotations. In this example, we are using @WebServlet annotation to map the jsp pages to their respective servlets. To work with servlets, we need to extend the java class from HttpServlet. InsertDetails.java When the student enters the data through Insert.jsp and submits the page to insert the details into DB, based on the URL “/InsertDetails” in JSP page, InsertDetails.java servlet class will be mapped and executed. Java import java.io.IOException;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement; import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; @WebServlet("/InsertDetails")public class InsertDetails extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Jdbc Connection try { Class.forName(DbUtil.driver); } catch (ClassNotFoundException e) { System.out.println("Class not found " + e); } try { Connection conn = DriverManager.getConnection(DbUtil.url, DbUtil.user, DbUtil.password); System.out.println("connection successful"); // Query/statement to insert the values PreparedStatement st = conn.prepareStatement("insert into studentdetails values(?, ?, ?, ?)"); // set values into the query st.setInt(1, Integer.valueOf(request.getParameter("id"))); st.setString(2, request.getParameter("name")); st.setString(3, request.getParameter("email")); st.setString(4, request.getParameter("phnum")); // Execute the query st.executeUpdate(); st.close(); conn.close(); // Redirect the response to success page response.sendRedirect("Success.jsp?msg=Insert"); } catch (Exception e) { e.printStackTrace(); } }} We need to import all the required packages for the servlet and JDBC connection. To insert the details, we need to use the doPost method of the servlet class. First, establish the JDBC connection inside the try/catch block to handle the exception if arises. Using Class.forName(), load the PostgreSQL driver. Then using Connection and DriverManager object, get the connection to the PostgreSQL server. Prepare statement object with the insert query and set the student information into respective parameters and execute the query. Once the query is executed, close the statement and connection object to avoid resource leak. Then redirect the page to Success.jsp page with a successful message to display on the screen. DeleteDetails.java Same as the insert operation delete servlet also will be mapped based on the URL specified. When a student enters the ID value to delete the student information, DeleteDetails.java servlet class will be mapped and executed. Java import java.io.IOException;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement; import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; @WebServlet("/DeleteDetails")public class DeleteDetails extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { Class.forName(DbUtil.driver); } catch (ClassNotFoundException e) { System.out.println("Class not found " + e); } try { Connection conn = DriverManager.getConnection(DbUtil.url, DbUtil.user, DbUtil.password); System.out.println("connection successful"); PreparedStatement st = conn.prepareStatement("delete from studentdetails where stuid=?"); st.setInt(1, Integer.valueOf(request.getParameter("id"))); st.executeUpdate(); st.close(); conn.close(); response.sendRedirect("Success.jsp?msg=Delete"); } catch (Exception e) { e.printStackTrace(); } }} As specified in the insert servlet, the same way delete the servlet also will work. First, establish JDBC connection and prepare to delete statement which takes an ID as an input parameter. Once the delete operation is completed, display the success message in the UI. SelectDetails.java To populate the student information based on the ID submitted. Java import java.io.IOException;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet; import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; @WebServlet("/SelectDetails")public class SelectDetails extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { Class.forName(DbUtil.driver); } catch (ClassNotFoundException e) { System.out.println("Class not found " + e); } try { int id = 0; String name = "", email = "", ph = ""; Connection conn = DriverManager.getConnection(DbUtil.url, DbUtil.user, DbUtil.password); System.out.println("connection successful"); PreparedStatement st = conn.prepareStatement("select * from studentdetails where stuid=?"); st.setInt(1, Integer.valueOf(request.getParameter("id"))); ResultSet rs = st.executeQuery(); while (rs.next()) { id = rs.getInt(1); name = rs.getString(2); email = rs.getString(3); ph = rs.getString(4); } rs.close(); st.close(); conn.close(); response.sendRedirect("Result.jsp?id=" + id + "&name=" + name + "&email=" + email + "&phone=" + ph); } catch (Exception e) { e.printStackTrace(); } } } Here, we are fetching the details, so we need to use the doGet() method of the servlet class. Establish a JDBC connection and prepare a select statement with ID as input parameter and get all the details. In order to display this information, send these values to the Result.jsp page. UpdateDetails.java If the student wants to update any information, then we need to get the respective ID and perform the operation. Java import java.io.IOException;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement; import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; @WebServlet("/UpdateDetails")public class UpdateDetails extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { Class.forName(DbUtil.driver); } catch (ClassNotFoundException e) { System.out.println("Class not found " + e); } try { Connection conn = DriverManager.getConnection(DbUtil.url, DbUtil.user, DbUtil.password); System.out.println("connection successful"); PreparedStatement st = conn .prepareStatement("update studentdetails set stuname=?, email=?, phonenum=? where stuid=?"); st.setString(1, request.getParameter("name")); st.setString(2, request.getParameter("email")); st.setString(3, request.getParameter("phnum")); st.setInt(4, Integer.valueOf(request.getParameter("id"))); st.executeUpdate(); st.close(); conn.close(); response.sendRedirect("Success.jsp?msg=Update"); } catch (Exception e) { e.printStackTrace(); } } } We are updating the student information, hence the doPost() method is called. Establish JDBC connection and prepare update statement passing ID as the input parameter. Execute the query and display the success message in the UI. Step 6: Run the Application Now, run the application using Run As -> Run on Server. The application will be deployed on the Tomcat server. Run the URL, http://localhost:8081/ServletsPostgre/Home.jsp, in the browser to get the home page of the application. Home.jsp To insert the details, click on Insert data. On clicking, redirects to Insert.jsp page and displays below UI. Insert.jsp Enter all the details and click on Insert Data. After successful insertion, a success message will be displayed on the screen. Successful message Return to the home page. Check if the data is inserted successfully in PostgreSQL DB. Insertion To fetch the values from the DB, click on Select Data on the Home page. Select.jsp Enter the ID which you want to fetch the details and click View data. The result will be displayed on the Result.jsp page. Student_info If the data needs to be updated, click on Update Data, or if don’t just return to the home page. If we click on update data, redirect to the Update.jsp page. Update.jsp Here, the Id will be displayed on the load of the page and will be read-only. Update the data and click on update data. After updating success message will be displayed. Check if the data is updated in PostgreSQL DB. Updated_details Finally, to delete the data from DB, click on Delete data on the home page. Delete.jsp Enter the ID which has to be deleted and click on Delete Data. The information will be deleted from the DB and a success message will be displayed as below. Deletion_successful Check in the DB if the information is deleted. After delete operation In this way, we can perform all the insert, update, delete and select operations using Servlets with JDBC. java-servlet JDBC Picked 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": "\n20 Dec, 2021" }, { "code": null, "e": 314, "s": 28, "text": "Servlets are the Java programs that run on the Java-enabled web server or application server. They are used to handle the request obtained from the webserver, process the request, produce the response, then send a response back to the webserver. Properties of Servlets are as follows:" }, { "code": null, "e": 348, "s": 314, "text": "Servlets work on the server-side." }, { "code": null, "e": 427, "s": 348, "text": "Servlets are capable of handling complex requests obtained from the webserver." }, { "code": null, "e": 442, "s": 427, "text": "Prerequisites:" }, { "code": null, "e": 467, "s": 442, "text": "Basic Servlet knowledge." }, { "code": null, "e": 492, "s": 467, "text": "JDBC connection in Java." }, { "code": null, "e": 603, "s": 492, "text": "We can use any database to store the data, in this example, the PostgreSQL database management system is used." }, { "code": null, "e": 662, "s": 603, "text": "SQL Language – Insert, Delete, Update & Select statements." }, { "code": null, "e": 693, "s": 662, "text": "Eclipse IDE and Tomcat server." }, { "code": null, "e": 846, "s": 693, "text": "In this example, we will be creating a simple “Student Database Management system” in which, we can insert, update, delete and view the student details." }, { "code": null, "e": 858, "s": 846, "text": "Application" }, { "code": null, "e": 893, "s": 858, "text": "Step 1: Create Table in PostgreSQL" }, { "code": null, "e": 953, "s": 893, "text": "Create a Table studentdetails to store details of students." }, { "code": null, "e": 1150, "s": 953, "text": "Add columns, stuid- to store student id, stuname – to store student name, email – to store email id of student and phonenum – to store phone number of student. And insert some data into the table." }, { "code": null, "e": 1168, "s": 1150, "text": "Table and columns" }, { "code": null, "e": 1216, "s": 1168, "text": "Step 2: Create a Dynamic web project in Eclipse" }, { "code": null, "e": 1293, "s": 1216, "text": "In Eclipse IDE, create a Dynamic web project as the below project structure." }, { "code": null, "e": 1396, "s": 1293, "text": "To connect with PostgreSQL DB, add “postgresql-42.2.18.jar” in the project under “WEB-INF/lib” folder." }, { "code": null, "e": 1414, "s": 1396, "text": "Project Structure" }, { "code": null, "e": 1480, "s": 1414, "text": "Step 3: Create required JSP’s to get the details from the student" }, { "code": null, "e": 1489, "s": 1480, "text": "Home.jsp" }, { "code": null, "e": 1663, "s": 1489, "text": "This is the welcome page of the project. On this page, we will be displaying the different types of operations such as Insert, Delete and Select data on the Student details." }, { "code": null, "e": 1668, "s": 1663, "text": "HTML" }, { "code": "<%@ page language=\"java\" contentType=\"text/html; charset=ISO-8859-1\" pageEncoding=\"ISO-8859-1\"%><!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\"><html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\"><title>Welcome Page</title></head><body> <h2 align=\"center\">Welcome to Student database management system</h2> <br /> <table align=\"center\"> <tr> <td>To insert your details into the Database:</td> <td><input type=\"button\" value=\"Insert data\" onclick=\"window.location.href='Insert.jsp'\" /></td> </tr> <tr> <td>To delete your details from the Database:</td> <td><input type=\"button\" value=\"Delete data\" onclick=\"window.location.href='Delete.jsp'\" /></td> </tr> <tr> <td>To view your details from the Database:</td> <td><input type=\"button\" value=\"Select data\" onclick=\"window.location.href='Select.jsp'\" /></td> </tr> </table> </body> </html>", "e": 2767, "s": 1668, "text": null }, { "code": null, "e": 2842, "s": 2767, "text": "Based on the student selection, the respective JSP page will be displayed." }, { "code": null, "e": 2853, "s": 2842, "text": "Insert.jsp" }, { "code": null, "e": 3027, "s": 2853, "text": "This page takes the required values from the student – Student Id, Student Name, Email Id, and Phone number and submits the page to Insert servlet to store the values in DB." }, { "code": null, "e": 3032, "s": 3027, "text": "HTML" }, { "code": "<%@ page language=\"java\" contentType=\"text/html; charset=ISO-8859-1\" pageEncoding=\"ISO-8859-1\"%><!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\"><html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\"><title>Insert Details</title></head><body> <h2>Fill in the details</h2> <form action=\"./InsertDetails\" method=\"post\"> <table> <tr> <td>ID:</td> <td><input type=\"text\" name=\"id\" maxlength=\"6\" size=\"7\" /></td> </tr> <tr> <td>Name:</td> <td><input type=\"text\" name=\"name\" maxlength=\"30\" size=\"25\" /></td> </tr> <tr> <td>Email Id:</td> <td><input type=\"text\" name=\"email\" maxlength=\"40\" size=\"35\" /></td> </tr> <tr> <td>Phone Number:</td> <td><input type=\"text\" name=\"phnum\" maxlength=\"10\" size=\"11\" /></td> </tr> <tr /> </table> <br /> <input type=\"submit\" value=\"Insert Data\" /> </form> <br /> <input type=\"button\" value=\"Return to Home\" onclick=\"window.location.href='Home.jsp'\" /> </body> </html>", "e": 4286, "s": 3032, "text": null }, { "code": null, "e": 4410, "s": 4286, "text": "Based on the action and method specified, it will map the respective servlet and go to the doPost method() in that servlet." }, { "code": null, "e": 4421, "s": 4410, "text": "Delete.jsp" }, { "code": null, "e": 4580, "s": 4421, "text": "To delete the student information from DB, we need the ID of the student. This page takes the id from the student and submits the value to the Delete servlet." }, { "code": null, "e": 4585, "s": 4580, "text": "HTML" }, { "code": "<%@ page language=\"java\" contentType=\"text/html; charset=ISO-8859-1\" pageEncoding=\"ISO-8859-1\"%><!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\"><html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\"><title>Delete Details</title></head><body> <form action=\"./DeleteDetails\" method=\"post\"> <table> <tr> <td>Enter ID:</td> <td><input type=\"text\" name=\"id\" maxlength=\"6\" size=\"7\" /></td> </tr> </table> <br /> <input type=\"submit\" value=\"Delete Data\" /> </form> <br /> <input type=\"button\" value=\"Return to Home\" onclick=\"window.location.href='Home.jsp'\" /> </body> </html>", "e": 5341, "s": 4585, "text": null }, { "code": null, "e": 5353, "s": 5341, "text": "Success.jsp" }, { "code": null, "e": 5428, "s": 5353, "text": "To display the success message after insert, update and delete operations." }, { "code": null, "e": 5433, "s": 5428, "text": "HTML" }, { "code": "<%@ page language=\"java\" contentType=\"text/html; charset=ISO-8859-1\" pageEncoding=\"ISO-8859-1\"%><!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\"><html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\"><title>Success Page</title></head><body> <form action=\"Home.jsp\"> <h3> <%=request.getParameter(\"msg\")%> Successful </h3> <br /> <input type=\"submit\" value=\"Return to Home page\" /> </form> </body></html>", "e": 5975, "s": 5433, "text": null }, { "code": null, "e": 6084, "s": 5975, "text": "After successful insertion or deletion of the values, this page will display the success message to the UI. " }, { "code": null, "e": 6095, "s": 6084, "text": "Select.jsp" }, { "code": null, "e": 6262, "s": 6095, "text": "To populate the student information from DB, we need the ID of the student. This page takes the id provided and submits it to the Select servlet to fetch the details." }, { "code": null, "e": 6267, "s": 6262, "text": "HTML" }, { "code": "<%@ page language=\"java\" contentType=\"text/html; charset=ISO-8859-1\" pageEncoding=\"ISO-8859-1\"%><!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\"><html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\"><title>Select Details</title></head><body> <form action=\"./SelectDetails\" method=\"get\"> <table> <tr> <td>Enter ID:</td> <td><input type=\"text\" name=\"id\" maxlength=\"6\" size=\"7\" /></td> </tr> </table> <br /> <input type=\"submit\" value=\"View Data\" /> </form> <br /> <input type=\"button\" value=\"Return to Home\" onclick=\"window.location.href='Home.jsp'\" /> </body> </html>", "e": 7018, "s": 6267, "text": null }, { "code": null, "e": 7029, "s": 7018, "text": "Result.jsp" }, { "code": null, "e": 7161, "s": 7029, "text": "This page is to populate the student information in the UI. To display the result set of the student details based on the given id." }, { "code": null, "e": 7166, "s": 7161, "text": "HTML" }, { "code": "<%@ page language=\"java\" contentType=\"text/html; charset=ISO-8859-1\" pageEncoding=\"ISO-8859-1\"%><!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\"><html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\"><title>Student Details - Result</title></head><body> <h2>Details</h2> <form> <input type=\"hidden\" name=\"stid\" value=\"<%=request.getParameter(\"id\")%>\"> <table> <tr> <td>ID:</td> <td><%=request.getParameter(\"id\")%></td> </tr> <tr> <td>Name:</td> <td><%=request.getParameter(\"name\")%></td> </tr> <tr> <td>Email Id:</td> <td><%=request.getParameter(\"email\")%></td> </tr> <tr> <td>Phone Number:</td> <td><%=request.getParameter(\"phone\")%></td> </tr> <tr /> </table> <br /> </form> <br /> <input type=\"button\" value=\"Update data\" onclick=\"update()\" /> <br /> <input type=\"button\" value=\"Return to Home\" onclick=\"window.location.href='Home.jsp'\" /> </body> <script language=\"javascript\" type=\"text/javascript\"> function update() { var sid = document.forms[0].elements['stid'].value; window.location.href = \"Update.jsp?id=\" + sid; }</script></html>", "e": 8606, "s": 7166, "text": null }, { "code": null, "e": 8617, "s": 8606, "text": "Update.jsp" }, { "code": null, "e": 8793, "s": 8617, "text": "Once the information is populated, if the student wants to update their details, this page takes the updated information from the student and submits it to the Update servlet." }, { "code": null, "e": 8798, "s": 8793, "text": "HTML" }, { "code": "<%@ page language=\"java\" contentType=\"text/html; charset=ISO-8859-1\" pageEncoding=\"ISO-8859-1\"%><!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\"><html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\"><title>Update Details</title></head><body> <h2>Fill in your details</h2> <form action=\"./UpdateDetails\" method=\"post\"> <table> <tr> <td>ID:</td> <td><input type=\"text\" name=\"id\" value=\"<%=request.getParameter(\"id\")%>\" readonly=\"readonly\"> </td> </tr> <tr> <td>Name:</td> <td><input type=\"text\" name=\"name\" maxlength=\"30\" size=\"25\" /></td> </tr> <tr> <td>Email Id:</td> <td><input type=\"text\" name=\"email\" maxlength=\"40\" size=\"35\" /></td> </tr> <tr> <td>Phone Number:</td> <td><input type=\"text\" name=\"phnum\" maxlength=\"10\" size=\"11\" /></td> </tr> <tr /> </table> <br /> <input type=\"submit\" value=\"Update Data\" /> </form> <br /> <input type=\"button\" value=\"Return to Home\" onclick=\"window.location.href='Home.jsp'\" /> </body></html>", "e": 10117, "s": 8798, "text": null }, { "code": null, "e": 10251, "s": 10117, "text": "We are making the ID value as read-only so that it won’t be changed and the information will be updated with respect to the ID value." }, { "code": null, "e": 10278, "s": 10251, "text": "Step 4: Create DBUtil.java" }, { "code": null, "e": 10556, "s": 10278, "text": "To establish a JDBC connection with PostgreSQL, we need to specify the driver, URL, username, and password objects of the PostgreSQL. In order to reuse these objects in all the servlets to make a connection with the DB, we can provide these values in separate class like below." }, { "code": null, "e": 10561, "s": 10556, "text": "Java" }, { "code": "public class DbUtil { public static String url = \"jdbc:postgresql://localhost/postgres\"; public static String user = \"root\"; public static String password = \"root\"; public static String driver = \"org.postgresql.Driver\"; }", "e": 10798, "s": 10561, "text": null }, { "code": null, "e": 10886, "s": 10798, "text": "Instead of using a java class, we can specify these values in the properties file also." }, { "code": null, "e": 10928, "s": 10886, "text": "Step 5: Create respective servlet classes" }, { "code": null, "e": 11218, "s": 10928, "text": "Servlet classes and JSP pages can be mapped through the web.xml(deployment descriptor) or by using annotations. In this example, we are using @WebServlet annotation to map the jsp pages to their respective servlets. To work with servlets, we need to extend the java class from HttpServlet." }, { "code": null, "e": 11237, "s": 11218, "text": "InsertDetails.java" }, { "code": null, "e": 11450, "s": 11237, "text": "When the student enters the data through Insert.jsp and submits the page to insert the details into DB, based on the URL “/InsertDetails” in JSP page, InsertDetails.java servlet class will be mapped and executed." }, { "code": null, "e": 11455, "s": 11450, "text": "Java" }, { "code": "import java.io.IOException;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement; import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; @WebServlet(\"/InsertDetails\")public class InsertDetails extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Jdbc Connection try { Class.forName(DbUtil.driver); } catch (ClassNotFoundException e) { System.out.println(\"Class not found \" + e); } try { Connection conn = DriverManager.getConnection(DbUtil.url, DbUtil.user, DbUtil.password); System.out.println(\"connection successful\"); // Query/statement to insert the values PreparedStatement st = conn.prepareStatement(\"insert into studentdetails values(?, ?, ?, ?)\"); // set values into the query st.setInt(1, Integer.valueOf(request.getParameter(\"id\"))); st.setString(2, request.getParameter(\"name\")); st.setString(3, request.getParameter(\"email\")); st.setString(4, request.getParameter(\"phnum\")); // Execute the query st.executeUpdate(); st.close(); conn.close(); // Redirect the response to success page response.sendRedirect(\"Success.jsp?msg=Insert\"); } catch (Exception e) { e.printStackTrace(); } }}", "e": 13181, "s": 11455, "text": null }, { "code": null, "e": 13262, "s": 13181, "text": "We need to import all the required packages for the servlet and JDBC connection." }, { "code": null, "e": 13340, "s": 13262, "text": "To insert the details, we need to use the doPost method of the servlet class." }, { "code": null, "e": 13439, "s": 13340, "text": "First, establish the JDBC connection inside the try/catch block to handle the exception if arises." }, { "code": null, "e": 13490, "s": 13439, "text": "Using Class.forName(), load the PostgreSQL driver." }, { "code": null, "e": 13583, "s": 13490, "text": "Then using Connection and DriverManager object, get the connection to the PostgreSQL server." }, { "code": null, "e": 13712, "s": 13583, "text": "Prepare statement object with the insert query and set the student information into respective parameters and execute the query." }, { "code": null, "e": 13806, "s": 13712, "text": "Once the query is executed, close the statement and connection object to avoid resource leak." }, { "code": null, "e": 13901, "s": 13806, "text": "Then redirect the page to Success.jsp page with a successful message to display on the screen." }, { "code": null, "e": 13920, "s": 13901, "text": "DeleteDetails.java" }, { "code": null, "e": 14144, "s": 13920, "text": "Same as the insert operation delete servlet also will be mapped based on the URL specified. When a student enters the ID value to delete the student information, DeleteDetails.java servlet class will be mapped and executed." }, { "code": null, "e": 14149, "s": 14144, "text": "Java" }, { "code": "import java.io.IOException;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement; import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; @WebServlet(\"/DeleteDetails\")public class DeleteDetails extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { Class.forName(DbUtil.driver); } catch (ClassNotFoundException e) { System.out.println(\"Class not found \" + e); } try { Connection conn = DriverManager.getConnection(DbUtil.url, DbUtil.user, DbUtil.password); System.out.println(\"connection successful\"); PreparedStatement st = conn.prepareStatement(\"delete from studentdetails where stuid=?\"); st.setInt(1, Integer.valueOf(request.getParameter(\"id\"))); st.executeUpdate(); st.close(); conn.close(); response.sendRedirect(\"Success.jsp?msg=Delete\"); } catch (Exception e) { e.printStackTrace(); } }}", "e": 15479, "s": 14149, "text": null }, { "code": null, "e": 15563, "s": 15479, "text": "As specified in the insert servlet, the same way delete the servlet also will work." }, { "code": null, "e": 15669, "s": 15563, "text": "First, establish JDBC connection and prepare to delete statement which takes an ID as an input parameter." }, { "code": null, "e": 15748, "s": 15669, "text": "Once the delete operation is completed, display the success message in the UI." }, { "code": null, "e": 15767, "s": 15748, "text": "SelectDetails.java" }, { "code": null, "e": 15830, "s": 15767, "text": "To populate the student information based on the ID submitted." }, { "code": null, "e": 15835, "s": 15830, "text": "Java" }, { "code": "import java.io.IOException;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet; import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; @WebServlet(\"/SelectDetails\")public class SelectDetails extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { Class.forName(DbUtil.driver); } catch (ClassNotFoundException e) { System.out.println(\"Class not found \" + e); } try { int id = 0; String name = \"\", email = \"\", ph = \"\"; Connection conn = DriverManager.getConnection(DbUtil.url, DbUtil.user, DbUtil.password); System.out.println(\"connection successful\"); PreparedStatement st = conn.prepareStatement(\"select * from studentdetails where stuid=?\"); st.setInt(1, Integer.valueOf(request.getParameter(\"id\"))); ResultSet rs = st.executeQuery(); while (rs.next()) { id = rs.getInt(1); name = rs.getString(2); email = rs.getString(3); ph = rs.getString(4); } rs.close(); st.close(); conn.close(); response.sendRedirect(\"Result.jsp?id=\" + id + \"&name=\" + name + \"&email=\" + email + \"&phone=\" + ph); } catch (Exception e) { e.printStackTrace(); } } }", "e": 17560, "s": 15835, "text": null }, { "code": null, "e": 17654, "s": 17560, "text": "Here, we are fetching the details, so we need to use the doGet() method of the servlet class." }, { "code": null, "e": 17765, "s": 17654, "text": "Establish a JDBC connection and prepare a select statement with ID as input parameter and get all the details." }, { "code": null, "e": 17845, "s": 17765, "text": "In order to display this information, send these values to the Result.jsp page." }, { "code": null, "e": 17864, "s": 17845, "text": "UpdateDetails.java" }, { "code": null, "e": 17977, "s": 17864, "text": "If the student wants to update any information, then we need to get the respective ID and perform the operation." }, { "code": null, "e": 17982, "s": 17977, "text": "Java" }, { "code": "import java.io.IOException;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement; import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; @WebServlet(\"/UpdateDetails\")public class UpdateDetails extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { Class.forName(DbUtil.driver); } catch (ClassNotFoundException e) { System.out.println(\"Class not found \" + e); } try { Connection conn = DriverManager.getConnection(DbUtil.url, DbUtil.user, DbUtil.password); System.out.println(\"connection successful\"); PreparedStatement st = conn .prepareStatement(\"update studentdetails set stuname=?, email=?, phonenum=? where stuid=?\"); st.setString(1, request.getParameter(\"name\")); st.setString(2, request.getParameter(\"email\")); st.setString(3, request.getParameter(\"phnum\")); st.setInt(4, Integer.valueOf(request.getParameter(\"id\"))); st.executeUpdate(); st.close(); conn.close(); response.sendRedirect(\"Success.jsp?msg=Update\"); } catch (Exception e) { e.printStackTrace(); } } }", "e": 19538, "s": 17982, "text": null }, { "code": null, "e": 19616, "s": 19538, "text": "We are updating the student information, hence the doPost() method is called." }, { "code": null, "e": 19706, "s": 19616, "text": "Establish JDBC connection and prepare update statement passing ID as the input parameter." }, { "code": null, "e": 19767, "s": 19706, "text": "Execute the query and display the success message in the UI." }, { "code": null, "e": 19795, "s": 19767, "text": "Step 6: Run the Application" }, { "code": null, "e": 20023, "s": 19795, "text": "Now, run the application using Run As -> Run on Server. The application will be deployed on the Tomcat server. Run the URL, http://localhost:8081/ServletsPostgre/Home.jsp, in the browser to get the home page of the application." }, { "code": null, "e": 20032, "s": 20023, "text": "Home.jsp" }, { "code": null, "e": 20142, "s": 20032, "text": "To insert the details, click on Insert data. On clicking, redirects to Insert.jsp page and displays below UI." }, { "code": null, "e": 20153, "s": 20142, "text": "Insert.jsp" }, { "code": null, "e": 20201, "s": 20153, "text": "Enter all the details and click on Insert Data." }, { "code": null, "e": 20280, "s": 20201, "text": "After successful insertion, a success message will be displayed on the screen." }, { "code": null, "e": 20299, "s": 20280, "text": "Successful message" }, { "code": null, "e": 20324, "s": 20299, "text": "Return to the home page." }, { "code": null, "e": 20385, "s": 20324, "text": "Check if the data is inserted successfully in PostgreSQL DB." }, { "code": null, "e": 20395, "s": 20385, "text": "Insertion" }, { "code": null, "e": 20467, "s": 20395, "text": "To fetch the values from the DB, click on Select Data on the Home page." }, { "code": null, "e": 20478, "s": 20467, "text": "Select.jsp" }, { "code": null, "e": 20548, "s": 20478, "text": "Enter the ID which you want to fetch the details and click View data." }, { "code": null, "e": 20601, "s": 20548, "text": "The result will be displayed on the Result.jsp page." }, { "code": null, "e": 20614, "s": 20601, "text": "Student_info" }, { "code": null, "e": 20711, "s": 20614, "text": "If the data needs to be updated, click on Update Data, or if don’t just return to the home page." }, { "code": null, "e": 20772, "s": 20711, "text": "If we click on update data, redirect to the Update.jsp page." }, { "code": null, "e": 20783, "s": 20772, "text": "Update.jsp" }, { "code": null, "e": 20861, "s": 20783, "text": "Here, the Id will be displayed on the load of the page and will be read-only." }, { "code": null, "e": 20953, "s": 20861, "text": "Update the data and click on update data. After updating success message will be displayed." }, { "code": null, "e": 21000, "s": 20953, "text": "Check if the data is updated in PostgreSQL DB." }, { "code": null, "e": 21016, "s": 21000, "text": "Updated_details" }, { "code": null, "e": 21092, "s": 21016, "text": "Finally, to delete the data from DB, click on Delete data on the home page." }, { "code": null, "e": 21103, "s": 21092, "text": "Delete.jsp" }, { "code": null, "e": 21166, "s": 21103, "text": "Enter the ID which has to be deleted and click on Delete Data." }, { "code": null, "e": 21260, "s": 21166, "text": "The information will be deleted from the DB and a success message will be displayed as below." }, { "code": null, "e": 21280, "s": 21260, "text": "Deletion_successful" }, { "code": null, "e": 21327, "s": 21280, "text": "Check in the DB if the information is deleted." }, { "code": null, "e": 21350, "s": 21327, "text": "After delete operation" }, { "code": null, "e": 21458, "s": 21350, "text": "In this way, we can perform all the insert, update, delete and select operations using Servlets with JDBC. " }, { "code": null, "e": 21471, "s": 21458, "text": "java-servlet" }, { "code": null, "e": 21476, "s": 21471, "text": "JDBC" }, { "code": null, "e": 21483, "s": 21476, "text": "Picked" }, { "code": null, "e": 21488, "s": 21483, "text": "Java" }, { "code": null, "e": 21493, "s": 21488, "text": "Java" } ]
Django ModelForm – Create form from Models
16 May, 2022 Django ModelForm is a class that is used to directly convert a model into a Django form. If you’re building a database-driven app, chances are you’ll have forms that map closely to Django models. For example, a User Registration model and form would have the same quality and quantity of model fields and form fields. So instead of creating a redundant code to first create a form and then map it to the model in a view, we can directly use ModelForm. It takes as an argument the name of the model and converts it into a Django Form. Not only this, ModelForm offers a lot of methods and features which automate the entire process and help remove code redundancy. To explain the working of the project, we will use project geeksforgeeks, create a model and map it to Django forms. Refer to the following articles to check how to create a project and an app in Django. How to Create a Basic Project using MVT in Django? How to Create an App in Django ? Now when we have our project ready, create a model in geeks/models.py, Python3 # import the standard Django Model# from built-in libraryfrom django.db import models # declare a new model with a name "GeeksModel"class GeeksModel(models.Model): # fields of the model title = models.CharField(max_length = 200) description = models.TextField() last_modified = models.DateTimeField(auto_now_add = True) img = models.ImageField(upload_to = "images/") # renames the instances of the model # with their title name def __str__(self): return self.title Before we create a model let’s register our app in the main project. Go to geeksforgeeks/settings.py file and add geeks app in INSTALLED_APPS list. If we make migrations before this step it will display a message saying there are no changes made. Now, run following commands to create the model, Python manage.py makemigrations Python manage.py migrate We can check that model has been successfully created at http://127.0.0.1:8000/admin/geeks/geeksmodel/add/, To create a form directly for this model, dive into geeks/forms.py and Enter following code, Python3 # import form class from djangofrom django import forms # import GeeksModel from models.pyfrom .models import GeeksModel # create a ModelFormclass GeeksForm(forms.ModelForm): # specify the name of model to use class Meta: model = GeeksModel fields = "__all__" This form takes two arguments fields or exclude. fields – It is strongly recommended that you explicitly set all fields that should be edited in the form using the fields attribute. Failure to do so can easily lead to security problems when a form unexpectedly allows a user to set certain fields, especially when new fields are added to a model. Depending on how the form is rendered, the problem may not even be visible on the web page. Set the fields attribute to the special value ‘__all__’ to indicate that all fields in the model should be used. exclude – Set the exclude attribute of the ModelForm’s inner Meta class to a list of fields to be excluded from the form. For example: class PartialAuthorForm(ModelForm): class Meta: model = Author exclude = ['title'] Finally, to complete our MVT structure, create a view that would render the form and directly save it to the database. In geeks/views.py, Python3 from django.shortcuts import renderfrom .forms import GeeksForm def home_view(request): context ={} # create object of form form = GeeksForm(request.POST or None, request.FILES or None) # check if form data is valid if form.is_valid(): # save the form data to model form.save() context['form']= form return render(request, "home.html", context) Everything is set, Now visit http://127.0.0.1:8000/, Now you can see that every model field is mapped into a form field and displayed correspondingly. Field mappings are discussed later in this article. So now let’s try entering data into the form and check if it gets saved into the database. Hit submit and Bingo the form gets saved automatically to database. We can verify it at http://localhost:8000/admin/geeks/geeksmodel/. The generated Form class will have a form field for every model field specified, in the order specified in the fields attribute. Each model field has a corresponding default form field. For example, a CharField on a model is represented as a CharField on a form. A model ManyToManyField is represented as a MultipleChoiceField. Here is the full list of conversions: paramtwot2021 Django-forms Django-models Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n16 May, 2022" }, { "code": null, "e": 716, "s": 53, "text": "Django ModelForm is a class that is used to directly convert a model into a Django form. If you’re building a database-driven app, chances are you’ll have forms that map closely to Django models. For example, a User Registration model and form would have the same quality and quantity of model fields and form fields. So instead of creating a redundant code to first create a form and then map it to the model in a view, we can directly use ModelForm. It takes as an argument the name of the model and converts it into a Django Form. Not only this, ModelForm offers a lot of methods and features which automate the entire process and help remove code redundancy." }, { "code": null, "e": 833, "s": 716, "text": "To explain the working of the project, we will use project geeksforgeeks, create a model and map it to Django forms." }, { "code": null, "e": 920, "s": 833, "text": "Refer to the following articles to check how to create a project and an app in Django." }, { "code": null, "e": 971, "s": 920, "text": "How to Create a Basic Project using MVT in Django?" }, { "code": null, "e": 1004, "s": 971, "text": "How to Create an App in Django ?" }, { "code": null, "e": 1076, "s": 1004, "text": "Now when we have our project ready, create a model in geeks/models.py, " }, { "code": null, "e": 1084, "s": 1076, "text": "Python3" }, { "code": "# import the standard Django Model# from built-in libraryfrom django.db import models # declare a new model with a name \"GeeksModel\"class GeeksModel(models.Model): # fields of the model title = models.CharField(max_length = 200) description = models.TextField() last_modified = models.DateTimeField(auto_now_add = True) img = models.ImageField(upload_to = \"images/\") # renames the instances of the model # with their title name def __str__(self): return self.title", "e": 1595, "s": 1084, "text": null }, { "code": null, "e": 1843, "s": 1595, "text": "Before we create a model let’s register our app in the main project. Go to geeksforgeeks/settings.py file and add geeks app in INSTALLED_APPS list. If we make migrations before this step it will display a message saying there are no changes made. " }, { "code": null, "e": 1892, "s": 1843, "text": "Now, run following commands to create the model," }, { "code": null, "e": 1949, "s": 1892, "text": "Python manage.py makemigrations\nPython manage.py migrate" }, { "code": null, "e": 2152, "s": 1949, "text": "We can check that model has been successfully created at http://127.0.0.1:8000/admin/geeks/geeksmodel/add/, To create a form directly for this model, dive into geeks/forms.py and Enter following code, " }, { "code": null, "e": 2160, "s": 2152, "text": "Python3" }, { "code": "# import form class from djangofrom django import forms # import GeeksModel from models.pyfrom .models import GeeksModel # create a ModelFormclass GeeksForm(forms.ModelForm): # specify the name of model to use class Meta: model = GeeksModel fields = \"__all__\"", "e": 2440, "s": 2160, "text": null }, { "code": null, "e": 2489, "s": 2440, "text": "This form takes two arguments fields or exclude." }, { "code": null, "e": 2992, "s": 2489, "text": "fields – It is strongly recommended that you explicitly set all fields that should be edited in the form using the fields attribute. Failure to do so can easily lead to security problems when a form unexpectedly allows a user to set certain fields, especially when new fields are added to a model. Depending on how the form is rendered, the problem may not even be visible on the web page. Set the fields attribute to the special value ‘__all__’ to indicate that all fields in the model should be used." }, { "code": null, "e": 3127, "s": 2992, "text": "exclude – Set the exclude attribute of the ModelForm’s inner Meta class to a list of fields to be excluded from the form. For example:" }, { "code": null, "e": 3230, "s": 3127, "text": "class PartialAuthorForm(ModelForm):\n class Meta:\n model = Author\n exclude = ['title']" }, { "code": null, "e": 3369, "s": 3230, "text": "Finally, to complete our MVT structure, create a view that would render the form and directly save it to the database. In geeks/views.py, " }, { "code": null, "e": 3377, "s": 3369, "text": "Python3" }, { "code": "from django.shortcuts import renderfrom .forms import GeeksForm def home_view(request): context ={} # create object of form form = GeeksForm(request.POST or None, request.FILES or None) # check if form data is valid if form.is_valid(): # save the form data to model form.save() context['form']= form return render(request, \"home.html\", context)", "e": 3764, "s": 3377, "text": null }, { "code": null, "e": 4060, "s": 3764, "text": "Everything is set, Now visit http://127.0.0.1:8000/, Now you can see that every model field is mapped into a form field and displayed correspondingly. Field mappings are discussed later in this article. So now let’s try entering data into the form and check if it gets saved into the database. " }, { "code": null, "e": 4196, "s": 4060, "text": "Hit submit and Bingo the form gets saved automatically to database. We can verify it at http://localhost:8000/admin/geeks/geeksmodel/. " }, { "code": null, "e": 4562, "s": 4196, "text": "The generated Form class will have a form field for every model field specified, in the order specified in the fields attribute. Each model field has a corresponding default form field. For example, a CharField on a model is represented as a CharField on a form. A model ManyToManyField is represented as a MultipleChoiceField. Here is the full list of conversions:" }, { "code": null, "e": 4576, "s": 4562, "text": "paramtwot2021" }, { "code": null, "e": 4589, "s": 4576, "text": "Django-forms" }, { "code": null, "e": 4603, "s": 4589, "text": "Django-models" }, { "code": null, "e": 4617, "s": 4603, "text": "Python Django" }, { "code": null, "e": 4624, "s": 4617, "text": "Python" } ]
Batch Script - DATE and TIME
The date and time in DOS Scripting have the following two basic commands for retrieving the date and time of the system. This command gets the system date. DATE @echo off echo %DATE% The current date will be displayed in the command prompt. For example, Mon 12/28/2015 This command sets or displays the time. TIME @echo off echo %TIME% The current system time will be displayed. For example, 22:06:52.87 Following are some implementations which can be used to get the date and time in different formats. @echo off echo/Today is: %year%-%month%-%day% goto :EOF setlocal ENABLEEXTENSIONS set t = 2&if "%date%z" LSS "A" set t = 1 for /f "skip=1 tokens = 2-4 delims = (-)" %%a in ('echo/^|date') do ( for /f "tokens = %t%-4 delims=.-/ " %%d in ('date/t') do ( set %%a=%%d&set %%b=%%e&set %%c=%%f)) endlocal&set %1=%yy%&set %2=%mm%&set %3=%dd%&goto :EOF The above command produces the following output. Today is: 2015-12-30 Print Add Notes Bookmark this page
[ { "code": null, "e": 2290, "s": 2169, "text": "The date and time in DOS Scripting have the following two basic commands for retrieving the date and time of the system." }, { "code": null, "e": 2325, "s": 2290, "text": "This command gets the system date." }, { "code": null, "e": 2331, "s": 2325, "text": "DATE\n" }, { "code": null, "e": 2354, "s": 2331, "text": "@echo off \necho %DATE%" }, { "code": null, "e": 2425, "s": 2354, "text": "The current date will be displayed in the command prompt. For example," }, { "code": null, "e": 2441, "s": 2425, "text": "Mon 12/28/2015\n" }, { "code": null, "e": 2481, "s": 2441, "text": "This command sets or displays the time." }, { "code": null, "e": 2487, "s": 2481, "text": "TIME\n" }, { "code": null, "e": 2510, "s": 2487, "text": "@echo off \necho %TIME%" }, { "code": null, "e": 2566, "s": 2510, "text": "The current system time will be displayed. For example," }, { "code": null, "e": 2579, "s": 2566, "text": "22:06:52.87\n" }, { "code": null, "e": 2679, "s": 2579, "text": "Following are some implementations which can be used to get the date and time in different formats." }, { "code": null, "e": 3042, "s": 2679, "text": "@echo off \necho/Today is: %year%-%month%-%day% \ngoto :EOF \nsetlocal ENABLEEXTENSIONS \nset t = 2&if \"%date%z\" LSS \"A\" set t = 1 \n\nfor /f \"skip=1 tokens = 2-4 delims = (-)\" %%a in ('echo/^|date') do ( \n for /f \"tokens = %t%-4 delims=.-/ \" %%d in ('date/t') do ( \n set %%a=%%d&set %%b=%%e&set %%c=%%f)) \nendlocal&set %1=%yy%&set %2=%mm%&set %3=%dd%&goto :EOF" }, { "code": null, "e": 3091, "s": 3042, "text": "The above command produces the following output." }, { "code": null, "e": 3113, "s": 3091, "text": "Today is: 2015-12-30\n" }, { "code": null, "e": 3120, "s": 3113, "text": " Print" }, { "code": null, "e": 3131, "s": 3120, "text": " Add Notes" } ]
Circular rotation of an array using deque in C++ - GeeksforGeeks
23 Sep, 2019 Given an array arr[] of integers and another integer D, the task is to perform D circular rotations on the array and print the modified array. Examples: Input: Arr[] = {1, 2, 3, 4, 5, 6}, D = 2Output: 5 6 1 2 3 4 Input: Arr[] = {1, 2, 3}, D = 2Output: 2 3 1 Approach:Using Deque in C++, a rotation can be performed deleting the last element from the deque and inserting it at the beginning of the same deque. Similarly, all the required rotations can be performed and then print the contents of the modified deque to get the required rotated array. If the number of rotations is more than the size of the deque then just take the mod with N, So, D = D%N.Where D is the number of rotations and N is the size of the deque. Below is the implementation of the above approach: // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to circular rotate// the array by d elementsvoid rotate(deque<int> deq, int d, int n){ // Push first d elements // from last to the beginning for (int i = 0; i < d; i++) { int val = deq.back(); deq.pop_back(); deq.push_front(val); } // Print the rotated array for (int i = 0; i < n; i++) { cout << deq[i] << " "; } cout << endl;} // Driver codeint main(){ deque<int> v = { 1, 2, 3, 4, 5, 6, 7 }; int n = v.size(); int d = 5; rotate(v, d % n, n);} 3 4 5 6 7 1 2 cpp-deque rotation Arrays Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Chocolate Distribution Problem Reversal algorithm for array rotation Window Sliding Technique Next Greater Element Find duplicates in O(n) time and O(1) extra space | Set 1 Building Heap from Array Remove duplicates from sorted array Count pairs with given sum Find subarray with given sum | Set 1 (Nonnegative Numbers) Trapping Rain Water
[ { "code": null, "e": 26175, "s": 26147, "text": "\n23 Sep, 2019" }, { "code": null, "e": 26318, "s": 26175, "text": "Given an array arr[] of integers and another integer D, the task is to perform D circular rotations on the array and print the modified array." }, { "code": null, "e": 26328, "s": 26318, "text": "Examples:" }, { "code": null, "e": 26388, "s": 26328, "text": "Input: Arr[] = {1, 2, 3, 4, 5, 6}, D = 2Output: 5 6 1 2 3 4" }, { "code": null, "e": 26433, "s": 26388, "text": "Input: Arr[] = {1, 2, 3}, D = 2Output: 2 3 1" }, { "code": null, "e": 26584, "s": 26433, "text": "Approach:Using Deque in C++, a rotation can be performed deleting the last element from the deque and inserting it at the beginning of the same deque." }, { "code": null, "e": 26724, "s": 26584, "text": "Similarly, all the required rotations can be performed and then print the contents of the modified deque to get the required rotated array." }, { "code": null, "e": 26896, "s": 26724, "text": "If the number of rotations is more than the size of the deque then just take the mod with N, So, D = D%N.Where D is the number of rotations and N is the size of the deque." }, { "code": null, "e": 26947, "s": 26896, "text": "Below is the implementation of the above approach:" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to circular rotate// the array by d elementsvoid rotate(deque<int> deq, int d, int n){ // Push first d elements // from last to the beginning for (int i = 0; i < d; i++) { int val = deq.back(); deq.pop_back(); deq.push_front(val); } // Print the rotated array for (int i = 0; i < n; i++) { cout << deq[i] << \" \"; } cout << endl;} // Driver codeint main(){ deque<int> v = { 1, 2, 3, 4, 5, 6, 7 }; int n = v.size(); int d = 5; rotate(v, d % n, n);}", "e": 27569, "s": 26947, "text": null }, { "code": null, "e": 27584, "s": 27569, "text": "3 4 5 6 7 1 2\n" }, { "code": null, "e": 27594, "s": 27584, "text": "cpp-deque" }, { "code": null, "e": 27603, "s": 27594, "text": "rotation" }, { "code": null, "e": 27610, "s": 27603, "text": "Arrays" }, { "code": null, "e": 27617, "s": 27610, "text": "Arrays" }, { "code": null, "e": 27715, "s": 27617, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27746, "s": 27715, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 27784, "s": 27746, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 27809, "s": 27784, "text": "Window Sliding Technique" }, { "code": null, "e": 27830, "s": 27809, "text": "Next Greater Element" }, { "code": null, "e": 27888, "s": 27830, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 27913, "s": 27888, "text": "Building Heap from Array" }, { "code": null, "e": 27949, "s": 27913, "text": "Remove duplicates from sorted array" }, { "code": null, "e": 27976, "s": 27949, "text": "Count pairs with given sum" }, { "code": null, "e": 28035, "s": 27976, "text": "Find subarray with given sum | Set 1 (Nonnegative Numbers)" } ]
Depth of an N-Ary tree - GeeksforGeeks
28 Jun, 2021 Given an N-Ary tree, find depth of the tree. An N-Ary tree is a tree in which nodes can have at most N children.Examples: Example 1: Example 2: N-Ary tree can be traversed just like a normal tree. We just have to consider all childs of a given node and recursively call that function on every node. C++ Java C# Javascript // C++ program to find the height of// an N-ary tree#include <bits/stdc++.h>using namespace std; // Structure of a node of an n-ary treestruct Node{ char key; vector<Node *> child;}; // Utility function to create a new tree nodeNode *newNode(int key){ Node *temp = new Node; temp->key = key; return temp;} // Function that will return the depth// of the treeint depthOfTree(struct Node *ptr){ // Base case if (!ptr) return 0; // Check for all children and find // the maximum depth int maxdepth = 0; for (vector<Node*>::iterator it = ptr->child.begin(); it != ptr->child.end(); it++) maxdepth = max(maxdepth, depthOfTree(*it)); return maxdepth + 1 ;} // Driver programint main(){ /* Let us create below tree * A * / / \ \ * B F D E * / \ | /|\ * K J G C H I * /\ \ * N M L */ Node *root = newNode('A'); (root->child).push_back(newNode('B')); (root->child).push_back(newNode('F')); (root->child).push_back(newNode('D')); (root->child).push_back(newNode('E')); (root->child[0]->child).push_back(newNode('K')); (root->child[0]->child).push_back(newNode('J')); (root->child[2]->child).push_back(newNode('G')); (root->child[3]->child).push_back(newNode('C')); (root->child[3]->child).push_back(newNode('H')); (root->child[3]->child).push_back(newNode('I')); (root->child[0]->child[0]->child).push_back(newNode('N')); (root->child[0]->child[0]->child).push_back(newNode('M')); (root->child[3]->child[2]->child).push_back(newNode('L')); cout << depthOfTree(root) << endl; return 0;} // Java program to find the height of// an N-ary treeimport java.util.*; class GFG{ // Structure of a node of an n-ary treestatic class Node{ char key; Vector<Node > child;}; // Utility function to create a new tree nodestatic Node newNode(int key){ Node temp = new Node(); temp.key = (char) key; temp.child = new Vector<Node>(); return temp;} // Function that will return the depth// of the treestatic int depthOfTree(Node ptr){ // Base case if (ptr == null) return 0; // Check for all children and find // the maximum depth int maxdepth = 0; for (Node it : ptr.child) maxdepth = Math.max(maxdepth, depthOfTree(it)); return maxdepth + 1 ;} // Driver Codepublic static void main(String[] args){ /* Let us create below tree * A * / / \ \ * B F D E * / \ | /|\ * K J G C H I * /\ \ * N M L */ Node root = newNode('A'); (root.child).add(newNode('B')); (root.child).add(newNode('F')); (root.child).add(newNode('D')); (root.child).add(newNode('E')); (root.child.get(0).child).add(newNode('K')); (root.child.get(0).child).add(newNode('J')); (root.child.get(2).child).add(newNode('G')); (root.child.get(3).child).add(newNode('C')); (root.child.get(3).child).add(newNode('H')); (root.child.get(3).child).add(newNode('I')); (root.child.get(0).child.get(0).child).add(newNode('N')); (root.child.get(0).child.get(0).child).add(newNode('M')); (root.child.get(3).child.get(2).child).add(newNode('L')); System.out.print(depthOfTree(root) + "\n");}} // This code is contributed by Rajput-Ji // C# program to find the height of// an N-ary treeusing System;using System.Collections.Generic; class GFG{ // Structure of a node of an n-ary treepublic class Node{ public char key; public List<Node > child;}; // Utility function to create a new tree nodestatic Node newNode(int key){ Node temp = new Node(); temp.key = (char) key; temp.child = new List<Node>(); return temp;} // Function that will return the depth// of the treestatic int depthOfTree(Node ptr){ // Base case if (ptr == null) return 0; // Check for all children and find // the maximum depth int maxdepth = 0; foreach (Node it in ptr.child) maxdepth = Math.Max(maxdepth, depthOfTree(it)); return maxdepth + 1 ;} // Driver Codepublic static void Main(String[] args){ /* Let us create below tree * A * / / \ \ * B F D E * / \ | /|\ * K J G C H I * /\ \ * N M L */ Node root = newNode('A'); (root.child).Add(newNode('B')); (root.child).Add(newNode('F')); (root.child).Add(newNode('D')); (root.child).Add(newNode('E')); (root.child[0].child).Add(newNode('K')); (root.child[0].child).Add(newNode('J')); (root.child[2].child).Add(newNode('G')); (root.child[3].child).Add(newNode('C')); (root.child[3].child).Add(newNode('H')); (root.child[3].child).Add(newNode('I')); (root.child[0].child[0].child).Add(newNode('N')); (root.child[0].child[0].child).Add(newNode('M')); (root.child[3].child[2].child).Add(newNode('L')); Console.Write(depthOfTree(root) + "\n");}} // This code is contributed by Rajput-Ji <script> // JavaScript program to find the height of// an N-ary tree // Structure of a node of an n-ary treeclass Node{ constructor() { this.key = 0; this.child = []; }}; // Utility function to create a new tree nodefunction newNode(key){ var temp = new Node(); temp.key = key; temp.child = []; return temp;} // Function that will return the depth// of the treefunction depthOfTree(ptr){ // Base case if (ptr == null) return 0; // Check for all children and find // the maximum depth var maxdepth = 0; for(var it of ptr.child) maxdepth = Math.max(maxdepth, depthOfTree(it)); return maxdepth + 1 ;} // Driver Code /* Let us create below tree* A* / / \ \* B F D E* / \ | /|\* K J G C H I* /\ \* N M L*/var root = newNode('A');(root.child).push(newNode('B'));(root.child).push(newNode('F'));(root.child).push(newNode('D'));(root.child).push(newNode('E'));(root.child[0].child).push(newNode('K'));(root.child[0].child).push(newNode('J'));(root.child[2].child).push(newNode('G'));(root.child[3].child).push(newNode('C'));(root.child[3].child).push(newNode('H'));(root.child[3].child).push(newNode('I'));(root.child[0].child[0].child).push(newNode('N'));(root.child[0].child[0].child).push(newNode('M'));(root.child[3].child[2].child).push(newNode('L'));document.write(depthOfTree(root) + "<br>"); </script> Output: 4 YouTubeGeeksforGeeks507K subscribersDepth of an N-Ary tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:40•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=x_hJLIOIqa8" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is contributed by Shubham Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Rajput-Ji itsok n-ary-tree Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Binary Tree | Set 3 (Types of Binary Tree) Binary Tree | Set 2 (Properties) Decision Tree A program to check if a binary tree is BST or not Introduction to Tree Data Structure Expression Tree Lowest Common Ancestor in a Binary Tree | Set 1 Complexity of different operations in Binary tree, Binary Search Tree and AVL tree Deletion in a Binary Tree Binary Tree (Array implementation)
[ { "code": null, "e": 26287, "s": 26259, "text": "\n28 Jun, 2021" }, { "code": null, "e": 26422, "s": 26287, "text": "Given an N-Ary tree, find depth of the tree. An N-Ary tree is a tree in which nodes can have at most N children.Examples: Example 1: " }, { "code": null, "e": 26435, "s": 26422, "text": "Example 2: " }, { "code": null, "e": 26594, "s": 26437, "text": "N-Ary tree can be traversed just like a normal tree. We just have to consider all childs of a given node and recursively call that function on every node. " }, { "code": null, "e": 26598, "s": 26594, "text": "C++" }, { "code": null, "e": 26603, "s": 26598, "text": "Java" }, { "code": null, "e": 26606, "s": 26603, "text": "C#" }, { "code": null, "e": 26617, "s": 26606, "text": "Javascript" }, { "code": "// C++ program to find the height of// an N-ary tree#include <bits/stdc++.h>using namespace std; // Structure of a node of an n-ary treestruct Node{ char key; vector<Node *> child;}; // Utility function to create a new tree nodeNode *newNode(int key){ Node *temp = new Node; temp->key = key; return temp;} // Function that will return the depth// of the treeint depthOfTree(struct Node *ptr){ // Base case if (!ptr) return 0; // Check for all children and find // the maximum depth int maxdepth = 0; for (vector<Node*>::iterator it = ptr->child.begin(); it != ptr->child.end(); it++) maxdepth = max(maxdepth, depthOfTree(*it)); return maxdepth + 1 ;} // Driver programint main(){ /* Let us create below tree * A * / / \\ \\ * B F D E * / \\ | /|\\ * K J G C H I * /\\ \\ * N M L */ Node *root = newNode('A'); (root->child).push_back(newNode('B')); (root->child).push_back(newNode('F')); (root->child).push_back(newNode('D')); (root->child).push_back(newNode('E')); (root->child[0]->child).push_back(newNode('K')); (root->child[0]->child).push_back(newNode('J')); (root->child[2]->child).push_back(newNode('G')); (root->child[3]->child).push_back(newNode('C')); (root->child[3]->child).push_back(newNode('H')); (root->child[3]->child).push_back(newNode('I')); (root->child[0]->child[0]->child).push_back(newNode('N')); (root->child[0]->child[0]->child).push_back(newNode('M')); (root->child[3]->child[2]->child).push_back(newNode('L')); cout << depthOfTree(root) << endl; return 0;}", "e": 28306, "s": 26617, "text": null }, { "code": "// Java program to find the height of// an N-ary treeimport java.util.*; class GFG{ // Structure of a node of an n-ary treestatic class Node{ char key; Vector<Node > child;}; // Utility function to create a new tree nodestatic Node newNode(int key){ Node temp = new Node(); temp.key = (char) key; temp.child = new Vector<Node>(); return temp;} // Function that will return the depth// of the treestatic int depthOfTree(Node ptr){ // Base case if (ptr == null) return 0; // Check for all children and find // the maximum depth int maxdepth = 0; for (Node it : ptr.child) maxdepth = Math.max(maxdepth, depthOfTree(it)); return maxdepth + 1 ;} // Driver Codepublic static void main(String[] args){ /* Let us create below tree * A * / / \\ \\ * B F D E * / \\ | /|\\ * K J G C H I * /\\ \\ * N M L */ Node root = newNode('A'); (root.child).add(newNode('B')); (root.child).add(newNode('F')); (root.child).add(newNode('D')); (root.child).add(newNode('E')); (root.child.get(0).child).add(newNode('K')); (root.child.get(0).child).add(newNode('J')); (root.child.get(2).child).add(newNode('G')); (root.child.get(3).child).add(newNode('C')); (root.child.get(3).child).add(newNode('H')); (root.child.get(3).child).add(newNode('I')); (root.child.get(0).child.get(0).child).add(newNode('N')); (root.child.get(0).child.get(0).child).add(newNode('M')); (root.child.get(3).child.get(2).child).add(newNode('L')); System.out.print(depthOfTree(root) + \"\\n\");}} // This code is contributed by Rajput-Ji", "e": 29998, "s": 28306, "text": null }, { "code": "// C# program to find the height of// an N-ary treeusing System;using System.Collections.Generic; class GFG{ // Structure of a node of an n-ary treepublic class Node{ public char key; public List<Node > child;}; // Utility function to create a new tree nodestatic Node newNode(int key){ Node temp = new Node(); temp.key = (char) key; temp.child = new List<Node>(); return temp;} // Function that will return the depth// of the treestatic int depthOfTree(Node ptr){ // Base case if (ptr == null) return 0; // Check for all children and find // the maximum depth int maxdepth = 0; foreach (Node it in ptr.child) maxdepth = Math.Max(maxdepth, depthOfTree(it)); return maxdepth + 1 ;} // Driver Codepublic static void Main(String[] args){ /* Let us create below tree * A * / / \\ \\ * B F D E * / \\ | /|\\ * K J G C H I * /\\ \\ * N M L */ Node root = newNode('A'); (root.child).Add(newNode('B')); (root.child).Add(newNode('F')); (root.child).Add(newNode('D')); (root.child).Add(newNode('E')); (root.child[0].child).Add(newNode('K')); (root.child[0].child).Add(newNode('J')); (root.child[2].child).Add(newNode('G')); (root.child[3].child).Add(newNode('C')); (root.child[3].child).Add(newNode('H')); (root.child[3].child).Add(newNode('I')); (root.child[0].child[0].child).Add(newNode('N')); (root.child[0].child[0].child).Add(newNode('M')); (root.child[3].child[2].child).Add(newNode('L')); Console.Write(depthOfTree(root) + \"\\n\");}} // This code is contributed by Rajput-Ji", "e": 31679, "s": 29998, "text": null }, { "code": "<script> // JavaScript program to find the height of// an N-ary tree // Structure of a node of an n-ary treeclass Node{ constructor() { this.key = 0; this.child = []; }}; // Utility function to create a new tree nodefunction newNode(key){ var temp = new Node(); temp.key = key; temp.child = []; return temp;} // Function that will return the depth// of the treefunction depthOfTree(ptr){ // Base case if (ptr == null) return 0; // Check for all children and find // the maximum depth var maxdepth = 0; for(var it of ptr.child) maxdepth = Math.max(maxdepth, depthOfTree(it)); return maxdepth + 1 ;} // Driver Code /* Let us create below tree* A* / / \\ \\* B F D E* / \\ | /|\\* K J G C H I* /\\ \\* N M L*/var root = newNode('A');(root.child).push(newNode('B'));(root.child).push(newNode('F'));(root.child).push(newNode('D'));(root.child).push(newNode('E'));(root.child[0].child).push(newNode('K'));(root.child[0].child).push(newNode('J'));(root.child[2].child).push(newNode('G'));(root.child[3].child).push(newNode('C'));(root.child[3].child).push(newNode('H'));(root.child[3].child).push(newNode('I'));(root.child[0].child[0].child).push(newNode('N'));(root.child[0].child[0].child).push(newNode('M'));(root.child[3].child[2].child).push(newNode('L'));document.write(depthOfTree(root) + \"<br>\"); </script>", "e": 33134, "s": 31679, "text": null }, { "code": null, "e": 33144, "s": 33134, "text": "Output: " }, { "code": null, "e": 33146, "s": 33144, "text": "4" }, { "code": null, "e": 33969, "s": 33148, "text": "YouTubeGeeksforGeeks507K subscribersDepth of an N-Ary tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:40•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=x_hJLIOIqa8\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 34391, "s": 33969, "text": "This article is contributed by Shubham Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 34401, "s": 34391, "text": "Rajput-Ji" }, { "code": null, "e": 34407, "s": 34401, "text": "itsok" }, { "code": null, "e": 34418, "s": 34407, "text": "n-ary-tree" }, { "code": null, "e": 34423, "s": 34418, "text": "Tree" }, { "code": null, "e": 34428, "s": 34423, "text": "Tree" }, { "code": null, "e": 34526, "s": 34428, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34569, "s": 34526, "text": "Binary Tree | Set 3 (Types of Binary Tree)" }, { "code": null, "e": 34602, "s": 34569, "text": "Binary Tree | Set 2 (Properties)" }, { "code": null, "e": 34616, "s": 34602, "text": "Decision Tree" }, { "code": null, "e": 34666, "s": 34616, "text": "A program to check if a binary tree is BST or not" }, { "code": null, "e": 34702, "s": 34666, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 34718, "s": 34702, "text": "Expression Tree" }, { "code": null, "e": 34766, "s": 34718, "text": "Lowest Common Ancestor in a Binary Tree | Set 1" }, { "code": null, "e": 34849, "s": 34766, "text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree" }, { "code": null, "e": 34875, "s": 34849, "text": "Deletion in a Binary Tree" } ]
How to bind an array to an IN() condition in PHP ? - GeeksforGeeks
20 May, 2020 Given a database containing some data and the task is to bind a PHP array to it by using MySQL IN() operator. Here we will look at a program that does the needful by taking a PHP array within the query and interpreting it. SQL IN() Operator: The SQL IN() operator allows you to pass multiple arguments in the where clause. It is often used as the shorthand for multiple OR statements. Syntax: SELECT <column_name(s)> FROM <table_name> WHERE <column_name> IN( value1, value2, ...); PHP implode() function: We will be using PHP predefined function implode() to deal with the array. The implode() function joins the array elements with a string. It requires two parameters to carry out the same. First is the string that will be used to join the array elements that can also be referred to as a glue string. Since it will be used to glue the elements together. Second is obviously the array on which the operation is required to be performed. Syntax: string implode(separator, array) Array Binding: As per our need, we simply need to bind the PHP array to IN() clause and to obtain this functionality, we first need to convert the given array to the form acceptable by the IN() clause, which is a job carried out by PHP implode() function. Also, keep in mind that by passing our array to the function, we are just converting the array in the form acceptable by IN() but it still is the same array. The following program will help you understand the concept practically and more carefully: Used DataBase: Here, we will use a database (database name: Geeks) to bind an array to an IN() condition in PHP. Table name: GFG The table name GFG contains the following information. Program 1: The following code takes PHP array of IDs from the GFG table and passes it to IN() operator to retrieve names, corresponding to given IDs. <?php // Connecting to the server$server = 'localhost';$username = 'root';$password = '';$dbname = 'Geeks'; // Declare and initialize an// array that need to be// passed to IN() operator$arr = array(1, 2, 3, 4, 5); // Joining array elements using// implode() function$ids = implode(', ', $arr); $conn = new mysqli($server, $username, $password, $dbname); // SQL query to pass the array $sql = ('SELECT NAME FROM GFG WHERE ID IN ('.$ids.')' ); $result = $conn->query($sql); if($result->num_rows > 0) { while($row = $result->fetch_assoc()) { echo $row['NAME'] . "<br>"; }} else { echo "0 results";} $conn->close(); ?> Output: MEGAN GINA DARVY DEBBY MICHEL Program 2: The following code uses the same information table but retrieves ID corresponding to the names given in the array. <?php // Connecting to server$server = 'localhost';$username = 'root';$password = '';$dbname = 'Geeks'; // Declare and initialize an// array that need to be// passed to IN() operator$arr = array("MEGAN", "TIM"); // Joining array elements using// implode() function$names = implode('\', \'', $arr); // Since array elements to be// searched, here are string// making it look like a string// so that sql can easily// interpret it$fin = "'" . $names . "'"; $conn = new mysqli($server, $username, $password, $dbname); // SQL query to pass the array $sql=('SELECT ID FROM GFG WHERE NAME IN ('.$fin.')' ); $result = $conn->query($sql); if($result->num_rows > 0) { while($row = $result->fetch_assoc()){ echo $row['ID'] . "<br>"; }} else { echo "0 results";} $conn->close(); ?> Output: 1 10 PHP-Misc Picked PHP PHP Programs Web Technologies Web technologies Questions PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to fetch data from localserver database and display on HTML table using PHP ? PHP str_replace() Function How to create admin login page using PHP? Different ways for passing data to view in Laravel Create a drop-down list that options fetched from a MySQL database in PHP How to call PHP function on the click of a Button ? How to fetch data from localserver database and display on HTML table using PHP ? How to create admin login page using PHP? How to pass form variables from one page to other page in PHP ? PHP | Ternary Operator
[ { "code": null, "e": 26327, "s": 26299, "text": "\n20 May, 2020" }, { "code": null, "e": 26550, "s": 26327, "text": "Given a database containing some data and the task is to bind a PHP array to it by using MySQL IN() operator. Here we will look at a program that does the needful by taking a PHP array within the query and interpreting it." }, { "code": null, "e": 26712, "s": 26550, "text": "SQL IN() Operator: The SQL IN() operator allows you to pass multiple arguments in the where clause. It is often used as the shorthand for multiple OR statements." }, { "code": null, "e": 26720, "s": 26712, "text": "Syntax:" }, { "code": null, "e": 26808, "s": 26720, "text": "SELECT <column_name(s)>\nFROM <table_name>\nWHERE <column_name> IN( value1, value2, ...);" }, { "code": null, "e": 27267, "s": 26808, "text": "PHP implode() function: We will be using PHP predefined function implode() to deal with the array. The implode() function joins the array elements with a string. It requires two parameters to carry out the same. First is the string that will be used to join the array elements that can also be referred to as a glue string. Since it will be used to glue the elements together. Second is obviously the array on which the operation is required to be performed." }, { "code": null, "e": 27275, "s": 27267, "text": "Syntax:" }, { "code": null, "e": 27308, "s": 27275, "text": "string implode(separator, array)" }, { "code": null, "e": 27722, "s": 27308, "text": "Array Binding: As per our need, we simply need to bind the PHP array to IN() clause and to obtain this functionality, we first need to convert the given array to the form acceptable by the IN() clause, which is a job carried out by PHP implode() function. Also, keep in mind that by passing our array to the function, we are just converting the array in the form acceptable by IN() but it still is the same array." }, { "code": null, "e": 27813, "s": 27722, "text": "The following program will help you understand the concept practically and more carefully:" }, { "code": null, "e": 27926, "s": 27813, "text": "Used DataBase: Here, we will use a database (database name: Geeks) to bind an array to an IN() condition in PHP." }, { "code": null, "e": 27997, "s": 27926, "text": "Table name: GFG The table name GFG contains the following information." }, { "code": null, "e": 28147, "s": 27997, "text": "Program 1: The following code takes PHP array of IDs from the GFG table and passes it to IN() operator to retrieve names, corresponding to given IDs." }, { "code": "<?php // Connecting to the server$server = 'localhost';$username = 'root';$password = '';$dbname = 'Geeks'; // Declare and initialize an// array that need to be// passed to IN() operator$arr = array(1, 2, 3, 4, 5); // Joining array elements using// implode() function$ids = implode(', ', $arr); $conn = new mysqli($server, $username, $password, $dbname); // SQL query to pass the array $sql = ('SELECT NAME FROM GFG WHERE ID IN ('.$ids.')' ); $result = $conn->query($sql); if($result->num_rows > 0) { while($row = $result->fetch_assoc()) { echo $row['NAME'] . \"<br>\"; }} else { echo \"0 results\";} $conn->close(); ?>", "e": 28808, "s": 28147, "text": null }, { "code": null, "e": 28816, "s": 28808, "text": "Output:" }, { "code": null, "e": 28846, "s": 28816, "text": "MEGAN\nGINA\nDARVY\nDEBBY\nMICHEL" }, { "code": null, "e": 28972, "s": 28846, "text": "Program 2: The following code uses the same information table but retrieves ID corresponding to the names given in the array." }, { "code": "<?php // Connecting to server$server = 'localhost';$username = 'root';$password = '';$dbname = 'Geeks'; // Declare and initialize an// array that need to be// passed to IN() operator$arr = array(\"MEGAN\", \"TIM\"); // Joining array elements using// implode() function$names = implode('\\', \\'', $arr); // Since array elements to be// searched, here are string// making it look like a string// so that sql can easily// interpret it$fin = \"'\" . $names . \"'\"; $conn = new mysqli($server, $username, $password, $dbname); // SQL query to pass the array $sql=('SELECT ID FROM GFG WHERE NAME IN ('.$fin.')' ); $result = $conn->query($sql); if($result->num_rows > 0) { while($row = $result->fetch_assoc()){ echo $row['ID'] . \"<br>\"; }} else { echo \"0 results\";} $conn->close(); ?>", "e": 29790, "s": 28972, "text": null }, { "code": null, "e": 29798, "s": 29790, "text": "Output:" }, { "code": null, "e": 29803, "s": 29798, "text": "1\n10" }, { "code": null, "e": 29812, "s": 29803, "text": "PHP-Misc" }, { "code": null, "e": 29819, "s": 29812, "text": "Picked" }, { "code": null, "e": 29823, "s": 29819, "text": "PHP" }, { "code": null, "e": 29836, "s": 29823, "text": "PHP Programs" }, { "code": null, "e": 29853, "s": 29836, "text": "Web Technologies" }, { "code": null, "e": 29880, "s": 29853, "text": "Web technologies Questions" }, { "code": null, "e": 29884, "s": 29880, "text": "PHP" }, { "code": null, "e": 29982, "s": 29884, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30064, "s": 29982, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 30091, "s": 30064, "text": "PHP str_replace() Function" }, { "code": null, "e": 30133, "s": 30091, "text": "How to create admin login page using PHP?" }, { "code": null, "e": 30184, "s": 30133, "text": "Different ways for passing data to view in Laravel" }, { "code": null, "e": 30258, "s": 30184, "text": "Create a drop-down list that options fetched from a MySQL database in PHP" }, { "code": null, "e": 30310, "s": 30258, "text": "How to call PHP function on the click of a Button ?" }, { "code": null, "e": 30392, "s": 30310, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 30434, "s": 30392, "text": "How to create admin login page using PHP?" }, { "code": null, "e": 30498, "s": 30434, "text": "How to pass form variables from one page to other page in PHP ?" } ]
Difference between tellg and tellp in C++ - GeeksforGeeks
23 Mar, 2021 In this article, we will discuss the functionality of basic_istream<>::tellg and basic_ostream<>::tellp and the difference between them. tellg(): The function is defined in the istream class, and used with input streams. It returns the position of the current character in the input stream. Syntax: pos_type tellg(); Return Type: If the pointer points to a valid position, then this function returns the current position of the get pointer. Otherwise, it returns “-1”. Program 1: Below is the C++ program to illustrate the use of tellg(): C++ // C++ program to illustrate the// use of tellg()#include <fstream>#include <iostream>using namespace std; // Driver Codeint main(){ ifstream fin; char ch; // Opens the existing file fin.open("gfg.text"); int pos; pos = fin.tellg(); cout << pos; fin >> ch; pos = fin.tellg(); cout << pos; fin >> ch; pos = fin.tellg(); cout << pos; return 0;} Input File: gfg.text hello students Output: tellp(): The function is defined in the ostream class, and used with output streams. It returns the position of the current character in the output stream where the character can be placed. Syntax: pos_type tellp(); Return Type: If the pointer points to a valid position, then this function returns the current position of the get pointer. Otherwise, it returns “-1”. Program 2: Below is the C++ program illustrating the use of tellp(): C++ // C++ program illustrating the// use of tellp()#include <fstream>#include <iostream>using namespace std; // Driver Codeint main(){ ofstream fout; char ch; // Opening the already existing file fout.open("gfg.text", ios::app); int pos; pos = fout.tellp(); cout << pos; fout << "print it"; pos = fin.tellp(); cout << pos; fout.close(); return 0;} Input File: gfg.text hello students print it Output: Tabular Difference between tellp() and tellg(): CPP-Library C++ Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Passing a function as a parameter in C++ Program to implement Singly Linked List in C++ using class cout in C++ Pi(π) in C++ with Examples Const keyword in C++ Handling the Divide by Zero Exception in C++ Why it is important to write "using namespace std" in C++ program? Dynamic _Cast in C++ isdigit() function in C/C++ with Examples Setting up Sublime Text for C++ Competitive Programming Environment
[ { "code": null, "e": 24163, "s": 24135, "text": "\n23 Mar, 2021" }, { "code": null, "e": 24300, "s": 24163, "text": "In this article, we will discuss the functionality of basic_istream<>::tellg and basic_ostream<>::tellp and the difference between them." }, { "code": null, "e": 24454, "s": 24300, "text": "tellg(): The function is defined in the istream class, and used with input streams. It returns the position of the current character in the input stream." }, { "code": null, "e": 24462, "s": 24454, "text": "Syntax:" }, { "code": null, "e": 24481, "s": 24462, "text": "pos_type tellg(); " }, { "code": null, "e": 24633, "s": 24481, "text": "Return Type: If the pointer points to a valid position, then this function returns the current position of the get pointer. Otherwise, it returns “-1”." }, { "code": null, "e": 24644, "s": 24633, "text": "Program 1:" }, { "code": null, "e": 24703, "s": 24644, "text": "Below is the C++ program to illustrate the use of tellg():" }, { "code": null, "e": 24707, "s": 24703, "text": "C++" }, { "code": "// C++ program to illustrate the// use of tellg()#include <fstream>#include <iostream>using namespace std; // Driver Codeint main(){ ifstream fin; char ch; // Opens the existing file fin.open(\"gfg.text\"); int pos; pos = fin.tellg(); cout << pos; fin >> ch; pos = fin.tellg(); cout << pos; fin >> ch; pos = fin.tellg(); cout << pos; return 0;}", "e": 25103, "s": 24707, "text": null }, { "code": null, "e": 25115, "s": 25103, "text": "Input File:" }, { "code": null, "e": 25143, "s": 25115, "text": " gfg.text\n \n hello students" }, { "code": null, "e": 25151, "s": 25143, "text": "Output:" }, { "code": null, "e": 25341, "s": 25151, "text": "tellp(): The function is defined in the ostream class, and used with output streams. It returns the position of the current character in the output stream where the character can be placed." }, { "code": null, "e": 25349, "s": 25341, "text": "Syntax:" }, { "code": null, "e": 25367, "s": 25349, "text": "pos_type tellp();" }, { "code": null, "e": 25519, "s": 25367, "text": "Return Type: If the pointer points to a valid position, then this function returns the current position of the get pointer. Otherwise, it returns “-1”." }, { "code": null, "e": 25530, "s": 25519, "text": "Program 2:" }, { "code": null, "e": 25588, "s": 25530, "text": "Below is the C++ program illustrating the use of tellp():" }, { "code": null, "e": 25592, "s": 25588, "text": "C++" }, { "code": "// C++ program illustrating the// use of tellp()#include <fstream>#include <iostream>using namespace std; // Driver Codeint main(){ ofstream fout; char ch; // Opening the already existing file fout.open(\"gfg.text\", ios::app); int pos; pos = fout.tellp(); cout << pos; fout << \"print it\"; pos = fin.tellp(); cout << pos; fout.close(); return 0;}", "e": 25980, "s": 25592, "text": null }, { "code": null, "e": 25992, "s": 25980, "text": "Input File:" }, { "code": null, "e": 26027, "s": 25992, "text": "gfg.text\n\nhello students\nprint it " }, { "code": null, "e": 26035, "s": 26027, "text": "Output:" }, { "code": null, "e": 26083, "s": 26035, "text": "Tabular Difference between tellp() and tellg():" }, { "code": null, "e": 26095, "s": 26083, "text": "CPP-Library" }, { "code": null, "e": 26108, "s": 26095, "text": "C++ Programs" }, { "code": null, "e": 26206, "s": 26108, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26215, "s": 26206, "text": "Comments" }, { "code": null, "e": 26228, "s": 26215, "text": "Old Comments" }, { "code": null, "e": 26269, "s": 26228, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 26328, "s": 26269, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 26340, "s": 26328, "text": "cout in C++" }, { "code": null, "e": 26367, "s": 26340, "text": "Pi(π) in C++ with Examples" }, { "code": null, "e": 26388, "s": 26367, "text": "Const keyword in C++" }, { "code": null, "e": 26433, "s": 26388, "text": "Handling the Divide by Zero Exception in C++" }, { "code": null, "e": 26500, "s": 26433, "text": "Why it is important to write \"using namespace std\" in C++ program?" }, { "code": null, "e": 26521, "s": 26500, "text": "Dynamic _Cast in C++" }, { "code": null, "e": 26563, "s": 26521, "text": "isdigit() function in C/C++ with Examples" } ]
Spring - Bean Definition Inheritance
A bean definition can contain a lot of configuration information, including constructor arguments, property values, and container-specific information such as initialization method, static factory method name, and so on. A child bean definition inherits configuration data from a parent definition. The child definition can override some values, or add others, as needed. Spring Bean definition inheritance has nothing to do with Java class inheritance but the inheritance concept is same. You can define a parent bean definition as a template and other child beans can inherit the required configuration from the parent bean. When you use XML-based configuration metadata, you indicate a child bean definition by using the parent attribute, specifying the parent bean as the value of this attribute. Let us have a working Eclipse IDE in place and take the following steps to create a Spring application − Following is the configuration file Beans.xml where we defined "helloWorld" bean which has two properties message1 and message2. Next "helloIndia" bean has been defined as a child of "helloWorld" bean by using parent attribute. The child bean inherits message2 property as is, and overrides message1 property and introduces one more property message3. <?xml version = "1.0" encoding = "UTF-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id = "helloWorld" class = "com.tutorialspoint.HelloWorld"> <property name = "message1" value = "Hello World!"/> <property name = "message2" value = "Hello Second World!"/> </bean> <bean id ="helloIndia" class = "com.tutorialspoint.HelloIndia" parent = "helloWorld"> <property name = "message1" value = "Hello India!"/> <property name = "message3" value = "Namaste India!"/> </bean> </beans> Here is the content of HelloWorld.java file − package com.tutorialspoint; public class HelloWorld { private String message1; private String message2; public void setMessage1(String message){ this.message1 = message; } public void setMessage2(String message){ this.message2 = message; } public void getMessage1(){ System.out.println("World Message1 : " + message1); } public void getMessage2(){ System.out.println("World Message2 : " + message2); } } Here is the content of HelloIndia.java file − package com.tutorialspoint; public class HelloIndia { private String message1; private String message2; private String message3; public void setMessage1(String message){ this.message1 = message; } public void setMessage2(String message){ this.message2 = message; } public void setMessage3(String message){ this.message3 = message; } public void getMessage1(){ System.out.println("India Message1 : " + message1); } public void getMessage2(){ System.out.println("India Message2 : " + message2); } public void getMessage3(){ System.out.println("India Message3 : " + message3); } } Following is the content of the MainApp.java file − package com.tutorialspoint; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); HelloWorld objA = (HelloWorld) context.getBean("helloWorld"); objA.getMessage1(); objA.getMessage2(); HelloIndia objB = (HelloIndia) context.getBean("helloIndia"); objB.getMessage1(); objB.getMessage2(); objB.getMessage3(); } } Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message − World Message1 : Hello World! World Message2 : Hello Second World! India Message1 : Hello India! India Message2 : Hello Second World! India Message3 : Namaste India! If you observed here, we did not pass message2 while creating "helloIndia" bean, but it got passed because of Bean Definition Inheritance. You can create a Bean definition template, which can be used by other child bean definitions without putting much effort. While defining a Bean Definition Template, you should not specify the class attribute and should specify abstract attribute and should specify the abstract attribute with a value of true as shown in the following code snippet − <?xml version = "1.0" encoding = "UTF-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id = "beanTeamplate" abstract = "true"> <property name = "message1" value = "Hello World!"/> <property name = "message2" value = "Hello Second World!"/> <property name = "message3" value = "Namaste India!"/> </bean> <bean id = "helloIndia" class = "com.tutorialspoint.HelloIndia" parent = "beanTeamplate"> <property name = "message1" value = "Hello India!"/> <property name = "message3" value = "Namaste India!"/> </bean> </beans> The parent bean cannot be instantiated on its own because it is incomplete, and it is also explicitly marked as abstract. When a definition is abstract like this, it is usable only as a pure template bean definition that serves as a parent definition for child definitions. 102 Lectures 8 hours Karthikeya T 39 Lectures 5 hours Chaand Sheikh 73 Lectures 5.5 hours Senol Atac 62 Lectures 4.5 hours Senol Atac 67 Lectures 4.5 hours Senol Atac 69 Lectures 5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2513, "s": 2292, "text": "A bean definition can contain a lot of configuration information, including constructor arguments, property values, and container-specific information such as initialization method, static factory method name, and so on." }, { "code": null, "e": 2664, "s": 2513, "text": "A child bean definition inherits configuration data from a parent definition. The child definition can override some values, or add others, as needed." }, { "code": null, "e": 2919, "s": 2664, "text": "Spring Bean definition inheritance has nothing to do with Java class inheritance but the inheritance concept is same. You can define a parent bean definition as a template and other child beans can inherit the required configuration from the parent bean." }, { "code": null, "e": 3093, "s": 2919, "text": "When you use XML-based configuration metadata, you indicate a child bean definition by using the parent attribute, specifying the parent bean as the value of this attribute." }, { "code": null, "e": 3198, "s": 3093, "text": "Let us have a working Eclipse IDE in place and take the following steps to create a Spring application −" }, { "code": null, "e": 3550, "s": 3198, "text": "Following is the configuration file Beans.xml where we defined \"helloWorld\" bean which has two properties message1 and message2. Next \"helloIndia\" bean has been defined as a child of \"helloWorld\" bean by using parent attribute. The child bean inherits message2 property as is, and overrides message1 property and introduces one more property message3." }, { "code": null, "e": 4288, "s": 3550, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\">\n\n <bean id = \"helloWorld\" class = \"com.tutorialspoint.HelloWorld\">\n <property name = \"message1\" value = \"Hello World!\"/>\n <property name = \"message2\" value = \"Hello Second World!\"/>\n </bean>\n\n <bean id =\"helloIndia\" class = \"com.tutorialspoint.HelloIndia\" parent = \"helloWorld\">\n <property name = \"message1\" value = \"Hello India!\"/>\n <property name = \"message3\" value = \"Namaste India!\"/>\n </bean>\n</beans>" }, { "code": null, "e": 4334, "s": 4288, "text": "Here is the content of HelloWorld.java file −" }, { "code": null, "e": 4794, "s": 4334, "text": "package com.tutorialspoint;\n\npublic class HelloWorld {\n private String message1;\n private String message2;\n\n public void setMessage1(String message){\n this.message1 = message;\n }\n public void setMessage2(String message){\n this.message2 = message;\n }\n public void getMessage1(){\n System.out.println(\"World Message1 : \" + message1);\n }\n public void getMessage2(){\n System.out.println(\"World Message2 : \" + message2);\n }\n}" }, { "code": null, "e": 4840, "s": 4794, "text": "Here is the content of HelloIndia.java file −" }, { "code": null, "e": 5501, "s": 4840, "text": "package com.tutorialspoint;\n\npublic class HelloIndia {\n private String message1;\n private String message2;\n private String message3;\n\n public void setMessage1(String message){\n this.message1 = message;\n }\n public void setMessage2(String message){\n this.message2 = message;\n }\n public void setMessage3(String message){\n this.message3 = message;\n }\n public void getMessage1(){\n System.out.println(\"India Message1 : \" + message1);\n }\n public void getMessage2(){\n System.out.println(\"India Message2 : \" + message2);\n }\n public void getMessage3(){\n System.out.println(\"India Message3 : \" + message3);\n }\n}" }, { "code": null, "e": 5553, "s": 5501, "text": "Following is the content of the MainApp.java file −" }, { "code": null, "e": 6145, "s": 5553, "text": "package com.tutorialspoint;\n\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.support.ClassPathXmlApplicationContext;\n\npublic class MainApp {\n public static void main(String[] args) {\n ApplicationContext context = new ClassPathXmlApplicationContext(\"Beans.xml\");\n \n HelloWorld objA = (HelloWorld) context.getBean(\"helloWorld\");\n objA.getMessage1();\n objA.getMessage2();\n\n HelloIndia objB = (HelloIndia) context.getBean(\"helloIndia\");\n objB.getMessage1();\n objB.getMessage2();\n objB.getMessage3();\n }\n}" }, { "code": null, "e": 6324, "s": 6145, "text": "Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −" }, { "code": null, "e": 6491, "s": 6324, "text": "World Message1 : Hello World!\nWorld Message2 : Hello Second World!\nIndia Message1 : Hello India!\nIndia Message2 : Hello Second World!\nIndia Message3 : Namaste India!\n" }, { "code": null, "e": 6630, "s": 6491, "text": "If you observed here, we did not pass message2 while creating \"helloIndia\" bean, but it got passed because of Bean Definition Inheritance." }, { "code": null, "e": 6981, "s": 6630, "text": "You can create a Bean definition template, which can be used by other child bean definitions without putting much effort. While defining a Bean Definition Template, you should not specify the class attribute and should specify abstract attribute and should specify the abstract attribute with a value of true as shown in the following code snippet −" }, { "code": null, "e": 7769, "s": 6981, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\">\n\n <bean id = \"beanTeamplate\" abstract = \"true\">\n <property name = \"message1\" value = \"Hello World!\"/>\n <property name = \"message2\" value = \"Hello Second World!\"/>\n <property name = \"message3\" value = \"Namaste India!\"/>\n </bean>\n\n <bean id = \"helloIndia\" class = \"com.tutorialspoint.HelloIndia\" parent = \"beanTeamplate\">\n <property name = \"message1\" value = \"Hello India!\"/>\n <property name = \"message3\" value = \"Namaste India!\"/>\n </bean>\n \n</beans>" }, { "code": null, "e": 8043, "s": 7769, "text": "The parent bean cannot be instantiated on its own because it is incomplete, and it is also explicitly marked as abstract. When a definition is abstract like this, it is usable only as a pure template bean definition that serves as a parent definition for child definitions." }, { "code": null, "e": 8077, "s": 8043, "text": "\n 102 Lectures \n 8 hours \n" }, { "code": null, "e": 8091, "s": 8077, "text": " Karthikeya T" }, { "code": null, "e": 8124, "s": 8091, "text": "\n 39 Lectures \n 5 hours \n" }, { "code": null, "e": 8139, "s": 8124, "text": " Chaand Sheikh" }, { "code": null, "e": 8174, "s": 8139, "text": "\n 73 Lectures \n 5.5 hours \n" }, { "code": null, "e": 8186, "s": 8174, "text": " Senol Atac" }, { "code": null, "e": 8221, "s": 8186, "text": "\n 62 Lectures \n 4.5 hours \n" }, { "code": null, "e": 8233, "s": 8221, "text": " Senol Atac" }, { "code": null, "e": 8268, "s": 8233, "text": "\n 67 Lectures \n 4.5 hours \n" }, { "code": null, "e": 8280, "s": 8268, "text": " Senol Atac" }, { "code": null, "e": 8313, "s": 8280, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 8325, "s": 8313, "text": " Senol Atac" }, { "code": null, "e": 8332, "s": 8325, "text": " Print" }, { "code": null, "e": 8343, "s": 8332, "text": " Add Notes" } ]
Cassandra - CQL Collections
CQL provides the facility of using Collection data types. Using these Collection types, you can store multiple values in a single variable. This chapter explains how to use Collections in Cassandra. List is used in the cases where the order of the elements is to be maintained, and a value is to be stored multiple times. You can get the values of a list data type using the index of the elements in the list. Given below is an example to create a sample table with two columns, name and email. To store multiple emails, we are using list. cqlsh:tutorialspoint> CREATE TABLE data(name text PRIMARY KEY, email list<text>); While inserting data into the elements in a list, enter all the values separated by comma within square braces [ ] as shown below. cqlsh:tutorialspoint> INSERT INTO data(name, email) VALUES ('ramu', ['[email protected]','[email protected]']) Given below is an example to update the list data type in a table called data. Here we are adding another email to the list. cqlsh:tutorialspoint> UPDATE data ... SET email = email +['[email protected]'] ... where name = 'ramu'; If you verify the table using SELECT statement, you will get the following result − cqlsh:tutorialspoint> SELECT * FROM data; name | email ------+-------------------------------------------------------------- ramu | ['[email protected]', '[email protected]', '[email protected]'] (1 rows) Set is a data type that is used to store a group of elements. The elements of a set will be returned in a sorted order. The following example creates a sample table with two columns, name and phone. For storing multiple phone numbers, we are using set. cqlsh:tutorialspoint> CREATE TABLE data2 (name text PRIMARY KEY, phone set<varint>); While inserting data into the elements in a set, enter all the values separated by comma within curly braces { } as shown below. cqlsh:tutorialspoint> INSERT INTO data2(name, phone)VALUES ('rahman', {9848022338,9848022339}); The following code shows how to update a set in a table named data2. Here we are adding another phone number to the set. cqlsh:tutorialspoint> UPDATE data2 ... SET phone = phone + {9848022330} ... where name = 'rahman'; If you verify the table using SELECT statement, you will get the following result − cqlsh:tutorialspoint> SELECT * FROM data2; name | phone --------+-------------------------------------- rahman | {9848022330, 9848022338, 9848022339} (1 rows) Map is a data type that is used to store a key-value pair of elements. The following example shows how to create a sample table with two columns, name and address. For storing multiple address values, we are using map. cqlsh:tutorialspoint> CREATE TABLE data3 (name text PRIMARY KEY, address map<timestamp, text>); While inserting data into the elements in a map, enter all the key : value pairs separated by comma within curly braces { } as shown below. cqlsh:tutorialspoint> INSERT INTO data3 (name, address) VALUES ('robin', {'home' : 'hyderabad' , 'office' : 'Delhi' } ); The following code shows how to update the map data type in a table named data3. Here we are changing the value of the key office, that is, we are changing the office address of a person named robin. cqlsh:tutorialspoint> UPDATE data3 ... SET address = address+{'office':'mumbai'} ... WHERE name = 'robin'; If you verify the table using SELECT statement, you will get the following result − cqlsh:tutorialspoint> select * from data3; name | address -------+------------------------------------------- robin | {'home': 'hyderabad', 'office': 'mumbai'} (1 rows) 27 Lectures 2 hours Navdeep Kaur 34 Lectures 1.5 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2486, "s": 2287, "text": "CQL provides the facility of using Collection data types. Using these Collection types, you can store multiple values in a single variable. This chapter explains how to use Collections in Cassandra." }, { "code": null, "e": 2518, "s": 2486, "text": "List is used in the cases where" }, { "code": null, "e": 2569, "s": 2518, "text": "the order of the elements is to be maintained, and" }, { "code": null, "e": 2609, "s": 2569, "text": "a value is to be stored multiple times." }, { "code": null, "e": 2697, "s": 2609, "text": "You can get the values of a list data type using the index of the elements in the list." }, { "code": null, "e": 2827, "s": 2697, "text": "Given below is an example to create a sample table with two columns, name and email. To store multiple emails, we are using list." }, { "code": null, "e": 2910, "s": 2827, "text": "cqlsh:tutorialspoint> CREATE TABLE data(name text PRIMARY KEY, email list<text>);\n" }, { "code": null, "e": 3041, "s": 2910, "text": "While inserting data into the elements in a list, enter all the values separated by comma within square braces [ ] as shown below." }, { "code": null, "e": 3145, "s": 3041, "text": "cqlsh:tutorialspoint> INSERT INTO data(name, email) VALUES ('ramu',\n['[email protected]','[email protected]'])\n" }, { "code": null, "e": 3270, "s": 3145, "text": "Given below is an example to update the list data type in a table called data. Here we are adding another email to the list." }, { "code": null, "e": 3380, "s": 3270, "text": "cqlsh:tutorialspoint> UPDATE data\n... SET email = email +['[email protected]']\n... where name = 'ramu';\n" }, { "code": null, "e": 3464, "s": 3380, "text": "If you verify the table using SELECT statement, you will get the following result −" }, { "code": null, "e": 3671, "s": 3464, "text": "cqlsh:tutorialspoint> SELECT * FROM data;\n\n name | email\n------+--------------------------------------------------------------\n ramu | ['[email protected]', '[email protected]', '[email protected]']\n\n(1 rows)\n" }, { "code": null, "e": 3791, "s": 3671, "text": "Set is a data type that is used to store a group of elements. The elements of a set will be returned in a sorted order." }, { "code": null, "e": 3924, "s": 3791, "text": "The following example creates a sample table with two columns, name and phone. For storing multiple phone numbers, we are using set." }, { "code": null, "e": 4010, "s": 3924, "text": "cqlsh:tutorialspoint> CREATE TABLE data2 (name text PRIMARY KEY, phone set<varint>);\n" }, { "code": null, "e": 4139, "s": 4010, "text": "While inserting data into the elements in a set, enter all the values separated by comma within curly braces { } as shown below." }, { "code": null, "e": 4239, "s": 4139, "text": "cqlsh:tutorialspoint> INSERT INTO data2(name, phone)VALUES ('rahman', {9848022338,9848022339});\n" }, { "code": null, "e": 4360, "s": 4239, "text": "The following code shows how to update a set in a table named data2. Here we are adding another phone number to the set." }, { "code": null, "e": 4466, "s": 4360, "text": "cqlsh:tutorialspoint> UPDATE data2\n ... SET phone = phone + {9848022330}\n ... where name = 'rahman';\n" }, { "code": null, "e": 4550, "s": 4466, "text": "If you verify the table using SELECT statement, you will get the following result −" }, { "code": null, "e": 4716, "s": 4550, "text": "cqlsh:tutorialspoint> SELECT * FROM data2;\n\n name | phone\n--------+--------------------------------------\n rahman | {9848022330, 9848022338, 9848022339}\n\n(1 rows)\n" }, { "code": null, "e": 4787, "s": 4716, "text": "Map is a data type that is used to store a key-value pair of elements." }, { "code": null, "e": 4935, "s": 4787, "text": "The following example shows how to create a sample table with two columns, name and address. For storing multiple address values, we are using map." }, { "code": null, "e": 5032, "s": 4935, "text": "cqlsh:tutorialspoint> CREATE TABLE data3 (name text PRIMARY KEY, address\nmap<timestamp, text>);\n" }, { "code": null, "e": 5172, "s": 5032, "text": "While inserting data into the elements in a map, enter all the key : value pairs separated by comma within curly braces { } as shown below." }, { "code": null, "e": 5297, "s": 5172, "text": "cqlsh:tutorialspoint> INSERT INTO data3 (name, address)\n VALUES ('robin', {'home' : 'hyderabad' , 'office' : 'Delhi' } );\n" }, { "code": null, "e": 5497, "s": 5297, "text": "The following code shows how to update the map data type in a table named data3. Here we are changing the value of the key office, that is, we are changing the office address of a person named robin." }, { "code": null, "e": 5611, "s": 5497, "text": "cqlsh:tutorialspoint> UPDATE data3\n ... SET address = address+{'office':'mumbai'}\n ... WHERE name = 'robin';\n" }, { "code": null, "e": 5695, "s": 5611, "text": "If you verify the table using SELECT statement, you will get the following result −" }, { "code": null, "e": 5870, "s": 5695, "text": "cqlsh:tutorialspoint> select * from data3;\n\n name | address\n-------+-------------------------------------------\n robin | {'home': 'hyderabad', 'office': 'mumbai'}\n\n(1 rows)\n" }, { "code": null, "e": 5903, "s": 5870, "text": "\n 27 Lectures \n 2 hours \n" }, { "code": null, "e": 5917, "s": 5903, "text": " Navdeep Kaur" }, { "code": null, "e": 5952, "s": 5917, "text": "\n 34 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5970, "s": 5952, "text": " Bigdata Engineer" }, { "code": null, "e": 5977, "s": 5970, "text": " Print" }, { "code": null, "e": 5988, "s": 5977, "text": " Add Notes" } ]
Deep Learning-Prepare Image for Dataset | by Karthick Nagarajan | Towards Data Science
Whenever we begin a machine learning project, the first thing that we need is a dataset. Dataset will be the pillar of your training model. You can build the dataset either automatically or manually. Here I am going to share about the manual process. Dataset is the collection of specific data for your ML project needs. The type of data depends on the kind of AI you need to train. Basically, you have two datasets: Training Testing Composition at 90% and 10% respectively Whenever you are training a custom model the important thing is images. Yes, of course the images play a main role in deep learning. The accuracy of your model will be based on the training images. So, before you train a custom model, you need to plan how to get images? Here, I’m going to share my ideas on the easy way to get images for a dataset. Yes, we can get images from Google. Using the Download All Images browser extension we can easily get images in a few minutes. You can check out here for more details about this extension! It is available on major browsers. Unfortunately, this extension is not available on the Safari browser. Chrome Firefox Opera Once you download images using this extension, you will see the downloaded images in a folder with random filenames. We can rename the files or remove the .png file using the below Python script. chrome.google.com Remove PNGs from the downloaded image folder. Rename your image files Here we have another way to prepare images for the Dataset. We can easily extract images from video files. Detecto gives a simple solution to get images from the video. Refer Detecto for more information. pip3 install detecto Using the following code we can extract images from video files. You can take pictures of objects which you will use to train your model. The important note is to make sure your images are not beyond 800x600. This will help your dataset train much quicker. I have prepared a video and explained about the above process. Please check out the below video blog. As an ML noob, I need to figure out the best way to prepare the dataset for training a model. I hope this will be useful. My ultimate idea is to create a Python package for this process. :) Yes, I will come up with my next article! Originally published at www.spritle.com
[ { "code": null, "e": 423, "s": 172, "text": "Whenever we begin a machine learning project, the first thing that we need is a dataset. Dataset will be the pillar of your training model. You can build the dataset either automatically or manually. Here I am going to share about the manual process." }, { "code": null, "e": 589, "s": 423, "text": "Dataset is the collection of specific data for your ML project needs. The type of data depends on the kind of AI you need to train. Basically, you have two datasets:" }, { "code": null, "e": 598, "s": 589, "text": "Training" }, { "code": null, "e": 606, "s": 598, "text": "Testing" }, { "code": null, "e": 646, "s": 606, "text": "Composition at 90% and 10% respectively" }, { "code": null, "e": 996, "s": 646, "text": "Whenever you are training a custom model the important thing is images. Yes, of course the images play a main role in deep learning. The accuracy of your model will be based on the training images. So, before you train a custom model, you need to plan how to get images? Here, I’m going to share my ideas on the easy way to get images for a dataset." }, { "code": null, "e": 1290, "s": 996, "text": "Yes, we can get images from Google. Using the Download All Images browser extension we can easily get images in a few minutes. You can check out here for more details about this extension! It is available on major browsers. Unfortunately, this extension is not available on the Safari browser." }, { "code": null, "e": 1297, "s": 1290, "text": "Chrome" }, { "code": null, "e": 1305, "s": 1297, "text": "Firefox" }, { "code": null, "e": 1311, "s": 1305, "text": "Opera" }, { "code": null, "e": 1507, "s": 1311, "text": "Once you download images using this extension, you will see the downloaded images in a folder with random filenames. We can rename the files or remove the .png file using the below Python script." }, { "code": null, "e": 1525, "s": 1507, "text": "chrome.google.com" }, { "code": null, "e": 1571, "s": 1525, "text": "Remove PNGs from the downloaded image folder." }, { "code": null, "e": 1595, "s": 1571, "text": "Rename your image files" }, { "code": null, "e": 1800, "s": 1595, "text": "Here we have another way to prepare images for the Dataset. We can easily extract images from video files. Detecto gives a simple solution to get images from the video. Refer Detecto for more information." }, { "code": null, "e": 1821, "s": 1800, "text": "pip3 install detecto" }, { "code": null, "e": 1886, "s": 1821, "text": "Using the following code we can extract images from video files." }, { "code": null, "e": 2078, "s": 1886, "text": "You can take pictures of objects which you will use to train your model. The important note is to make sure your images are not beyond 800x600. This will help your dataset train much quicker." }, { "code": null, "e": 2180, "s": 2078, "text": "I have prepared a video and explained about the above process. Please check out the below video blog." }, { "code": null, "e": 2370, "s": 2180, "text": "As an ML noob, I need to figure out the best way to prepare the dataset for training a model. I hope this will be useful. My ultimate idea is to create a Python package for this process. :)" }, { "code": null, "e": 2412, "s": 2370, "text": "Yes, I will come up with my next article!" } ]
instance initializer block in Java
Instance initializer block works are used to initialize the properties of an object. It is invoked before the constructor is invoked. It is invoked every time an object is created. See the example below − Live Demo public class Tester { { System.out.println("Inside instance initializer block"); } Tester(){ System.out.println("Inside constructor"); } public static void main(String[] arguments) { Tester test = new Tester(); Tester test1 = new Tester(); } } Inside instance initializer block Inside constructor Inside instance initializer block Inside constructor
[ { "code": null, "e": 1267, "s": 1062, "text": "Instance initializer block works are used to initialize the properties of an object. It is invoked before the constructor is invoked. It is invoked every time an object is created. See the example below −" }, { "code": null, "e": 1277, "s": 1267, "text": "Live Demo" }, { "code": null, "e": 1563, "s": 1277, "text": "public class Tester {\n {\n System.out.println(\"Inside instance initializer block\");\n }\n Tester(){\n System.out.println(\"Inside constructor\");\n }\n public static void main(String[] arguments) {\n Tester test = new Tester();\n Tester test1 = new Tester();\n }\n}" }, { "code": null, "e": 1669, "s": 1563, "text": "Inside instance initializer block\nInside constructor\nInside instance initializer block\nInside constructor" } ]
How to insert HTML content into an iFrame using jQuery?
27 Sep, 2019 Here is the task to insert HTML content into an iFrame using jQuery. To do so, we can use the jQuery contents() method. The .contents() method: It returns all the direct children, including text and comment nodes for the selected element. Syntax: $(selector).contents() Find the iframe in the body section. Get the value to be inserted in the iframe in the body section Place the value in the iframe jQuery code to show the working of this approach:Example 1: <!DOCTYPE html><html> <head> <title>How to insert HTML content into an iFrame using jQuery?</title> <script src="https://code.jquery.com/jquery-1.12.4.min.js"> </script> <style type="text/css"> textarea, iframe { display: block; margin: 10px 0; } iframe { width: 500px; border: 1px solid #000000; } </style></head> <body> <center> <h1 style="color:green;"> GeeksForGeeks </h1> <h3> How to insert HTML content into an iFrame using jQuery </h3> <textarea rows="2" cols="40" style="text-align:center;"> GEEKSFORGEEKS - A computer science portal for geeks. </textarea> <button type="button" onclick="updateIframe()"> Click to Insert </button> <iframe style="text-align:center;" id="myframe"></iframe> <script type="text/javascript"> function updateIframe() { var myFrame = $("#myframe").contents().find('body'); var textareaValue = $("textarea").val(); myFrame.html(textareaValue); } </script> </center></body> </html> Output:Before Click on the Button:After Click on the Button: Example 2: <!DOCTYPE html><html> <head> <title>How to insert HTML content into an iFrame using jQuery?</title> <script src="https://code.jquery.com/jquery-1.12.4.min.js"> </script> <style type="text/css"> iframe { width: 500px; border: 1px solid #000000; } </style></head> <body> <center> <h1 style="color:green;"> GeeksForGeeks </h1> <h3>How to insert HTML content into an iFrame using jQuery</h3> <h4>Text to be insert : "GEEKSFORGEEKS - A computer science portal for geeks."</h4> <iframe style="text-align:center;" id="iframe"> </iframe> <script> $("#iframe").ready(function() { var body = $("#iframe").contents().find("body"); body.append( 'GEEKSFORGEEKS - A computer science portal for geeks.'); }); </script> </center></body> </html> Output: shubham_singh JavaScript-Misc JQuery Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Form validation using jQuery jQuery | children() with Examples Scroll to the top of the page using JavaScript/jQuery How to Dynamically Add/Remove Table Rows using jQuery ? How to get the value in an input text box using jQuery ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Sep, 2019" }, { "code": null, "e": 148, "s": 28, "text": "Here is the task to insert HTML content into an iFrame using jQuery. To do so, we can use the jQuery contents() method." }, { "code": null, "e": 267, "s": 148, "text": "The .contents() method: It returns all the direct children, including text and comment nodes for the selected element." }, { "code": null, "e": 275, "s": 267, "text": "Syntax:" }, { "code": null, "e": 298, "s": 275, "text": "$(selector).contents()" }, { "code": null, "e": 335, "s": 298, "text": "Find the iframe in the body section." }, { "code": null, "e": 398, "s": 335, "text": "Get the value to be inserted in the iframe in the body section" }, { "code": null, "e": 428, "s": 398, "text": "Place the value in the iframe" }, { "code": null, "e": 488, "s": 428, "text": "jQuery code to show the working of this approach:Example 1:" }, { "code": "<!DOCTYPE html><html> <head> <title>How to insert HTML content into an iFrame using jQuery?</title> <script src=\"https://code.jquery.com/jquery-1.12.4.min.js\"> </script> <style type=\"text/css\"> textarea, iframe { display: block; margin: 10px 0; } iframe { width: 500px; border: 1px solid #000000; } </style></head> <body> <center> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <h3> How to insert HTML content into an iFrame using jQuery </h3> <textarea rows=\"2\" cols=\"40\" style=\"text-align:center;\"> GEEKSFORGEEKS - A computer science portal for geeks. </textarea> <button type=\"button\" onclick=\"updateIframe()\"> Click to Insert </button> <iframe style=\"text-align:center;\" id=\"myframe\"></iframe> <script type=\"text/javascript\"> function updateIframe() { var myFrame = $(\"#myframe\").contents().find('body'); var textareaValue = $(\"textarea\").val(); myFrame.html(textareaValue); } </script> </center></body> </html>", "e": 1690, "s": 488, "text": null }, { "code": null, "e": 1751, "s": 1690, "text": "Output:Before Click on the Button:After Click on the Button:" }, { "code": null, "e": 1762, "s": 1751, "text": "Example 2:" }, { "code": "<!DOCTYPE html><html> <head> <title>How to insert HTML content into an iFrame using jQuery?</title> <script src=\"https://code.jquery.com/jquery-1.12.4.min.js\"> </script> <style type=\"text/css\"> iframe { width: 500px; border: 1px solid #000000; } </style></head> <body> <center> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <h3>How to insert HTML content into an iFrame using jQuery</h3> <h4>Text to be insert : \"GEEKSFORGEEKS - A computer science portal for geeks.\"</h4> <iframe style=\"text-align:center;\" id=\"iframe\"> </iframe> <script> $(\"#iframe\").ready(function() { var body = $(\"#iframe\").contents().find(\"body\"); body.append( 'GEEKSFORGEEKS - A computer science portal for geeks.'); }); </script> </center></body> </html>", "e": 2710, "s": 1762, "text": null }, { "code": null, "e": 2718, "s": 2710, "text": "Output:" }, { "code": null, "e": 2732, "s": 2718, "text": "shubham_singh" }, { "code": null, "e": 2748, "s": 2732, "text": "JavaScript-Misc" }, { "code": null, "e": 2755, "s": 2748, "text": "JQuery" }, { "code": null, "e": 2772, "s": 2755, "text": "Web Technologies" }, { "code": null, "e": 2799, "s": 2772, "text": "Web technologies Questions" }, { "code": null, "e": 2897, "s": 2799, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2926, "s": 2897, "text": "Form validation using jQuery" }, { "code": null, "e": 2960, "s": 2926, "text": "jQuery | children() with Examples" }, { "code": null, "e": 3014, "s": 2960, "text": "Scroll to the top of the page using JavaScript/jQuery" }, { "code": null, "e": 3070, "s": 3014, "text": "How to Dynamically Add/Remove Table Rows using jQuery ?" }, { "code": null, "e": 3127, "s": 3070, "text": "How to get the value in an input text box using jQuery ?" }, { "code": null, "e": 3189, "s": 3127, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3222, "s": 3189, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3283, "s": 3222, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3333, "s": 3283, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Longest Palindromic Substring | Set 2
30 Jun, 2022 Given a string, find the longest substring which is a palindrome. Examples: Input: Given string :"forgeeksskeegfor", Output: "geeksskeeg". Input: Given string :"Geeks", Output: "ee". Common mistake : Wrong Approach: Some people will be tempted to come up with a O(n) time complexity quick solution, which is unfortunately flawed (however can be corrected easily): (i)Reverse S and and store it in S’. (ii)Find the longest common substring between S and S’ which must also be the longest palindromic substring. This seemed to work, let’s see some examples below. For example, S = “caba” then S’ = “abac”. The longest common substring between S and S’ is “aba”, which is the answer. Let’s try another example: S = “abacdfgdcaba” then S’ = “abacdgfdcaba”. The longest common substring between S and S’ is “abacd”. Clearly, this is not a valid palindrome. Correct Approach: We could see that the longest common substring method fails when there exists a reversed copy of a non-palindromic substring in some other part of S. To rectify this, each time we find a longest common substring candidate, we check if the substring’s indices are the same as the reversed substring’s original indices. If it is, then we attempt to update the longest palindrome found so far; if not, we skip this and find the next candidate. This gives us an O(n^2) Dynamic Programming solution which uses O(n^2) space (which could be improved to use O(n) space). Dyanamic programming Approach: Dynamic programming solution is already discussed here in the previous post. The time complexity of the Dynamic Programming based solution is O(n^2) and it requires O(n^2) extra space. We can find the longest palindrome substring( LPS ) in (n^2) time with O(1) extra space. The algorithm below is very simple and easy to understand. The idea is to Fix a center and expand in both directions for longer palindromes and keep track of the longest palindrome seen so far. ALGO: Maintain a variable ‘ maxLength = 1 ‘ (for storing LPS length) and ‘ start =0 ‘ (for storing starting index of LPS ).The idea is very simple, we will traverse through the entire string with i=0 to i<(length of string).while traversing, initialize ‘low‘ and ‘high‘ pointer such that low= i-1 and high= i+1.keep incrementing ‘high’ until str[high]==str[i] .similarly keep decrementing ‘low’ until str[low]==str[i].finally we will keep incrementing ‘high’ and decrementing ‘low’ until str[low]==str[high].calculate length=high-low-1, if length > maxLength then maxLength = length and start = low+1 .Print the LPS and return maxLength. Maintain a variable ‘ maxLength = 1 ‘ (for storing LPS length) and ‘ start =0 ‘ (for storing starting index of LPS ). The idea is very simple, we will traverse through the entire string with i=0 to i<(length of string).while traversing, initialize ‘low‘ and ‘high‘ pointer such that low= i-1 and high= i+1.keep incrementing ‘high’ until str[high]==str[i] .similarly keep decrementing ‘low’ until str[low]==str[i].finally we will keep incrementing ‘high’ and decrementing ‘low’ until str[low]==str[high].calculate length=high-low-1, if length > maxLength then maxLength = length and start = low+1 . while traversing, initialize ‘low‘ and ‘high‘ pointer such that low= i-1 and high= i+1.keep incrementing ‘high’ until str[high]==str[i] .similarly keep decrementing ‘low’ until str[low]==str[i].finally we will keep incrementing ‘high’ and decrementing ‘low’ until str[low]==str[high].calculate length=high-low-1, if length > maxLength then maxLength = length and start = low+1 . while traversing, initialize ‘low‘ and ‘high‘ pointer such that low= i-1 and high= i+1. keep incrementing ‘high’ until str[high]==str[i] . similarly keep decrementing ‘low’ until str[low]==str[i]. finally we will keep incrementing ‘high’ and decrementing ‘low’ until str[low]==str[high]. calculate length=high-low-1, if length > maxLength then maxLength = length and start = low+1 . Print the LPS and return maxLength. C++ C Java Python3 C# Javascript // A O(n^2) time and O(1) space program to// find the longest palindromic substring// easy to understand as compared to previous version.#include <bits/stdc++.h>using namespace std; // A utility function to print// a substring str[low..high]// This function prints the// longest palindrome substring (LPS)// of str[]. It also returns the// length of the longest palindromeint longestPalSubstr(string str){ int n = str.size(); // calculating size of string if (n < 2) return n; // if string is empty then size will be 0. // if n==1 then, answer will be 1(single // character will always palindrome) int maxLength = 1, start = 0; int low, high; for (int i = 0; i < n; i++) { low = i - 1; high = i + 1; while (high < n && str[high] == str[i]) // increment 'high' high++; while (low >= 0 && str[low] == str[i]) // decrement 'low' low--; while (low >= 0 && high < n && str[low] == str[high]) { low--; high++; } int length = high - low - 1; if (maxLength < length) { maxLength = length; start = low + 1; } } cout << "Longest palindrome substring is: "; cout << str.substr(start, maxLength); return maxLength;} // Driver program to test above functionsint main(){ string str = "forgeeksskeegfor"; cout << "\nLength is: " << longestPalSubstr(str) << endl; return 0;} // A O(n^2) time and O(1) space// program to find the longest// palindromic substring#include <stdio.h>#include <string.h> // A utility function to print// a substring str[low..high]void printSubStr(char* str, int low, int high){ for (int i = low; i <= high; ++i) printf("%c", str[i]);} // This function prints the longest// palindrome substring (LPS)// of str[]. It also returns the// length of the longest palindromeint longestPalSubstr(char* str){ int n = strlen(str); // calculating size of string if (n < 2) return n; // if string is empty then size will be 0. // if n==1 then, answer will be 1(single // character will always palindrome) int maxLength = 1, start = 0; int low, high; for (int i = 0; i < n; i++) { low = i - 1; high = i + 1; while (high < n && str[high] == str[i]) // increment 'high' high++; while (low >= 0 && str[low] == str[i]) // decrement 'low' low--; while (low >= 0 && high < n && str[low] == str[high]) { low--; // decrement low high++; // increment high } int length = high - low - 1; if (maxLength < length) { maxLength = length; start = low + 1; } } printf("Longest palindrome substring is: "); printSubStr(str, start, start + maxLength - 1); return maxLength;} // Driver program to test above functionsint main(){ char str[] = "forgeeksskeegfor"; printf("\nLength is: %d", longestPalSubstr(str)); return 0;} // Java implementation of O(n^2)// time and O(1) space method// to find the longest palindromic substringpublic class LongestPalinSubstring { // This function prints the // longest palindrome substring // (LPS) of str[]. It also // returns the length of the // longest palindrome static int longestPalSubstr(String str) { int n = str.length(); // calculcharAting size of string if (n < 2) return n; // if string is empty then size will be 0. // if n==1 then, answer will be 1(single // character will always palindrome) int maxLength = 1,start=0; int low, high; for (int i = 0; i < n; i++) { low = i - 1; high = i + 1; while ( high < n && str.charAt(high) == str.charAt(i)) //increment 'high' high++; while ( low >= 0 && str.charAt(low) == str.charAt(i)) // decrement 'low' low--; while (low >= 0 && high < n && str.charAt(low) == str.charAt(high) ){ low--; high++; } int length = high - low - 1; if (maxLength < length){ maxLength = length; start=low+1; } } System.out.print("Longest palindrome substring is: "); System.out.println(str.substring(start, start + maxLength )); return maxLength; } // Driver program to test above function public static void main(String[] args) { String str = "forgeeksskeegfor"; System.out.println("Length is: " + longestPalSubstr(str)); }} # A O(n ^ 2) time and O(1) space program to find the# longest palindromic substring # This function prints the longest palindrome substring (LPS)# of str[]. It also returns the length of the longest palindrome def longestPalSubstr(string): n = len(string) # calculating size of string if (n < 2): return n # if string is empty then size will be 0. # if n==1 then, answer will be 1(single # character will always palindrome) start=0 maxLength = 1 for i in range(n): low = i - 1 high = i + 1 while (high < n and string[high] == string[i] ): high=high+1 while (low >= 0 and string[low] == string[i] ): low=low-1 while (low >= 0 and high < n and string[low] == string[high] ): low=low-1 high=high+1 length = high - low - 1 if (maxLength < length): maxLength = length start=low+1 print ("Longest palindrome substring is:",end=" ") print (string[start:start + maxLength]) return maxLength # Driver program to test above functionsstring = ("forgeeksskeegfor")print("Length is: " + str(longestPalSubstr(string))) // C# implementation of O(n^2) time// and O(1) space method to find the// longest palindromic substringusing System; class GFG { // This function prints the longest // palindrome substring (LPS) of str[]. // It also returns the length of the // longest palindrome public static int longestPalSubstr(string str) { int n = str.Length; // calculcharAting size of string if (n < 2) return n; // if string is empty then size will be 0. // if n==1 then, answer will be 1(single // character will always palindrome) int maxLength = 1,start=0; int low, high; for (int i = 0; i < n; i++) { low = i - 1; high = i + 1; while ( high < n && str[high] == str[i] ) //increment 'high' high++; while ( low >= 0 && str[low] == str[i]) // decrement 'low' low--; while (low >= 0 && high < n && str[low] == str[high] ){ low--; high++; } int length = high - low - 1; if (maxLength < length){ maxLength = length; start=low+1; } } Console.Write("Longest palindrome substring is: "); Console.WriteLine(str.Substring(start, maxLength)); return maxLength; } // Driver Code public static void Main(string[] args) { string str = "forgeeksskeegfor"; Console.WriteLine("Length is: " + longestPalSubstr(str)); }} <script> // A O(n^2) time and O(1) space program to// find the longest palindromic substring// easy to understand as compared to previous version. // A utility function to print// a substring str[low..high]// This function prints the// longest palindrome substring (LPS)// of str[]. It also returns the// length of the longest palindromefunction longestPalSubstr(str){ let n = str.length; // calculating size of string if (n < 2) return n; // if string is empty then size will be 0. // if n==1 then, answer will be 1(single // character will always palindrome) let maxLength = 1,start=0; let low, high; for (let i = 0; i < n; i++) { low = i - 1; high = i + 1; while ( high < n && str[high] == str[i]) //increment 'high' high++; while ( low >= 0 && str[low] == str[i]) // decrement 'low' low--; while (low >= 0 && high < n && str[low] == str[high]){ low--; high++; } let length = high - low - 1; if (maxLength < length) { maxLength = length; start=low+1; } } document.write("Longest palindrome substring is: "); document.write(str.substring(start,maxLength+start)); return maxLength;} // Driver program to test above functions let str = "forgeeksskeegfor";document.write("</br>","Length is: " + longestPalSubstr(str),"</br>"); </script> Longest palindrome substring is: geeksskeeg Length is: 10 Complexity Analysis: Time complexity: O(n^2), where n is the length of the input string. Outer Loop that traverses through the entire string, and Inner Loop that is used to expand from i . Auxiliary Space: O(1). No extra space is needed. The Above approach is a cleaner way. The function implementation to print the LPS and return the maxLength is given below: C++ Java C# // A O(n^2) time and O(1) space program to// find the longest palindromic substring// easy to understand as compared to previous version. #include <bits/stdc++.h>using namespace std; int maxLength; // variables to store andstring res; // update maxLength and res // A utility function to get the longest palindrome// starting and expanding out from given center indicesvoid cSubUtil(string& s, int l, int r){ // check if the indices lie in the range of string // and also if it is palindrome while (l >= 0 && r < s.length() && s[l] == s[r]) { // expand the boundary l--; r++; } // if it's length is greater than maxLength update // maxLength and res if (r - l - 1 >= maxLength) { res = s.substr(l + 1, r - l - 1); maxLength = r - l - 1; } return;}// A function which takes a string prints the LPS and// returns the length of LPSint longestPalSubstr(string str){ res = ""; maxLength = 1; // for every index in the string check palindromes // starting from that index for (int i = 0; i < str.length(); i++) { // check for odd length palindromes cSubUtil(str, i, i); // check for even length palindromes cSubUtil(str, i, i + 1); } cout << "Longest palindrome substring is: "; cout << res << "\n"; return maxLength;} // Driver program to test above functionsint main(){ string str = "forgeeksskeegfor"; cout << "\nLength is: " << longestPalSubstr(str) << endl; return 0;} // Java implementation of O(n^2)// time and O(1) space method// to find the longest palindromic substring public class LongestPalinSubstring { static int maxLength; // variables to store and static String res; // update maxLength and res // A utility function to get the longest palindrome // starting and expanding out from given center indices static void cSubUtil(String s, int l, int r) { // check if the indices lie in the range of string // and also if it is palindrome while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { // expand the boundary l--; r++; } // if it's length is greater than maxLength update // maxLength and res if (r - l - 1 >= maxLength) { res = s.substring(l + 1, r); maxLength = r - l - 1; } return; } // A function which takes a string prints the LPS and // returns the length of LPS static int longestPalSubstr(String str) { res = ""; maxLength = 1; // for every index in the string check palindromes // starting from that index for (int i = 0; i < str.length(); i++) { // check for odd length palindromes cSubUtil(str, i, i); // check for even length palindromes cSubUtil(str, i, i + 1); } System.out.print( "Longest palindrome substring is: "); System.out.println(res); return maxLength; } // Driver program to test above function public static void main(String[] args) { String str = "forgeeksskeegfor"; System.out.println("Length is: " + longestPalSubstr(str)); }} // C# implementation of O(n^2) time// and O(1) space method to find the// longest palindromic substringusing System; class GFG { static int maxLength; // variables to store and static string res; // update maxLength and res // A utility function to get the longest palindrome // starting and expanding out from given center indices public static void cSubUtil(string s, int l, int r) { // check if the indices lie in the range of string // and also if it is palindrome while (l >= 0 && r < s.Length && s[l] == s[r]) { // expand the boundary l--; r++; } // if it's length is greater than maxLength update // maxLength and res if (r - l - 1 >= maxLength) { res = s.Substring(l + 1, r - l - 1); maxLength = r - l - 1; } return; } // A function which takes a string prints the LPS and // returns the length of LPS public static int longestPalSubstr(string str) { res = ""; maxLength = 1; // for every index in the string check palindromes // starting from that index for (int i = 0; i < str.Length; i++) { // check for odd length palindromes cSubUtil(str, i, i); // check for even length palindromes cSubUtil(str, i, i + 1); } Console.Write("Longest palindrome substring is: "); Console.WriteLine(res); return maxLength; } // Driver Code public static void Main(string[] args) { string str = "forgeeksskeegfor"; Console.WriteLine("Length is: " + longestPalSubstr(str)); }} Longest palindrome substring is: geeksskeeg Length is: 10 Please write comments if you find anything incorrect, or have more information about the topic discussed above. shrikanth13 ukasp rathbhupendra andrew1234 sourabh1996 rag2127 RaviOstwal yogesh vishwakarma kk9826225 amartyaghoshgfg oyesaurabh shinjanpatra 20ec01033 abhijeet19403 Accolite Amazon Groupon Microsoft palindrome Strings Accolite Amazon Microsoft Groupon Strings palindrome Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Check for Balanced Brackets in an expression (well-formedness) using Stack Different Methods to Reverse a String in C++ Python program to check if a string is palindrome or not KMP Algorithm for Pattern Searching What is Data Structure: Types, Classifications and Applications Top 50 String Coding Problems for Interviews Length of the longest substring without repeating characters Convert string to char array in C++ Reverse words in a given string Check whether two strings are anagram of each other
[ { "code": null, "e": 54, "s": 26, "text": "\n30 Jun, 2022" }, { "code": null, "e": 121, "s": 54, "text": "Given a string, find the longest substring which is a palindrome. " }, { "code": null, "e": 132, "s": 121, "text": "Examples: " }, { "code": null, "e": 243, "s": 132, "text": "Input: Given string :\"forgeeksskeegfor\", \nOutput: \"geeksskeeg\".\n\nInput: Given string :\"Geeks\", \nOutput: \"ee\". " }, { "code": null, "e": 279, "s": 243, "text": "Common mistake : Wrong Approach: " }, { "code": null, "e": 427, "s": 279, "text": "Some people will be tempted to come up with a O(n) time complexity quick solution, which is unfortunately flawed (however can be corrected easily):" }, { "code": null, "e": 577, "s": 427, "text": " (i)Reverse S and and store it in S’. (ii)Find the longest common substring between S and S’ which must also be the longest palindromic substring." }, { "code": null, "e": 629, "s": 577, "text": "This seemed to work, let’s see some examples below." }, { "code": null, "e": 672, "s": 629, "text": "For example, S = “caba” then S’ = “abac”." }, { "code": null, "e": 749, "s": 672, "text": "The longest common substring between S and S’ is “aba”, which is the answer." }, { "code": null, "e": 821, "s": 749, "text": "Let’s try another example: S = “abacdfgdcaba” then S’ = “abacdgfdcaba”." }, { "code": null, "e": 920, "s": 821, "text": "The longest common substring between S and S’ is “abacd”. Clearly, this is not a valid palindrome." }, { "code": null, "e": 938, "s": 920, "text": "Correct Approach:" }, { "code": null, "e": 1501, "s": 938, "text": "We could see that the longest common substring method fails when there exists a reversed copy of a non-palindromic substring in some other part of S. To rectify this, each time we find a longest common substring candidate, we check if the substring’s indices are the same as the reversed substring’s original indices. If it is, then we attempt to update the longest palindrome found so far; if not, we skip this and find the next candidate. This gives us an O(n^2) Dynamic Programming solution which uses O(n^2) space (which could be improved to use O(n) space)." }, { "code": null, "e": 1807, "s": 1501, "text": "Dyanamic programming Approach: Dynamic programming solution is already discussed here in the previous post. The time complexity of the Dynamic Programming based solution is O(n^2) and it requires O(n^2) extra space. We can find the longest palindrome substring( LPS ) in (n^2) time with O(1) extra space. " }, { "code": null, "e": 2001, "s": 1807, "text": "The algorithm below is very simple and easy to understand. The idea is to Fix a center and expand in both directions for longer palindromes and keep track of the longest palindrome seen so far." }, { "code": null, "e": 2007, "s": 2001, "text": "ALGO:" }, { "code": null, "e": 2640, "s": 2007, "text": "Maintain a variable ‘ maxLength = 1 ‘ (for storing LPS length) and ‘ start =0 ‘ (for storing starting index of LPS ).The idea is very simple, we will traverse through the entire string with i=0 to i<(length of string).while traversing, initialize ‘low‘ and ‘high‘ pointer such that low= i-1 and high= i+1.keep incrementing ‘high’ until str[high]==str[i] .similarly keep decrementing ‘low’ until str[low]==str[i].finally we will keep incrementing ‘high’ and decrementing ‘low’ until str[low]==str[high].calculate length=high-low-1, if length > maxLength then maxLength = length and start = low+1 .Print the LPS and return maxLength. " }, { "code": null, "e": 2758, "s": 2640, "text": "Maintain a variable ‘ maxLength = 1 ‘ (for storing LPS length) and ‘ start =0 ‘ (for storing starting index of LPS )." }, { "code": null, "e": 3238, "s": 2758, "text": "The idea is very simple, we will traverse through the entire string with i=0 to i<(length of string).while traversing, initialize ‘low‘ and ‘high‘ pointer such that low= i-1 and high= i+1.keep incrementing ‘high’ until str[high]==str[i] .similarly keep decrementing ‘low’ until str[low]==str[i].finally we will keep incrementing ‘high’ and decrementing ‘low’ until str[low]==str[high].calculate length=high-low-1, if length > maxLength then maxLength = length and start = low+1 ." }, { "code": null, "e": 3617, "s": 3238, "text": "while traversing, initialize ‘low‘ and ‘high‘ pointer such that low= i-1 and high= i+1.keep incrementing ‘high’ until str[high]==str[i] .similarly keep decrementing ‘low’ until str[low]==str[i].finally we will keep incrementing ‘high’ and decrementing ‘low’ until str[low]==str[high].calculate length=high-low-1, if length > maxLength then maxLength = length and start = low+1 ." }, { "code": null, "e": 3705, "s": 3617, "text": "while traversing, initialize ‘low‘ and ‘high‘ pointer such that low= i-1 and high= i+1." }, { "code": null, "e": 3756, "s": 3705, "text": "keep incrementing ‘high’ until str[high]==str[i] ." }, { "code": null, "e": 3814, "s": 3756, "text": "similarly keep decrementing ‘low’ until str[low]==str[i]." }, { "code": null, "e": 3905, "s": 3814, "text": "finally we will keep incrementing ‘high’ and decrementing ‘low’ until str[low]==str[high]." }, { "code": null, "e": 4000, "s": 3905, "text": "calculate length=high-low-1, if length > maxLength then maxLength = length and start = low+1 ." }, { "code": null, "e": 4037, "s": 4000, "text": "Print the LPS and return maxLength. " }, { "code": null, "e": 4041, "s": 4037, "text": "C++" }, { "code": null, "e": 4043, "s": 4041, "text": "C" }, { "code": null, "e": 4048, "s": 4043, "text": "Java" }, { "code": null, "e": 4056, "s": 4048, "text": "Python3" }, { "code": null, "e": 4059, "s": 4056, "text": "C#" }, { "code": null, "e": 4070, "s": 4059, "text": "Javascript" }, { "code": "// A O(n^2) time and O(1) space program to// find the longest palindromic substring// easy to understand as compared to previous version.#include <bits/stdc++.h>using namespace std; // A utility function to print// a substring str[low..high]// This function prints the// longest palindrome substring (LPS)// of str[]. It also returns the// length of the longest palindromeint longestPalSubstr(string str){ int n = str.size(); // calculating size of string if (n < 2) return n; // if string is empty then size will be 0. // if n==1 then, answer will be 1(single // character will always palindrome) int maxLength = 1, start = 0; int low, high; for (int i = 0; i < n; i++) { low = i - 1; high = i + 1; while (high < n && str[high] == str[i]) // increment 'high' high++; while (low >= 0 && str[low] == str[i]) // decrement 'low' low--; while (low >= 0 && high < n && str[low] == str[high]) { low--; high++; } int length = high - low - 1; if (maxLength < length) { maxLength = length; start = low + 1; } } cout << \"Longest palindrome substring is: \"; cout << str.substr(start, maxLength); return maxLength;} // Driver program to test above functionsint main(){ string str = \"forgeeksskeegfor\"; cout << \"\\nLength is: \" << longestPalSubstr(str) << endl; return 0;}", "e": 5590, "s": 4070, "text": null }, { "code": "// A O(n^2) time and O(1) space// program to find the longest// palindromic substring#include <stdio.h>#include <string.h> // A utility function to print// a substring str[low..high]void printSubStr(char* str, int low, int high){ for (int i = low; i <= high; ++i) printf(\"%c\", str[i]);} // This function prints the longest// palindrome substring (LPS)// of str[]. It also returns the// length of the longest palindromeint longestPalSubstr(char* str){ int n = strlen(str); // calculating size of string if (n < 2) return n; // if string is empty then size will be 0. // if n==1 then, answer will be 1(single // character will always palindrome) int maxLength = 1, start = 0; int low, high; for (int i = 0; i < n; i++) { low = i - 1; high = i + 1; while (high < n && str[high] == str[i]) // increment 'high' high++; while (low >= 0 && str[low] == str[i]) // decrement 'low' low--; while (low >= 0 && high < n && str[low] == str[high]) { low--; // decrement low high++; // increment high } int length = high - low - 1; if (maxLength < length) { maxLength = length; start = low + 1; } } printf(\"Longest palindrome substring is: \"); printSubStr(str, start, start + maxLength - 1); return maxLength;} // Driver program to test above functionsint main(){ char str[] = \"forgeeksskeegfor\"; printf(\"\\nLength is: %d\", longestPalSubstr(str)); return 0;}", "e": 7194, "s": 5590, "text": null }, { "code": "// Java implementation of O(n^2)// time and O(1) space method// to find the longest palindromic substringpublic class LongestPalinSubstring { // This function prints the // longest palindrome substring // (LPS) of str[]. It also // returns the length of the // longest palindrome static int longestPalSubstr(String str) { int n = str.length(); // calculcharAting size of string if (n < 2) return n; // if string is empty then size will be 0. // if n==1 then, answer will be 1(single // character will always palindrome) int maxLength = 1,start=0; int low, high; for (int i = 0; i < n; i++) { low = i - 1; high = i + 1; while ( high < n && str.charAt(high) == str.charAt(i)) //increment 'high' high++; while ( low >= 0 && str.charAt(low) == str.charAt(i)) // decrement 'low' low--; while (low >= 0 && high < n && str.charAt(low) == str.charAt(high) ){ low--; high++; } int length = high - low - 1; if (maxLength < length){ maxLength = length; start=low+1; } } System.out.print(\"Longest palindrome substring is: \"); System.out.println(str.substring(start, start + maxLength )); return maxLength; } // Driver program to test above function public static void main(String[] args) { String str = \"forgeeksskeegfor\"; System.out.println(\"Length is: \" + longestPalSubstr(str)); }}", "e": 8883, "s": 7194, "text": null }, { "code": "# A O(n ^ 2) time and O(1) space program to find the# longest palindromic substring # This function prints the longest palindrome substring (LPS)# of str[]. It also returns the length of the longest palindrome def longestPalSubstr(string): n = len(string) # calculating size of string if (n < 2): return n # if string is empty then size will be 0. # if n==1 then, answer will be 1(single # character will always palindrome) start=0 maxLength = 1 for i in range(n): low = i - 1 high = i + 1 while (high < n and string[high] == string[i] ): high=high+1 while (low >= 0 and string[low] == string[i] ): low=low-1 while (low >= 0 and high < n and string[low] == string[high] ): low=low-1 high=high+1 length = high - low - 1 if (maxLength < length): maxLength = length start=low+1 print (\"Longest palindrome substring is:\",end=\" \") print (string[start:start + maxLength]) return maxLength # Driver program to test above functionsstring = (\"forgeeksskeegfor\")print(\"Length is: \" + str(longestPalSubstr(string)))", "e": 10161, "s": 8883, "text": null }, { "code": "// C# implementation of O(n^2) time// and O(1) space method to find the// longest palindromic substringusing System; class GFG { // This function prints the longest // palindrome substring (LPS) of str[]. // It also returns the length of the // longest palindrome public static int longestPalSubstr(string str) { int n = str.Length; // calculcharAting size of string if (n < 2) return n; // if string is empty then size will be 0. // if n==1 then, answer will be 1(single // character will always palindrome) int maxLength = 1,start=0; int low, high; for (int i = 0; i < n; i++) { low = i - 1; high = i + 1; while ( high < n && str[high] == str[i] ) //increment 'high' high++; while ( low >= 0 && str[low] == str[i]) // decrement 'low' low--; while (low >= 0 && high < n && str[low] == str[high] ){ low--; high++; } int length = high - low - 1; if (maxLength < length){ maxLength = length; start=low+1; } } Console.Write(\"Longest palindrome substring is: \"); Console.WriteLine(str.Substring(start, maxLength)); return maxLength; } // Driver Code public static void Main(string[] args) { string str = \"forgeeksskeegfor\"; Console.WriteLine(\"Length is: \" + longestPalSubstr(str)); }}", "e": 11747, "s": 10161, "text": null }, { "code": "<script> // A O(n^2) time and O(1) space program to// find the longest palindromic substring// easy to understand as compared to previous version. // A utility function to print// a substring str[low..high]// This function prints the// longest palindrome substring (LPS)// of str[]. It also returns the// length of the longest palindromefunction longestPalSubstr(str){ let n = str.length; // calculating size of string if (n < 2) return n; // if string is empty then size will be 0. // if n==1 then, answer will be 1(single // character will always palindrome) let maxLength = 1,start=0; let low, high; for (let i = 0; i < n; i++) { low = i - 1; high = i + 1; while ( high < n && str[high] == str[i]) //increment 'high' high++; while ( low >= 0 && str[low] == str[i]) // decrement 'low' low--; while (low >= 0 && high < n && str[low] == str[high]){ low--; high++; } let length = high - low - 1; if (maxLength < length) { maxLength = length; start=low+1; } } document.write(\"Longest palindrome substring is: \"); document.write(str.substring(start,maxLength+start)); return maxLength;} // Driver program to test above functions let str = \"forgeeksskeegfor\";document.write(\"</br>\",\"Length is: \" + longestPalSubstr(str),\"</br>\"); </script>", "e": 13240, "s": 11747, "text": null }, { "code": null, "e": 13299, "s": 13240, "text": "Longest palindrome substring is: geeksskeeg\nLength is: 10\n" }, { "code": null, "e": 13322, "s": 13299, "text": "Complexity Analysis: " }, { "code": null, "e": 13490, "s": 13322, "text": "Time complexity: O(n^2), where n is the length of the input string. Outer Loop that traverses through the entire string, and Inner Loop that is used to expand from i ." }, { "code": null, "e": 13539, "s": 13490, "text": "Auxiliary Space: O(1). No extra space is needed." }, { "code": null, "e": 13576, "s": 13539, "text": "The Above approach is a cleaner way." }, { "code": null, "e": 13662, "s": 13576, "text": "The function implementation to print the LPS and return the maxLength is given below:" }, { "code": null, "e": 13666, "s": 13662, "text": "C++" }, { "code": null, "e": 13671, "s": 13666, "text": "Java" }, { "code": null, "e": 13674, "s": 13671, "text": "C#" }, { "code": "// A O(n^2) time and O(1) space program to// find the longest palindromic substring// easy to understand as compared to previous version. #include <bits/stdc++.h>using namespace std; int maxLength; // variables to store andstring res; // update maxLength and res // A utility function to get the longest palindrome// starting and expanding out from given center indicesvoid cSubUtil(string& s, int l, int r){ // check if the indices lie in the range of string // and also if it is palindrome while (l >= 0 && r < s.length() && s[l] == s[r]) { // expand the boundary l--; r++; } // if it's length is greater than maxLength update // maxLength and res if (r - l - 1 >= maxLength) { res = s.substr(l + 1, r - l - 1); maxLength = r - l - 1; } return;}// A function which takes a string prints the LPS and// returns the length of LPSint longestPalSubstr(string str){ res = \"\"; maxLength = 1; // for every index in the string check palindromes // starting from that index for (int i = 0; i < str.length(); i++) { // check for odd length palindromes cSubUtil(str, i, i); // check for even length palindromes cSubUtil(str, i, i + 1); } cout << \"Longest palindrome substring is: \"; cout << res << \"\\n\"; return maxLength;} // Driver program to test above functionsint main(){ string str = \"forgeeksskeegfor\"; cout << \"\\nLength is: \" << longestPalSubstr(str) << endl; return 0;}", "e": 15179, "s": 13674, "text": null }, { "code": "// Java implementation of O(n^2)// time and O(1) space method// to find the longest palindromic substring public class LongestPalinSubstring { static int maxLength; // variables to store and static String res; // update maxLength and res // A utility function to get the longest palindrome // starting and expanding out from given center indices static void cSubUtil(String s, int l, int r) { // check if the indices lie in the range of string // and also if it is palindrome while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { // expand the boundary l--; r++; } // if it's length is greater than maxLength update // maxLength and res if (r - l - 1 >= maxLength) { res = s.substring(l + 1, r); maxLength = r - l - 1; } return; } // A function which takes a string prints the LPS and // returns the length of LPS static int longestPalSubstr(String str) { res = \"\"; maxLength = 1; // for every index in the string check palindromes // starting from that index for (int i = 0; i < str.length(); i++) { // check for odd length palindromes cSubUtil(str, i, i); // check for even length palindromes cSubUtil(str, i, i + 1); } System.out.print( \"Longest palindrome substring is: \"); System.out.println(res); return maxLength; } // Driver program to test above function public static void main(String[] args) { String str = \"forgeeksskeegfor\"; System.out.println(\"Length is: \" + longestPalSubstr(str)); }}", "e": 16933, "s": 15179, "text": null }, { "code": "// C# implementation of O(n^2) time// and O(1) space method to find the// longest palindromic substringusing System; class GFG { static int maxLength; // variables to store and static string res; // update maxLength and res // A utility function to get the longest palindrome // starting and expanding out from given center indices public static void cSubUtil(string s, int l, int r) { // check if the indices lie in the range of string // and also if it is palindrome while (l >= 0 && r < s.Length && s[l] == s[r]) { // expand the boundary l--; r++; } // if it's length is greater than maxLength update // maxLength and res if (r - l - 1 >= maxLength) { res = s.Substring(l + 1, r - l - 1); maxLength = r - l - 1; } return; } // A function which takes a string prints the LPS and // returns the length of LPS public static int longestPalSubstr(string str) { res = \"\"; maxLength = 1; // for every index in the string check palindromes // starting from that index for (int i = 0; i < str.Length; i++) { // check for odd length palindromes cSubUtil(str, i, i); // check for even length palindromes cSubUtil(str, i, i + 1); } Console.Write(\"Longest palindrome substring is: \"); Console.WriteLine(res); return maxLength; } // Driver Code public static void Main(string[] args) { string str = \"forgeeksskeegfor\"; Console.WriteLine(\"Length is: \" + longestPalSubstr(str)); }}", "e": 18619, "s": 16933, "text": null }, { "code": null, "e": 18679, "s": 18619, "text": "Longest palindrome substring is: geeksskeeg\n\nLength is: 10\n" }, { "code": null, "e": 18791, "s": 18679, "text": "Please write comments if you find anything incorrect, or have more information about the topic discussed above." }, { "code": null, "e": 18803, "s": 18791, "text": "shrikanth13" }, { "code": null, "e": 18809, "s": 18803, "text": "ukasp" }, { "code": null, "e": 18823, "s": 18809, "text": "rathbhupendra" }, { "code": null, "e": 18834, "s": 18823, "text": "andrew1234" }, { "code": null, "e": 18846, "s": 18834, "text": "sourabh1996" }, { "code": null, "e": 18854, "s": 18846, "text": "rag2127" }, { "code": null, "e": 18865, "s": 18854, "text": "RaviOstwal" }, { "code": null, "e": 18884, "s": 18865, "text": "yogesh vishwakarma" }, { "code": null, "e": 18894, "s": 18884, "text": "kk9826225" }, { "code": null, "e": 18910, "s": 18894, "text": "amartyaghoshgfg" }, { "code": null, "e": 18921, "s": 18910, "text": "oyesaurabh" }, { "code": null, "e": 18934, "s": 18921, "text": "shinjanpatra" }, { "code": null, "e": 18944, "s": 18934, "text": "20ec01033" }, { "code": null, "e": 18958, "s": 18944, "text": "abhijeet19403" }, { "code": null, "e": 18967, "s": 18958, "text": "Accolite" }, { "code": null, "e": 18974, "s": 18967, "text": "Amazon" }, { "code": null, "e": 18982, "s": 18974, "text": "Groupon" }, { "code": null, "e": 18992, "s": 18982, "text": "Microsoft" }, { "code": null, "e": 19003, "s": 18992, "text": "palindrome" }, { "code": null, "e": 19011, "s": 19003, "text": "Strings" }, { "code": null, "e": 19020, "s": 19011, "text": "Accolite" }, { "code": null, "e": 19027, "s": 19020, "text": "Amazon" }, { "code": null, "e": 19037, "s": 19027, "text": "Microsoft" }, { "code": null, "e": 19045, "s": 19037, "text": "Groupon" }, { "code": null, "e": 19053, "s": 19045, "text": "Strings" }, { "code": null, "e": 19064, "s": 19053, "text": "palindrome" }, { "code": null, "e": 19162, "s": 19064, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 19237, "s": 19162, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" }, { "code": null, "e": 19282, "s": 19237, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 19339, "s": 19282, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 19375, "s": 19339, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 19439, "s": 19375, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 19484, "s": 19439, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 19545, "s": 19484, "text": "Length of the longest substring without repeating characters" }, { "code": null, "e": 19581, "s": 19545, "text": "Convert string to char array in C++" }, { "code": null, "e": 19613, "s": 19581, "text": "Reverse words in a given string" } ]
Optional ifPresentOrElse() method in Java with examples
30 Jul, 2019 The ifPresentOrElse(Consumer, Runnable) method of java.util.Optional class helps us to perform the specified Consumer action the value of this Optional object. If a value is not present in this Optional, then this method performs the given empty-based Runnable emptyAction, passed as the second parameter Syntax: public void ifPresentOrElse(Consumer<T> action, Runnable emptyAction) Parameters: This method accepts two parameters: action: which is the action to be performed on this Optional, if a value is present. emptyAction: which is the empty-based action to be performed, if no value is present. Return value: This method returns nothing. Exception: This method throw NullPointerException if a value is present and the given action is null, or no value is present and the given empty-based action is null. Below programs illustrate ifPresentOrElse() method: Note: As this method was added in Java 9, the programs need JDK 9 to execute. Program 1: // Java program to demonstrate// Optional.ifPresentOrElse() method import java.util.*; public class GFG { public static void main(String[] args) { // create a Optional Optional<Integer> op = Optional.of(9455); // print value System.out.println("Optional: " + op); // apply ifPresentOrElse op.ifPresentOrElse( (value) -> { System.out.println( "Value is present, its: " + value); }, () -> { System.out.println( "Value is empty"); }); }} Output: Optional: Optional[9455] Value is present, its: 9455 Program 2: // Java program to demonstrate// Optional.ifPresentOrElse method import java.util.*; public class GFG { public static void main(String[] args) { // create a Optional Optional<Integer> op = Optional.empty(); // print value System.out.println("Optional: " + op); try { // apply ifPresentOrElse op.ifPresentOrElse( (value) -> { System.out.println( "Value is present, its: " + value); }, () -> { System.out.println( "Value is empty"); }); } catch (Exception e) { System.out.println(e); } }} Output: Optional: Optional.empty Value is empty Reference: https://docs.oracle.com/javase/9/docs/api/java/util/Optional.html#ifPresentOrElse-java.util.function.Consumer-java.lang.Runnable- Java - util package Java-Functions Java-Optional Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java Stream In Java Collections in Java Singleton Class in Java Set in Java Stack Class in Java Initializing a List in Java Introduction to Java Constructors in Java Multithreading in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n30 Jul, 2019" }, { "code": null, "e": 359, "s": 54, "text": "The ifPresentOrElse(Consumer, Runnable) method of java.util.Optional class helps us to perform the specified Consumer action the value of this Optional object. If a value is not present in this Optional, then this method performs the given empty-based Runnable emptyAction, passed as the second parameter" }, { "code": null, "e": 367, "s": 359, "text": "Syntax:" }, { "code": null, "e": 466, "s": 367, "text": "public void ifPresentOrElse(Consumer<T> action,\n Runnable emptyAction)\n" }, { "code": null, "e": 514, "s": 466, "text": "Parameters: This method accepts two parameters:" }, { "code": null, "e": 599, "s": 514, "text": "action: which is the action to be performed on this Optional, if a value is present." }, { "code": null, "e": 685, "s": 599, "text": "emptyAction: which is the empty-based action to be performed, if no value is present." }, { "code": null, "e": 728, "s": 685, "text": "Return value: This method returns nothing." }, { "code": null, "e": 895, "s": 728, "text": "Exception: This method throw NullPointerException if a value is present and the given action is null, or no value is present and the given empty-based action is null." }, { "code": null, "e": 947, "s": 895, "text": "Below programs illustrate ifPresentOrElse() method:" }, { "code": null, "e": 1025, "s": 947, "text": "Note: As this method was added in Java 9, the programs need JDK 9 to execute." }, { "code": null, "e": 1036, "s": 1025, "text": "Program 1:" }, { "code": "// Java program to demonstrate// Optional.ifPresentOrElse() method import java.util.*; public class GFG { public static void main(String[] args) { // create a Optional Optional<Integer> op = Optional.of(9455); // print value System.out.println(\"Optional: \" + op); // apply ifPresentOrElse op.ifPresentOrElse( (value) -> { System.out.println( \"Value is present, its: \" + value); }, () -> { System.out.println( \"Value is empty\"); }); }}", "e": 1693, "s": 1036, "text": null }, { "code": null, "e": 1701, "s": 1693, "text": "Output:" }, { "code": null, "e": 1755, "s": 1701, "text": "Optional: Optional[9455]\nValue is present, its: 9455\n" }, { "code": null, "e": 1766, "s": 1755, "text": "Program 2:" }, { "code": "// Java program to demonstrate// Optional.ifPresentOrElse method import java.util.*; public class GFG { public static void main(String[] args) { // create a Optional Optional<Integer> op = Optional.empty(); // print value System.out.println(\"Optional: \" + op); try { // apply ifPresentOrElse op.ifPresentOrElse( (value) -> { System.out.println( \"Value is present, its: \" + value); }, () -> { System.out.println( \"Value is empty\"); }); } catch (Exception e) { System.out.println(e); } }}", "e": 2552, "s": 1766, "text": null }, { "code": null, "e": 2560, "s": 2552, "text": "Output:" }, { "code": null, "e": 2601, "s": 2560, "text": "Optional: Optional.empty\nValue is empty\n" }, { "code": null, "e": 2742, "s": 2601, "text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/util/Optional.html#ifPresentOrElse-java.util.function.Consumer-java.lang.Runnable-" }, { "code": null, "e": 2762, "s": 2742, "text": "Java - util package" }, { "code": null, "e": 2777, "s": 2762, "text": "Java-Functions" }, { "code": null, "e": 2791, "s": 2777, "text": "Java-Optional" }, { "code": null, "e": 2796, "s": 2791, "text": "Java" }, { "code": null, "e": 2801, "s": 2796, "text": "Java" }, { "code": null, "e": 2899, "s": 2801, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2918, "s": 2899, "text": "Interfaces in Java" }, { "code": null, "e": 2933, "s": 2918, "text": "Stream In Java" }, { "code": null, "e": 2953, "s": 2933, "text": "Collections in Java" }, { "code": null, "e": 2977, "s": 2953, "text": "Singleton Class in Java" }, { "code": null, "e": 2989, "s": 2977, "text": "Set in Java" }, { "code": null, "e": 3009, "s": 2989, "text": "Stack Class in Java" }, { "code": null, "e": 3037, "s": 3009, "text": "Initializing a List in Java" }, { "code": null, "e": 3058, "s": 3037, "text": "Introduction to Java" }, { "code": null, "e": 3079, "s": 3058, "text": "Constructors in Java" } ]
scriptreplay command in Linux with Examples
17 Apr, 2019 scriptreplay command is used to replay a typescript/terminal_activity stored in the log file that was recorded by the script command. With the help of timing information, the log files are played and the outputs are generated in the terminal with the same speed the original script was recorded. The replay does not run the command again but it only displays the same information once again, thus scriptreplay must be run on the same type of terminal the typescript was recorded in order to work properly.By default, the replay displays the information stored in typescript file if no other filename is specified. Syntax: scriptreplay [-t] timingfile [typescript] [divisor] Example: To replay a recorded script with script filename as geeksforgeeks and timing output file as time_log. Options: -t, –timing: This option is used for script timing output file.Example: To replay the script timing file, time_log. Example: To replay the script timing file, time_log. -s, –typescript: This option is used for script terminal session output file.Example: To replay the script namely geeksforgeeks using -s option. Example: To replay the script namely geeksforgeeks using -s option. -d, –divisor: This option is used when we want to speed up or slow down execution with time divisor. The argument here is a floating point number.Example 1: To replay the script, geeksforgeeks with 2x speed we will use 2 as a divisor.Input:The replay speed will increase by twice.Output:Example 2: To replay the script, geeksforgeeks with 2 times slower we will use 0.2 as a divisor. Example 1: To replay the script, geeksforgeeks with 2x speed we will use 2 as a divisor. Input: The replay speed will increase by twice. Output: Example 2: To replay the script, geeksforgeeks with 2 times slower we will use 0.2 as a divisor. -V, –version: Output version information and exit. -h, –help: Display this help and exit. linux-command Linux-misc-commands 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 Introduction to Linux Operating System SED command in Linux | Set 2 Array Basics in Shell Scripting | Set 1 nohup Command in Linux with Examples chmod command in Linux with examples mv command in Linux with examples Basic Operators in Shell Scripting
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Apr, 2019" }, { "code": null, "e": 642, "s": 28, "text": "scriptreplay command is used to replay a typescript/terminal_activity stored in the log file that was recorded by the script command. With the help of timing information, the log files are played and the outputs are generated in the terminal with the same speed the original script was recorded. The replay does not run the command again but it only displays the same information once again, thus scriptreplay must be run on the same type of terminal the typescript was recorded in order to work properly.By default, the replay displays the information stored in typescript file if no other filename is specified." }, { "code": null, "e": 650, "s": 642, "text": "Syntax:" }, { "code": null, "e": 702, "s": 650, "text": "scriptreplay [-t] timingfile [typescript] [divisor]" }, { "code": null, "e": 813, "s": 702, "text": "Example: To replay a recorded script with script filename as geeksforgeeks and timing output file as time_log." }, { "code": null, "e": 822, "s": 813, "text": "Options:" }, { "code": null, "e": 938, "s": 822, "text": "-t, –timing: This option is used for script timing output file.Example: To replay the script timing file, time_log." }, { "code": null, "e": 991, "s": 938, "text": "Example: To replay the script timing file, time_log." }, { "code": null, "e": 1136, "s": 991, "text": "-s, –typescript: This option is used for script terminal session output file.Example: To replay the script namely geeksforgeeks using -s option." }, { "code": null, "e": 1204, "s": 1136, "text": "Example: To replay the script namely geeksforgeeks using -s option." }, { "code": null, "e": 1588, "s": 1204, "text": "-d, –divisor: This option is used when we want to speed up or slow down execution with time divisor. The argument here is a floating point number.Example 1: To replay the script, geeksforgeeks with 2x speed we will use 2 as a divisor.Input:The replay speed will increase by twice.Output:Example 2: To replay the script, geeksforgeeks with 2 times slower we will use 0.2 as a divisor." }, { "code": null, "e": 1677, "s": 1588, "text": "Example 1: To replay the script, geeksforgeeks with 2x speed we will use 2 as a divisor." }, { "code": null, "e": 1684, "s": 1677, "text": "Input:" }, { "code": null, "e": 1725, "s": 1684, "text": "The replay speed will increase by twice." }, { "code": null, "e": 1733, "s": 1725, "text": "Output:" }, { "code": null, "e": 1830, "s": 1733, "text": "Example 2: To replay the script, geeksforgeeks with 2 times slower we will use 0.2 as a divisor." }, { "code": null, "e": 1881, "s": 1830, "text": "-V, –version: Output version information and exit." }, { "code": null, "e": 1920, "s": 1881, "text": "-h, –help: Display this help and exit." }, { "code": null, "e": 1934, "s": 1920, "text": "linux-command" }, { "code": null, "e": 1954, "s": 1934, "text": "Linux-misc-commands" }, { "code": null, "e": 1965, "s": 1954, "text": "Linux-Unix" }, { "code": null, "e": 2063, "s": 1965, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2089, "s": 2063, "text": "Docker - COPY Instruction" }, { "code": null, "e": 2124, "s": 2089, "text": "scp command in Linux with Examples" }, { "code": null, "e": 2161, "s": 2124, "text": "chown command in Linux with Examples" }, { "code": null, "e": 2200, "s": 2161, "text": "Introduction to Linux Operating System" }, { "code": null, "e": 2229, "s": 2200, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 2269, "s": 2229, "text": "Array Basics in Shell Scripting | Set 1" }, { "code": null, "e": 2306, "s": 2269, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 2343, "s": 2306, "text": "chmod command in Linux with examples" }, { "code": null, "e": 2377, "s": 2343, "text": "mv command in Linux with examples" } ]
How to replace an HTML element with another one using JavaScript ?
18 Nov, 2020 Document Object Model (DOM) is a platform and language-neutral interface which is used by programs and scripts to dynamically access the content, style and structure. Please refer to DOM (Document Object Model) to know the details. We can implement this by using DOM’s createElement(), createTextNode(), appendChild(), replaceChild() methods and childNodes property. Let us discuss these methods and property to replace one HTML element to another. createElement(): It is used to create an element node with the specified name.Syntax:var element = document.createElement("Element_name"); In this example, the element is “h1” tag, so write var element=document.createElement("h1"); var element = document.createElement("Element_name"); In this example, the element is “h1” tag, so write var element=document.createElement("h1"); createTextNode(): The method is used to create a text node.Syntax: var txt = document.createTextNode("Some_Text"); var txt = document.createTextNode("Some_Text"); appendChild(): After creating text node, we have to append it to the element by using appendChild() method.Syntax: element.appendChild(Node_To_append); Syntax: element.appendChild(Node_To_append); The following shows the working code on how to use these methods and property discussed above. HTML <!DOCTYPE html><html> <body> <h2> Using DOM'S to print Hello World </h2> <script> var h = document.createElement("h3"); var txt = document .createTextNode("Hello World!!"); h.appendChild(txt); document.body.appendChild(h); </script></body> </html> Output: Before Clicking the Button: After Clicking the Button: childNodes[Position]: This property returns a collection of child nodes as a NodeList object. The nodes are sorted as they appear in source code and can be accessed by index number starting from 0. replaceChild(): It replace a child node with new node. old_Node.replaceChild(new_Node, old_node.childNodes[node_position]); Example: The following code shows how to replace element with another one. HTML <!DOCTYPE html><html> <body> <div id="p1"> <p id="red">Hello World </p> <!-- We are going to replace Hello World!! in "p" tag with "Hello Geeks" in "h2" tag--> <button onclick="repFun()"> Click Me </button> </div> <p id="demo"></p> <script> function repFun() { // Creating "h2" element var H = document.createElement("h2"); // Retaining id H.setAttribute("id", "red"); // Creating Text node var txt = document.createTextNode("Hello Geeks!!"); // Accessing the Element we want to replace var repNode = document.getElementById("p1"); // Appending Text Node in Element H.appendChild(txt); // Replacing one element with another p1.replaceChild(H, p1.childNodes[0]); } </script></body> </html> Output: Before clicking the Button: After clicking the Button: HTML-Misc JavaScript-Misc HTML JavaScript Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) Design a Tribute Page using HTML & CSS Build a Survey Form using HTML and CSS Angular File Upload Design a web page using HTML and CSS Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Difference Between PUT and PATCH Request How to append HTML code to a div using JavaScript ?
[ { "code": null, "e": 54, "s": 26, "text": "\n18 Nov, 2020" }, { "code": null, "e": 421, "s": 54, "text": "Document Object Model (DOM) is a platform and language-neutral interface which is used by programs and scripts to dynamically access the content, style and structure. Please refer to DOM (Document Object Model) to know the details. We can implement this by using DOM’s createElement(), createTextNode(), appendChild(), replaceChild() methods and childNodes property." }, { "code": null, "e": 503, "s": 421, "text": "Let us discuss these methods and property to replace one HTML element to another." }, { "code": null, "e": 736, "s": 503, "text": "createElement(): It is used to create an element node with the specified name.Syntax:var element = document.createElement(\"Element_name\"); \nIn this example, the element is “h1” tag, so write var element=document.createElement(\"h1\");" }, { "code": null, "e": 792, "s": 736, "text": "var element = document.createElement(\"Element_name\"); \n" }, { "code": null, "e": 843, "s": 792, "text": "In this example, the element is “h1” tag, so write" }, { "code": null, "e": 886, "s": 843, "text": " var element=document.createElement(\"h1\");" }, { "code": null, "e": 1001, "s": 886, "text": "createTextNode(): The method is used to create a text node.Syntax: var txt = document.createTextNode(\"Some_Text\");" }, { "code": null, "e": 1050, "s": 1001, "text": " var txt = document.createTextNode(\"Some_Text\");" }, { "code": null, "e": 1202, "s": 1050, "text": "appendChild(): After creating text node, we have to append it to the element by using appendChild() method.Syntax: element.appendChild(Node_To_append);" }, { "code": null, "e": 1210, "s": 1202, "text": "Syntax:" }, { "code": null, "e": 1248, "s": 1210, "text": " element.appendChild(Node_To_append);" }, { "code": null, "e": 1343, "s": 1248, "text": "The following shows the working code on how to use these methods and property discussed above." }, { "code": null, "e": 1348, "s": 1343, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <h2> Using DOM'S to print Hello World </h2> <script> var h = document.createElement(\"h3\"); var txt = document .createTextNode(\"Hello World!!\"); h.appendChild(txt); document.body.appendChild(h); </script></body> </html>", "e": 1685, "s": 1348, "text": null }, { "code": null, "e": 1693, "s": 1685, "text": "Output:" }, { "code": null, "e": 1721, "s": 1693, "text": "Before Clicking the Button:" }, { "code": null, "e": 1748, "s": 1721, "text": "After Clicking the Button:" }, { "code": null, "e": 1946, "s": 1748, "text": "childNodes[Position]: This property returns a collection of child nodes as a NodeList object. The nodes are sorted as they appear in source code and can be accessed by index number starting from 0." }, { "code": null, "e": 2001, "s": 1946, "text": "replaceChild(): It replace a child node with new node." }, { "code": null, "e": 2070, "s": 2001, "text": "old_Node.replaceChild(new_Node, old_node.childNodes[node_position]);" }, { "code": null, "e": 2145, "s": 2070, "text": "Example: The following code shows how to replace element with another one." }, { "code": null, "e": 2150, "s": 2145, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <div id=\"p1\"> <p id=\"red\">Hello World </p> <!-- We are going to replace Hello World!! in \"p\" tag with \"Hello Geeks\" in \"h2\" tag--> <button onclick=\"repFun()\"> Click Me </button> </div> <p id=\"demo\"></p> <script> function repFun() { // Creating \"h2\" element var H = document.createElement(\"h2\"); // Retaining id H.setAttribute(\"id\", \"red\"); // Creating Text node var txt = document.createTextNode(\"Hello Geeks!!\"); // Accessing the Element we want to replace var repNode = document.getElementById(\"p1\"); // Appending Text Node in Element H.appendChild(txt); // Replacing one element with another p1.replaceChild(H, p1.childNodes[0]); } </script></body> </html>", "e": 3113, "s": 2150, "text": null }, { "code": null, "e": 3121, "s": 3113, "text": "Output:" }, { "code": null, "e": 3149, "s": 3121, "text": "Before clicking the Button:" }, { "code": null, "e": 3176, "s": 3149, "text": "After clicking the Button:" }, { "code": null, "e": 3186, "s": 3176, "text": "HTML-Misc" }, { "code": null, "e": 3202, "s": 3186, "text": "JavaScript-Misc" }, { "code": null, "e": 3207, "s": 3202, "text": "HTML" }, { "code": null, "e": 3218, "s": 3207, "text": "JavaScript" }, { "code": null, "e": 3235, "s": 3218, "text": "Web Technologies" }, { "code": null, "e": 3262, "s": 3235, "text": "Web technologies Questions" }, { "code": null, "e": 3267, "s": 3262, "text": "HTML" }, { "code": null, "e": 3365, "s": 3267, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3389, "s": 3365, "text": "REST API (Introduction)" }, { "code": null, "e": 3428, "s": 3389, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 3467, "s": 3428, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 3487, "s": 3467, "text": "Angular File Upload" }, { "code": null, "e": 3524, "s": 3487, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 3585, "s": 3524, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3657, "s": 3585, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 3697, "s": 3657, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 3738, "s": 3697, "text": "Difference Between PUT and PATCH Request" } ]
Python Program to convert a list into matrix with size of each row increasing by a number
24 Jan, 2021 Given a list and a number N, the task here is to write a python program to convert it to matrix where each row has N elements more than previous row elements from list. Input : test_list = [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1], N = 3 Output : [[4, 6, 8], [4, 6, 8, 1, 2, 9], [4, 6, 8, 1, 2, 9, 0, 10, 12], [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1]] Explanation : Each row has 3 elements more than previous row. Input : test_list = [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1], N = 4 Output : [[4, 6, 8, 1], [4, 6, 8, 1, 2, 9, 0, 10], [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1]] Explanation : Each row has 4 elements more than previous row. Method 1 : Using loop and slicing In this, we perform task of getting chunks using slicing, and conversion of list into Matrix is done using loop. Program: Python3 # initializing listtest_list = [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1] # printing original listprint("The original list is : " + str(test_list)) # initializing NN = 3 res = []for idx in range(0, len(test_list) // N): # getting incremented chunks res.append(test_list[0: (idx + 1) * N]) # printing resultprint("Constructed Chunk Matrix : " + str(res)) Output: The original list is : [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1] Constructed Chunk Matrix : [[4, 6, 8], [4, 6, 8, 1, 2, 9], [4, 6, 8, 1, 2, 9, 0, 10, 12], [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1]] Method 2 : Using list comprehension and list slicing In this, we perform task of setting values using list comprehension as a shorthand. Rest all the operations are done similar to above method. Program: Python3 # initializing listtest_list = [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1] # printing original listprint("The original list is : " + str(test_list)) # initializing NN = 3 # getting incremented chunks# using list comprehension as shorthandres = [test_list[0: (idx + 1) * N] for idx in range(0, len(test_list) // N)] # printing resultprint("Constructed Chunk Matrix : " + str(res)) Output: The original list is : [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1] Constructed Chunk Matrix : [[4, 6, 8], [4, 6, 8, 1, 2, 9], [4, 6, 8, 1, 2, 9, 0, 10, 12], [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1]] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python | os.path.join() method Introduction To PYTHON Python OOPs Concepts 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": 28, "s": 0, "text": "\n24 Jan, 2021" }, { "code": null, "e": 197, "s": 28, "text": "Given a list and a number N, the task here is to write a python program to convert it to matrix where each row has N elements more than previous row elements from list." }, { "code": null, "e": 263, "s": 197, "text": "Input : test_list = [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1], N = 3" }, { "code": null, "e": 375, "s": 263, "text": "Output : [[4, 6, 8], [4, 6, 8, 1, 2, 9], [4, 6, 8, 1, 2, 9, 0, 10, 12], [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1]]" }, { "code": null, "e": 437, "s": 375, "text": "Explanation : Each row has 3 elements more than previous row." }, { "code": null, "e": 503, "s": 437, "text": "Input : test_list = [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1], N = 4" }, { "code": null, "e": 594, "s": 503, "text": "Output : [[4, 6, 8, 1], [4, 6, 8, 1, 2, 9, 0, 10], [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1]]" }, { "code": null, "e": 656, "s": 594, "text": "Explanation : Each row has 4 elements more than previous row." }, { "code": null, "e": 690, "s": 656, "text": "Method 1 : Using loop and slicing" }, { "code": null, "e": 803, "s": 690, "text": "In this, we perform task of getting chunks using slicing, and conversion of list into Matrix is done using loop." }, { "code": null, "e": 812, "s": 803, "text": "Program:" }, { "code": null, "e": 820, "s": 812, "text": "Python3" }, { "code": "# initializing listtest_list = [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing NN = 3 res = []for idx in range(0, len(test_list) // N): # getting incremented chunks res.append(test_list[0: (idx + 1) * N]) # printing resultprint(\"Constructed Chunk Matrix : \" + str(res))", "e": 1182, "s": 820, "text": null }, { "code": null, "e": 1190, "s": 1182, "text": "Output:" }, { "code": null, "e": 1252, "s": 1190, "text": "The original list is : [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1]" }, { "code": null, "e": 1382, "s": 1252, "text": "Constructed Chunk Matrix : [[4, 6, 8], [4, 6, 8, 1, 2, 9], [4, 6, 8, 1, 2, 9, 0, 10, 12], [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1]]" }, { "code": null, "e": 1436, "s": 1382, "text": "Method 2 : Using list comprehension and list slicing " }, { "code": null, "e": 1578, "s": 1436, "text": "In this, we perform task of setting values using list comprehension as a shorthand. Rest all the operations are done similar to above method." }, { "code": null, "e": 1587, "s": 1578, "text": "Program:" }, { "code": null, "e": 1595, "s": 1587, "text": "Python3" }, { "code": "# initializing listtest_list = [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing NN = 3 # getting incremented chunks# using list comprehension as shorthandres = [test_list[0: (idx + 1) * N] for idx in range(0, len(test_list) // N)] # printing resultprint(\"Constructed Chunk Matrix : \" + str(res))", "e": 1974, "s": 1595, "text": null }, { "code": null, "e": 1982, "s": 1974, "text": "Output:" }, { "code": null, "e": 2044, "s": 1982, "text": "The original list is : [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1]" }, { "code": null, "e": 2174, "s": 2044, "text": "Constructed Chunk Matrix : [[4, 6, 8], [4, 6, 8, 1, 2, 9], [4, 6, 8, 1, 2, 9, 0, 10, 12], [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1]]" }, { "code": null, "e": 2195, "s": 2174, "text": "Python list-programs" }, { "code": null, "e": 2202, "s": 2195, "text": "Python" }, { "code": null, "e": 2218, "s": 2202, "text": "Python Programs" }, { "code": null, "e": 2316, "s": 2218, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2348, "s": 2316, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2375, "s": 2348, "text": "Python Classes and Objects" }, { "code": null, "e": 2406, "s": 2375, "text": "Python | os.path.join() method" }, { "code": null, "e": 2429, "s": 2406, "text": "Introduction To PYTHON" }, { "code": null, "e": 2450, "s": 2429, "text": "Python OOPs Concepts" }, { "code": null, "e": 2472, "s": 2450, "text": "Defaultdict in Python" }, { "code": null, "e": 2511, "s": 2472, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2549, "s": 2511, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2598, "s": 2549, "text": "Python | Convert string dictionary to dictionary" } ]
How to sum two integers without using arithmetic operators in C/C++?
27 Jun, 2020 Given two integers a and b, how can we evaluate the sum a + b without using operators such as +, -, ++, –, ...? An interesting way would be: // May not work with C++ compilers and// may produce warnings in C. // Returns sum of 'a' and 'b'int sum(int a, int b) { char *p = a; return (int)&p[b];} Despite its awkwardness at first sight, we can easily understand what is happening. First, we created a pointer p. The value of a pointer is a memory address. In this case, the value of p is the address a.Remember: p points to position a. In that example, if we want to know the value of position a (999) we ask to *p. If we want to know the address of variable a (41), we ask to &a. If we evaluated p[b], we’d get the value of memory in position p + b. In fact, we evaluate &p[b], witch is the same as getting address p + b without accessing its value. As p = a, &p[b] will return the address a + b. We don’t want to return a memory address (int*). We want to return an integer (int). So, we cast &p[b] to int. What happens if we change the type of p from char* to int*? Let me fix what I said before: When we evaluate p[b] we don’t evaluate p + b. We evaluate p + sizeof(*p) * b. Why? Imagine this example: Variables of type int occupies fours positions in the memory. This sizeof(*p) considers the quantity of positions each variable occupies in the memory. We want to evaluate p + b. In other words, we want sizeof(*p) equals to 1. Consequently, if *p is a char, we’re happy. Let’s look the sum’s truth table (forgive the carry for now): Looking carefully, we notice that the sum’s and xor’s truth table are the same. It’s 1 only when the input differs. Now, how can we detect carry? Let’s look the carry’s truth table. Looking carefully, we notice that the sum’s and xor’s truth table are the same. It’s 1 only when the input differs. Now, how can we detect carry? Let’s look the carry’s truth table. Looking carefully one more time, we notice that the carry’s and logical and’s truth table are identicals. Now, we have to shift a & 1 to left and sum with a ^ b. However, these operations may have carries as well. No problem, just sum a ^ b with a & 1 shifted to left recursively. // Returns sum of a and b using bitwise// operators.int sum(int a, int b) { int s = a ^ b; int carry = a & b; if (carry == 0) return s; else return sum(s, carry << 1);} This solution has been discussed here. Let’s remember some facts: The printf returns the number of characters printed successfully. The specifier %*c requests two parameters: The first one is the customized width and the second is character. For example, printf(“%*c”, 5, ‘a’) will print ” a”. The special character ‘\r’ returns the cursor from the beginning of output string. For example, printf(“abcd\r12”) will print “12cd”. Keeping that in mind, we can understand this function: // Returns sum of a and b using printf// Constraints: a, b > 0.int sum(int a, int b) { return printf("%*c%*c", a, '\r', b, '\r');} This solution has been discussed here. This article is contributed by Igor Carpanese. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Akanksha_Rai Bitwise-XOR C Language C++ Mathematical Mathematical CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Function Pointer in C Multidimensional Arrays in C / C++ Left Shift and Right Shift Operators in C/C++ Different Methods to Reverse a String in C++ Vector in C++ STL Map in C++ Standard Template Library (STL) Initialize a vector in C++ (7 different ways) Set in C++ Standard Template Library (STL) vector erase() and clear() in C++
[ { "code": null, "e": 54, "s": 26, "text": "\n27 Jun, 2020" }, { "code": null, "e": 166, "s": 54, "text": "Given two integers a and b, how can we evaluate the sum a + b without using operators such as +, -, ++, –, ...?" }, { "code": null, "e": 195, "s": 166, "text": "An interesting way would be:" }, { "code": "// May not work with C++ compilers and// may produce warnings in C. // Returns sum of 'a' and 'b'int sum(int a, int b) { char *p = a; return (int)&p[b];}", "e": 356, "s": 195, "text": null }, { "code": null, "e": 740, "s": 356, "text": "Despite its awkwardness at first sight, we can easily understand what is happening. First, we created a pointer p. The value of a pointer is a memory address. In this case, the value of p is the address a.Remember: p points to position a. In that example, if we want to know the value of position a (999) we ask to *p. If we want to know the address of variable a (41), we ask to &a." }, { "code": null, "e": 957, "s": 740, "text": "If we evaluated p[b], we’d get the value of memory in position p + b. In fact, we evaluate &p[b], witch is the same as getting address p + b without accessing its value. As p = a, &p[b] will return the address a + b." }, { "code": null, "e": 1068, "s": 957, "text": "We don’t want to return a memory address (int*). We want to return an integer (int). So, we cast &p[b] to int." }, { "code": null, "e": 1327, "s": 1068, "text": "What happens if we change the type of p from char* to int*? Let me fix what I said before: When we evaluate p[b] we don’t evaluate p + b. We evaluate p + sizeof(*p) * b. Why? Imagine this example: Variables of type int occupies fours positions in the memory." }, { "code": null, "e": 1417, "s": 1327, "text": "This sizeof(*p) considers the quantity of positions each variable occupies in the memory." }, { "code": null, "e": 1536, "s": 1417, "text": "We want to evaluate p + b. In other words, we want sizeof(*p) equals to 1. Consequently, if *p is a char, we’re happy." }, { "code": null, "e": 1598, "s": 1536, "text": "Let’s look the sum’s truth table (forgive the carry for now):" }, { "code": null, "e": 1714, "s": 1598, "text": "Looking carefully, we notice that the sum’s and xor’s truth table are the same. It’s 1 only when the input differs." }, { "code": null, "e": 1780, "s": 1714, "text": "Now, how can we detect carry? Let’s look the carry’s truth table." }, { "code": null, "e": 1896, "s": 1780, "text": "Looking carefully, we notice that the sum’s and xor’s truth table are the same. It’s 1 only when the input differs." }, { "code": null, "e": 1962, "s": 1896, "text": "Now, how can we detect carry? Let’s look the carry’s truth table." }, { "code": null, "e": 2243, "s": 1962, "text": "Looking carefully one more time, we notice that the carry’s and logical and’s truth table are identicals. Now, we have to shift a & 1 to left and sum with a ^ b. However, these operations may have carries as well. No problem, just sum a ^ b with a & 1 shifted to left recursively." }, { "code": "// Returns sum of a and b using bitwise// operators.int sum(int a, int b) { int s = a ^ b; int carry = a & b; if (carry == 0) return s; else return sum(s, carry << 1);}", "e": 2426, "s": 2243, "text": null }, { "code": null, "e": 2465, "s": 2426, "text": "This solution has been discussed here." }, { "code": null, "e": 2494, "s": 2467, "text": "Let’s remember some facts:" }, { "code": null, "e": 2560, "s": 2494, "text": "The printf returns the number of characters printed successfully." }, { "code": null, "e": 2722, "s": 2560, "text": "The specifier %*c requests two parameters: The first one is the customized width and the second is character. For example, printf(“%*c”, 5, ‘a’) will print ” a”." }, { "code": null, "e": 2856, "s": 2722, "text": "The special character ‘\\r’ returns the cursor from the beginning of output string. For example, printf(“abcd\\r12”) will print “12cd”." }, { "code": null, "e": 2911, "s": 2856, "text": "Keeping that in mind, we can understand this function:" }, { "code": "// Returns sum of a and b using printf// Constraints: a, b > 0.int sum(int a, int b) { return printf(\"%*c%*c\", a, '\\r', b, '\\r');}", "e": 3045, "s": 2911, "text": null }, { "code": null, "e": 3084, "s": 3045, "text": "This solution has been discussed here." }, { "code": null, "e": 3352, "s": 3084, "text": "This article is contributed by Igor Carpanese. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 3476, "s": 3352, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 3489, "s": 3476, "text": "Akanksha_Rai" }, { "code": null, "e": 3501, "s": 3489, "text": "Bitwise-XOR" }, { "code": null, "e": 3512, "s": 3501, "text": "C Language" }, { "code": null, "e": 3516, "s": 3512, "text": "C++" }, { "code": null, "e": 3529, "s": 3516, "text": "Mathematical" }, { "code": null, "e": 3542, "s": 3529, "text": "Mathematical" }, { "code": null, "e": 3546, "s": 3542, "text": "CPP" }, { "code": null, "e": 3644, "s": 3546, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3661, "s": 3644, "text": "Substring in C++" }, { "code": null, "e": 3683, "s": 3661, "text": "Function Pointer in C" }, { "code": null, "e": 3718, "s": 3683, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 3764, "s": 3718, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 3809, "s": 3764, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 3827, "s": 3809, "text": "Vector in C++ STL" }, { "code": null, "e": 3870, "s": 3827, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 3916, "s": 3870, "text": "Initialize a vector in C++ (7 different ways)" }, { "code": null, "e": 3959, "s": 3916, "text": "Set in C++ Standard Template Library (STL)" } ]
Serializable Interface in Java
24 Nov, 2020 The Serializable interface is present in java.io package. It is a marker interface. A Marker Interface does not have any methods and fields. Thus classes implementing it do not have to implement any methods. Classes implement it if they want their instances to be Serialized or Deserialized. Serialization is a mechanism of converting the state of an object into a byte stream. Serialization is done using ObjectOutputStream. Deserialization is the reverse process where the byte stream is used to recreate the actual Java object in memory. This mechanism is used to persist the object. Deserialization is done using ObjectInputStream. Thus it can be used to make an eligible for saving its state into a file. Declaration public interface Serializable Example: The below example shows a class that implements Serializable Interface. Java // Java Program to demonstrate a class// implementing Serializable interface import java.io.Serializable; public static class Student implements Serializable { public String name = null; public String dept = null; public int id = 0;} Here, you can see that Student class implements Serializable, but does not have any methods to implement from Serializable. Example: Below example code explains Serializing and Deserializing an object. Java // Java program to illustrate Serializable interfaceimport java.io.*; // By implementing Serializable interface// we make sure that state of instances of class A// can be saved in a file.class A implements Serializable { int i; String s; // A class constructor public A(int i, String s) { this.i = i; this.s = s; }} public class Test { public static void main(String[] args) throws IOException, ClassNotFoundException { A a = new A(20, "GeeksForGeeks"); // Serializing 'a' FileOutputStream fos = new FileOutputStream("xyz.txt"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(a); // De-serializing 'a' FileInputStream fis = new FileInputStream("xyz.txt"); ObjectInputStream ois = new ObjectInputStream(fis); A b = (A)ois.readObject(); // down-casting object System.out.println(b.i + " " + b.s); // closing streams oos.close(); ois.close(); }} Output: 20 GeeksForGeeks Must Read: Serialization and Deserialization in Java Java-Collections Java-I/O Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Nov, 2020" }, { "code": null, "e": 739, "s": 28, "text": "The Serializable interface is present in java.io package. It is a marker interface. A Marker Interface does not have any methods and fields. Thus classes implementing it do not have to implement any methods. Classes implement it if they want their instances to be Serialized or Deserialized. Serialization is a mechanism of converting the state of an object into a byte stream. Serialization is done using ObjectOutputStream. Deserialization is the reverse process where the byte stream is used to recreate the actual Java object in memory. This mechanism is used to persist the object. Deserialization is done using ObjectInputStream. Thus it can be used to make an eligible for saving its state into a file. " }, { "code": null, "e": 751, "s": 739, "text": "Declaration" }, { "code": null, "e": 782, "s": 751, "text": "public interface Serializable\n" }, { "code": null, "e": 863, "s": 782, "text": "Example: The below example shows a class that implements Serializable Interface." }, { "code": null, "e": 868, "s": 863, "text": "Java" }, { "code": "// Java Program to demonstrate a class// implementing Serializable interface import java.io.Serializable; public static class Student implements Serializable { public String name = null; public String dept = null; public int id = 0;}", "e": 1113, "s": 868, "text": null }, { "code": null, "e": 1237, "s": 1113, "text": "Here, you can see that Student class implements Serializable, but does not have any methods to implement from Serializable." }, { "code": null, "e": 1315, "s": 1237, "text": "Example: Below example code explains Serializing and Deserializing an object." }, { "code": null, "e": 1320, "s": 1315, "text": "Java" }, { "code": "// Java program to illustrate Serializable interfaceimport java.io.*; // By implementing Serializable interface// we make sure that state of instances of class A// can be saved in a file.class A implements Serializable { int i; String s; // A class constructor public A(int i, String s) { this.i = i; this.s = s; }} public class Test { public static void main(String[] args) throws IOException, ClassNotFoundException { A a = new A(20, \"GeeksForGeeks\"); // Serializing 'a' FileOutputStream fos = new FileOutputStream(\"xyz.txt\"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(a); // De-serializing 'a' FileInputStream fis = new FileInputStream(\"xyz.txt\"); ObjectInputStream ois = new ObjectInputStream(fis); A b = (A)ois.readObject(); // down-casting object System.out.println(b.i + \" \" + b.s); // closing streams oos.close(); ois.close(); }}", "e": 2370, "s": 1320, "text": null }, { "code": null, "e": 2378, "s": 2370, "text": "Output:" }, { "code": null, "e": 2396, "s": 2378, "text": "20 GeeksForGeeks\n" }, { "code": null, "e": 2449, "s": 2396, "text": "Must Read: Serialization and Deserialization in Java" }, { "code": null, "e": 2466, "s": 2449, "text": "Java-Collections" }, { "code": null, "e": 2475, "s": 2466, "text": "Java-I/O" }, { "code": null, "e": 2480, "s": 2475, "text": "Java" }, { "code": null, "e": 2485, "s": 2480, "text": "Java" }, { "code": null, "e": 2502, "s": 2485, "text": "Java-Collections" } ]
How to pass multiple arguments to function ?
01 Feb, 2022 A Routine is a named group of instructions performing some tasks. A routine can always be invoked as well as called multiple times as required in a given program. When the routine stops, the execution immediately returns to the stage from which the routine was called. Such routines may be predefined in the programming language or designed or implemented by the programmer. A Function is the Python version of the routine in a program. Some functions are designed to return values, while others are designed for other purposes.We pass arguments in a function, we can pass no arguments at all, single arguments or multiple arguments to a function and can call the function multiple times.Example: Python # no argument is passed # function definitiondef displayMessage(): print("Geeks for Geeks") # function calldisplayMessage() Output: Geeks for Geeks In the above program, the displayMessage() function is called without passing any arguments to it. Python # single argument is passed # function definitiondef displayMessage(msg): print("Hello "+msg+" !") msg = "R2J" # function calldisplayMessage(msg) Output: Hello R2J ! In the above program, the displayMessage() function is called by passing an argument to it. A formal argument is an argument that is present in the function definition. An actual argument is an argument, which is present in the function call.Passing multiple arguments to a function in Python: We can pass multiple arguments to a python function by predetermining the formal parameters in the function definition. Python # multiple arguments are passed # function definitiondef displayMessage(argument1, argument2, argument3): print(argument1+" "+argument2+" "+argument3) # function calldisplayMessage("Geeks", "4", "Geeks") Output: Geeks 4 Geeks In the above program, multiple arguments are passed to the displayMessage() function in which the number of arguments to be passed was fixed. We can pass multiple arguments to a python function without predetermining the formal parameters using the below syntax: def functionName(*argument) The * symbol is used to pass a variable number of arguments to a function. Typically, this syntax is used to avoid the code failing when we don’t know how many arguments will be sent to the function. Python # variable number of non keyword arguments passed # function definitiondef calculateTotalSum(*arguments): totalSum = 0 for number in arguments: totalSum += number print(totalSum) # function callcalculateTotalSum(5, 4, 3, 2, 1) Output: 15 In the above program, the variable number of arguments are passed to the displayMessage() function in which the number of arguments to be passed is not predetermined. (This syntax is only used to pass non-keyword arguments to the function.) We can pass multiple keyword arguments to a python function without predetermining the formal parameters using the below syntax: def functionName(**argument) The ** symbol is used before an argument to pass a keyword argument dictionary to a function, this syntax used to successfully run the code when we don’t know how many keyword arguments will be sent to the function. Python # variable number of keyword arguments passed # function definitiondef displayArgument(**arguments): for arg in arguments.items(): print(arg) # function calldisplayArgument(argument1 ="Geeks", argument2 = 4, argument3 ="Geeks") Output: ('argument2', 4) ('argument3', 'Geeks') ('argument1', 'Geeks') In the above program, variable number of keyword arguments are passed to the displayArgument() function. Here is a program to illustrate all the above cases to pass multiple arguments in a function. Python # single argument, non keyword argument# and keyword argument are passed # function definitiondef displayArguments(argument1, *argument2, **argument3): # displaying predetermined argument print(argument1) # displaying non keyword arguments for arg in argument2: print(arg) # displaying non keyword arguments for arg in argument3.items(): print(arg) arg1 = "Welcome"arg3 = "Geeks" # function calldisplayArguments(arg1, "to", arg3, agr4 = 4, arg5 ="Geeks !") Output: Welcome to Geeks ('agr4', 4) ('arg5', 'Geeks!') The above program illustrates the use of the variable number of both non-keyword arguments and keyword arguments as well as a non-asterisk argument in a function. The non-asterisk argument is always used before the single asterisk argument and the single asterisk argument is always used before the double-asterisk argument in a function definition. Akanksha_Rai sagar0719kumar simmytarika5 surinderdawra388 rkbhola5 Python-Functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n01 Feb, 2022" }, { "code": null, "e": 218, "s": 54, "text": "A Routine is a named group of instructions performing some tasks. A routine can always be invoked as well as called multiple times as required in a given program. " }, { "code": null, "e": 752, "s": 218, "text": "When the routine stops, the execution immediately returns to the stage from which the routine was called. Such routines may be predefined in the programming language or designed or implemented by the programmer. A Function is the Python version of the routine in a program. Some functions are designed to return values, while others are designed for other purposes.We pass arguments in a function, we can pass no arguments at all, single arguments or multiple arguments to a function and can call the function multiple times.Example:" }, { "code": null, "e": 759, "s": 752, "text": "Python" }, { "code": "# no argument is passed # function definitiondef displayMessage(): print(\"Geeks for Geeks\") # function calldisplayMessage()", "e": 888, "s": 759, "text": null }, { "code": null, "e": 896, "s": 888, "text": "Output:" }, { "code": null, "e": 912, "s": 896, "text": "Geeks for Geeks" }, { "code": null, "e": 1011, "s": 912, "text": "In the above program, the displayMessage() function is called without passing any arguments to it." }, { "code": null, "e": 1018, "s": 1011, "text": "Python" }, { "code": "# single argument is passed # function definitiondef displayMessage(msg): print(\"Hello \"+msg+\" !\") msg = \"R2J\" # function calldisplayMessage(msg)", "e": 1170, "s": 1018, "text": null }, { "code": null, "e": 1178, "s": 1170, "text": "Output:" }, { "code": null, "e": 1190, "s": 1178, "text": "Hello R2J !" }, { "code": null, "e": 1484, "s": 1190, "text": "In the above program, the displayMessage() function is called by passing an argument to it. A formal argument is an argument that is present in the function definition. An actual argument is an argument, which is present in the function call.Passing multiple arguments to a function in Python:" }, { "code": null, "e": 1606, "s": 1484, "text": "We can pass multiple arguments to a python function by predetermining the formal parameters in the function definition. " }, { "code": null, "e": 1613, "s": 1606, "text": "Python" }, { "code": "# multiple arguments are passed # function definitiondef displayMessage(argument1, argument2, argument3): print(argument1+\" \"+argument2+\" \"+argument3) # function calldisplayMessage(\"Geeks\", \"4\", \"Geeks\")", "e": 1826, "s": 1613, "text": null }, { "code": null, "e": 1834, "s": 1826, "text": "Output:" }, { "code": null, "e": 1848, "s": 1834, "text": "Geeks 4 Geeks" }, { "code": null, "e": 1990, "s": 1848, "text": "In the above program, multiple arguments are passed to the displayMessage() function in which the number of arguments to be passed was fixed." }, { "code": null, "e": 2111, "s": 1990, "text": "We can pass multiple arguments to a python function without predetermining the formal parameters using the below syntax:" }, { "code": null, "e": 2139, "s": 2111, "text": "def functionName(*argument)" }, { "code": null, "e": 2341, "s": 2139, "text": "The * symbol is used to pass a variable number of arguments to a function. Typically, this syntax is used to avoid the code failing when we don’t know how many arguments will be sent to the function. " }, { "code": null, "e": 2348, "s": 2341, "text": "Python" }, { "code": "# variable number of non keyword arguments passed # function definitiondef calculateTotalSum(*arguments): totalSum = 0 for number in arguments: totalSum += number print(totalSum) # function callcalculateTotalSum(5, 4, 3, 2, 1)", "e": 2591, "s": 2348, "text": null }, { "code": null, "e": 2599, "s": 2591, "text": "Output:" }, { "code": null, "e": 2602, "s": 2599, "text": "15" }, { "code": null, "e": 2843, "s": 2602, "text": "In the above program, the variable number of arguments are passed to the displayMessage() function in which the number of arguments to be passed is not predetermined. (This syntax is only used to pass non-keyword arguments to the function.)" }, { "code": null, "e": 2972, "s": 2843, "text": "We can pass multiple keyword arguments to a python function without predetermining the formal parameters using the below syntax:" }, { "code": null, "e": 3001, "s": 2972, "text": "def functionName(**argument)" }, { "code": null, "e": 3219, "s": 3001, "text": "The ** symbol is used before an argument to pass a keyword argument dictionary to a function, this syntax used to successfully run the code when we don’t know how many keyword arguments will be sent to the function. " }, { "code": null, "e": 3226, "s": 3219, "text": "Python" }, { "code": "# variable number of keyword arguments passed # function definitiondef displayArgument(**arguments): for arg in arguments.items(): print(arg) # function calldisplayArgument(argument1 =\"Geeks\", argument2 = 4, argument3 =\"Geeks\")", "e": 3479, "s": 3226, "text": null }, { "code": null, "e": 3487, "s": 3479, "text": "Output:" }, { "code": null, "e": 3550, "s": 3487, "text": "('argument2', 4)\n('argument3', 'Geeks')\n('argument1', 'Geeks')" }, { "code": null, "e": 3655, "s": 3550, "text": "In the above program, variable number of keyword arguments are passed to the displayArgument() function." }, { "code": null, "e": 3750, "s": 3655, "text": "Here is a program to illustrate all the above cases to pass multiple arguments in a function. " }, { "code": null, "e": 3757, "s": 3750, "text": "Python" }, { "code": "# single argument, non keyword argument# and keyword argument are passed # function definitiondef displayArguments(argument1, *argument2, **argument3): # displaying predetermined argument print(argument1) # displaying non keyword arguments for arg in argument2: print(arg) # displaying non keyword arguments for arg in argument3.items(): print(arg) arg1 = \"Welcome\"arg3 = \"Geeks\" # function calldisplayArguments(arg1, \"to\", arg3, agr4 = 4, arg5 =\"Geeks !\")", "e": 4278, "s": 3757, "text": null }, { "code": null, "e": 4286, "s": 4278, "text": "Output:" }, { "code": null, "e": 4334, "s": 4286, "text": "Welcome\nto\nGeeks\n('agr4', 4)\n('arg5', 'Geeks!')" }, { "code": null, "e": 4685, "s": 4334, "text": "The above program illustrates the use of the variable number of both non-keyword arguments and keyword arguments as well as a non-asterisk argument in a function. The non-asterisk argument is always used before the single asterisk argument and the single asterisk argument is always used before the double-asterisk argument in a function definition. " }, { "code": null, "e": 4698, "s": 4685, "text": "Akanksha_Rai" }, { "code": null, "e": 4713, "s": 4698, "text": "sagar0719kumar" }, { "code": null, "e": 4726, "s": 4713, "text": "simmytarika5" }, { "code": null, "e": 4743, "s": 4726, "text": "surinderdawra388" }, { "code": null, "e": 4752, "s": 4743, "text": "rkbhola5" }, { "code": null, "e": 4769, "s": 4752, "text": "Python-Functions" }, { "code": null, "e": 4776, "s": 4769, "text": "Python" } ]
SQL queries on clustered and non-clustered Indexes
22 May, 2022 Prerequisite – Indexing in Databases Indexing is a procedure that returns your requested data faster from the defined table. Without indexing, the SQL server has to scan the whole table for your data. By indexing, SQL server will do the exact same thing you do when searching for content in a book by checking the index page. In the same way, a table’s index allows us to locate the exact data without scanning the whole table. There are two types of indexing in SQL. Clustered indexNon-clustered index Clustered index Non-clustered index 1. Clustered – Clustered index is the type of indexing that establishes a physical sorting order of rows. Suppose you have a table Student_info which contains ROLL_NO as a primary key, then Clustered index which is self created on that primary key will sort the Student_info table as per ROLL_NO. Clustered index is like Dictionary; in the dictionary, sorting order is alphabetical and there is no separate index page. Examples: Input: CREATE TABLE Student_info ( ROLL_NO int(10) primary key, NAME varchar(20), DEPARTMENT varchar(20), ); insert into Student_info values(1410110405, 'H Agarwal', 'CSE') insert into Student_info values(1410110404, 'S Samadder', 'CSE') insert into Student_info values(1410110403, 'MD Irfan', 'CSE') SELECT * FROM Student_info Output: If we want to create a Clustered index on another column, first we have to remove the primary key, and then we can remove the previous index. Note that defining a column as a primary key makes that column the Clustered Index of that table. To make any other column, the clustered index, first we have to remove the previous one as follows below. Syntax: //Drop index drop index table_name.index_name //Create Clustered index index create Clustered index IX_table_name_column_name on table_name (column_name ASC) Note: We can create only one clustered index in a table. 2. Non-clustered: Non-Clustered index is an index structure separate from the data stored in a table that reorders one or more selected columns. The non-clustered index is created to improve the performance of frequently used queries not covered by a clustered index. It’s like a textbook; the index page is created separately at the beginning of that book. Examples: Input: CREATE TABLE Student_info ( ROLL_NO int(10), NAME varchar(20), DEPARTMENT varchar(20), ); insert into Student_info values(1410110405, 'H Agarwal', 'CSE') insert into Student_info values(1410110404, 'S Samadder', 'CSE') insert into Student_info values(1410110403, 'MD Irfan', 'CSE') SELECT * FROM Student_info Output: Note: We can create one or more Non_Clustered index in a table. Syntax: //Create Non-Clustered index create NonClustered index IX_table_name_column_name on table_name (column_name ASC) Table: Student_info Input: create NonClustered index IX_Student_info_NAME on Student_info (NAME ASC) Output:Index Clustered vs Non-Clustered index: In a table there can be only one clustered index or one or more than one non_clustered index. In Clustered index there is no separate index storage but in Non_Clustered index there is separate index storage for the index. Clustered index is slower than Non_Clustered index. ManasChhabra2 U235 simmytarika5 jimkgreene DBMS Indexing Picked DBMS SQL DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SQL | Join (Inner, Left, Right and Full Joins) SQL | WITH clause SQL query to find second highest salary? CTE in SQL Difference between Clustered and Non-clustered index SQL | DDL, DQL, DML, DCL and TCL Commands SQL | Join (Inner, Left, Right and Full Joins) SQL | WITH clause How to find Nth highest salary from a table CTE in SQL
[ { "code": null, "e": 52, "s": 24, "text": "\n22 May, 2022" }, { "code": null, "e": 520, "s": 52, "text": "Prerequisite – Indexing in Databases Indexing is a procedure that returns your requested data faster from the defined table. Without indexing, the SQL server has to scan the whole table for your data. By indexing, SQL server will do the exact same thing you do when searching for content in a book by checking the index page. In the same way, a table’s index allows us to locate the exact data without scanning the whole table. There are two types of indexing in SQL." }, { "code": null, "e": 555, "s": 520, "text": "Clustered indexNon-clustered index" }, { "code": null, "e": 571, "s": 555, "text": "Clustered index" }, { "code": null, "e": 591, "s": 571, "text": "Non-clustered index" }, { "code": null, "e": 1011, "s": 591, "text": "1. Clustered – Clustered index is the type of indexing that establishes a physical sorting order of rows. Suppose you have a table Student_info which contains ROLL_NO as a primary key, then Clustered index which is self created on that primary key will sort the Student_info table as per ROLL_NO. Clustered index is like Dictionary; in the dictionary, sorting order is alphabetical and there is no separate index page. " }, { "code": null, "e": 1021, "s": 1011, "text": "Examples:" }, { "code": null, "e": 1353, "s": 1021, "text": "Input:\nCREATE TABLE Student_info\n(\nROLL_NO int(10) primary key,\nNAME varchar(20),\nDEPARTMENT varchar(20),\n);\ninsert into Student_info values(1410110405, 'H Agarwal', 'CSE') \ninsert into Student_info values(1410110404, 'S Samadder', 'CSE')\ninsert into Student_info values(1410110403, 'MD Irfan', 'CSE') \n\nSELECT * FROM Student_info " }, { "code": null, "e": 1361, "s": 1353, "text": "Output:" }, { "code": null, "e": 1708, "s": 1361, "text": "If we want to create a Clustered index on another column, first we have to remove the primary key, and then we can remove the previous index. Note that defining a column as a primary key makes that column the Clustered Index of that table. To make any other column, the clustered index, first we have to remove the previous one as follows below. " }, { "code": null, "e": 1716, "s": 1708, "text": "Syntax:" }, { "code": null, "e": 1890, "s": 1716, "text": "//Drop index\ndrop index table_name.index_name\n//Create Clustered index index\ncreate Clustered index IX_table_name_column_name \n on table_name (column_name ASC) " }, { "code": null, "e": 1947, "s": 1890, "text": "Note: We can create only one clustered index in a table." }, { "code": null, "e": 2315, "s": 1947, "text": "2. Non-clustered: Non-Clustered index is an index structure separate from the data stored in a table that reorders one or more selected columns. The non-clustered index is created to improve the performance of frequently used queries not covered by a clustered index. It’s like a textbook; the index page is created separately at the beginning of that book. Examples:" }, { "code": null, "e": 2635, "s": 2315, "text": "Input: \nCREATE TABLE Student_info\n(\nROLL_NO int(10),\nNAME varchar(20),\nDEPARTMENT varchar(20),\n);\ninsert into Student_info values(1410110405, 'H Agarwal', 'CSE') \ninsert into Student_info values(1410110404, 'S Samadder', 'CSE')\ninsert into Student_info values(1410110403, 'MD Irfan', 'CSE')\n\nSELECT * FROM Student_info " }, { "code": null, "e": 2643, "s": 2635, "text": "Output:" }, { "code": null, "e": 2715, "s": 2643, "text": "Note: We can create one or more Non_Clustered index in a table. Syntax:" }, { "code": null, "e": 2836, "s": 2715, "text": "//Create Non-Clustered index\ncreate NonClustered index IX_table_name_column_name \n on table_name (column_name ASC) " }, { "code": null, "e": 2856, "s": 2836, "text": "Table: Student_info" }, { "code": null, "e": 2950, "s": 2856, "text": "Input: create NonClustered index IX_Student_info_NAME on Student_info (NAME ASC) Output:Index" }, { "code": null, "e": 2984, "s": 2950, "text": "Clustered vs Non-Clustered index:" }, { "code": null, "e": 3078, "s": 2984, "text": "In a table there can be only one clustered index or one or more than one non_clustered index." }, { "code": null, "e": 3206, "s": 3078, "text": "In Clustered index there is no separate index storage but in Non_Clustered index there is separate index storage for the index." }, { "code": null, "e": 3258, "s": 3206, "text": "Clustered index is slower than Non_Clustered index." }, { "code": null, "e": 3272, "s": 3258, "text": "ManasChhabra2" }, { "code": null, "e": 3277, "s": 3272, "text": "U235" }, { "code": null, "e": 3290, "s": 3277, "text": "simmytarika5" }, { "code": null, "e": 3301, "s": 3290, "text": "jimkgreene" }, { "code": null, "e": 3315, "s": 3301, "text": "DBMS Indexing" }, { "code": null, "e": 3322, "s": 3315, "text": "Picked" }, { "code": null, "e": 3327, "s": 3322, "text": "DBMS" }, { "code": null, "e": 3331, "s": 3327, "text": "SQL" }, { "code": null, "e": 3336, "s": 3331, "text": "DBMS" }, { "code": null, "e": 3340, "s": 3336, "text": "SQL" }, { "code": null, "e": 3438, "s": 3340, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3485, "s": 3438, "text": "SQL | Join (Inner, Left, Right and Full Joins)" }, { "code": null, "e": 3503, "s": 3485, "text": "SQL | WITH clause" }, { "code": null, "e": 3544, "s": 3503, "text": "SQL query to find second highest salary?" }, { "code": null, "e": 3555, "s": 3544, "text": "CTE in SQL" }, { "code": null, "e": 3608, "s": 3555, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 3650, "s": 3608, "text": "SQL | DDL, DQL, DML, DCL and TCL Commands" }, { "code": null, "e": 3697, "s": 3650, "text": "SQL | Join (Inner, Left, Right and Full Joins)" }, { "code": null, "e": 3715, "s": 3697, "text": "SQL | WITH clause" }, { "code": null, "e": 3759, "s": 3715, "text": "How to find Nth highest salary from a table" } ]
Create matrix of zeros in R
29 Oct, 2021 R programming language offers us a variety of ways to create a matrix and fill it in such a way that all the element values are equivalent to 0. Let’s see those ways – The in-built matrix() method in R can be used to create a matrix with a given set of values, that is, n x m dimensions, and initialize it with a specified value. All the elements are initialized with the same value. If either of the m or n parameters is not specified, an attempt is made to infer the missing value from the length of data and the other parameter(s) that are given. If neither of them is given, then a one-column matrix is returned as an output. This matrix can then be stored in a variable and then its elements can be accessed and manipulated. Syntax: matrix(0, n, m) Parameters: 0 – value to initialize the matrix with n – no. of rows m – no. of columns Return type : a matrix or scalar of zeros Example: R # initializing a matrix of 0s of 2*3 dimensionsmat = matrix(0, 2, 3) # print the matrixprint (mat) Output [,1] [,2] [,3] [1,] 0 0 0 [2,] 0 0 0 The replicate() method is used to create a replica of the second argument of the method vec, by appending it n times. It applies the same specified vector repeatedly to form a 2D matrix. The method belongs to the apply set of functions used in R and uses it as its parent or base class. The second argument is specified by enclosing within numeric(int) value. Also, the numeric method creates a real vector of the specified length. The elements of the vector are all equal to 0 on numeric application. Syntax: replicate ( n , numeric (m) ) Parameter : n – no. of rows numeric(m) – no. of columns in the matrix, specified as a numeric parameter Return type : a matrix or scalar of zeros Example: R # initializing a matrix of 0s of 2*3 dimensionsmat = replicate( 6, numeric(3) ) # print the matrixprint ("Matrix : ")print (mat) Output [,1] [,2] [,3] [,4] [,5] [,6] [1,] 0 0 0 0 0 0 [2,] 0 0 0 0 0 0 [3,] 0 0 0 0 0 0 rep() method in R can be used to create a one row matrix, which creates the number of columns equivalent to the value in the second argument of the method. The first argument, specifies the vector to repeat and stack together y times, which in this case is 0. We can specify 0L instead of 0. Syntax: rep (0 , y) Arguments : y – number of columns in matrix Return type : Single row matrix of zeros Example: R print ("Matrix : ") # create a matrix of single 0 and 10 columnsrep(0, 10) Output [1] “Matrix : “ [1] 0 0 0 0 0 0 0 0 0 0 There are several other methods, like numeric() or integer() which can be used to create a vector of zeros. All of these methods takes an argument the length, specifying the number of zeros to combine. The behavior of integer() and numeric() methods is almost same. Syntax: numeric(size) integer(size) Example: R print ("Matrix using numeric() method:")# create a matrix of single 0 and 8 columnsnumeric (8) print ("Matrix using integer() method:")# create a matrix of single 0 and 5 columnsinteger (5) Output [1] “Matrix using numeric() method:” [1] 0 0 0 0 0 0 0 0 [1] “Matrix using integer() method:” [1] 0 0 0 0 0 chhabradhanvi Picked R-Matrix R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Oct, 2021" }, { "code": null, "e": 196, "s": 28, "text": "R programming language offers us a variety of ways to create a matrix and fill it in such a way that all the element values are equivalent to 0. Let’s see those ways –" }, { "code": null, "e": 759, "s": 196, "text": "The in-built matrix() method in R can be used to create a matrix with a given set of values, that is, n x m dimensions, and initialize it with a specified value. All the elements are initialized with the same value. If either of the m or n parameters is not specified, an attempt is made to infer the missing value from the length of data and the other parameter(s) that are given. If neither of them is given, then a one-column matrix is returned as an output. This matrix can then be stored in a variable and then its elements can be accessed and manipulated. " }, { "code": null, "e": 783, "s": 759, "text": "Syntax: matrix(0, n, m)" }, { "code": null, "e": 795, "s": 783, "text": "Parameters:" }, { "code": null, "e": 835, "s": 795, "text": "0 – value to initialize the matrix with" }, { "code": null, "e": 851, "s": 835, "text": "n – no. of rows" }, { "code": null, "e": 870, "s": 851, "text": "m – no. of columns" }, { "code": null, "e": 912, "s": 870, "text": "Return type : a matrix or scalar of zeros" }, { "code": null, "e": 922, "s": 912, "text": "Example: " }, { "code": null, "e": 924, "s": 922, "text": "R" }, { "code": "# initializing a matrix of 0s of 2*3 dimensionsmat = matrix(0, 2, 3) # print the matrixprint (mat)", "e": 1024, "s": 924, "text": null }, { "code": null, "e": 1031, "s": 1024, "text": "Output" }, { "code": null, "e": 1051, "s": 1031, "text": " [,1] [,2] [,3]" }, { "code": null, "e": 1071, "s": 1051, "text": "[1,] 0 0 0" }, { "code": null, "e": 1091, "s": 1071, "text": "[2,] 0 0 0" }, { "code": null, "e": 1593, "s": 1091, "text": "The replicate() method is used to create a replica of the second argument of the method vec, by appending it n times. It applies the same specified vector repeatedly to form a 2D matrix. The method belongs to the apply set of functions used in R and uses it as its parent or base class. The second argument is specified by enclosing within numeric(int) value. Also, the numeric method creates a real vector of the specified length. The elements of the vector are all equal to 0 on numeric application." }, { "code": null, "e": 1631, "s": 1593, "text": "Syntax: replicate ( n , numeric (m) )" }, { "code": null, "e": 1643, "s": 1631, "text": "Parameter :" }, { "code": null, "e": 1659, "s": 1643, "text": "n – no. of rows" }, { "code": null, "e": 1735, "s": 1659, "text": "numeric(m) – no. of columns in the matrix, specified as a numeric parameter" }, { "code": null, "e": 1777, "s": 1735, "text": "Return type : a matrix or scalar of zeros" }, { "code": null, "e": 1786, "s": 1777, "text": "Example:" }, { "code": null, "e": 1788, "s": 1786, "text": "R" }, { "code": "# initializing a matrix of 0s of 2*3 dimensionsmat = replicate( 6, numeric(3) ) # print the matrixprint (\"Matrix : \")print (mat)", "e": 1918, "s": 1788, "text": null }, { "code": null, "e": 1925, "s": 1918, "text": "Output" }, { "code": null, "e": 1961, "s": 1925, "text": " [,1] [,2] [,3] [,4] [,5] [,6]" }, { "code": null, "e": 1996, "s": 1961, "text": "[1,] 0 0 0 0 0 0" }, { "code": null, "e": 2031, "s": 1996, "text": "[2,] 0 0 0 0 0 0" }, { "code": null, "e": 2066, "s": 2031, "text": "[3,] 0 0 0 0 0 0" }, { "code": null, "e": 2359, "s": 2066, "text": "rep() method in R can be used to create a one row matrix, which creates the number of columns equivalent to the value in the second argument of the method. The first argument, specifies the vector to repeat and stack together y times, which in this case is 0. We can specify 0L instead of 0. " }, { "code": null, "e": 2379, "s": 2359, "text": "Syntax: rep (0 , y)" }, { "code": null, "e": 2423, "s": 2379, "text": "Arguments : y – number of columns in matrix" }, { "code": null, "e": 2464, "s": 2423, "text": "Return type : Single row matrix of zeros" }, { "code": null, "e": 2473, "s": 2464, "text": "Example:" }, { "code": null, "e": 2475, "s": 2473, "text": "R" }, { "code": "print (\"Matrix : \") # create a matrix of single 0 and 10 columnsrep(0, 10)", "e": 2551, "s": 2475, "text": null }, { "code": null, "e": 2558, "s": 2551, "text": "Output" }, { "code": null, "e": 2574, "s": 2558, "text": "[1] “Matrix : “" }, { "code": null, "e": 2598, "s": 2574, "text": "[1] 0 0 0 0 0 0 0 0 0 0" }, { "code": null, "e": 2866, "s": 2598, "text": "There are several other methods, like numeric() or integer() which can be used to create a vector of zeros. All of these methods takes an argument the length, specifying the number of zeros to combine. The behavior of integer() and numeric() methods is almost same. " }, { "code": null, "e": 2874, "s": 2866, "text": "Syntax:" }, { "code": null, "e": 2888, "s": 2874, "text": "numeric(size)" }, { "code": null, "e": 2902, "s": 2888, "text": "integer(size)" }, { "code": null, "e": 2911, "s": 2902, "text": "Example:" }, { "code": null, "e": 2913, "s": 2911, "text": "R" }, { "code": "print (\"Matrix using numeric() method:\")# create a matrix of single 0 and 8 columnsnumeric (8) print (\"Matrix using integer() method:\")# create a matrix of single 0 and 5 columnsinteger (5)", "e": 3104, "s": 2913, "text": null }, { "code": null, "e": 3111, "s": 3104, "text": "Output" }, { "code": null, "e": 3148, "s": 3111, "text": "[1] “Matrix using numeric() method:”" }, { "code": null, "e": 3168, "s": 3148, "text": "[1] 0 0 0 0 0 0 0 0" }, { "code": null, "e": 3205, "s": 3168, "text": "[1] “Matrix using integer() method:”" }, { "code": null, "e": 3219, "s": 3205, "text": "[1] 0 0 0 0 0" }, { "code": null, "e": 3233, "s": 3219, "text": "chhabradhanvi" }, { "code": null, "e": 3240, "s": 3233, "text": "Picked" }, { "code": null, "e": 3249, "s": 3240, "text": "R-Matrix" }, { "code": null, "e": 3260, "s": 3249, "text": "R Language" } ]
HTML | <frame> noresize Attribute
30 Sep, 2019 The HTML <frame> noresize attribute is used to specify that the frame element can not be resize by the user. This type of attribute is used to looks at the size of the frame element. Syntax: <frame noresize="noresize"> Attribute Values: noresize: It defines the frame element that can not be resize by the user. Note: The <frame> tag is not supported by HTML 5. Example: <!DOCTYPE html> <html> <head> <title>HTML frame noresize Attribute</title> </head> <frameset cols="30%, 40%, 30%"> <frame name="top" src="attr1.png" noresize="noresize"/> <frame name="main" src="gradient3.png" marginwidth="30" /> <frame name="bottom" marginwidth="30" src="col_last.png" marginwidth="40" /> </frameset> </html> Output: Supported Browsers: The browsers supported by HTML <frame> noresize Attribute are listed below: Google Chrome Internet Explorer Firefox Safari Opera HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) Design a Tribute Page using HTML & CSS Build a Survey Form using HTML and CSS Design a web page using HTML and CSS Angular File Upload 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": 53, "s": 25, "text": "\n30 Sep, 2019" }, { "code": null, "e": 236, "s": 53, "text": "The HTML <frame> noresize attribute is used to specify that the frame element can not be resize by the user. This type of attribute is used to looks at the size of the frame element." }, { "code": null, "e": 244, "s": 236, "text": "Syntax:" }, { "code": null, "e": 272, "s": 244, "text": "<frame noresize=\"noresize\">" }, { "code": null, "e": 290, "s": 272, "text": "Attribute Values:" }, { "code": null, "e": 365, "s": 290, "text": "noresize: It defines the frame element that can not be resize by the user." }, { "code": null, "e": 415, "s": 365, "text": "Note: The <frame> tag is not supported by HTML 5." }, { "code": null, "e": 424, "s": 415, "text": "Example:" }, { "code": "<!DOCTYPE html> <html> <head> <title>HTML frame noresize Attribute</title> </head> <frameset cols=\"30%, 40%, 30%\"> <frame name=\"top\" src=\"attr1.png\" noresize=\"noresize\"/> <frame name=\"main\" src=\"gradient3.png\" marginwidth=\"30\" /> <frame name=\"bottom\" marginwidth=\"30\" src=\"col_last.png\" marginwidth=\"40\" /> </frameset> </html> ", "e": 814, "s": 424, "text": null }, { "code": null, "e": 822, "s": 814, "text": "Output:" }, { "code": null, "e": 918, "s": 822, "text": "Supported Browsers: The browsers supported by HTML <frame> noresize Attribute are listed below:" }, { "code": null, "e": 932, "s": 918, "text": "Google Chrome" }, { "code": null, "e": 950, "s": 932, "text": "Internet Explorer" }, { "code": null, "e": 958, "s": 950, "text": "Firefox" }, { "code": null, "e": 965, "s": 958, "text": "Safari" }, { "code": null, "e": 971, "s": 965, "text": "Opera" }, { "code": null, "e": 987, "s": 971, "text": "HTML-Attributes" }, { "code": null, "e": 992, "s": 987, "text": "HTML" }, { "code": null, "e": 1009, "s": 992, "text": "Web Technologies" }, { "code": null, "e": 1014, "s": 1009, "text": "HTML" }, { "code": null, "e": 1112, "s": 1014, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1136, "s": 1112, "text": "REST API (Introduction)" }, { "code": null, "e": 1175, "s": 1136, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 1214, "s": 1175, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 1251, "s": 1214, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 1271, "s": 1251, "text": "Angular File Upload" }, { "code": null, "e": 1304, "s": 1271, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1365, "s": 1304, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1408, "s": 1365, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 1480, "s": 1408, "text": "Differences between Functional Components and Class Components in React" } ]
Java Program to print all permutations of a given string
10 Dec, 2021 A permutation also called an “arrangement number” or “order,” is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation. Source: Mathword(http://mathworld.wolfram.com/Permutation.html) Below are the permutations of string ABC. ABC ACB BAC BCA CBA CAB Here is a solution that is used as a basis in backtracking. Java // Java program to print all // permutations of a given string. public class Permutation { public static void main(String[] args) { String str = "ABC"; int n = str.length(); Permutation permutation = new Permutation(); permutation.permute(str, 0, n-1); } /* Permutation function @param str string to calculate permutation for @param l starting index @param r end index */ private void permute(String str, int l, int r) { if (l == r) System.out.println(str); else { for (int i = l; i <= r; i++) { str = swap(str,l,i); permute(str, l+1, r); str = swap(str,l,i); } } } /* Swap Characters at position @param a string value @param i position 1 @param j position 2 @return swapped string */ public String swap(String a, int i, int j) { char temp; char[] charArray = a.toCharArray(); temp = charArray[i] ; charArray[i] = charArray[j]; charArray[j] = temp; return String.valueOf(charArray); } } // This code is contributed by Mihir Joshi Output: ABC ACB BAC BCA CBA CAB Algorithm Paradigm: Backtracking Time Complexity: O(n*n!) Note that there are n! permutations and it requires O(n) time to print a permutation. Auxiliary Space: O(r – l) Note: The above solution prints duplicate permutations if there are repeating characters in the input string. Please see the below link for a solution that prints only distinct permutations even if there are duplicates in input.Print all distinct permutations of a given string with duplicates. Permutations of a given string using STL Another approach: Java import java.util.*;// Java program to implement// the above approachclass GFG{ static void permute(String s, String answer){ if (s.length() == 0) { System.out.print(answer + " "); return; } for(int i = 0 ;i < s.length(); i++) { char ch = s.charAt(i); String left_substr = s.substring(0, i); String right_substr = s.substring(i + 1); String rest = left_substr + right_substr; permute(rest, answer + ch); }} // Driver codepublic static void main(String args[]){ Scanner scan = new Scanner(System.in); String s; String answer=""; System.out.print( "Enter the string : "); s = scan.next(); System.out.print( "\nAll possible strings are : "); permute(s, answer);}}// This code is contributed by adityapande88 Output: Enter the string : abc All possible strings are : abc acb bac bca cab cba Time Complexity: O(n*n!) The time complexity is the same as the above approach, i.e. there are n! permutations and it requires O(n) time to print a permutation. Auxiliary Space: O(|s|) Java Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Iterate Over the Characters of a String in Java How to Convert Char to String in Java? How to Get Elements By Index from HashSet in Java? Java Program to Write into a File How to Write Data into Excel Sheet using Java? Java Program to Read a File to String Comparing two ArrayList In Java SHA-1 Hash Java Program to Convert File to a Byte Array Java Program to Find Sum of Array Elements
[ { "code": null, "e": 54, "s": 26, "text": "\n10 Dec, 2021" }, { "code": null, "e": 262, "s": 54, "text": "A permutation also called an “arrangement number” or “order,” is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation. " }, { "code": null, "e": 326, "s": 262, "text": "Source: Mathword(http://mathworld.wolfram.com/Permutation.html)" }, { "code": null, "e": 392, "s": 326, "text": "Below are the permutations of string ABC. ABC ACB BAC BCA CBA CAB" }, { "code": null, "e": 452, "s": 392, "text": "Here is a solution that is used as a basis in backtracking." }, { "code": null, "e": 457, "s": 452, "text": "Java" }, { "code": "// Java program to print all // permutations of a given string. public class Permutation { public static void main(String[] args) { String str = \"ABC\"; int n = str.length(); Permutation permutation = new Permutation(); permutation.permute(str, 0, n-1); } /* Permutation function @param str string to calculate permutation for @param l starting index @param r end index */ private void permute(String str, int l, int r) { if (l == r) System.out.println(str); else { for (int i = l; i <= r; i++) { str = swap(str,l,i); permute(str, l+1, r); str = swap(str,l,i); } } } /* Swap Characters at position @param a string value @param i position 1 @param j position 2 @return swapped string */ public String swap(String a, int i, int j) { char temp; char[] charArray = a.toCharArray(); temp = charArray[i] ; charArray[i] = charArray[j]; charArray[j] = temp; return String.valueOf(charArray); } } // This code is contributed by Mihir Joshi ", "e": 1739, "s": 457, "text": null }, { "code": null, "e": 1748, "s": 1739, "text": "Output: " }, { "code": null, "e": 1772, "s": 1748, "text": "ABC\nACB\nBAC\nBCA\nCBA\nCAB" }, { "code": null, "e": 1806, "s": 1772, "text": "Algorithm Paradigm: Backtracking " }, { "code": null, "e": 1917, "s": 1806, "text": "Time Complexity: O(n*n!) Note that there are n! permutations and it requires O(n) time to print a permutation." }, { "code": null, "e": 1943, "s": 1917, "text": "Auxiliary Space: O(r – l)" }, { "code": null, "e": 2279, "s": 1943, "text": "Note: The above solution prints duplicate permutations if there are repeating characters in the input string. Please see the below link for a solution that prints only distinct permutations even if there are duplicates in input.Print all distinct permutations of a given string with duplicates. Permutations of a given string using STL" }, { "code": null, "e": 2297, "s": 2279, "text": "Another approach:" }, { "code": null, "e": 2302, "s": 2297, "text": "Java" }, { "code": "import java.util.*;// Java program to implement// the above approachclass GFG{ static void permute(String s, String answer){ if (s.length() == 0) { System.out.print(answer + \" \"); return; } for(int i = 0 ;i < s.length(); i++) { char ch = s.charAt(i); String left_substr = s.substring(0, i); String right_substr = s.substring(i + 1); String rest = left_substr + right_substr; permute(rest, answer + ch); }} // Driver codepublic static void main(String args[]){ Scanner scan = new Scanner(System.in); String s; String answer=\"\"; System.out.print( \"Enter the string : \"); s = scan.next(); System.out.print( \"\\nAll possible strings are : \"); permute(s, answer);}}// This code is contributed by adityapande88", "e": 3149, "s": 2302, "text": null }, { "code": null, "e": 3157, "s": 3149, "text": "Output:" }, { "code": null, "e": 3236, "s": 3157, "text": "Enter the string : abc\nAll possible strings are : abc acb bac bca cab cba" }, { "code": null, "e": 3397, "s": 3236, "text": "Time Complexity: O(n*n!) The time complexity is the same as the above approach, i.e. there are n! permutations and it requires O(n) time to print a permutation." }, { "code": null, "e": 3421, "s": 3397, "text": "Auxiliary Space: O(|s|)" }, { "code": null, "e": 3435, "s": 3421, "text": "Java Programs" }, { "code": null, "e": 3533, "s": 3435, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3581, "s": 3533, "text": "Iterate Over the Characters of a String in Java" }, { "code": null, "e": 3620, "s": 3581, "text": "How to Convert Char to String in Java?" }, { "code": null, "e": 3671, "s": 3620, "text": "How to Get Elements By Index from HashSet in Java?" }, { "code": null, "e": 3705, "s": 3671, "text": "Java Program to Write into a File" }, { "code": null, "e": 3752, "s": 3705, "text": "How to Write Data into Excel Sheet using Java?" }, { "code": null, "e": 3790, "s": 3752, "text": "Java Program to Read a File to String" }, { "code": null, "e": 3822, "s": 3790, "text": "Comparing two ArrayList In Java" }, { "code": null, "e": 3833, "s": 3822, "text": "SHA-1 Hash" }, { "code": null, "e": 3878, "s": 3833, "text": "Java Program to Convert File to a Byte Array" } ]
How to change the column names in R within aggregate function?
The column names in an R data frame are an important part of the data because by reading the column names any viewer is likely to understand the theoretical background behind it. If that name is not appropriate then we might want to change it. While using the aggregate function to calculate mean or any other statistical summary, it is possible to change that name with another name by defining the new name with list. Consider the below data frame − set.seed(1) x1<-rnorm(100) x2<-rep(c(LETTERS[1:25]),times=4) df<-data.frame(x1,x2) head(df,20) x1 x2 1 -0.62645381 A 2 0.18364332 B 3 -0.83562861 C 4 1.59528080 D 5 0.32950777 E 6 -0.82046838 F 7 0.48742905 G 8 0.73832471 H 9 0.57578135 I 10 -0.30538839 J 11 1.51178117 K 12 0.38984324 L 13 -0.62124058 M 14 -2.21469989 N 15 1.12493092 O 16 -0.04493361 P 17 -0.01619026 Q 18 0.94383621 R 19 0.82122120 S 20 0.59390132 T tail(df,20) x1 x2 81 -0.5686687 F 82 -0.1351786 G 83 1.1780870 H 84 -1.5235668 I 85 0.5939462 J 86 0.3329504 K 87 1.0630998 L 88 -0.3041839 M 89 0.3700188 N 90 0.2670988 O 91 -0.5425200 P 92 1.2078678 Q 93 1.1604026 R 94 0.7002136 S 95 1.5868335 T 96 0.5584864 U 97 -1.2765922 V 98 -0.5732654 W 99 -1.2246126 X 100 -0.4734006 Y Changing the name of columns inside aggregate function with mean − new_df <- aggregate(list(One=df$x1),list(Two=df$x2),mean) head(new_df) Two One 1 A 0.001742391 2 B -0.256867612 3 C -0.491038988 4 D 0.015527244 5 E 0.397738022 6 F 0.487485583 new_df Two One 1 A 0.001742391 2 B -0.256867612 3 C -0.491038988 4 D 0.015527244 5 E 0.397738022 6 F 0.487485583 7 G -0.029439692 8 H 0.314987172 9 I -0.107967715 10 J -0.305889090 11 K 0.957838684 12 L 0.254853279 13 M -0.073749635 14 N -0.179163387 15 O 0.352983062 16 P -0.140796234 17 Q -0.216660692 18 R 1.066689266 19 S 0.557837845 20 T 0.916147688 21 U 0.311369542 22 V -0.209955094 23 W 0.220139712 24 X -1.065102039 25 Y -0.056525141
[ { "code": null, "e": 1482, "s": 1062, "text": "The column names in an R data frame are an important part of the data because by reading the column names any viewer is likely to understand the theoretical background behind it. If that name is not appropriate then we might want to change it. While using the aggregate function to calculate mean or any other statistical summary, it is possible to change that name with another name by defining the new name with list." }, { "code": null, "e": 1514, "s": 1482, "text": "Consider the below data frame −" }, { "code": null, "e": 2334, "s": 1514, "text": "set.seed(1)\nx1<-rnorm(100)\nx2<-rep(c(LETTERS[1:25]),times=4)\ndf<-data.frame(x1,x2)\nhead(df,20)\n x1 x2\n1 -0.62645381 A\n2 0.18364332 B\n3 -0.83562861 C\n4 1.59528080 D\n5 0.32950777 E\n6 -0.82046838 F\n7 0.48742905 G\n8 0.73832471 H\n9 0.57578135 I\n10 -0.30538839 J\n11 1.51178117 K\n12 0.38984324 L\n13 -0.62124058 M\n14 -2.21469989 N\n15 1.12493092 O\n16 -0.04493361 P\n17 -0.01619026 Q\n18 0.94383621 R\n19 0.82122120 S\n20 0.59390132 T\ntail(df,20)\n x1 x2\n81 -0.5686687 F\n82 -0.1351786 G\n83 1.1780870 H\n84 -1.5235668 I\n85 0.5939462 J\n86 0.3329504 K\n87 1.0630998 L\n88 -0.3041839 M\n89 0.3700188 N\n90 0.2670988 O\n91 -0.5425200 P\n92 1.2078678 Q\n93 1.1604026 R\n94 0.7002136 S\n95 1.5868335 T\n96 0.5584864 U\n97 -1.2765922 V\n98 -0.5732654 W\n99 -1.2246126 X\n100 -0.4734006 Y" }, { "code": null, "e": 2401, "s": 2334, "text": "Changing the name of columns inside aggregate function with mean −" }, { "code": null, "e": 3050, "s": 2401, "text": "new_df <- aggregate(list(One=df$x1),list(Two=df$x2),mean)\nhead(new_df)\n Two One\n1 A 0.001742391\n2 B -0.256867612\n3 C -0.491038988\n4 D 0.015527244\n5 E 0.397738022\n6 F 0.487485583\nnew_df\n Two One\n1 A 0.001742391\n2 B -0.256867612\n3 C -0.491038988\n4 D 0.015527244\n5 E 0.397738022\n6 F 0.487485583\n7 G -0.029439692\n8 H 0.314987172\n9 I -0.107967715\n10 J -0.305889090\n11 K 0.957838684\n12 L 0.254853279\n13 M -0.073749635\n14 N -0.179163387\n15 O 0.352983062\n16 P -0.140796234\n17 Q -0.216660692\n18 R 1.066689266\n19 S 0.557837845\n20 T 0.916147688\n21 U 0.311369542\n22 V -0.209955094\n23 W 0.220139712\n24 X -1.065102039\n25 Y -0.056525141" } ]
JavaScript Array find() Method - GeeksforGeeks
16 Nov, 2021 The arr.find() method in Javascript is used to get the value of the first element in the array that satisfies the provided condition. It checks all the elements of the array and whichever first element satisfies the condition is going to print. This function will not work function having the empty array elements, also does not change the original array. Syntax: array.find(function(currentValue, index, arr),thisValue); Parameters: This method accepts 5 parameters as mentioned above and described below: function: It is the function of the array that works on each element. currentValue: This parameter holds the current element. index: It is an optional parameter that holds the index of the current element. arr: It is an optional parameter that holds the array object the current element belongs to. thisValue: This parameter is optional. If a value is to be passed to the function to be used as its “this” value else the value “undefined” will be passed as its “this” value. Return value: It returns the array element value if any of the elements in the array satisfy the condition, otherwise it returns undefined. We will understand the concept of the Javascript Array find() method through the examples. Example 1: The below example illustrates the JavaScript Array find() method to find a positive number. Javascript <script> // Input array contain some elements. var array = [-10, -0.20, 0.30, -40, -50]; // Method (return element > 0). var found = array.find(function (element) { return element > 0; }); // Printing desired values. document.write(found);</script> Output: 0.3 Example 2: Here, the arr.find() method in JavaScript returns the value of the first element in the array that satisfies the provided testing method. Javascript <script> // Input array contain some elements. var array = [10, 20, 30, 40, 50]; // Method (return element > 10). var found = array.find(function (element) { return element > 20; }); // Printing desired values. document.write(found);</script> Output: 30 Example 3: In this example, whenever we need to get the value of the first element in the array that satisfies the provided testing method at that time we use arr.find() method in JavaScript. JavaScript <script> // Input array contain some elements. var array = [2, 7, 8, 9]; // Provided testing method (return element > 4). var found = array.find(function (element) { return element > 4; }); // Printing desired values. document.write(found);</script> Output: 7 Supported Browsers: The browsers supported by JavaScript Array find() method are listed below: Google Chrome 45.0 Microsoft Edge 12.0 Mozilla Firefox 25.0 Safari 7.1 Opera 32.0 JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples. bhaskargeeksforgeeks javascript-array JavaScript-Methods JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Convert a string to an integer in JavaScript Form validation using HTML and JavaScript Difference Between PUT and PATCH Request Installation of Node.js on Linux Express.js express.Router() Function Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 24207, "s": 24179, "text": "\n16 Nov, 2021" }, { "code": null, "e": 24563, "s": 24207, "text": "The arr.find() method in Javascript is used to get the value of the first element in the array that satisfies the provided condition. It checks all the elements of the array and whichever first element satisfies the condition is going to print. This function will not work function having the empty array elements, also does not change the original array." }, { "code": null, "e": 24571, "s": 24563, "text": "Syntax:" }, { "code": null, "e": 24629, "s": 24571, "text": "array.find(function(currentValue, index, arr),thisValue);" }, { "code": null, "e": 24714, "s": 24629, "text": "Parameters: This method accepts 5 parameters as mentioned above and described below:" }, { "code": null, "e": 24784, "s": 24714, "text": "function: It is the function of the array that works on each element." }, { "code": null, "e": 24840, "s": 24784, "text": "currentValue: This parameter holds the current element." }, { "code": null, "e": 24920, "s": 24840, "text": "index: It is an optional parameter that holds the index of the current element." }, { "code": null, "e": 25013, "s": 24920, "text": "arr: It is an optional parameter that holds the array object the current element belongs to." }, { "code": null, "e": 25189, "s": 25013, "text": "thisValue: This parameter is optional. If a value is to be passed to the function to be used as its “this” value else the value “undefined” will be passed as its “this” value." }, { "code": null, "e": 25329, "s": 25189, "text": "Return value: It returns the array element value if any of the elements in the array satisfy the condition, otherwise it returns undefined." }, { "code": null, "e": 25420, "s": 25329, "text": "We will understand the concept of the Javascript Array find() method through the examples." }, { "code": null, "e": 25523, "s": 25420, "text": "Example 1: The below example illustrates the JavaScript Array find() method to find a positive number." }, { "code": null, "e": 25534, "s": 25523, "text": "Javascript" }, { "code": "<script> // Input array contain some elements. var array = [-10, -0.20, 0.30, -40, -50]; // Method (return element > 0). var found = array.find(function (element) { return element > 0; }); // Printing desired values. document.write(found);</script>", "e": 25813, "s": 25534, "text": null }, { "code": null, "e": 25821, "s": 25813, "text": "Output:" }, { "code": null, "e": 25825, "s": 25821, "text": "0.3" }, { "code": null, "e": 25974, "s": 25825, "text": "Example 2: Here, the arr.find() method in JavaScript returns the value of the first element in the array that satisfies the provided testing method." }, { "code": null, "e": 25985, "s": 25974, "text": "Javascript" }, { "code": "<script> // Input array contain some elements. var array = [10, 20, 30, 40, 50]; // Method (return element > 10). var found = array.find(function (element) { return element > 20; }); // Printing desired values. document.write(found);</script>", "e": 26258, "s": 25985, "text": null }, { "code": null, "e": 26266, "s": 26258, "text": "Output:" }, { "code": null, "e": 26269, "s": 26266, "text": "30" }, { "code": null, "e": 26462, "s": 26269, "text": "Example 3: In this example, whenever we need to get the value of the first element in the array that satisfies the provided testing method at that time we use arr.find() method in JavaScript. " }, { "code": null, "e": 26473, "s": 26462, "text": "JavaScript" }, { "code": "<script> // Input array contain some elements. var array = [2, 7, 8, 9]; // Provided testing method (return element > 4). var found = array.find(function (element) { return element > 4; }); // Printing desired values. document.write(found);</script>", "e": 26753, "s": 26473, "text": null }, { "code": null, "e": 26761, "s": 26753, "text": "Output:" }, { "code": null, "e": 26763, "s": 26761, "text": "7" }, { "code": null, "e": 26858, "s": 26763, "text": "Supported Browsers: The browsers supported by JavaScript Array find() method are listed below:" }, { "code": null, "e": 26877, "s": 26858, "text": "Google Chrome 45.0" }, { "code": null, "e": 26897, "s": 26877, "text": "Microsoft Edge 12.0" }, { "code": null, "e": 26918, "s": 26897, "text": "Mozilla Firefox 25.0" }, { "code": null, "e": 26929, "s": 26918, "text": "Safari 7.1" }, { "code": null, "e": 26940, "s": 26929, "text": "Opera 32.0" }, { "code": null, "e": 27159, "s": 26940, "text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples." }, { "code": null, "e": 27180, "s": 27159, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 27197, "s": 27180, "text": "javascript-array" }, { "code": null, "e": 27216, "s": 27197, "text": "JavaScript-Methods" }, { "code": null, "e": 27227, "s": 27216, "text": "JavaScript" }, { "code": null, "e": 27244, "s": 27227, "text": "Web Technologies" }, { "code": null, "e": 27342, "s": 27244, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27351, "s": 27342, "text": "Comments" }, { "code": null, "e": 27364, "s": 27351, "text": "Old Comments" }, { "code": null, "e": 27425, "s": 27364, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27497, "s": 27425, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 27542, "s": 27497, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27584, "s": 27542, "text": "Form validation using HTML and JavaScript" }, { "code": null, "e": 27625, "s": 27584, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 27658, "s": 27625, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27695, "s": 27658, "text": "Express.js express.Router() Function" }, { "code": null, "e": 27757, "s": 27695, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27800, "s": 27757, "text": "How to fetch data from an API in ReactJS ?" } ]
Feature Selection Using Random forest | by Akash Dubey | Towards Data Science
Random forests are one the most popular machine learning algorithms. They are so successful because they provide in general a good predictive performance, low overfitting, and easy interpretability. This interpretability is given by the fact that it is straightforward to derive the importance of each variable on the tree decision. In other words, it is easy to compute how much each variable is contributing to the decision. Feature selection using Random forest comes under the category of Embedded methods. Embedded methods combine the qualities of filter and wrapper methods. They are implemented by algorithms that have their own built-in feature selection methods. Some of the benefits of embedded methods are : They are highly accurate. They generalize better. They are interpretable How does Random forest select features? Random forests consist of 4 –12 hundred decision trees, each of them built over a random extraction of the observations from the dataset and a random extraction of the features. Not every tree sees all the features or all the observations, and this guarantees that the trees are de-correlated and therefore less prone to over-fitting. Each tree is also a sequence of yes-no questions based on a single or combination of features. At each node (this is at each question), the three divides the dataset into 2 buckets, each of them hosting observations that are more similar among themselves and different from the ones in the other bucket. Therefore, the importance of each feature is derived from how “pure” each of the buckets is. Does it work differently for Classification and Regression? For classification, the measure of impurity is either the Gini impurity or the information gain/entropy. For regression the measure of impurity is variance. Therefore, when training a tree, it is possible to compute how much each feature decreases the impurity. The more a feature decreases the impurity, the more important the feature is. In random forests, the impurity decrease from each feature can be averaged across trees to determine the final importance of the variable. To give a better intuition, features that are selected at the top of the trees are in general more important than features that are selected at the end nodes of the trees, as generally the top splits lead to bigger information gains. Let's see some Python code on how to select features using Random forest. Here I will not apply Random forest to the actual dataset but it can be easily applied to any actual dataset. Importing libraries Importing libraries import pandas as pdfrom sklearn.ensemble import RandomForestClassfierfrom sklearn.feature_selection import SelectFromModel 2. In all feature selection procedures, it is a good practice to select the features by examining only the training set. This is to avoid overfitting. So considering we have a train and a test dataset. We select the features from the train set and then transfer the changes to the test set later. X_train,y_train,X_test,y_test = train_test_split(data,test_size=0.3) 3. Here I will do the model fitting and feature selection altogether in one line of code. Firstly, I specify the random forest instance, indicating the number of trees. Then I use selectFromModel object from sklearn to automatically select the features. sel = SelectFromModel(RandomForestClassifier(n_estimators = 100))sel.fit(X_train, y_train) SelectFromModel will select those features which importance is greater than the mean importance of all the features by default, but we can alter this threshold if we want. 4. To see which features are important we can use get_support method on the fitted model. sel.get_support() It will return an array of boolean values. True for the features whose importance is greater than the mean importance and False for the rest. 5. We can now make a list and count the selected features. selected_feat= X_train.columns[(sel.get_support())]len(selected_feat) It will return an Integer representing the number of features selected by the random forest. 6. To get the name of the features selected print(selected_feat) It will return the name of the selected features. 7. We can also check and plot the distribution of importance. pd.series(sel.estimator_,feature_importances_,.ravel()).hist() It will return a histogram showing the distribution of the features selected using this feature selection technique. We can of course tune the parameters of the Decision Tree.Where we put the cut-off to select features is a bit arbitrary. One way is to select the top 10, 20 features. Alternatively, the top 10th percentile. For this, we can use mutual info in combination with SelectKBest or SelectPercentile from sklearn. Few of the limitations of Random forest are : Correlated features will be given equal or similar importance, but overall reduced importance compared to the same tree built without correlated counterparts. Random Forests and decision trees, in general, give preference to features with high cardinality ( Trees are biased to these type of variables ). Selecting features by using tree derived feature importance is a very straightforward, fast and generally accurate way of selecting good features for machine learning. In particular, if we are going to build tree methods. However, as I said, correlated features will show in a tree similar and lowered importance, compared to what their importance would be if the tree was built without correlated counterparts. In situations like this, it is better to select features recursively, rather than all together as we have done here.
[ { "code": null, "e": 599, "s": 172, "text": "Random forests are one the most popular machine learning algorithms. They are so successful because they provide in general a good predictive performance, low overfitting, and easy interpretability. This interpretability is given by the fact that it is straightforward to derive the importance of each variable on the tree decision. In other words, it is easy to compute how much each variable is contributing to the decision." }, { "code": null, "e": 891, "s": 599, "text": "Feature selection using Random forest comes under the category of Embedded methods. Embedded methods combine the qualities of filter and wrapper methods. They are implemented by algorithms that have their own built-in feature selection methods. Some of the benefits of embedded methods are :" }, { "code": null, "e": 917, "s": 891, "text": "They are highly accurate." }, { "code": null, "e": 941, "s": 917, "text": "They generalize better." }, { "code": null, "e": 964, "s": 941, "text": "They are interpretable" }, { "code": null, "e": 1004, "s": 964, "text": "How does Random forest select features?" }, { "code": null, "e": 1736, "s": 1004, "text": "Random forests consist of 4 –12 hundred decision trees, each of them built over a random extraction of the observations from the dataset and a random extraction of the features. Not every tree sees all the features or all the observations, and this guarantees that the trees are de-correlated and therefore less prone to over-fitting. Each tree is also a sequence of yes-no questions based on a single or combination of features. At each node (this is at each question), the three divides the dataset into 2 buckets, each of them hosting observations that are more similar among themselves and different from the ones in the other bucket. Therefore, the importance of each feature is derived from how “pure” each of the buckets is." }, { "code": null, "e": 1796, "s": 1736, "text": "Does it work differently for Classification and Regression?" }, { "code": null, "e": 1901, "s": 1796, "text": "For classification, the measure of impurity is either the Gini impurity or the information gain/entropy." }, { "code": null, "e": 1953, "s": 1901, "text": "For regression the measure of impurity is variance." }, { "code": null, "e": 2275, "s": 1953, "text": "Therefore, when training a tree, it is possible to compute how much each feature decreases the impurity. The more a feature decreases the impurity, the more important the feature is. In random forests, the impurity decrease from each feature can be averaged across trees to determine the final importance of the variable." }, { "code": null, "e": 2509, "s": 2275, "text": "To give a better intuition, features that are selected at the top of the trees are in general more important than features that are selected at the end nodes of the trees, as generally the top splits lead to bigger information gains." }, { "code": null, "e": 2583, "s": 2509, "text": "Let's see some Python code on how to select features using Random forest." }, { "code": null, "e": 2693, "s": 2583, "text": "Here I will not apply Random forest to the actual dataset but it can be easily applied to any actual dataset." }, { "code": null, "e": 2713, "s": 2693, "text": "Importing libraries" }, { "code": null, "e": 2733, "s": 2713, "text": "Importing libraries" }, { "code": null, "e": 2856, "s": 2733, "text": "import pandas as pdfrom sklearn.ensemble import RandomForestClassfierfrom sklearn.feature_selection import SelectFromModel" }, { "code": null, "e": 3007, "s": 2856, "text": "2. In all feature selection procedures, it is a good practice to select the features by examining only the training set. This is to avoid overfitting." }, { "code": null, "e": 3153, "s": 3007, "text": "So considering we have a train and a test dataset. We select the features from the train set and then transfer the changes to the test set later." }, { "code": null, "e": 3222, "s": 3153, "text": "X_train,y_train,X_test,y_test = train_test_split(data,test_size=0.3)" }, { "code": null, "e": 3312, "s": 3222, "text": "3. Here I will do the model fitting and feature selection altogether in one line of code." }, { "code": null, "e": 3391, "s": 3312, "text": "Firstly, I specify the random forest instance, indicating the number of trees." }, { "code": null, "e": 3476, "s": 3391, "text": "Then I use selectFromModel object from sklearn to automatically select the features." }, { "code": null, "e": 3567, "s": 3476, "text": "sel = SelectFromModel(RandomForestClassifier(n_estimators = 100))sel.fit(X_train, y_train)" }, { "code": null, "e": 3739, "s": 3567, "text": "SelectFromModel will select those features which importance is greater than the mean importance of all the features by default, but we can alter this threshold if we want." }, { "code": null, "e": 3829, "s": 3739, "text": "4. To see which features are important we can use get_support method on the fitted model." }, { "code": null, "e": 3847, "s": 3829, "text": "sel.get_support()" }, { "code": null, "e": 3989, "s": 3847, "text": "It will return an array of boolean values. True for the features whose importance is greater than the mean importance and False for the rest." }, { "code": null, "e": 4048, "s": 3989, "text": "5. We can now make a list and count the selected features." }, { "code": null, "e": 4118, "s": 4048, "text": "selected_feat= X_train.columns[(sel.get_support())]len(selected_feat)" }, { "code": null, "e": 4211, "s": 4118, "text": "It will return an Integer representing the number of features selected by the random forest." }, { "code": null, "e": 4255, "s": 4211, "text": "6. To get the name of the features selected" }, { "code": null, "e": 4276, "s": 4255, "text": "print(selected_feat)" }, { "code": null, "e": 4326, "s": 4276, "text": "It will return the name of the selected features." }, { "code": null, "e": 4388, "s": 4326, "text": "7. We can also check and plot the distribution of importance." }, { "code": null, "e": 4451, "s": 4388, "text": "pd.series(sel.estimator_,feature_importances_,.ravel()).hist()" }, { "code": null, "e": 4568, "s": 4451, "text": "It will return a histogram showing the distribution of the features selected using this feature selection technique." }, { "code": null, "e": 4875, "s": 4568, "text": "We can of course tune the parameters of the Decision Tree.Where we put the cut-off to select features is a bit arbitrary. One way is to select the top 10, 20 features. Alternatively, the top 10th percentile. For this, we can use mutual info in combination with SelectKBest or SelectPercentile from sklearn." }, { "code": null, "e": 4921, "s": 4875, "text": "Few of the limitations of Random forest are :" }, { "code": null, "e": 5080, "s": 4921, "text": "Correlated features will be given equal or similar importance, but overall reduced importance compared to the same tree built without correlated counterparts." }, { "code": null, "e": 5226, "s": 5080, "text": "Random Forests and decision trees, in general, give preference to features with high cardinality ( Trees are biased to these type of variables )." }, { "code": null, "e": 5448, "s": 5226, "text": "Selecting features by using tree derived feature importance is a very straightforward, fast and generally accurate way of selecting good features for machine learning. In particular, if we are going to build tree methods." }, { "code": null, "e": 5638, "s": 5448, "text": "However, as I said, correlated features will show in a tree similar and lowered importance, compared to what their importance would be if the tree was built without correlated counterparts." } ]
Application Layer - GeeksforGeeks
09 Oct, 2019 The Layer 1 (Physical Layer) PDU is the bit or, more generally, symbol The Layer 2 (Data Link Layer) PDU is the frame. The Layer 3 (Network Layer) PDU is the packet. The Layer 4 (Transport Layer) PDU is the segment for TCP or the datagram for UDP. The Layer 5 (Application Layer) PDU is the data or message. m1: Send an email from a mail client to a mail server m2: Download an email from mailbox server to a mail client m3: Checking email in a web browser The web browser requests a webpage using HTTP.The web browser establishes a TCP connection with the web server.The web server sends the requested webpage using HTTP.The web browser resolves the domain name using DNS. The web browser requests a webpage using HTTP. The web browser establishes a TCP connection with the web server. The web server sends the requested webpage using HTTP. The web browser resolves the domain name using DNS. (i) HTTP (ii) FTP (iii) TCP (iv) POP3 Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Must Do Coding Questions for Product Based Companies How to calculate MOVING AVERAGE in a Pandas DataFrame? What is "network ID" and "host ID" in IP Addresses? Create a dictionary with list comprehension in Python What is Transmission Control Protocol (TCP)? Python - Update values of a list of dictionaries How to Calculate Number of Host in a Subnet? Bash Scripting - How to check If File Exists How to Get Cell Value from Pandas DataFrame? How to Calculate Correlation Between Two Columns in Pandas?
[ { "code": null, "e": 36666, "s": 36638, "text": "\n09 Oct, 2019" }, { "code": null, "e": 36995, "s": 36666, "text": " The Layer 1 (Physical Layer) PDU is the bit or, more generally, symbol \n The Layer 2 (Data Link Layer) PDU is the frame.\n The Layer 3 (Network Layer) PDU is the packet.\n The Layer 4 (Transport Layer) PDU is the segment\n for TCP or the datagram for UDP.\n The Layer 5 (Application Layer) PDU is the data or message.\n" }, { "code": null, "e": 37144, "s": 36995, "text": "m1: Send an email from a mail client to a mail server\nm2: Download an email from mailbox server to a mail client\nm3: Checking email in a web browser" }, { "code": null, "e": 37361, "s": 37144, "text": "The web browser requests a webpage using HTTP.The web browser establishes a TCP connection with the web server.The web server sends the requested webpage using HTTP.The web browser resolves the domain name using DNS." }, { "code": null, "e": 37408, "s": 37361, "text": "The web browser requests a webpage using HTTP." }, { "code": null, "e": 37474, "s": 37408, "text": "The web browser establishes a TCP connection with the web server." }, { "code": null, "e": 37529, "s": 37474, "text": "The web server sends the requested webpage using HTTP." }, { "code": null, "e": 37581, "s": 37529, "text": "The web browser resolves the domain name using DNS." }, { "code": null, "e": 37621, "s": 37581, "text": "(i) HTTP\n(ii) FTP\n(iii) TCP\n(iv) POP3 " }, { "code": null, "e": 37719, "s": 37621, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 37772, "s": 37719, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 37827, "s": 37772, "text": "How to calculate MOVING AVERAGE in a Pandas DataFrame?" }, { "code": null, "e": 37879, "s": 37827, "text": "What is \"network ID\" and \"host ID\" in IP Addresses?" }, { "code": null, "e": 37933, "s": 37879, "text": "Create a dictionary with list comprehension in Python" }, { "code": null, "e": 37978, "s": 37933, "text": "What is Transmission Control Protocol (TCP)?" }, { "code": null, "e": 38027, "s": 37978, "text": "Python - Update values of a list of dictionaries" }, { "code": null, "e": 38072, "s": 38027, "text": "How to Calculate Number of Host in a Subnet?" }, { "code": null, "e": 38117, "s": 38072, "text": "Bash Scripting - How to check If File Exists" }, { "code": null, "e": 38162, "s": 38117, "text": "How to Get Cell Value from Pandas DataFrame?" } ]
The @Override Annotation in Java - GeeksforGeeks
06 Dec, 2021 The @Override annotation is a standard Java annotation that was first introduced in Java 1.5. The @Override annotation denotes that the child class method overrides the base class method. For two reasons, the @Override annotation is useful. If the annotated method does not actually override anything, the compiler issues a warning.It can help to make the source code more readable. If the annotated method does not actually override anything, the compiler issues a warning. It can help to make the source code more readable. Why we use @Override annotation: Because of the following two advantages, using the @Override annotation when overriding a method is considered a best practice for coding in Java: 1) You’ll get a compile-time error if the programmer makes a mistake while overriding, such as using the wrong method name or parameter types. Because you are informing the compiler that you are overriding this method by using this annotation. If you don’t use the annotation, the sub-class method will be treated as a new method in the subclass (rather than the overriding method). 2) It improves the code’s readability. If you change the signature of an overridden method, all sub-classes that override it will throw a compilation error, which will eventually lead to you changing the signature in the subclasses. If you have a large number of classes in your application, this annotation will greatly assist you in identifying the classes that need to be changed when a method’s signature is changed. Syntax: public @interface Override Example 1: Without usage of abstract class Java // Java Program Illustrating Override Annotation // Importing input output classesimport java.io.*; // Class 1// Parent classclass ParentClass { // Method inside parent class public void display() { // Print statement whenever // method of parent class is called System.out.println("We are in base class method"); }} // Class 2// Child classclass ChildClass extends ParentClass { // @Override // Method inside child class public void display() { // Print statement whenever // method of child class is called System.out.println("We are in child class method"); }} // Clas 3// OverrideAnnotationTestpublic class GFG { // Main driver method public static void main(String args[]) { // Display message only System.out.println( "Example of @Override annotation"); // Creating an object of parent class // with reference t ochild class ParentClass obj = new ChildClass(); // Calling the method to execute inside classes obj.display(); }} Output: Example 2: Using the abstract class Java // Java Program illustrating Override Annotation// Using Abstract class // Importing input output classesimport java.io.*; // Class 1// Helper abstract classabstract class Vehicle { // Calling this method public abstract void method();} // Class 2// Helper classclass Car extends Vehicle { // @Override // Method of Car class public void method() { // Print statement whenever this method is called System.out.println("This is Car"); }} // Class 3// Helper classclass Bike extends Vehicle { // @Override // Method of bike class public void method() { // Print statement whenever this method is called System.out.println("This is Bike"); }} // Class 4// OverrideAnnotationExamplepublic class GFG { // Main drive method public static void main(String[] args) { // Creating object of both the classes // namely Car and Bike Car Carobj = new Car(); // Calling method over car object Carobj.method(); Bike Bikeobj = new Bike(); // Similarly calling method over bike object Bikeobj.method(); }} This is Car This is Bike singhhimanshu2009 anikakapoor rkbhola5 Java-Object Oriented Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Exceptions in Java Constructors in Java Functional Interfaces in Java Different ways of Reading a text file in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java? Iterate through List in Java
[ { "code": null, "e": 25347, "s": 25319, "text": "\n06 Dec, 2021" }, { "code": null, "e": 25535, "s": 25347, "text": "The @Override annotation is a standard Java annotation that was first introduced in Java 1.5. The @Override annotation denotes that the child class method overrides the base class method." }, { "code": null, "e": 25588, "s": 25535, "text": "For two reasons, the @Override annotation is useful." }, { "code": null, "e": 25730, "s": 25588, "text": "If the annotated method does not actually override anything, the compiler issues a warning.It can help to make the source code more readable." }, { "code": null, "e": 25822, "s": 25730, "text": "If the annotated method does not actually override anything, the compiler issues a warning." }, { "code": null, "e": 25873, "s": 25822, "text": "It can help to make the source code more readable." }, { "code": null, "e": 25906, "s": 25873, "text": "Why we use @Override annotation:" }, { "code": null, "e": 26053, "s": 25906, "text": "Because of the following two advantages, using the @Override annotation when overriding a method is considered a best practice for coding in Java:" }, { "code": null, "e": 26436, "s": 26053, "text": "1) You’ll get a compile-time error if the programmer makes a mistake while overriding, such as using the wrong method name or parameter types. Because you are informing the compiler that you are overriding this method by using this annotation. If you don’t use the annotation, the sub-class method will be treated as a new method in the subclass (rather than the overriding method)." }, { "code": null, "e": 26857, "s": 26436, "text": "2) It improves the code’s readability. If you change the signature of an overridden method, all sub-classes that override it will throw a compilation error, which will eventually lead to you changing the signature in the subclasses. If you have a large number of classes in your application, this annotation will greatly assist you in identifying the classes that need to be changed when a method’s signature is changed." }, { "code": null, "e": 26865, "s": 26857, "text": "Syntax:" }, { "code": null, "e": 26892, "s": 26865, "text": "public @interface Override" }, { "code": null, "e": 26936, "s": 26892, "text": "Example 1: Without usage of abstract class " }, { "code": null, "e": 26941, "s": 26936, "text": "Java" }, { "code": "// Java Program Illustrating Override Annotation // Importing input output classesimport java.io.*; // Class 1// Parent classclass ParentClass { // Method inside parent class public void display() { // Print statement whenever // method of parent class is called System.out.println(\"We are in base class method\"); }} // Class 2// Child classclass ChildClass extends ParentClass { // @Override // Method inside child class public void display() { // Print statement whenever // method of child class is called System.out.println(\"We are in child class method\"); }} // Clas 3// OverrideAnnotationTestpublic class GFG { // Main driver method public static void main(String args[]) { // Display message only System.out.println( \"Example of @Override annotation\"); // Creating an object of parent class // with reference t ochild class ParentClass obj = new ChildClass(); // Calling the method to execute inside classes obj.display(); }}", "e": 28023, "s": 26941, "text": null }, { "code": null, "e": 28031, "s": 28023, "text": "Output:" }, { "code": null, "e": 28067, "s": 28031, "text": "Example 2: Using the abstract class" }, { "code": null, "e": 28072, "s": 28067, "text": "Java" }, { "code": "// Java Program illustrating Override Annotation// Using Abstract class // Importing input output classesimport java.io.*; // Class 1// Helper abstract classabstract class Vehicle { // Calling this method public abstract void method();} // Class 2// Helper classclass Car extends Vehicle { // @Override // Method of Car class public void method() { // Print statement whenever this method is called System.out.println(\"This is Car\"); }} // Class 3// Helper classclass Bike extends Vehicle { // @Override // Method of bike class public void method() { // Print statement whenever this method is called System.out.println(\"This is Bike\"); }} // Class 4// OverrideAnnotationExamplepublic class GFG { // Main drive method public static void main(String[] args) { // Creating object of both the classes // namely Car and Bike Car Carobj = new Car(); // Calling method over car object Carobj.method(); Bike Bikeobj = new Bike(); // Similarly calling method over bike object Bikeobj.method(); }}", "e": 29201, "s": 28072, "text": null }, { "code": null, "e": 29226, "s": 29201, "text": "This is Car\nThis is Bike" }, { "code": null, "e": 29244, "s": 29226, "text": "singhhimanshu2009" }, { "code": null, "e": 29256, "s": 29244, "text": "anikakapoor" }, { "code": null, "e": 29265, "s": 29256, "text": "rkbhola5" }, { "code": null, "e": 29286, "s": 29265, "text": "Java-Object Oriented" }, { "code": null, "e": 29293, "s": 29286, "text": "Picked" }, { "code": null, "e": 29298, "s": 29293, "text": "Java" }, { "code": null, "e": 29312, "s": 29298, "text": "Java Programs" }, { "code": null, "e": 29317, "s": 29312, "text": "Java" }, { "code": null, "e": 29415, "s": 29317, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29430, "s": 29415, "text": "Stream In Java" }, { "code": null, "e": 29449, "s": 29430, "text": "Exceptions in Java" }, { "code": null, "e": 29470, "s": 29449, "text": "Constructors in Java" }, { "code": null, "e": 29500, "s": 29470, "text": "Functional Interfaces in Java" }, { "code": null, "e": 29546, "s": 29500, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 29572, "s": 29546, "text": "Java Programming Examples" }, { "code": null, "e": 29606, "s": 29572, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 29653, "s": 29606, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 29685, "s": 29653, "text": "How to Iterate HashMap in Java?" } ]
How to share intent from intentservice in android?
Before getting into example, we should know what Intent service is in android. Intent Service is going to do back ground operation asynchronously. When user call startService() from activity , it doesn’t create instance for each request. It going to stop service after done some action in service class or else we need to stop service using stopSelf(). This example demonstrate about How to share intent from intentservice. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:app = "http://schemas.android.com/apk/res-auto" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity"> <TextView android:id = "@+id/text" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:text = "Start Service" android:textSize = "25sp" app:layout_constraintBottom_toBottomOf = "parent" app:layout_constraintLeft_toLeftOf = "parent" app:layout_constraintRight_toRightOf = "parent" app:layout_constraintTop_toTopOf = "parent" /> </android.support.constraint.ConstraintLayout> In the above code, we have taken text view. When user click on text view, it will open default share dialog from android OS. Step 3 − Add the following code to src/MainActivity.java package com.example.andy.myapplication; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.TextView; public class MainActivity extends AppCompatActivity { TextView text; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); text = findViewById(R.id.text); text.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startService(new Intent(MainActivity.this, service.class)); } }); } } Create a class called service.class file and add the following code – package com.example.andy.myapplication; import android.app.IntentService; import android.content.Intent; import android.os.IBinder; public class service extends IntentService { public static volatile boolean shouldStop = false; public service() { super(service.class.getSimpleName()); } @Override public IBinder onBind(Intent intent) { return null; } @Override protected void onHandleIntent(Intent intent) { Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND); sharingIntent.setType("text/plain"); sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject Here"); sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Tutorialspoint.com"); startActivity(Intent.createChooser(sharingIntent, "Sharing")); if(shouldStop) { stopSelf(); return; } } } To stop service, User the following code in service class – stopSelf(); Step 4 − Add the following code to manifest.xml <?xml version = "1.0" encoding = "utf-8"?> <manifest xmlns:android = "http://schemas.android.com/apk/res/android" package = "com.example.andy.myapplication"> <uses-permission android:name = "android.permission.WAKE_LOCK"/> <application android:allowBackup = "true" android:icon = "@mipmap/ic_launcher" android:label = "@string/app_name" android:roundIcon = "@mipmap/ic_launcher_round" android:supportsRtl = "true" android:theme = "@style/AppTheme"> <activity android:name = ".MainActivity"> <intent-filter> <action android:name = "android.intent.action.MAIN" /> <category android:name = "android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name = ".service"/> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – In the above result, it shown default screen of application. When user clicks on the textview, it will show default share dialog from mobile os as shown below – Click here to download the project code
[ { "code": null, "e": 1415, "s": 1062, "text": "Before getting into example, we should know what Intent service is in android. Intent Service is going to do back ground operation asynchronously. When user call startService() from activity , it doesn’t create instance for each request. It going to stop service after done some action in service class or else we need to stop service using stopSelf()." }, { "code": null, "e": 1486, "s": 1415, "text": "This example demonstrate about How to share intent from intentservice." }, { "code": null, "e": 1615, "s": 1486, "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": 1680, "s": 1615, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2521, "s": 1680, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<android.support.constraint.ConstraintLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\">\n <TextView\n android:id = \"@+id/text\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\"\n android:text = \"Start Service\"\n android:textSize = \"25sp\"\n app:layout_constraintBottom_toBottomOf = \"parent\"\n app:layout_constraintLeft_toLeftOf = \"parent\"\n app:layout_constraintRight_toRightOf = \"parent\"\n app:layout_constraintTop_toTopOf = \"parent\" />\n</android.support.constraint.ConstraintLayout>" }, { "code": null, "e": 2646, "s": 2521, "text": "In the above code, we have taken text view. When user click on text view, it will open default share dialog from android OS." }, { "code": null, "e": 2703, "s": 2646, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3393, "s": 2703, "text": "package com.example.andy.myapplication;\n\nimport android.content.Intent;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.TextView;\n\npublic class MainActivity extends AppCompatActivity {\n TextView text;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n text = findViewById(R.id.text);\n text.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n startService(new Intent(MainActivity.this, service.class));\n }\n });\n }\n}" }, { "code": null, "e": 3463, "s": 3393, "text": "Create a class called service.class file and add the following code –" }, { "code": null, "e": 4343, "s": 3463, "text": "package com.example.andy.myapplication;\nimport android.app.IntentService;\nimport android.content.Intent;\nimport android.os.IBinder;\npublic class service extends IntentService {\n public static volatile boolean shouldStop = false;\n public service() {\n super(service.class.getSimpleName());\n }\n @Override\n public IBinder onBind(Intent intent) {\n return null;\n }\n @Override\n protected void onHandleIntent(Intent intent) {\n Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);\n sharingIntent.setType(\"text/plain\");\n sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, \"Subject Here\");\n sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, \"Tutorialspoint.com\");\n startActivity(Intent.createChooser(sharingIntent, \"Sharing\"));\n if(shouldStop) {\n stopSelf();\n return;\n }\n }\n}" }, { "code": null, "e": 4403, "s": 4343, "text": "To stop service, User the following code in service class –" }, { "code": null, "e": 4415, "s": 4403, "text": "stopSelf();" }, { "code": null, "e": 4463, "s": 4415, "text": "Step 4 − Add the following code to manifest.xml" }, { "code": null, "e": 5289, "s": 4463, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.example.andy.myapplication\">\n <uses-permission android:name = \"android.permission.WAKE_LOCK\"/>\n <application\n android:allowBackup = \"true\"\n android:icon = \"@mipmap/ic_launcher\"\n android:label = \"@string/app_name\"\n android:roundIcon = \"@mipmap/ic_launcher_round\"\n android:supportsRtl = \"true\"\n android:theme = \"@style/AppTheme\">\n <activity android:name = \".MainActivity\">\n <intent-filter>\n <action android:name = \"android.intent.action.MAIN\" />\n <category android:name = \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n <service android:name = \".service\"/>\n </application>\n</manifest>" }, { "code": null, "e": 5636, "s": 5289, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" }, { "code": null, "e": 5797, "s": 5636, "text": "In the above result, it shown default screen of application. When user clicks on the textview, it will show default share dialog from mobile os as shown below –" }, { "code": null, "e": 5837, "s": 5797, "text": "Click here to download the project code" } ]
DateTime.ToFileTimeUtc() Method in C# - GeeksforGeeks
10 Feb, 2019 This method is used to convert the value of the current DateTime object to a Windows file time. Syntax: public long ToFileTimeUtc (); Return Value: This method returns the value of the current DateTime object expressed as a Windows file time. Exception: This method will give ArgumentOutOfRangeException if the resulting file time would represent a date and time before 12:00 midnight January 1, 1601 C.E. UTC. Below programs illustrate the use of DateTime.ToFileTimeUtc() Method: Example 1: // C# program to demonstrate the// DateTime.ToFileTimeUtc()// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // creating object of DateTime DateTime date = new DateTime(2011, 1, 1, 4, 0, 15); // converting current DateTime object // to a Windows file time. // using ToFileTimeUtc() method; long value = date.ToFileTimeUtc(); // Display the TimeSpan Console.WriteLine("Windows file time(UTC) "+ "is {0}", value); } catch (ArgumentOutOfRangeException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }} Windows file time(UTC) is 129383280150000000 Example 2: For ArgumentOutOfRangeException // C# program to demonstrate the// DateTime.ToFileTimeUtc()// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // creating object of DateTime DateTime date = new DateTime(1600, 1, 1, 4, 0, 15); // converting current DateTime // object to a Windows file time. // using ToFileTimeUtc() method; long value = date.ToFileTimeUtc(); // Display the TimeSpan Console.WriteLine("Windows file time(UTC) is "+ "{0}", value); } catch (ArgumentOutOfRangeException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }} Exception Thrown: System.ArgumentOutOfRangeException Reference: https://docs.microsoft.com/en-us/dotnet/api/system.datetime.tofiletimeutc?view=netframework-4.7.2 CSharp DateTime Struct CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Extension Method in C# HashSet in C# with Examples Top 50 C# Interview Questions & Answers Partial Classes in C# C# | How to insert an element in an Array? C# | List Class C# | Inheritance Lambda Expressions in C# Linked List Implementation in C# Convert String to Character Array in C#
[ { "code": null, "e": 24302, "s": 24274, "text": "\n10 Feb, 2019" }, { "code": null, "e": 24398, "s": 24302, "text": "This method is used to convert the value of the current DateTime object to a Windows file time." }, { "code": null, "e": 24436, "s": 24398, "text": "Syntax: public long ToFileTimeUtc ();" }, { "code": null, "e": 24545, "s": 24436, "text": "Return Value: This method returns the value of the current DateTime object expressed as a Windows file time." }, { "code": null, "e": 24713, "s": 24545, "text": "Exception: This method will give ArgumentOutOfRangeException if the resulting file time would represent a date and time before 12:00 midnight January 1, 1601 C.E. UTC." }, { "code": null, "e": 24783, "s": 24713, "text": "Below programs illustrate the use of DateTime.ToFileTimeUtc() Method:" }, { "code": null, "e": 24794, "s": 24783, "text": "Example 1:" }, { "code": "// C# program to demonstrate the// DateTime.ToFileTimeUtc()// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // creating object of DateTime DateTime date = new DateTime(2011, 1, 1, 4, 0, 15); // converting current DateTime object // to a Windows file time. // using ToFileTimeUtc() method; long value = date.ToFileTimeUtc(); // Display the TimeSpan Console.WriteLine(\"Windows file time(UTC) \"+ \"is {0}\", value); } catch (ArgumentOutOfRangeException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}", "e": 25639, "s": 24794, "text": null }, { "code": null, "e": 25685, "s": 25639, "text": "Windows file time(UTC) is 129383280150000000\n" }, { "code": null, "e": 25728, "s": 25685, "text": "Example 2: For ArgumentOutOfRangeException" }, { "code": "// C# program to demonstrate the// DateTime.ToFileTimeUtc()// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // creating object of DateTime DateTime date = new DateTime(1600, 1, 1, 4, 0, 15); // converting current DateTime // object to a Windows file time. // using ToFileTimeUtc() method; long value = date.ToFileTimeUtc(); // Display the TimeSpan Console.WriteLine(\"Windows file time(UTC) is \"+ \"{0}\", value); } catch (ArgumentOutOfRangeException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}", "e": 26580, "s": 25728, "text": null }, { "code": null, "e": 26634, "s": 26580, "text": "Exception Thrown: System.ArgumentOutOfRangeException\n" }, { "code": null, "e": 26645, "s": 26634, "text": "Reference:" }, { "code": null, "e": 26743, "s": 26645, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.datetime.tofiletimeutc?view=netframework-4.7.2" }, { "code": null, "e": 26766, "s": 26743, "text": "CSharp DateTime Struct" }, { "code": null, "e": 26780, "s": 26766, "text": "CSharp-method" }, { "code": null, "e": 26783, "s": 26780, "text": "C#" }, { "code": null, "e": 26881, "s": 26783, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26890, "s": 26881, "text": "Comments" }, { "code": null, "e": 26903, "s": 26890, "text": "Old Comments" }, { "code": null, "e": 26926, "s": 26903, "text": "Extension Method in C#" }, { "code": null, "e": 26954, "s": 26926, "text": "HashSet in C# with Examples" }, { "code": null, "e": 26994, "s": 26954, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 27016, "s": 26994, "text": "Partial Classes in C#" }, { "code": null, "e": 27059, "s": 27016, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 27075, "s": 27059, "text": "C# | List Class" }, { "code": null, "e": 27092, "s": 27075, "text": "C# | Inheritance" }, { "code": null, "e": 27117, "s": 27092, "text": "Lambda Expressions in C#" }, { "code": null, "e": 27150, "s": 27117, "text": "Linked List Implementation in C#" } ]
How to detect if JavaScript is disabled in a browser?
To detect if JavaScript is disabled in a web browser, use the <noscript> tag. The HTML <noscript> tag is used to handle the browsers, which do recognize <script> tag but do not support scripting. This tag is used to display an alternate text message. Here’s an example, <!DOCTYPE html> <html> <head> <title>HTML noscript Tag</title> </head> <body> <script> <!-- document.write("Hello JavaScript!") --> </script> <noscript> Your browser does not support JavaScript! </noscript> </body> </html>
[ { "code": null, "e": 1313, "s": 1062, "text": "To detect if JavaScript is disabled in a web browser, use the <noscript> tag. The HTML <noscript> tag is used to handle the browsers, which do recognize <script> tag but do not support scripting. This tag is used to display an alternate text message." }, { "code": null, "e": 1332, "s": 1313, "text": "Here’s an example," }, { "code": null, "e": 1643, "s": 1332, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML noscript Tag</title>\n </head>\n\n <body>\n <script>\n <!--\n document.write(\"Hello JavaScript!\")\n -->\n </script>\n \n <noscript>\n Your browser does not support JavaScript!\n </noscript>\n </body>\n</html>" } ]
How to pass data into table from a form using React Components - GeeksforGeeks
21 Sep, 2021 ReactJS is a front-end library used to build UI components. In this article, we will learn to pass data into a table from a form using React Components. This will be done using two React components named Table and form. We will enter data into a form, which will be displayed in the table on ‘submit’. Creating React Application And Installing Module: Step 1: Create a React application using the following command. npx create-react-app Step 2: After creating your project folder(i.e. my-first-app), move to it by using the following command. cd my-first-app Project Structure: It will look like this. Step 3: Create a dummy JSON file; that initially contains the following one object and save it as data.json [ {"id":1,"name":"Akshit","city":"Moradabad"} ] Implementation: Now write down the following code in respective files. table.jsx import React, { useState } from 'react'; function StudentForm(props) { const [name, setName] = useState(''); const [city, setCity] = useState(''); const changeName = (event) => { setName(event.target.value); }; const changeCity = (event) => { setCity(event.target.value); }; const transferValue = (event) => { event.preventDefault(); const val = { name, city, }; props.func(val); clearState(); }; const clearState = () => { setName(''); setCity(''); }; return ( <div> <label>Name</label> <input type="text" value={name} onChange={changeName} /> <label>City</label> <input type="text" value={city} onChange={changeCity} /> <button onClick={transferValue}> Click Me</button> </div> );} export default StudentForm; form.jsx import React, { useState } from 'react';import StudentForm from './form';import jsonData from './data.json'; function TableData() { const [studentData, setStudentData] = useState(jsonData); const tableRows = studentData.map((info) => { return ( <tr> <td>{info.id}</td> <td>{info.name}</td> <td>{info.city}</td> </tr> ); }); const addRows = (data) => { const totalStudents = studentData.length; data.id = totalStudents + 1; const updatedStudentData = [...studentData]; updatedStudentData.push(data); setStudentData(updatedStudentData); }; return ( <div> <table className="table table-stripped"> <thead> <tr> <th>Sr.NO</th> <th>Name</th> <th>City</th> </tr> </thead> <tbody>{tableRows}</tbody> </table> <StudentForm func={addRows} /> </div> );} export default TableData; App.js import TableData from './table'; function App() { return ( <div className="App"> <h1>Hello Geeks!!!</h1> <TableData /> </div> );} export default App; 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: Blogathon-2021 React-Questions Blogathon ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Create a Table With Multiple Foreign Keys in SQL? How to Import JSON Data into SQL Server? Stratified Sampling in Pandas SQL Query to Convert Datetime to Date How to Install Tkinter in Windows? How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? How to pass data from child component to its parent in ReactJS ? How to pass data from one component to other component in ReactJS ? ReactJS Functional Components
[ { "code": null, "e": 26247, "s": 26219, "text": "\n21 Sep, 2021" }, { "code": null, "e": 26549, "s": 26247, "text": "ReactJS is a front-end library used to build UI components. In this article, we will learn to pass data into a table from a form using React Components. This will be done using two React components named Table and form. We will enter data into a form, which will be displayed in the table on ‘submit’." }, { "code": null, "e": 26599, "s": 26549, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 26663, "s": 26599, "text": "Step 1: Create a React application using the following command." }, { "code": null, "e": 26685, "s": 26663, "text": "npx create-react-app " }, { "code": null, "e": 26791, "s": 26685, "text": "Step 2: After creating your project folder(i.e. my-first-app), move to it by using the following command." }, { "code": null, "e": 26807, "s": 26791, "text": "cd my-first-app" }, { "code": null, "e": 26853, "s": 26809, "text": "Project Structure: It will look like this. " }, { "code": null, "e": 26961, "s": 26853, "text": "Step 3: Create a dummy JSON file; that initially contains the following one object and save it as data.json" }, { "code": null, "e": 27009, "s": 26961, "text": "[ {\"id\":1,\"name\":\"Akshit\",\"city\":\"Moradabad\"} ]" }, { "code": null, "e": 27080, "s": 27009, "text": "Implementation: Now write down the following code in respective files." }, { "code": null, "e": 27090, "s": 27080, "text": "table.jsx" }, { "code": "import React, { useState } from 'react'; function StudentForm(props) { const [name, setName] = useState(''); const [city, setCity] = useState(''); const changeName = (event) => { setName(event.target.value); }; const changeCity = (event) => { setCity(event.target.value); }; const transferValue = (event) => { event.preventDefault(); const val = { name, city, }; props.func(val); clearState(); }; const clearState = () => { setName(''); setCity(''); }; return ( <div> <label>Name</label> <input type=\"text\" value={name} onChange={changeName} /> <label>City</label> <input type=\"text\" value={city} onChange={changeCity} /> <button onClick={transferValue}> Click Me</button> </div> );} export default StudentForm;", "e": 27894, "s": 27090, "text": null }, { "code": null, "e": 27903, "s": 27894, "text": "form.jsx" }, { "code": "import React, { useState } from 'react';import StudentForm from './form';import jsonData from './data.json'; function TableData() { const [studentData, setStudentData] = useState(jsonData); const tableRows = studentData.map((info) => { return ( <tr> <td>{info.id}</td> <td>{info.name}</td> <td>{info.city}</td> </tr> ); }); const addRows = (data) => { const totalStudents = studentData.length; data.id = totalStudents + 1; const updatedStudentData = [...studentData]; updatedStudentData.push(data); setStudentData(updatedStudentData); }; return ( <div> <table className=\"table table-stripped\"> <thead> <tr> <th>Sr.NO</th> <th>Name</th> <th>City</th> </tr> </thead> <tbody>{tableRows}</tbody> </table> <StudentForm func={addRows} /> </div> );} export default TableData;", "e": 28832, "s": 27903, "text": null }, { "code": null, "e": 28839, "s": 28832, "text": "App.js" }, { "code": "import TableData from './table'; function App() { return ( <div className=\"App\"> <h1>Hello Geeks!!!</h1> <TableData /> </div> );} export default App;", "e": 29009, "s": 28839, "text": null }, { "code": null, "e": 29122, "s": 29009, "text": "Step to Run Application: Run the application using the following command from the root directory of the project." }, { "code": null, "e": 29132, "s": 29122, "text": "npm start" }, { "code": null, "e": 29231, "s": 29132, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 29246, "s": 29231, "text": "Blogathon-2021" }, { "code": null, "e": 29262, "s": 29246, "text": "React-Questions" }, { "code": null, "e": 29272, "s": 29262, "text": "Blogathon" }, { "code": null, "e": 29280, "s": 29272, "text": "ReactJS" }, { "code": null, "e": 29297, "s": 29280, "text": "Web Technologies" }, { "code": null, "e": 29395, "s": 29297, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29452, "s": 29395, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 29493, "s": 29452, "text": "How to Import JSON Data into SQL Server?" }, { "code": null, "e": 29523, "s": 29493, "text": "Stratified Sampling in Pandas" }, { "code": null, "e": 29561, "s": 29523, "text": "SQL Query to Convert Datetime to Date" }, { "code": null, "e": 29596, "s": 29561, "text": "How to Install Tkinter in Windows?" }, { "code": null, "e": 29639, "s": 29596, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29684, "s": 29639, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 29749, "s": 29684, "text": "How to pass data from child component to its parent in ReactJS ?" }, { "code": null, "e": 29817, "s": 29749, "text": "How to pass data from one component to other component in ReactJS ?" } ]
How to re-index an array in PHP? - GeeksforGeeks
22 May, 2019 The re-index of an array can be done by using some inbuilt function together. These functions are: array_combine() Function: The array_combine() function is an inbuilt function in PHP which is used to combine two arrays and create a new array by using one array for keys and another array for values. That is all elements of one array will be the keys of new array and all elements of second array will be the values of this new array. range() Function: The range() function is an inbuilt function in PHP which is used to create an array of elements of any kind such as integer, alphabets within a given range (from low to high) i.e, list’s first element is considered as low and last one is considered as high. count() Function: The count() function is used to count the current elements in the array. The function might return 0 for the variable that has been set to an empty array. Also for the variable which is not set the function returns 0. array_values() Function: This function is used to get an array of values from another array that may contain key-value pairs or just values. The function creates another array where it stores all the values and by default assigns numerical keys to the values. We will use array_values() function to get all the values of the array and range() function to create an array of elements which we want to use as new keys or new index of the array (reindexing). Then the array_combine() function will combine both the array as keys and values. Example 1: <?php // Declare an associative array$arr = array ( 0 => 'Tony', 1 => 'Stark', 2 => 'Iron', 3 => 'Man' ); echo "Array before re-indexing\n"; // Using foreach loop to print array elementsforeach( $arr as $key => $value) { echo "Index: " . $key . " Value: " . $value . "\n"; } // Set the index number from three$New_start_index = 3; $arr = array_combine(range($New_start_index, count($arr) + ($New_start_index-1)), array_values($arr)); echo "\nArray after re-indexing\n"; // Using foreach loop to print array elementsforeach( $arr as $key => $value) { echo "Index: ".$key." Value: ".$value."\n"; } ?> Array before re-indexing Index: 0 Value: Tony Index: 1 Value: Stark Index: 2 Value: Iron Index: 3 Value: Man Array after re-indexing Index: 3 Value: Tony Index: 4 Value: Stark Index: 5 Value: Iron Index: 6 Value: Man Example 2: Add some data at the beginning of the array and then slice the array from the index. <?php // Declare an associative array$arr = array ( 0 => 'Tony', 1 => 'Stark', 2 => 'Iron', 3 => 'Man'); echo "Array before re-indexing\n"; // Using foreach loop to print array elementsforeach( $arr as $key => $value) { echo "Index: " . $key . " Value: " . $value . "\n"; } // Set the index number from three$New_start_index = 3; $raw_data = range( 0, $New_start_index-1 ); // Add data to the start of the arrayforeach( $raw_data as $key => $value) { array_unshift($arr, $value);} $arr = array_values($arr); // Remove the unnecessary index so we start at 10$arr = array_slice($arr, $New_start_index, count($arr), true);echo "\nArray after re indexing\n"; // Using foreach loop to print array foreach( $arr as $key => $value) { echo "Index: ".$key." Value: ".$value."\n"; } ?> Array before re-indexing Index: 0 Value: Tony Index: 1 Value: Stark Index: 2 Value: Iron Index: 3 Value: Man Array after re indexing Index: 3 Value: Tony Index: 4 Value: Stark Index: 5 Value: Iron Index: 6 Value: Man In this example, first add some data to the array and for that again we are doing this with the help of loop and then remove the data which we added so it is also not a good choice to re-index array. This method is not suitable for re-index alphabetical keys. Example 3: This example re-index the array from alphabet ‘p’. Two extra functions are used to re-index the alphabets which are: ord() Function: The ord() function is an inbuilt function in PHP that returns the ASCII value of the first character of a string. chr() Function: The chr() function is an built-in function in PHP which is used to convert a ASCII value to a character. <?php // Declare an associative array$arr = array( 'a' => 'India', 'b' => 'America', 'c' => 'Russia', 'd' => 'China'); echo "Array before re-indexing\n"; // Using foreach loop to print array elementsforeach( $arr as $key => $value) { echo "Index: " . $key . " Value: " . $value . "\n"; } // Set the index from 'p'$New_start_index = 'p'; // The ord() function is used to get ascii value// The chr() function to convert number to ASCII char$arr = array_combine(range($New_start_index, chr(count($arr) + (ord($New_start_index)-1))), array_values($arr)); echo "\nArray after re indexing\n"; // Using foreach loop to print array foreach( $arr as $key => $value) { echo "Index: " . $key . " Value: " . $value . "\n"; } ?> Array before re-indexing Index: a Value: India Index: b Value: America Index: c Value: Russia Index: d Value: China Array after re indexing Index: p Value: India Index: q Value: America Index: r Value: Russia Index: s Value: China Akanksha_Rai Picked PHP PHP Programs Web Technologies Web technologies Questions PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to fetch data from localserver database and display on HTML table using PHP ? PHP str_replace() Function How to create admin login page using PHP? Different ways for passing data to view in Laravel Create a drop-down list that options fetched from a MySQL database in PHP How to call PHP function on the click of a Button ? How to fetch data from localserver database and display on HTML table using PHP ? How to create admin login page using PHP? How to pass form variables from one page to other page in PHP ? PHP | Ternary Operator
[ { "code": null, "e": 26327, "s": 26299, "text": "\n22 May, 2019" }, { "code": null, "e": 26426, "s": 26327, "text": "The re-index of an array can be done by using some inbuilt function together. These functions are:" }, { "code": null, "e": 26763, "s": 26426, "text": "array_combine() Function: The array_combine() function is an inbuilt function in PHP which is used to combine two arrays and create a new array by using one array for keys and another array for values. That is all elements of one array will be the keys of new array and all elements of second array will be the values of this new array." }, { "code": null, "e": 27039, "s": 26763, "text": "range() Function: The range() function is an inbuilt function in PHP which is used to create an array of elements of any kind such as integer, alphabets within a given range (from low to high) i.e, list’s first element is considered as low and last one is considered as high." }, { "code": null, "e": 27275, "s": 27039, "text": "count() Function: The count() function is used to count the current elements in the array. The function might return 0 for the variable that has been set to an empty array. Also for the variable which is not set the function returns 0." }, { "code": null, "e": 27535, "s": 27275, "text": "array_values() Function: This function is used to get an array of values from another array that may contain key-value pairs or just values. The function creates another array where it stores all the values and by default assigns numerical keys to the values." }, { "code": null, "e": 27813, "s": 27535, "text": "We will use array_values() function to get all the values of the array and range() function to create an array of elements which we want to use as new keys or new index of the array (reindexing). Then the array_combine() function will combine both the array as keys and values." }, { "code": null, "e": 27824, "s": 27813, "text": "Example 1:" }, { "code": "<?php // Declare an associative array$arr = array ( 0 => 'Tony', 1 => 'Stark', 2 => 'Iron', 3 => 'Man' ); echo \"Array before re-indexing\\n\"; // Using foreach loop to print array elementsforeach( $arr as $key => $value) { echo \"Index: \" . $key . \" Value: \" . $value . \"\\n\"; } // Set the index number from three$New_start_index = 3; $arr = array_combine(range($New_start_index, count($arr) + ($New_start_index-1)), array_values($arr)); echo \"\\nArray after re-indexing\\n\"; // Using foreach loop to print array elementsforeach( $arr as $key => $value) { echo \"Index: \".$key.\" Value: \".$value.\"\\n\"; } ?>", "e": 28483, "s": 27824, "text": null }, { "code": null, "e": 28702, "s": 28483, "text": "Array before re-indexing\nIndex: 0 Value: Tony\nIndex: 1 Value: Stark\nIndex: 2 Value: Iron\nIndex: 3 Value: Man\n\nArray after re-indexing\nIndex: 3 Value: Tony\nIndex: 4 Value: Stark\nIndex: 5 Value: Iron\nIndex: 6 Value: Man\n" }, { "code": null, "e": 28798, "s": 28702, "text": "Example 2: Add some data at the beginning of the array and then slice the array from the index." }, { "code": "<?php // Declare an associative array$arr = array ( 0 => 'Tony', 1 => 'Stark', 2 => 'Iron', 3 => 'Man'); echo \"Array before re-indexing\\n\"; // Using foreach loop to print array elementsforeach( $arr as $key => $value) { echo \"Index: \" . $key . \" Value: \" . $value . \"\\n\"; } // Set the index number from three$New_start_index = 3; $raw_data = range( 0, $New_start_index-1 ); // Add data to the start of the arrayforeach( $raw_data as $key => $value) { array_unshift($arr, $value);} $arr = array_values($arr); // Remove the unnecessary index so we start at 10$arr = array_slice($arr, $New_start_index, count($arr), true);echo \"\\nArray after re indexing\\n\"; // Using foreach loop to print array foreach( $arr as $key => $value) { echo \"Index: \".$key.\" Value: \".$value.\"\\n\"; } ?>", "e": 29610, "s": 28798, "text": null }, { "code": null, "e": 29829, "s": 29610, "text": "Array before re-indexing\nIndex: 0 Value: Tony\nIndex: 1 Value: Stark\nIndex: 2 Value: Iron\nIndex: 3 Value: Man\n\nArray after re indexing\nIndex: 3 Value: Tony\nIndex: 4 Value: Stark\nIndex: 5 Value: Iron\nIndex: 6 Value: Man\n" }, { "code": null, "e": 30089, "s": 29829, "text": "In this example, first add some data to the array and for that again we are doing this with the help of loop and then remove the data which we added so it is also not a good choice to re-index array. This method is not suitable for re-index alphabetical keys." }, { "code": null, "e": 30217, "s": 30089, "text": "Example 3: This example re-index the array from alphabet ‘p’. Two extra functions are used to re-index the alphabets which are:" }, { "code": null, "e": 30347, "s": 30217, "text": "ord() Function: The ord() function is an inbuilt function in PHP that returns the ASCII value of the first character of a string." }, { "code": null, "e": 30468, "s": 30347, "text": "chr() Function: The chr() function is an built-in function in PHP which is used to convert a ASCII value to a character." }, { "code": "<?php // Declare an associative array$arr = array( 'a' => 'India', 'b' => 'America', 'c' => 'Russia', 'd' => 'China'); echo \"Array before re-indexing\\n\"; // Using foreach loop to print array elementsforeach( $arr as $key => $value) { echo \"Index: \" . $key . \" Value: \" . $value . \"\\n\"; } // Set the index from 'p'$New_start_index = 'p'; // The ord() function is used to get ascii value// The chr() function to convert number to ASCII char$arr = array_combine(range($New_start_index, chr(count($arr) + (ord($New_start_index)-1))), array_values($arr)); echo \"\\nArray after re indexing\\n\"; // Using foreach loop to print array foreach( $arr as $key => $value) { echo \"Index: \" . $key . \" Value: \" . $value . \"\\n\"; } ?>", "e": 31237, "s": 30468, "text": null }, { "code": null, "e": 31470, "s": 31237, "text": "Array before re-indexing\nIndex: a Value: India\nIndex: b Value: America\nIndex: c Value: Russia\nIndex: d Value: China\n\nArray after re indexing\nIndex: p Value: India\nIndex: q Value: America\nIndex: r Value: Russia\nIndex: s Value: China\n" }, { "code": null, "e": 31483, "s": 31470, "text": "Akanksha_Rai" }, { "code": null, "e": 31490, "s": 31483, "text": "Picked" }, { "code": null, "e": 31494, "s": 31490, "text": "PHP" }, { "code": null, "e": 31507, "s": 31494, "text": "PHP Programs" }, { "code": null, "e": 31524, "s": 31507, "text": "Web Technologies" }, { "code": null, "e": 31551, "s": 31524, "text": "Web technologies Questions" }, { "code": null, "e": 31555, "s": 31551, "text": "PHP" }, { "code": null, "e": 31653, "s": 31555, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31735, "s": 31653, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 31762, "s": 31735, "text": "PHP str_replace() Function" }, { "code": null, "e": 31804, "s": 31762, "text": "How to create admin login page using PHP?" }, { "code": null, "e": 31855, "s": 31804, "text": "Different ways for passing data to view in Laravel" }, { "code": null, "e": 31929, "s": 31855, "text": "Create a drop-down list that options fetched from a MySQL database in PHP" }, { "code": null, "e": 31981, "s": 31929, "text": "How to call PHP function on the click of a Button ?" }, { "code": null, "e": 32063, "s": 31981, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 32105, "s": 32063, "text": "How to create admin login page using PHP?" }, { "code": null, "e": 32169, "s": 32105, "text": "How to pass form variables from one page to other page in PHP ?" } ]
Python 3 - Number fabs() Method
The fabs() method returns the absolute value of x. Although similar to the abs() function, there are differences between the two functions. They are − abs() is a built in function whereas fabs() is defined in math module. abs() is a built in function whereas fabs() is defined in math module. fabs() function works only on float and integer whereas abs() works with complex number also. fabs() function works only on float and integer whereas abs() works with complex number also. Following is the syntax for the fabs() method − import math math.fabs( x ) Note − This function is not accessible directly, so we need to import the math module and then we need to call this function using the math static object. x − This is a numeric value. This method returns the absolute value of x. The following example shows the usage of the fabs() method. #!/usr/bin/python3 import math # This will import math module print ("math.fabs(-45.17) : ", math.fabs(-45.17)) print ("math.fabs(100.12) : ", math.fabs(100.12)) print ("math.fabs(100.72) : ", math.fabs(100.72)) print ("math.fabs(math.pi) : ", math.fabs(math.pi)) When we run the above program, it produces the following result − math.fabs(-45.17) : 45.17 math.fabs(100) : 100.0 math.fabs(100.72) : 100.72 math.fabs(math.pi) : 3.141592653589793 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2491, "s": 2340, "text": "The fabs() method returns the absolute value of x. Although similar to the abs() function, there are differences between the two functions. They are −" }, { "code": null, "e": 2562, "s": 2491, "text": "abs() is a built in function whereas fabs() is defined in math module." }, { "code": null, "e": 2633, "s": 2562, "text": "abs() is a built in function whereas fabs() is defined in math module." }, { "code": null, "e": 2727, "s": 2633, "text": "fabs() function works only on float and integer whereas abs() works with complex number also." }, { "code": null, "e": 2821, "s": 2727, "text": "fabs() function works only on float and integer whereas abs() works with complex number also." }, { "code": null, "e": 2869, "s": 2821, "text": "Following is the syntax for the fabs() method −" }, { "code": null, "e": 2898, "s": 2869, "text": "import math\n\nmath.fabs( x )\n" }, { "code": null, "e": 3053, "s": 2898, "text": "Note − This function is not accessible directly, so we need to import the math module and then we need to call this function using the math static object." }, { "code": null, "e": 3082, "s": 3053, "text": "x − This is a numeric value." }, { "code": null, "e": 3127, "s": 3082, "text": "This method returns the absolute value of x." }, { "code": null, "e": 3187, "s": 3127, "text": "The following example shows the usage of the fabs() method." }, { "code": null, "e": 3454, "s": 3187, "text": "#!/usr/bin/python3\nimport math # This will import math module\n\nprint (\"math.fabs(-45.17) : \", math.fabs(-45.17))\nprint (\"math.fabs(100.12) : \", math.fabs(100.12))\nprint (\"math.fabs(100.72) : \", math.fabs(100.72))\nprint (\"math.fabs(math.pi) : \", math.fabs(math.pi))" }, { "code": null, "e": 3520, "s": 3454, "text": "When we run the above program, it produces the following result −" }, { "code": null, "e": 3640, "s": 3520, "text": "math.fabs(-45.17) : 45.17\nmath.fabs(100) : 100.0\nmath.fabs(100.72) : 100.72\nmath.fabs(math.pi) : 3.141592653589793\n" }, { "code": null, "e": 3677, "s": 3640, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3693, "s": 3677, "text": " Malhar Lathkar" }, { "code": null, "e": 3726, "s": 3693, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3745, "s": 3726, "text": " Arnab Chakraborty" }, { "code": null, "e": 3780, "s": 3745, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3802, "s": 3780, "text": " In28Minutes Official" }, { "code": null, "e": 3836, "s": 3802, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3864, "s": 3836, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3899, "s": 3864, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3913, "s": 3899, "text": " Lets Kode It" }, { "code": null, "e": 3946, "s": 3913, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3963, "s": 3946, "text": " Abhilash Nelson" }, { "code": null, "e": 3970, "s": 3963, "text": " Print" }, { "code": null, "e": 3981, "s": 3970, "text": " Add Notes" } ]
Add new column with default value in PySpark dataframe - GeeksforGeeks
29 Jun, 2021 In this article, we are going to see how to add a new column with a default value in PySpark Dataframe. The three ways to add a column to PandPySpark as DataFrame with Default Value. Using pyspark.sql.DataFrame.withColumn(colName, col) Using pyspark.sql.DataFrame.select(*cols) Using pyspark.sql.SparkSession.sql(sqlQuery) It Adds a column or replaces the existing column that has the same name to a DataFrame and returns a new DataFrame with all existing columns to new ones. The column expression must be an expression over this DataFrame and adding a column from some other DataFrame will raise an error. Syntax: pyspark.sql.DataFrame.withColumn(colName, col) Parameters: This method accepts the following parameter as mentioned above and described below. colName: It is a string and contains name of the new column. col: It is a Column expression for the new column. Returns: DataFrame First, create a simple DataFrame. Python3 import findsparkfindspark.init() # Importing the modulesfrom datetime import datetime, dateimport pandas as pdfrom pyspark.sql import SparkSession # creating the sessionspark = SparkSession.builder.getOrCreate() # creating the dataframepandas_df = pd.DataFrame({ 'Name': ['Anurag', 'Manjeet', 'Shubham', 'Saurabh', 'Ujjawal'], 'Address': ['Patna', 'Delhi', 'Coimbatore', 'Greater noida', 'Patna'], 'ID': [20123, 20124, 20145, 20146, 20147], 'Sell': [140000, 300000, 600000, 200000, 600000]})df = spark.createDataFrame(pandas_df)print("Original DataFrame :")df.show() Output: Add a new column with Default Value: Python3 # Add new column with NUllfrom pyspark.sql.functions import litdf = df.withColumn("Rewards", lit(None))df.show() # Add new constanst columndf = df.withColumn("Bonus Percent", lit(0.25))df.show() Output: We can use pyspark.sql.DataFrame.select() create a new column in DataFrame and set it to default values. It projects a set of expressions and returns a new DataFrame. Syntax: pyspark.sql.DataFrame.select(*cols) Parameters: This method accepts the following parameter as mentioned above and described below. cols: It contains column names (string) or expressions (Column) Returns: DataFrame First, create a simple DataFrame. Python3 import findsparkfindspark.init() # Importing the modulesfrom datetime import datetime, dateimport pandas as pdfrom pyspark.sql import SparkSession # creating the sessionspark = SparkSession.builder.getOrCreate() # creating the dataframepandas_df = pd.DataFrame({ 'Name': ['Anurag', 'Manjeet', 'Shubham', 'Saurabh', 'Ujjawal'], 'Address': ['Patna', 'Delhi', 'Coimbatore', 'Greater noida', 'Patna'], 'ID': [20123, 20124, 20145, 20146, 20147], 'Sell': [140000, 300000, 600000, 200000, 600000]})df = spark.createDataFrame(pandas_df)print("Original DataFrame :")df.show() Output: Add a new column with Default Value: Python3 # Add new column with NUllfrom pyspark.sql.functions import litdf = df.select('*', lit(None).alias("Rewards")) # Add new constanst columndf = df.select('*', lit(0.25).alias("Bonus Percent"))df.show() Output: We can use pyspark.sql.SparkSession.sql() create a new column in DataFrame and set it to default values. It returns a DataFrame representing the result of the given query. Syntax: pyspark.sql.SparkSession.sql(sqlQuery) Parameters: This method accepts the following parameter as mentioned above and described below. sqlQuery: It is a string and contains the sql executable query. Returns: DataFrame First, create a simple DataFrame: Python3 import findsparkfindspark.init() # Importing the modulesfrom datetime import datetime, dateimport pandas as pdfrom pyspark.sql import SparkSession # creating the sessionspark = SparkSession.builder.getOrCreate() # creating the dataframepandas_df = pd.DataFrame({ 'Name': ['Anurag', 'Manjeet', 'Shubham', 'Saurabh', 'Ujjawal'], 'Address': ['Patna', 'Delhi', 'Coimbatore', 'Greater noida', 'Patna'], 'ID': [20123, 20124, 20145, 20146, 20147], 'Sell': [140000, 300000, 600000, 200000, 600000]})df = spark.createDataFrame(pandas_df)print("Original DataFrame :")df.show() Output: Add a new column with Default Value: Python3 # Add columns to DataFrame using SQLdf.createOrReplaceTempView("GFG_Table") # Add new column with NUlldf=spark.sql("select *, null as Rewards from GFG_Table") # Add new constanst columndf.createOrReplaceTempView("GFG_Table")df=spark.sql("select *, '0.25' as Bonus_Percent from GFG_Table")df.show() Output: Picked Python-Pyspark Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python Classes and Objects Create a directory in Python Python | os.path.join() method Python | Pandas dataframe.groupby() Python | Get unique values from a list
[ { "code": null, "e": 24390, "s": 24362, "text": "\n29 Jun, 2021" }, { "code": null, "e": 24494, "s": 24390, "text": "In this article, we are going to see how to add a new column with a default value in PySpark Dataframe." }, { "code": null, "e": 24573, "s": 24494, "text": "The three ways to add a column to PandPySpark as DataFrame with Default Value." }, { "code": null, "e": 24626, "s": 24573, "text": "Using pyspark.sql.DataFrame.withColumn(colName, col)" }, { "code": null, "e": 24668, "s": 24626, "text": "Using pyspark.sql.DataFrame.select(*cols)" }, { "code": null, "e": 24713, "s": 24668, "text": "Using pyspark.sql.SparkSession.sql(sqlQuery)" }, { "code": null, "e": 24998, "s": 24713, "text": "It Adds a column or replaces the existing column that has the same name to a DataFrame and returns a new DataFrame with all existing columns to new ones. The column expression must be an expression over this DataFrame and adding a column from some other DataFrame will raise an error." }, { "code": null, "e": 25053, "s": 24998, "text": "Syntax: pyspark.sql.DataFrame.withColumn(colName, col)" }, { "code": null, "e": 25149, "s": 25053, "text": "Parameters: This method accepts the following parameter as mentioned above and described below." }, { "code": null, "e": 25210, "s": 25149, "text": "colName: It is a string and contains name of the new column." }, { "code": null, "e": 25261, "s": 25210, "text": "col: It is a Column expression for the new column." }, { "code": null, "e": 25280, "s": 25261, "text": "Returns: DataFrame" }, { "code": null, "e": 25314, "s": 25280, "text": "First, create a simple DataFrame." }, { "code": null, "e": 25322, "s": 25314, "text": "Python3" }, { "code": "import findsparkfindspark.init() # Importing the modulesfrom datetime import datetime, dateimport pandas as pdfrom pyspark.sql import SparkSession # creating the sessionspark = SparkSession.builder.getOrCreate() # creating the dataframepandas_df = pd.DataFrame({ 'Name': ['Anurag', 'Manjeet', 'Shubham', 'Saurabh', 'Ujjawal'], 'Address': ['Patna', 'Delhi', 'Coimbatore', 'Greater noida', 'Patna'], 'ID': [20123, 20124, 20145, 20146, 20147], 'Sell': [140000, 300000, 600000, 200000, 600000]})df = spark.createDataFrame(pandas_df)print(\"Original DataFrame :\")df.show()", "e": 25931, "s": 25322, "text": null }, { "code": null, "e": 25939, "s": 25931, "text": "Output:" }, { "code": null, "e": 25976, "s": 25939, "text": "Add a new column with Default Value:" }, { "code": null, "e": 25984, "s": 25976, "text": "Python3" }, { "code": "# Add new column with NUllfrom pyspark.sql.functions import litdf = df.withColumn(\"Rewards\", lit(None))df.show() # Add new constanst columndf = df.withColumn(\"Bonus Percent\", lit(0.25))df.show()", "e": 26180, "s": 25984, "text": null }, { "code": null, "e": 26188, "s": 26180, "text": "Output:" }, { "code": null, "e": 26355, "s": 26188, "text": "We can use pyspark.sql.DataFrame.select() create a new column in DataFrame and set it to default values. It projects a set of expressions and returns a new DataFrame." }, { "code": null, "e": 26399, "s": 26355, "text": "Syntax: pyspark.sql.DataFrame.select(*cols)" }, { "code": null, "e": 26495, "s": 26399, "text": "Parameters: This method accepts the following parameter as mentioned above and described below." }, { "code": null, "e": 26559, "s": 26495, "text": "cols: It contains column names (string) or expressions (Column)" }, { "code": null, "e": 26578, "s": 26559, "text": "Returns: DataFrame" }, { "code": null, "e": 26612, "s": 26578, "text": "First, create a simple DataFrame." }, { "code": null, "e": 26620, "s": 26612, "text": "Python3" }, { "code": "import findsparkfindspark.init() # Importing the modulesfrom datetime import datetime, dateimport pandas as pdfrom pyspark.sql import SparkSession # creating the sessionspark = SparkSession.builder.getOrCreate() # creating the dataframepandas_df = pd.DataFrame({ 'Name': ['Anurag', 'Manjeet', 'Shubham', 'Saurabh', 'Ujjawal'], 'Address': ['Patna', 'Delhi', 'Coimbatore', 'Greater noida', 'Patna'], 'ID': [20123, 20124, 20145, 20146, 20147], 'Sell': [140000, 300000, 600000, 200000, 600000]})df = spark.createDataFrame(pandas_df)print(\"Original DataFrame :\")df.show()", "e": 27229, "s": 26620, "text": null }, { "code": null, "e": 27237, "s": 27229, "text": "Output:" }, { "code": null, "e": 27274, "s": 27237, "text": "Add a new column with Default Value:" }, { "code": null, "e": 27282, "s": 27274, "text": "Python3" }, { "code": "# Add new column with NUllfrom pyspark.sql.functions import litdf = df.select('*', lit(None).alias(\"Rewards\")) # Add new constanst columndf = df.select('*', lit(0.25).alias(\"Bonus Percent\"))df.show()", "e": 27483, "s": 27282, "text": null }, { "code": null, "e": 27491, "s": 27483, "text": "Output:" }, { "code": null, "e": 27663, "s": 27491, "text": "We can use pyspark.sql.SparkSession.sql() create a new column in DataFrame and set it to default values. It returns a DataFrame representing the result of the given query." }, { "code": null, "e": 27710, "s": 27663, "text": "Syntax: pyspark.sql.SparkSession.sql(sqlQuery)" }, { "code": null, "e": 27806, "s": 27710, "text": "Parameters: This method accepts the following parameter as mentioned above and described below." }, { "code": null, "e": 27870, "s": 27806, "text": "sqlQuery: It is a string and contains the sql executable query." }, { "code": null, "e": 27889, "s": 27870, "text": "Returns: DataFrame" }, { "code": null, "e": 27923, "s": 27889, "text": "First, create a simple DataFrame:" }, { "code": null, "e": 27931, "s": 27923, "text": "Python3" }, { "code": "import findsparkfindspark.init() # Importing the modulesfrom datetime import datetime, dateimport pandas as pdfrom pyspark.sql import SparkSession # creating the sessionspark = SparkSession.builder.getOrCreate() # creating the dataframepandas_df = pd.DataFrame({ 'Name': ['Anurag', 'Manjeet', 'Shubham', 'Saurabh', 'Ujjawal'], 'Address': ['Patna', 'Delhi', 'Coimbatore', 'Greater noida', 'Patna'], 'ID': [20123, 20124, 20145, 20146, 20147], 'Sell': [140000, 300000, 600000, 200000, 600000]})df = spark.createDataFrame(pandas_df)print(\"Original DataFrame :\")df.show()", "e": 28540, "s": 27931, "text": null }, { "code": null, "e": 28548, "s": 28540, "text": "Output:" }, { "code": null, "e": 28585, "s": 28548, "text": "Add a new column with Default Value:" }, { "code": null, "e": 28593, "s": 28585, "text": "Python3" }, { "code": "# Add columns to DataFrame using SQLdf.createOrReplaceTempView(\"GFG_Table\") # Add new column with NUlldf=spark.sql(\"select *, null as Rewards from GFG_Table\") # Add new constanst columndf.createOrReplaceTempView(\"GFG_Table\")df=spark.sql(\"select *, '0.25' as Bonus_Percent from GFG_Table\")df.show()", "e": 28893, "s": 28593, "text": null }, { "code": null, "e": 28901, "s": 28893, "text": "Output:" }, { "code": null, "e": 28908, "s": 28901, "text": "Picked" }, { "code": null, "e": 28923, "s": 28908, "text": "Python-Pyspark" }, { "code": null, "e": 28930, "s": 28923, "text": "Python" }, { "code": null, "e": 29028, "s": 28930, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29060, "s": 29028, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29102, "s": 29060, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29144, "s": 29102, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29200, "s": 29144, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29222, "s": 29200, "text": "Defaultdict in Python" }, { "code": null, "e": 29249, "s": 29222, "text": "Python Classes and Objects" }, { "code": null, "e": 29278, "s": 29249, "text": "Create a directory in Python" }, { "code": null, "e": 29309, "s": 29278, "text": "Python | os.path.join() method" }, { "code": null, "e": 29345, "s": 29309, "text": "Python | Pandas dataframe.groupby()" } ]