title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
A Hands-On Application of Homography: IPM | by Daryl Tan | Towards Data Science
|
In computer vision, homography is a transformation matrix H when applied on a projective plane maps it to another plane (or image). In the case of Inverse Perspective Mapping (IPM), we want to produce a birds-eye view image of the scene from the front-facing image plane.
In the field of autonomous driving, IPM aids in several downstream tasks such as lane marking detection, path planning and intersection prediction solely from using a monocular camera as this orthographic view is scale-invariant. Emphasising the importance of this technique.
IPM first assume the world to be flat on a plane. Then it maps all pixels from a given viewpoint onto this flat plane through homography projection.
In practice, IPM works well in the immediate vicinity of the camera. For faraway features in the scene, blurring and stretching of the scene become more prominent during perspective projection as a smaller number of pixel is represented, limiting the application of IPM. This can be observed in figure 1, where severe undesirable distortion is produced farther away. To be exact, the lookahead distance is approximately 50m in the figure.
In addition, the following constraints must hold:
The camera is in a fixed position: Since the position of the road is sensitive to the camera, a slight perturbation in position or orientation will change how the 3D scene is projected onto an image plane.The surface is planar: Any object with height or elevation will violate this condition. Non-planar surfaces will create artefacts/distortion in the BEV image.Free of objects with height. All points above the ground will induce artefacts as a consequence of perspective projection between 2 planes lying arbitrarily in the 3D scene.
The camera is in a fixed position: Since the position of the road is sensitive to the camera, a slight perturbation in position or orientation will change how the 3D scene is projected onto an image plane.
The surface is planar: Any object with height or elevation will violate this condition. Non-planar surfaces will create artefacts/distortion in the BEV image.
Free of objects with height. All points above the ground will induce artefacts as a consequence of perspective projection between 2 planes lying arbitrarily in the 3D scene.
In this article, I will attempt to explain the idea of IPM. More importantly, this post is dedicated to how we can work out and apply the homography using only Python and Numpy.
Next, I will show that somewhat similar results can be obtained using OpenCV. We will be using a relatively common road scene from Cityscape dataset as an example. Feel free to message me regarding any questions/doubts or even mistakes you might have spotted.
The code for this article is available here. And all inline text refers to some variable or function in the code.
The problem that we are trying to solve is to transform a frontal view image into a birds-eye view image. IPM does this by removing the perspective effect from the front-facing camera and remap its image onto a top-view 2D domain. The image in BEV is one that attempts to preserve distance and parallel lines, correcting perspective effect.
The following bullet points summarise the procedure for homography based IPM:
Model the road (X, Y, Z=0) as a flat 2D plane. Some approximation must be made with regard to resolution as the road are discretized onto the BEV image.
Determine and construct the projection matrix P from known extrinsic and intrinsic parameters. Usually, this is obtained through calibration.
Transform and warped the road by applying P. Also known as a perspective projection.
Remap the frontal pixel to the new image plane.
I will go into more details in the following sections.
Before we get started, it is important to know where the camera is relative to the road. For the road scene in Cityscape, the camera is mounted on top of the vehicle pitching slightly downwards. The exact position and orientation is written in the file camera.json . Note that the values are relative to the ego-vehicle.
To understand IPM, some background knowledge about perspective projection and camera projective geometry is required. I will briefly describe what you need to know about those topics in this section.
Perspective projection precisely describes how the world around us gets mapped on a 2D plane. During this mapping, 2 parallel lines in the world (euclidean space) are transformed into a pair of line in the new plane which converges at the point of infinity. Referring to figure 3, the parallel properties of the 2 cubes placed in the world are not preserved from where we are observing right now. An example of this would be the lane lines.
In the case of our example as shown in figure 4, when the road is observed from a different viewpoint, notice that the same region looks different. Parallel lies are no longer preserved in a projective transformation P.
The camera model describes the perspective projection from the 3D scene to a 2D image. The image formed depends on the intrinsic and extrinsic properties.
The extrinsic [R|t] describes the relative position and orientation of the world relative to the camera. It brings the scene in world coordinate into the camera coordinate system.
The intrinsic, K defines how the 3D scene will be warped onto the image with respect to change in the focal length and camera center. Note: This is a simple pinhole camera model. Other factors such as pixel skew and lens distortion are not reflected in the equation.
In our problem. the origin is set to the top left-hand corner of the image plane 2. The idea is to project the entire scene (X, Y, Z) lying on image plane 2 onto the camera image plane 1.
As mention, we assumed that the road is flat on the ground. Therefore, Z = 0 for every points lying on the road. Which effectively transform the problem into planar homography. This is one method that can be done in OpenCV to perform the image warping.
ipm_from_parameters
The approach I have taken to tackle the problem is as follows:
Slice out a region of the road that we wish to view in BEV plane. For this region, define the pixel resolution, absolute distance per pixel (scale) and pose (position and orientation).Apply the perspective projection perspective for all 3D points (X, Y, Z=0) in the region using camera projection model to pixel coordinate.Resample from the front view image the corresponding pixels and map it back to image plane 2. Some form of interpolation is needed to prevent holes and aliasing effect. I use bilinear interpolation bilinear_sampler .
Slice out a region of the road that we wish to view in BEV plane. For this region, define the pixel resolution, absolute distance per pixel (scale) and pose (position and orientation).
Apply the perspective projection perspective for all 3D points (X, Y, Z=0) in the region using camera projection model to pixel coordinate.
Resample from the front view image the corresponding pixels and map it back to image plane 2. Some form of interpolation is needed to prevent holes and aliasing effect. I use bilinear interpolation bilinear_sampler .
Lets now go through each point mention above.
As the vehicle moves, we want the viewing region to be consistent relative to it. Hence the plane is defined with respect to the vehicle.
The origin of the plane is located at the top left corner. The viewable region is illuminated and depends on the field of view of the camera. That is why unobservable pixel (black) is on the image after IPM. I have defined the plane with the following properties (figure 7)
Size of the region in pixels: 500 X 500
Resolution: 0.1m per pixel.
The camera is located and aligned with the midpoint of the plane’s y-axis.
The camera parameters are given in camera.json and given with respect to the ego-vehicle. Since the projection model requires us to define the scene with respect to the camera, some manipulation is required to reverse the transformation.
# Notablynp.linag.inv(T) = - Tnp.linag.inv(R) = np.transpose(R) # property of orthogonal matrix
The extrinsic and intrinsic parameters are constructed in this function load_camera_params.
The projective transformation is then applied after transforming the points into homogenous representation. The pixels are scale normalize. i.e. effective focal length = 1. This is done in perspective .
As we move further away from the camera, sparsity becomes more observable as a consequence of perspective. Therefore, I use bilinear interpolation as an approximation.
This is done by taking the weighted (by distance) sum of the 4 corners
(px, py) = w0 * im0 + w1 * im1 + w2 * im2 + w3 * im3
ipm_from_opencv
Now that we understand how to perform the perspective warping. Let’s see how all the above steps can be easily performed in OpenCV. This is done by formulating the problem as a plane to plane transformation.
OpenCV does this by solving for the homography matrix H internally using point correspondence. H now is equivalent to the camera matrix that I have discussed above. A minimum of 4 points is required to estimate H via least-squares method.
There are only 2 steps to perform the transformation
Pick at least 4 salient features in the image and define its new location in the target image. Pass these correspondences into cv2.getPerspectiveTransform to obtain projection matrix.
Apply the projection matrix to the image using cv2.warpPerspective. This will warp it to a bird's eye view and at the same time, applying the desire interpolation method that you have chosen.
The most convenient features to choose are the lane lines. Since we know for sure they are going to be parallel in the target image (BEV).
To show that it produces approximately the same result as the derived method discuss previously, I picked out the points denoting the green polygon vertices as shown in figure 4.
And there we have it. I hope you will find this post useful if you are working on computer vision.
|
[
{
"code": null,
"e": 444,
"s": 172,
"text": "In computer vision, homography is a transformation matrix H when applied on a projective plane maps it to another plane (or image). In the case of Inverse Perspective Mapping (IPM), we want to produce a birds-eye view image of the scene from the front-facing image plane."
},
{
"code": null,
"e": 720,
"s": 444,
"text": "In the field of autonomous driving, IPM aids in several downstream tasks such as lane marking detection, path planning and intersection prediction solely from using a monocular camera as this orthographic view is scale-invariant. Emphasising the importance of this technique."
},
{
"code": null,
"e": 869,
"s": 720,
"text": "IPM first assume the world to be flat on a plane. Then it maps all pixels from a given viewpoint onto this flat plane through homography projection."
},
{
"code": null,
"e": 1308,
"s": 869,
"text": "In practice, IPM works well in the immediate vicinity of the camera. For faraway features in the scene, blurring and stretching of the scene become more prominent during perspective projection as a smaller number of pixel is represented, limiting the application of IPM. This can be observed in figure 1, where severe undesirable distortion is produced farther away. To be exact, the lookahead distance is approximately 50m in the figure."
},
{
"code": null,
"e": 1358,
"s": 1308,
"text": "In addition, the following constraints must hold:"
},
{
"code": null,
"e": 1895,
"s": 1358,
"text": "The camera is in a fixed position: Since the position of the road is sensitive to the camera, a slight perturbation in position or orientation will change how the 3D scene is projected onto an image plane.The surface is planar: Any object with height or elevation will violate this condition. Non-planar surfaces will create artefacts/distortion in the BEV image.Free of objects with height. All points above the ground will induce artefacts as a consequence of perspective projection between 2 planes lying arbitrarily in the 3D scene."
},
{
"code": null,
"e": 2101,
"s": 1895,
"text": "The camera is in a fixed position: Since the position of the road is sensitive to the camera, a slight perturbation in position or orientation will change how the 3D scene is projected onto an image plane."
},
{
"code": null,
"e": 2260,
"s": 2101,
"text": "The surface is planar: Any object with height or elevation will violate this condition. Non-planar surfaces will create artefacts/distortion in the BEV image."
},
{
"code": null,
"e": 2434,
"s": 2260,
"text": "Free of objects with height. All points above the ground will induce artefacts as a consequence of perspective projection between 2 planes lying arbitrarily in the 3D scene."
},
{
"code": null,
"e": 2612,
"s": 2434,
"text": "In this article, I will attempt to explain the idea of IPM. More importantly, this post is dedicated to how we can work out and apply the homography using only Python and Numpy."
},
{
"code": null,
"e": 2872,
"s": 2612,
"text": "Next, I will show that somewhat similar results can be obtained using OpenCV. We will be using a relatively common road scene from Cityscape dataset as an example. Feel free to message me regarding any questions/doubts or even mistakes you might have spotted."
},
{
"code": null,
"e": 2986,
"s": 2872,
"text": "The code for this article is available here. And all inline text refers to some variable or function in the code."
},
{
"code": null,
"e": 3327,
"s": 2986,
"text": "The problem that we are trying to solve is to transform a frontal view image into a birds-eye view image. IPM does this by removing the perspective effect from the front-facing camera and remap its image onto a top-view 2D domain. The image in BEV is one that attempts to preserve distance and parallel lines, correcting perspective effect."
},
{
"code": null,
"e": 3405,
"s": 3327,
"text": "The following bullet points summarise the procedure for homography based IPM:"
},
{
"code": null,
"e": 3558,
"s": 3405,
"text": "Model the road (X, Y, Z=0) as a flat 2D plane. Some approximation must be made with regard to resolution as the road are discretized onto the BEV image."
},
{
"code": null,
"e": 3700,
"s": 3558,
"text": "Determine and construct the projection matrix P from known extrinsic and intrinsic parameters. Usually, this is obtained through calibration."
},
{
"code": null,
"e": 3785,
"s": 3700,
"text": "Transform and warped the road by applying P. Also known as a perspective projection."
},
{
"code": null,
"e": 3833,
"s": 3785,
"text": "Remap the frontal pixel to the new image plane."
},
{
"code": null,
"e": 3888,
"s": 3833,
"text": "I will go into more details in the following sections."
},
{
"code": null,
"e": 4209,
"s": 3888,
"text": "Before we get started, it is important to know where the camera is relative to the road. For the road scene in Cityscape, the camera is mounted on top of the vehicle pitching slightly downwards. The exact position and orientation is written in the file camera.json . Note that the values are relative to the ego-vehicle."
},
{
"code": null,
"e": 4409,
"s": 4209,
"text": "To understand IPM, some background knowledge about perspective projection and camera projective geometry is required. I will briefly describe what you need to know about those topics in this section."
},
{
"code": null,
"e": 4850,
"s": 4409,
"text": "Perspective projection precisely describes how the world around us gets mapped on a 2D plane. During this mapping, 2 parallel lines in the world (euclidean space) are transformed into a pair of line in the new plane which converges at the point of infinity. Referring to figure 3, the parallel properties of the 2 cubes placed in the world are not preserved from where we are observing right now. An example of this would be the lane lines."
},
{
"code": null,
"e": 5070,
"s": 4850,
"text": "In the case of our example as shown in figure 4, when the road is observed from a different viewpoint, notice that the same region looks different. Parallel lies are no longer preserved in a projective transformation P."
},
{
"code": null,
"e": 5225,
"s": 5070,
"text": "The camera model describes the perspective projection from the 3D scene to a 2D image. The image formed depends on the intrinsic and extrinsic properties."
},
{
"code": null,
"e": 5405,
"s": 5225,
"text": "The extrinsic [R|t] describes the relative position and orientation of the world relative to the camera. It brings the scene in world coordinate into the camera coordinate system."
},
{
"code": null,
"e": 5672,
"s": 5405,
"text": "The intrinsic, K defines how the 3D scene will be warped onto the image with respect to change in the focal length and camera center. Note: This is a simple pinhole camera model. Other factors such as pixel skew and lens distortion are not reflected in the equation."
},
{
"code": null,
"e": 5860,
"s": 5672,
"text": "In our problem. the origin is set to the top left-hand corner of the image plane 2. The idea is to project the entire scene (X, Y, Z) lying on image plane 2 onto the camera image plane 1."
},
{
"code": null,
"e": 6113,
"s": 5860,
"text": "As mention, we assumed that the road is flat on the ground. Therefore, Z = 0 for every points lying on the road. Which effectively transform the problem into planar homography. This is one method that can be done in OpenCV to perform the image warping."
},
{
"code": null,
"e": 6133,
"s": 6113,
"text": "ipm_from_parameters"
},
{
"code": null,
"e": 6196,
"s": 6133,
"text": "The approach I have taken to tackle the problem is as follows:"
},
{
"code": null,
"e": 6736,
"s": 6196,
"text": "Slice out a region of the road that we wish to view in BEV plane. For this region, define the pixel resolution, absolute distance per pixel (scale) and pose (position and orientation).Apply the perspective projection perspective for all 3D points (X, Y, Z=0) in the region using camera projection model to pixel coordinate.Resample from the front view image the corresponding pixels and map it back to image plane 2. Some form of interpolation is needed to prevent holes and aliasing effect. I use bilinear interpolation bilinear_sampler ."
},
{
"code": null,
"e": 6921,
"s": 6736,
"text": "Slice out a region of the road that we wish to view in BEV plane. For this region, define the pixel resolution, absolute distance per pixel (scale) and pose (position and orientation)."
},
{
"code": null,
"e": 7061,
"s": 6921,
"text": "Apply the perspective projection perspective for all 3D points (X, Y, Z=0) in the region using camera projection model to pixel coordinate."
},
{
"code": null,
"e": 7278,
"s": 7061,
"text": "Resample from the front view image the corresponding pixels and map it back to image plane 2. Some form of interpolation is needed to prevent holes and aliasing effect. I use bilinear interpolation bilinear_sampler ."
},
{
"code": null,
"e": 7324,
"s": 7278,
"text": "Lets now go through each point mention above."
},
{
"code": null,
"e": 7462,
"s": 7324,
"text": "As the vehicle moves, we want the viewing region to be consistent relative to it. Hence the plane is defined with respect to the vehicle."
},
{
"code": null,
"e": 7736,
"s": 7462,
"text": "The origin of the plane is located at the top left corner. The viewable region is illuminated and depends on the field of view of the camera. That is why unobservable pixel (black) is on the image after IPM. I have defined the plane with the following properties (figure 7)"
},
{
"code": null,
"e": 7776,
"s": 7736,
"text": "Size of the region in pixels: 500 X 500"
},
{
"code": null,
"e": 7804,
"s": 7776,
"text": "Resolution: 0.1m per pixel."
},
{
"code": null,
"e": 7879,
"s": 7804,
"text": "The camera is located and aligned with the midpoint of the plane’s y-axis."
},
{
"code": null,
"e": 8117,
"s": 7879,
"text": "The camera parameters are given in camera.json and given with respect to the ego-vehicle. Since the projection model requires us to define the scene with respect to the camera, some manipulation is required to reverse the transformation."
},
{
"code": null,
"e": 8213,
"s": 8117,
"text": "# Notablynp.linag.inv(T) = - Tnp.linag.inv(R) = np.transpose(R) # property of orthogonal matrix"
},
{
"code": null,
"e": 8305,
"s": 8213,
"text": "The extrinsic and intrinsic parameters are constructed in this function load_camera_params."
},
{
"code": null,
"e": 8508,
"s": 8305,
"text": "The projective transformation is then applied after transforming the points into homogenous representation. The pixels are scale normalize. i.e. effective focal length = 1. This is done in perspective ."
},
{
"code": null,
"e": 8676,
"s": 8508,
"text": "As we move further away from the camera, sparsity becomes more observable as a consequence of perspective. Therefore, I use bilinear interpolation as an approximation."
},
{
"code": null,
"e": 8747,
"s": 8676,
"text": "This is done by taking the weighted (by distance) sum of the 4 corners"
},
{
"code": null,
"e": 8800,
"s": 8747,
"text": "(px, py) = w0 * im0 + w1 * im1 + w2 * im2 + w3 * im3"
},
{
"code": null,
"e": 8816,
"s": 8800,
"text": "ipm_from_opencv"
},
{
"code": null,
"e": 9024,
"s": 8816,
"text": "Now that we understand how to perform the perspective warping. Let’s see how all the above steps can be easily performed in OpenCV. This is done by formulating the problem as a plane to plane transformation."
},
{
"code": null,
"e": 9263,
"s": 9024,
"text": "OpenCV does this by solving for the homography matrix H internally using point correspondence. H now is equivalent to the camera matrix that I have discussed above. A minimum of 4 points is required to estimate H via least-squares method."
},
{
"code": null,
"e": 9316,
"s": 9263,
"text": "There are only 2 steps to perform the transformation"
},
{
"code": null,
"e": 9500,
"s": 9316,
"text": "Pick at least 4 salient features in the image and define its new location in the target image. Pass these correspondences into cv2.getPerspectiveTransform to obtain projection matrix."
},
{
"code": null,
"e": 9692,
"s": 9500,
"text": "Apply the projection matrix to the image using cv2.warpPerspective. This will warp it to a bird's eye view and at the same time, applying the desire interpolation method that you have chosen."
},
{
"code": null,
"e": 9831,
"s": 9692,
"text": "The most convenient features to choose are the lane lines. Since we know for sure they are going to be parallel in the target image (BEV)."
},
{
"code": null,
"e": 10010,
"s": 9831,
"text": "To show that it produces approximately the same result as the derived method discuss previously, I picked out the points denoting the green polygon vertices as shown in figure 4."
}
] |
Get the number of siblings of a node in JTree with Java
|
Use the getSiblingCount() method to get the number of siblings of a node in JTree. For example, let’s say we have a node, which isn’t a root node. For that, we will find the sibling count −
node1.getSiblingCount()
The following is an example to get the number of siblings of a node −
package my;
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
public class SwingDemo {
public static void main(String[] args) throws Exception {
JFrame frame = new JFrame("Demo");
DefaultMutableTreeNode node = new DefaultMutableTreeNode("Project");
DefaultMutableTreeNode node1 = new DefaultMutableTreeNode("QA");
DefaultMutableTreeNode node2 = new DefaultMutableTreeNode("Domain");
DefaultMutableTreeNode node3 = new DefaultMutableTreeNode("Topics");
DefaultMutableTreeNode node4 = new DefaultMutableTreeNode("Tools");
node.add(node1);
node.add(node2);
node.add(node3);
node.add(node4);
DefaultMutableTreeNode one = new DefaultMutableTreeNode("Python QA");
DefaultMutableTreeNode two = new DefaultMutableTreeNode("jQuery QA");
DefaultMutableTreeNode three = new DefaultMutableTreeNode("Management ");
DefaultMutableTreeNode four = new DefaultMutableTreeNode("Finance");
DefaultMutableTreeNode five = new DefaultMutableTreeNode("Networking");
DefaultMutableTreeNode six = new DefaultMutableTreeNode("MIS");
DefaultMutableTreeNode seven = new DefaultMutableTreeNode("DBMS");
DefaultMutableTreeNode eight = new DefaultMutableTreeNode("CSS");
DefaultMutableTreeNode nine = new DefaultMutableTreeNode("MongoDB");
DefaultMutableTreeNode ten = new DefaultMutableTreeNode("Code Formatter");
DefaultMutableTreeNode eleven = new DefaultMutableTreeNode("XML Editor");
DefaultMutableTreeNode twelve = new DefaultMutableTreeNode("Code Beatifier");
DefaultMutableTreeNode thirteen = new DefaultMutableTreeNode("Internet Speed Tester");
node1.add(one);
node1.add(two);
node2.add(three);
node2.add(four);
node2.add(five);
node3.add(six);
node3.add(seven);
node3.add(eight);
node3.add(nine);
node4.add(ten);
node4.add(eleven);
node4.add(twelve);
node4.add(thirteen);
JTree tree = new JTree(node);
for (int i = 0; i < tree.getRowCount(); i++) {
tree.expandRow(i);
}
tree.putClientProperty("JTree.lineStyle", "Angled");
System.out.println("Number of children of root node = " + node.getChildCount());
System.out.println("Depth of Tree = " + node.getDepth());
System.out.println("Count of Tree Leaves(root node) = " + node.getLeafCount());
System.out.println("Count of Tree Leaves(node1) = " + node1.getLeafCount());
System.out.println("Number of levels above root node = " + node.getLevel());
System.out.println("Number of levels above node1 = " + node1.getLevel());
System.out.println("Number of levels above node2 = " + node2.getLevel());
System.out.println("Number of levels above node3 = " + node3.getLevel());
System.out.println("Number of levels above node4 = " + node4.getLevel());
System.out.println("Sibling count of root node = " + node.getSiblingCount());
System.out.println("Sibling count of node1 = " + node1.getSiblingCount());
System.out.println("Sibling count of child node three = " + three.getSiblingCount());
tree.setRowHeight(20);
frame.add(tree);
frame.setSize(600,450);
frame.setVisible(true);
}
}
The following is our JTree −
The output is as follows displaying the result in Console −
|
[
{
"code": null,
"e": 1252,
"s": 1062,
"text": "Use the getSiblingCount() method to get the number of siblings of a node in JTree. For example, let’s say we have a node, which isn’t a root node. For that, we will find the sibling count −"
},
{
"code": null,
"e": 1276,
"s": 1252,
"text": "node1.getSiblingCount()"
},
{
"code": null,
"e": 1346,
"s": 1276,
"text": "The following is an example to get the number of siblings of a node −"
},
{
"code": null,
"e": 4650,
"s": 1346,
"text": "package my;\nimport javax.swing.JFrame;\nimport javax.swing.JTree;\nimport javax.swing.tree.DefaultMutableTreeNode;\npublic class SwingDemo {\n public static void main(String[] args) throws Exception {\n JFrame frame = new JFrame(\"Demo\");\n DefaultMutableTreeNode node = new DefaultMutableTreeNode(\"Project\");\n DefaultMutableTreeNode node1 = new DefaultMutableTreeNode(\"QA\");\n DefaultMutableTreeNode node2 = new DefaultMutableTreeNode(\"Domain\");\n DefaultMutableTreeNode node3 = new DefaultMutableTreeNode(\"Topics\");\n DefaultMutableTreeNode node4 = new DefaultMutableTreeNode(\"Tools\");\n node.add(node1);\n node.add(node2);\n node.add(node3);\n node.add(node4);\n DefaultMutableTreeNode one = new DefaultMutableTreeNode(\"Python QA\");\n DefaultMutableTreeNode two = new DefaultMutableTreeNode(\"jQuery QA\");\n DefaultMutableTreeNode three = new DefaultMutableTreeNode(\"Management \");\n DefaultMutableTreeNode four = new DefaultMutableTreeNode(\"Finance\");\n DefaultMutableTreeNode five = new DefaultMutableTreeNode(\"Networking\");\n DefaultMutableTreeNode six = new DefaultMutableTreeNode(\"MIS\");\n DefaultMutableTreeNode seven = new DefaultMutableTreeNode(\"DBMS\");\n DefaultMutableTreeNode eight = new DefaultMutableTreeNode(\"CSS\");\n DefaultMutableTreeNode nine = new DefaultMutableTreeNode(\"MongoDB\");\n DefaultMutableTreeNode ten = new DefaultMutableTreeNode(\"Code Formatter\");\n DefaultMutableTreeNode eleven = new DefaultMutableTreeNode(\"XML Editor\");\n DefaultMutableTreeNode twelve = new DefaultMutableTreeNode(\"Code Beatifier\");\n DefaultMutableTreeNode thirteen = new DefaultMutableTreeNode(\"Internet Speed Tester\");\n node1.add(one);\n node1.add(two);\n node2.add(three);\n node2.add(four);\n node2.add(five);\n node3.add(six);\n node3.add(seven);\n node3.add(eight);\n node3.add(nine);\n node4.add(ten);\n node4.add(eleven);\n node4.add(twelve);\n node4.add(thirteen);\n JTree tree = new JTree(node);\n for (int i = 0; i < tree.getRowCount(); i++) {\n tree.expandRow(i);\n }\n tree.putClientProperty(\"JTree.lineStyle\", \"Angled\");\n System.out.println(\"Number of children of root node = \" + node.getChildCount());\n System.out.println(\"Depth of Tree = \" + node.getDepth());\n System.out.println(\"Count of Tree Leaves(root node) = \" + node.getLeafCount());\n System.out.println(\"Count of Tree Leaves(node1) = \" + node1.getLeafCount());\n System.out.println(\"Number of levels above root node = \" + node.getLevel());\n System.out.println(\"Number of levels above node1 = \" + node1.getLevel());\n System.out.println(\"Number of levels above node2 = \" + node2.getLevel());\n System.out.println(\"Number of levels above node3 = \" + node3.getLevel());\n System.out.println(\"Number of levels above node4 = \" + node4.getLevel());\n System.out.println(\"Sibling count of root node = \" + node.getSiblingCount());\n System.out.println(\"Sibling count of node1 = \" + node1.getSiblingCount());\n System.out.println(\"Sibling count of child node three = \" + three.getSiblingCount());\n tree.setRowHeight(20);\n frame.add(tree);\n frame.setSize(600,450);\n frame.setVisible(true);\n }\n}"
},
{
"code": null,
"e": 4679,
"s": 4650,
"text": "The following is our JTree −"
},
{
"code": null,
"e": 4739,
"s": 4679,
"text": "The output is as follows displaying the result in Console −"
}
] |
Ruby on Rails - Layouts
|
A layout defines the surroundings of an HTML page. It's the place to define a common look and feel of your final output. Layout files reside in app/views/layouts.
The process involves defining a layout template and then letting the controller know that it exists and to use it. First, let's create the template.
Add a new file called standard.html.erb to app/views/layouts. You let the controllers know what template to use by the name of the file, so following a same naming scheme is advised.
Add the following code to the new standard.html.erb file and save your changes −
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv = "Content-Type" content = "text/html; charset = iso-8859-1" />
<meta http-equiv = "Content-Language" content = "en-us" />
<title>Library Info System</title>
<%= stylesheet_link_tag "style" %>
</head>
<body id = "library">
<div id = "container">
<div id = "header">
<h1>Library Info System</h1>
<h3>Library powered by Ruby on Rails</h3>
</div>
<div id = "content">
<%= yield -%>
</div>
<div id = "sidebar"></div>
</div>
</body>
</html>
Everything you just added were standard HTML elements except two lines. The stylesheet_link_tag helper method outputs a stylesheet <link>. In this instance, we are linking style.css style sheet. The yield command lets Rails know that it should put the html.erb for the method called here.
Now open book_controller.rb and add the following line just below the first line −
class BookController < ApplicationController
layout 'standard'
def list
@books = Book.all
end
...................
It instructs the controller that we want to use a layout available in the standard.html.erb file. Now try browsing books that will produce the following screen.
Till now, we have not created any style sheet, so Rails is using the default style sheet. Now let's create a new file called style.css and save it in /public/stylesheets. Add the following code to this file.
body {
font-family: Helvetica, Geneva, Arial, sans-serif;
font-size: small;
font-color: #000;
background-color: #fff;
}
a:link, a:active, a:visited {
color: #CD0000;
}
input {
margin-bottom: 5px;
}
p {
line-height: 150%;
}
div#container {
width: 760px;
margin: 0 auto;
}
div#header {
text-align: center;
padding-bottom: 15px;
}
div#content {
float: left;
width: 450px;
padding: 10px;
}
div#content h3 {
margin-top: 15px;
}
ul#books {
list-style-type: none;
}
ul#books li {
line-height: 140%;
}
div#sidebar {
width: 200px;
margin-left: 480px;
}
ul#subjects {
width: 700px;
text-align: center;
padding: 5px;
background-color: #ececec;
border: 1px solid #ccc;
margin-bottom: 20px;
}
ul#subjects li {
display: inline;
padding-left: 5px;
}
Now refresh your browser and see the difference −
The next chapter explains how to develop applications using Rails Scaffolding to give user access to add, delete, and modify the records in any database.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2266,
"s": 2103,
"text": "A layout defines the surroundings of an HTML page. It's the place to define a common look and feel of your final output. Layout files reside in app/views/layouts."
},
{
"code": null,
"e": 2415,
"s": 2266,
"text": "The process involves defining a layout template and then letting the controller know that it exists and to use it. First, let's create the template."
},
{
"code": null,
"e": 2598,
"s": 2415,
"text": "Add a new file called standard.html.erb to app/views/layouts. You let the controllers know what template to use by the name of the file, so following a same naming scheme is advised."
},
{
"code": null,
"e": 2679,
"s": 2598,
"text": "Add the following code to the new standard.html.erb file and save your changes −"
},
{
"code": null,
"e": 3465,
"s": 2679,
"text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"http://www.w3.org/1999/xhtml\">\n\n <head>\n <meta http-equiv = \"Content-Type\" content = \"text/html; charset = iso-8859-1\" />\n <meta http-equiv = \"Content-Language\" content = \"en-us\" />\n <title>Library Info System</title>\n <%= stylesheet_link_tag \"style\" %>\n </head>\n\n <body id = \"library\">\n <div id = \"container\">\n \n <div id = \"header\">\n <h1>Library Info System</h1>\n <h3>Library powered by Ruby on Rails</h3>\n </div>\n\n <div id = \"content\">\n <%= yield -%>\n </div>\n\n <div id = \"sidebar\"></div>\n \n </div>\n </body>\n \n</html>"
},
{
"code": null,
"e": 3754,
"s": 3465,
"text": "Everything you just added were standard HTML elements except two lines. The stylesheet_link_tag helper method outputs a stylesheet <link>. In this instance, we are linking style.css style sheet. The yield command lets Rails know that it should put the html.erb for the method called here."
},
{
"code": null,
"e": 3837,
"s": 3754,
"text": "Now open book_controller.rb and add the following line just below the first line −"
},
{
"code": null,
"e": 3952,
"s": 3837,
"text": "class BookController < ApplicationController\nlayout 'standard'\ndef list\n@books = Book.all\nend\n...................\n"
},
{
"code": null,
"e": 4113,
"s": 3952,
"text": "It instructs the controller that we want to use a layout available in the standard.html.erb file. Now try browsing books that will produce the following screen."
},
{
"code": null,
"e": 4321,
"s": 4113,
"text": "Till now, we have not created any style sheet, so Rails is using the default style sheet. Now let's create a new file called style.css and save it in /public/stylesheets. Add the following code to this file."
},
{
"code": null,
"e": 5151,
"s": 4321,
"text": "body {\n font-family: Helvetica, Geneva, Arial, sans-serif;\n font-size: small;\n font-color: #000;\n background-color: #fff;\n}\n\na:link, a:active, a:visited {\n color: #CD0000;\n}\n\ninput { \n margin-bottom: 5px;\n}\n\np { \n line-height: 150%;\n}\n\ndiv#container {\n width: 760px;\n margin: 0 auto;\n}\n\ndiv#header {\n text-align: center;\n padding-bottom: 15px;\n}\n\ndiv#content {\n float: left;\n width: 450px;\n padding: 10px;\n}\n\ndiv#content h3 {\n margin-top: 15px;\n}\n\nul#books {\n list-style-type: none;\n}\n\nul#books li {\n line-height: 140%;\n}\n\ndiv#sidebar {\n width: 200px;\n margin-left: 480px;\n}\n\nul#subjects {\n width: 700px;\n text-align: center;\n padding: 5px;\n background-color: #ececec;\n border: 1px solid #ccc;\n margin-bottom: 20px;\n}\n\nul#subjects li {\n display: inline;\n padding-left: 5px;\n}"
},
{
"code": null,
"e": 5201,
"s": 5151,
"text": "Now refresh your browser and see the difference −"
},
{
"code": null,
"e": 5355,
"s": 5201,
"text": "The next chapter explains how to develop applications using Rails Scaffolding to give user access to add, delete, and modify the records in any database."
},
{
"code": null,
"e": 5362,
"s": 5355,
"text": " Print"
},
{
"code": null,
"e": 5373,
"s": 5362,
"text": " Add Notes"
}
] |
The easiest way to plot data from Pandas on a world map | by Udi Yosovzon | Towards Data Science
|
This guide is intended to be quick and easy, with the least amount of words and least amount of code, to show you how to plot data from a Pandas object on a world map using Matplotlib and Geopandas libraries.
The python libraries you need to install are pandas, geopandas and matplotlib. You can find the code for this tutorial on github: https://github.com/udiy/blogposts/tree/main/Easy%20map
The data in the Pandas object needs to have location coordinates, which means latitude and longitude. For this article, I am using data about fires in Australia, which can be found here: https://www.kaggle.com/carlosparadis/fires-from-space-australia-and-new-zeland.
The data comes from NASA satellites MODIS instrument, they monitor the fires from space, find acknowledgments at the end of this article. In the data, there’s a column called brightness, which is a measure of the temperature (in Kelvin) of the fire.
Let’s see some code now. First, we’ll have a quick look at loading and peeking at the data:
df = pd.read_csv("fire_archive_M6_96619.csv", usecols=["latitude", "longitude", "brightness", "acq_date"], parse_dates=["acq_date"])df.head()
Now let’s plot the data on a scatter plot, latitude on the y-axis, longitude on the x-axis:
df.plot(x="longitude", y="latitude", kind="scatter", c="brightness", colormap="YlOrRd")
Nice. Even without the use of a map, we can see the contours of Australia. Let’s add a map.
Geopandas lets you load the geometry for countries worldwide into an object called GeoDataFrame, which is very similar to pandas DataFrame object. It looks like this:
countries = gpd.read_file( gpd.datasets.get_path("naturalearth_lowres"))countries.head()
Once you have this object you can easily plot a world map, in the same way you would use the plot function in pandas:
countries.plot(color="lightgrey")
Since our focus is on Australia, we can slice the “countries” object so it shows us Australia only:
countries[countries["name"] == "Australia"].plot(color="lightgrey")
We’ll now use matplotlib to create a figure, and plot the map and the data together at the same time:
# initialize an axisfig, ax = plt.subplots(figsize=(8,6))# plot map on axiscountries = gpd.read_file( gpd.datasets.get_path("naturalearth_lowres"))countries[countries["name"] == "Australia"].plot(color="lightgrey", ax=ax)# parse dates for plot's titlefirst_month = df["acq_date"].min().strftime("%b %Y")last_month = df["acq_date"].max().strftime("%b %Y")# plot pointsdf.plot(x="longitude", y="latitude", kind="scatter", c="brightness", colormap="YlOrRd", title=f"Fires in Australia {first_month} to {last_month}", ax=ax)# add gridax.grid(b=True, alpha=0.5)plt.show()
The grid lines correspond to the ticks on both axes. Depending on the zoom level and our target on the map, we might want to add grid lines with smaller spacing, to do that we need to add extra ticks. For styling purposes, I prefer to add minor ticks, this way you can plot the minor grid in a different color, or transparency level. In the example below there is a minor grid with a spacing of 1 degree:
# get axes limitsx_lo, x_up = ax.get_xlim()y_lo, y_up = ax.get_ylim()# add minor ticks with a specified sapcing (deg)deg = 1ax.set_xticks(np.arange(np.ceil(x_lo), np.ceil(x_up), deg), minor=True)ax.set_yticks(np.arange(np.ceil(y_lo), np.ceil(y_up), deg), minor=True)ax.grid(b=True, which="minor", alpha=0.25)fig
We acknowledge the use of data and/or imagery from NASA’s Fire Information for Resource Management System (FIRMS) (https://earthdata.nasa.gov/firms), part of the NASA Earth Observing System Data and Information System (EOSDIS).
MODIS Collection 6 NRT Hotspot / Active Fire Detections MCD14ML distributed from NASA FIRMS. Available on-line [https://earthdata.nasa.gov/firms]. doi: 10.5067/FIRMS/MODIS/MCD14ML
Disclaimer by NASA: https://earthdata.nasa.gov/earth-observation-data/near-real-time/citation#ed-lance-disclaimer
That’s it, I hope you found this tutorial helpful and enjoyable :)
|
[
{
"code": null,
"e": 381,
"s": 172,
"text": "This guide is intended to be quick and easy, with the least amount of words and least amount of code, to show you how to plot data from a Pandas object on a world map using Matplotlib and Geopandas libraries."
},
{
"code": null,
"e": 566,
"s": 381,
"text": "The python libraries you need to install are pandas, geopandas and matplotlib. You can find the code for this tutorial on github: https://github.com/udiy/blogposts/tree/main/Easy%20map"
},
{
"code": null,
"e": 833,
"s": 566,
"text": "The data in the Pandas object needs to have location coordinates, which means latitude and longitude. For this article, I am using data about fires in Australia, which can be found here: https://www.kaggle.com/carlosparadis/fires-from-space-australia-and-new-zeland."
},
{
"code": null,
"e": 1083,
"s": 833,
"text": "The data comes from NASA satellites MODIS instrument, they monitor the fires from space, find acknowledgments at the end of this article. In the data, there’s a column called brightness, which is a measure of the temperature (in Kelvin) of the fire."
},
{
"code": null,
"e": 1175,
"s": 1083,
"text": "Let’s see some code now. First, we’ll have a quick look at loading and peeking at the data:"
},
{
"code": null,
"e": 1350,
"s": 1175,
"text": "df = pd.read_csv(\"fire_archive_M6_96619.csv\", usecols=[\"latitude\", \"longitude\", \"brightness\", \"acq_date\"], parse_dates=[\"acq_date\"])df.head()"
},
{
"code": null,
"e": 1442,
"s": 1350,
"text": "Now let’s plot the data on a scatter plot, latitude on the y-axis, longitude on the x-axis:"
},
{
"code": null,
"e": 1537,
"s": 1442,
"text": "df.plot(x=\"longitude\", y=\"latitude\", kind=\"scatter\", c=\"brightness\", colormap=\"YlOrRd\")"
},
{
"code": null,
"e": 1629,
"s": 1537,
"text": "Nice. Even without the use of a map, we can see the contours of Australia. Let’s add a map."
},
{
"code": null,
"e": 1796,
"s": 1629,
"text": "Geopandas lets you load the geometry for countries worldwide into an object called GeoDataFrame, which is very similar to pandas DataFrame object. It looks like this:"
},
{
"code": null,
"e": 1899,
"s": 1796,
"text": "countries = gpd.read_file( gpd.datasets.get_path(\"naturalearth_lowres\"))countries.head()"
},
{
"code": null,
"e": 2017,
"s": 1899,
"text": "Once you have this object you can easily plot a world map, in the same way you would use the plot function in pandas:"
},
{
"code": null,
"e": 2051,
"s": 2017,
"text": "countries.plot(color=\"lightgrey\")"
},
{
"code": null,
"e": 2151,
"s": 2051,
"text": "Since our focus is on Australia, we can slice the “countries” object so it shows us Australia only:"
},
{
"code": null,
"e": 2219,
"s": 2151,
"text": "countries[countries[\"name\"] == \"Australia\"].plot(color=\"lightgrey\")"
},
{
"code": null,
"e": 2321,
"s": 2219,
"text": "We’ll now use matplotlib to create a figure, and plot the map and the data together at the same time:"
},
{
"code": null,
"e": 2966,
"s": 2321,
"text": "# initialize an axisfig, ax = plt.subplots(figsize=(8,6))# plot map on axiscountries = gpd.read_file( gpd.datasets.get_path(\"naturalearth_lowres\"))countries[countries[\"name\"] == \"Australia\"].plot(color=\"lightgrey\", ax=ax)# parse dates for plot's titlefirst_month = df[\"acq_date\"].min().strftime(\"%b %Y\")last_month = df[\"acq_date\"].max().strftime(\"%b %Y\")# plot pointsdf.plot(x=\"longitude\", y=\"latitude\", kind=\"scatter\", c=\"brightness\", colormap=\"YlOrRd\", title=f\"Fires in Australia {first_month} to {last_month}\", ax=ax)# add gridax.grid(b=True, alpha=0.5)plt.show()"
},
{
"code": null,
"e": 3371,
"s": 2966,
"text": "The grid lines correspond to the ticks on both axes. Depending on the zoom level and our target on the map, we might want to add grid lines with smaller spacing, to do that we need to add extra ticks. For styling purposes, I prefer to add minor ticks, this way you can plot the minor grid in a different color, or transparency level. In the example below there is a minor grid with a spacing of 1 degree:"
},
{
"code": null,
"e": 3683,
"s": 3371,
"text": "# get axes limitsx_lo, x_up = ax.get_xlim()y_lo, y_up = ax.get_ylim()# add minor ticks with a specified sapcing (deg)deg = 1ax.set_xticks(np.arange(np.ceil(x_lo), np.ceil(x_up), deg), minor=True)ax.set_yticks(np.arange(np.ceil(y_lo), np.ceil(y_up), deg), minor=True)ax.grid(b=True, which=\"minor\", alpha=0.25)fig"
},
{
"code": null,
"e": 3911,
"s": 3683,
"text": "We acknowledge the use of data and/or imagery from NASA’s Fire Information for Resource Management System (FIRMS) (https://earthdata.nasa.gov/firms), part of the NASA Earth Observing System Data and Information System (EOSDIS)."
},
{
"code": null,
"e": 4091,
"s": 3911,
"text": "MODIS Collection 6 NRT Hotspot / Active Fire Detections MCD14ML distributed from NASA FIRMS. Available on-line [https://earthdata.nasa.gov/firms]. doi: 10.5067/FIRMS/MODIS/MCD14ML"
},
{
"code": null,
"e": 4205,
"s": 4091,
"text": "Disclaimer by NASA: https://earthdata.nasa.gov/earth-observation-data/near-real-time/citation#ed-lance-disclaimer"
}
] |
PyQt5 - Message Box - GeeksforGeeks
|
23 Sep, 2021
In this article, we will discuss the Message Box Widget of the PyQT5 module. It is used to display the message boxes. PyQt5 is a library used to create GUI using the Qt GUI framework. Qt is originally written in C++ but can be used in Python. The latest version of PyQt5 can be installed using the command:
pip install PyQt5
Message Boxes are usually used for declaring a small piece of information to the user. It gives users a pop-up box, that cannot be missed, to avoid important errors and information being missed by the users and in some cases, the user cannot continue without acknowledging the message box.
Based on the applications there are four types of message boxes. The following is the syntax for creating a message box. For any of the boxes, instantiation needs to be done.
Syntax:
msg_box_name = QMessageBox()
Now according to the requirement an appropriate message box is created.
This type of message box is used when related information needs to be passed to the user.
Syntax:
msg_box_name.setIcon(QMessageBox.Information)
This message box is used to get an answer from a user regarding some activity or action to be performed.
Syntax:
msg_box_name.setIcon(QMessageBox.Question)
This triggers a warning regarding the action the user is about to perform.
Syntax:
msg_box_name.setIcon(QMessageBox.Warning)
This is often used for getting the user’s opinion for a critical action.
Syntax:
msg_box_name.setIcon(QMessageBox.Critical)
Now to create a program that produces a message box first import all the required modules, and create a widget with four buttons, on clicking any of these a message box will be generated.
Now for each button associate a message box that pops when the respective button is clicked. For this first, instantiate a message box and add a required icon. Now set appropriate attributes for the pop that will be generated. Also, add buttons to deal with standard mechanisms.
Given below is the complete implementation.
Program:
Python
#import librariesimport sysfrom PyQt5.QtWidgets import * def window(): # create pyqt5 app app = QApplication(sys.argv) w = QWidget() # create buttons # b1- Information button b1 = QPushButton(w) b1.setText("Information") b1.move(45, 50) # b2- Warning button b2 = QPushButton(w) b2.setText("Warning") b2.move(150, 50) # b3- Question button b3 = QPushButton(w) b3.setText("Question") b3.move(50, 150) # b4- Critical button b4 = QPushButton(w) b4.setText("Critical") b4.move(150, 150) # declaring command when button clicked b1.clicked.connect(show_info_messagebox) b2.clicked.connect(show_warning_messagebox) b3.clicked.connect(show_question_messagebox) b4.clicked.connect(show_critical_messagebox) # setting title of the window w.setWindowTitle("PyQt MessageBox") # showing all the widgets w.show() # start the app sys.exit(app.exec_()) def show_info_messagebox(): msg = QMessageBox() msg.setIcon(QMessageBox.Information) # setting message for Message Box msg.setText("Information ") # setting Message box window title msg.setWindowTitle("Information MessageBox") # declaring buttons on Message Box msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel) # start the app retval = msg.exec_() def show_warning_messagebox(): msg = QMessageBox() msg.setIcon(QMessageBox.Warning) # setting message for Message Box msg.setText("Warning") # setting Message box window title msg.setWindowTitle("Warning MessageBox") # declaring buttons on Message Box msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel) # start the app retval = msg.exec_() def show_question_messagebox(): msg = QMessageBox() msg.setIcon(QMessageBox.Question) # setting message for Message Box msg.setText("Question") # setting Message box window title msg.setWindowTitle("Question MessageBox") # declaring buttons on Message Box msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel) # start the app retval = msg.exec_() def show_critical_messagebox(): msg = QMessageBox() msg.setIcon(QMessageBox.Critical) # setting message for Message Box msg.setText("Critical") # setting Message box window title msg.setWindowTitle("Critical MessageBox") # declaring buttons on Message Box msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel) # start the app retval = msg.exec_() if __name__ == '__main__': window()
Output
PyQt5-Widget
Python-gui
Python-PyQt
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()
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Python Classes and Objects
Create a directory in Python
|
[
{
"code": null,
"e": 23927,
"s": 23899,
"text": "\n23 Sep, 2021"
},
{
"code": null,
"e": 24234,
"s": 23927,
"text": "In this article, we will discuss the Message Box Widget of the PyQT5 module. It is used to display the message boxes. PyQt5 is a library used to create GUI using the Qt GUI framework. Qt is originally written in C++ but can be used in Python. The latest version of PyQt5 can be installed using the command:"
},
{
"code": null,
"e": 24252,
"s": 24234,
"text": "pip install PyQt5"
},
{
"code": null,
"e": 24542,
"s": 24252,
"text": "Message Boxes are usually used for declaring a small piece of information to the user. It gives users a pop-up box, that cannot be missed, to avoid important errors and information being missed by the users and in some cases, the user cannot continue without acknowledging the message box."
},
{
"code": null,
"e": 24717,
"s": 24542,
"text": "Based on the applications there are four types of message boxes. The following is the syntax for creating a message box. For any of the boxes, instantiation needs to be done."
},
{
"code": null,
"e": 24725,
"s": 24717,
"text": "Syntax:"
},
{
"code": null,
"e": 24755,
"s": 24725,
"text": "msg_box_name = QMessageBox() "
},
{
"code": null,
"e": 24827,
"s": 24755,
"text": "Now according to the requirement an appropriate message box is created."
},
{
"code": null,
"e": 24917,
"s": 24827,
"text": "This type of message box is used when related information needs to be passed to the user."
},
{
"code": null,
"e": 24925,
"s": 24917,
"text": "Syntax:"
},
{
"code": null,
"e": 24972,
"s": 24925,
"text": "msg_box_name.setIcon(QMessageBox.Information) "
},
{
"code": null,
"e": 25077,
"s": 24972,
"text": "This message box is used to get an answer from a user regarding some activity or action to be performed."
},
{
"code": null,
"e": 25085,
"s": 25077,
"text": "Syntax:"
},
{
"code": null,
"e": 25128,
"s": 25085,
"text": "msg_box_name.setIcon(QMessageBox.Question)"
},
{
"code": null,
"e": 25203,
"s": 25128,
"text": "This triggers a warning regarding the action the user is about to perform."
},
{
"code": null,
"e": 25211,
"s": 25203,
"text": "Syntax:"
},
{
"code": null,
"e": 25253,
"s": 25211,
"text": "msg_box_name.setIcon(QMessageBox.Warning)"
},
{
"code": null,
"e": 25328,
"s": 25253,
"text": "This is often used for getting the user’s opinion for a critical action. "
},
{
"code": null,
"e": 25336,
"s": 25328,
"text": "Syntax:"
},
{
"code": null,
"e": 25379,
"s": 25336,
"text": "msg_box_name.setIcon(QMessageBox.Critical)"
},
{
"code": null,
"e": 25569,
"s": 25379,
"text": "Now to create a program that produces a message box first import all the required modules, and create a widget with four buttons, on clicking any of these a message box will be generated. "
},
{
"code": null,
"e": 25848,
"s": 25569,
"text": "Now for each button associate a message box that pops when the respective button is clicked. For this first, instantiate a message box and add a required icon. Now set appropriate attributes for the pop that will be generated. Also, add buttons to deal with standard mechanisms."
},
{
"code": null,
"e": 25892,
"s": 25848,
"text": "Given below is the complete implementation."
},
{
"code": null,
"e": 25901,
"s": 25892,
"text": "Program:"
},
{
"code": null,
"e": 25908,
"s": 25901,
"text": "Python"
},
{
"code": "#import librariesimport sysfrom PyQt5.QtWidgets import * def window(): # create pyqt5 app app = QApplication(sys.argv) w = QWidget() # create buttons # b1- Information button b1 = QPushButton(w) b1.setText(\"Information\") b1.move(45, 50) # b2- Warning button b2 = QPushButton(w) b2.setText(\"Warning\") b2.move(150, 50) # b3- Question button b3 = QPushButton(w) b3.setText(\"Question\") b3.move(50, 150) # b4- Critical button b4 = QPushButton(w) b4.setText(\"Critical\") b4.move(150, 150) # declaring command when button clicked b1.clicked.connect(show_info_messagebox) b2.clicked.connect(show_warning_messagebox) b3.clicked.connect(show_question_messagebox) b4.clicked.connect(show_critical_messagebox) # setting title of the window w.setWindowTitle(\"PyQt MessageBox\") # showing all the widgets w.show() # start the app sys.exit(app.exec_()) def show_info_messagebox(): msg = QMessageBox() msg.setIcon(QMessageBox.Information) # setting message for Message Box msg.setText(\"Information \") # setting Message box window title msg.setWindowTitle(\"Information MessageBox\") # declaring buttons on Message Box msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel) # start the app retval = msg.exec_() def show_warning_messagebox(): msg = QMessageBox() msg.setIcon(QMessageBox.Warning) # setting message for Message Box msg.setText(\"Warning\") # setting Message box window title msg.setWindowTitle(\"Warning MessageBox\") # declaring buttons on Message Box msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel) # start the app retval = msg.exec_() def show_question_messagebox(): msg = QMessageBox() msg.setIcon(QMessageBox.Question) # setting message for Message Box msg.setText(\"Question\") # setting Message box window title msg.setWindowTitle(\"Question MessageBox\") # declaring buttons on Message Box msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel) # start the app retval = msg.exec_() def show_critical_messagebox(): msg = QMessageBox() msg.setIcon(QMessageBox.Critical) # setting message for Message Box msg.setText(\"Critical\") # setting Message box window title msg.setWindowTitle(\"Critical MessageBox\") # declaring buttons on Message Box msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel) # start the app retval = msg.exec_() if __name__ == '__main__': window()",
"e": 28536,
"s": 25908,
"text": null
},
{
"code": null,
"e": 28543,
"s": 28536,
"text": "Output"
},
{
"code": null,
"e": 28556,
"s": 28543,
"text": "PyQt5-Widget"
},
{
"code": null,
"e": 28567,
"s": 28556,
"text": "Python-gui"
},
{
"code": null,
"e": 28579,
"s": 28567,
"text": "Python-PyQt"
},
{
"code": null,
"e": 28586,
"s": 28579,
"text": "Python"
},
{
"code": null,
"e": 28684,
"s": 28586,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28693,
"s": 28684,
"text": "Comments"
},
{
"code": null,
"e": 28706,
"s": 28693,
"text": "Old Comments"
},
{
"code": null,
"e": 28738,
"s": 28706,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28794,
"s": 28738,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28836,
"s": 28794,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28878,
"s": 28836,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28914,
"s": 28878,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 28953,
"s": 28914,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28975,
"s": 28953,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 29006,
"s": 28975,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 29033,
"s": 29006,
"text": "Python Classes and Objects"
}
] |
How to read json array in reverse order in android?
|
This example demonstrate about How to read json array in reverse order in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:gravity="center"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/text"
android:textSize="30sp"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
In the above code, we have taken text view to show NAME from object.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
TextView textView;
RequestQueue queue;
String URL = "http://www.mocky.io/v2/597c41390f0000d002f4dbd1";
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
queue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
textView.setText(response.toString());
try {
JSONObject object=new JSONObject(response);
JSONArray array=object.getJSONArray("users");
for(int i=array.length()-1;i>=0;i--) {
JSONObject object1=array.getJSONObject(i);
String name =object1.getString("name");
UserInfo userInfo=new UserInfo(name);
textView.setText(userInfo.name);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("error",error.toString());
}
});
queue.add(request);
}
private class UserInfo {
String name;
public UserInfo(String name) {
this.name=name;
}
}
}
Step 4 − Add the following code to AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapplication">
<uses-permission android:name="android.permission.INTERNET" />
<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" />
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Step 5 − Add the following code to build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.myapplication"
minSdkVersion 15
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.volley:volley:1.1.0'
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
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": 1145,
"s": 1062,
"text": "This example demonstrate about How to read json array in reverse order in android."
},
{
"code": null,
"e": 1274,
"s": 1145,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1339,
"s": 1274,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1873,
"s": 1339,
"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:gravity=\"center\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/text\"\n android:textSize=\"30sp\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\" />\n</LinearLayout>"
},
{
"code": null,
"e": 1942,
"s": 1873,
"text": "In the above code, we have taken text view to show NAME from object."
},
{
"code": null,
"e": 1999,
"s": 1942,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 4108,
"s": 1999,
"text": "package com.example.myapplication;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.util.Log;\nimport android.widget.TextView;\nimport android.widget.Toast;\nimport com.android.volley.Request;\nimport com.android.volley.RequestQueue;\nimport com.android.volley.Response;\nimport com.android.volley.VolleyError;\nimport com.android.volley.toolbox.StringRequest;\nimport com.android.volley.toolbox.Volley;\nimport org.json.JSONArray;\nimport org.json.JSONException;\nimport org.json.JSONObject;\npublic class MainActivity extends AppCompatActivity {\n TextView textView;\n RequestQueue queue;\n String URL = \"http://www.mocky.io/v2/597c41390f0000d002f4dbd1\";\n @RequiresApi(api = Build.VERSION_CODES.N)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textView = findViewById(R.id.text);\n queue = Volley.newRequestQueue(this);\n StringRequest request = new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {\n @Override\n public void onResponse(String response) {\n textView.setText(response.toString());\n try {\n JSONObject object=new JSONObject(response);\n JSONArray array=object.getJSONArray(\"users\");\n for(int i=array.length()-1;i>=0;i--) {\n JSONObject object1=array.getJSONObject(i);\n String name =object1.getString(\"name\");\n UserInfo userInfo=new UserInfo(name);\n textView.setText(userInfo.name);\n }\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n }, new Response.ErrorListener() {\n @Override\n public void onErrorResponse(VolleyError error) {\n Log.d(\"error\",error.toString());\n }\n });\nqueue.add(request);\n}\nprivate class UserInfo {\nString name;\npublic UserInfo(String name) {\nthis.name=name;\n}\n}\n}"
},
{
"code": null,
"e": 4163,
"s": 4108,
"text": "Step 4 − Add the following code to AndroidManifest.xml"
},
{
"code": null,
"e": 4985,
"s": 4163,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.myapplication\">\n <uses-permission android:name=\"android.permission.INTERNET\" />\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 <action android:name=\"android.net.conn.CONNECTIVITY_CHANGE\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n</application>\n</manifest>"
},
{
"code": null,
"e": 5033,
"s": 4985,
"text": "Step 5 − Add the following code to build.gradle"
},
{
"code": null,
"e": 5989,
"s": 5033,
"text": "apply plugin: 'com.android.application'\nandroid {\n compileSdkVersion 28\n defaultConfig {\n applicationId \"com.example.myapplication\"\n minSdkVersion 15\n targetSdkVersion 28\n versionCode 1\n versionName \"1.0\"\n testInstrumentationRunner \"android.support.test.runner.AndroidJUnitRunner\"\n }\n buildTypes {\n release {\n minifyEnabled false\n proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'\n }\n }\n}\ndependencies {\n implementation fileTree(dir: 'libs', include: ['*.jar'])\n implementation 'com.android.volley:volley:1.1.0'\n implementation 'com.android.support:appcompat-v7:28.0.0'\n implementation 'com.android.support.constraint:constraint-layout:1.1.3'\n testImplementation 'junit:junit:4.12'\n androidTestImplementation 'com.android.support.test:runner:1.0.2'\n androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'\n}"
},
{
"code": null,
"e": 6336,
"s": 5989,
"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": 6376,
"s": 6336,
"text": "Click here to download the project code"
}
] |
How to divide each value in a data frame by column total in R?
|
To divide each value in a data frame by column total, we can use apply function and define the function for the division. For example, if we have a data frame called df that contains five columns then we can divide each value of these columns by column total using the command apply(df,2,function(x){x/sum(x)})
Consider the below data frame −
Live Demo
x1<-rpois(40,5)
x2<-rpois(40,2)
x3<-rpois(40,8)
df1<-data.frame(x1,x2,x3)
df1
x1 x2 x3
1 4 3 9
2 9 5 8
3 4 2 6
4 8 3 9
5 3 2 10
6 8 0 8
7 3 3 7
8 6 2 10
9 9 1 8
10 3 2 3
11 4 2 7
12 4 3 6
13 1 3 11
14 6 2 7
15 5 2 10
16 5 2 11
17 3 0 13
18 4 0 7
19 4 2 15
20 4 3 10
21 6 3 9
22 5 3 2
23 7 3 6
24 3 5 9
25 1 7 8
26 1 3 7
27 4 2 7
28 4 1 5
29 3 1 8
30 8 1 10
31 7 1 8
32 5 0 5
33 3 3 3
34 2 2 9
35 5 2 4
36 6 4 9
37 3 1 8
38 7 4 11
39 5 2 5
40 6 0 11
Dividing each value by column total in df1 −
apply(df1,2,function(x){x/sum(x)})
x1 x2 x3
[1,] 0.021276596 0.03333333 0.028213166
[2,] 0.047872340 0.05555556 0.025078370
[3,] 0.021276596 0.02222222 0.018808777
[4,] 0.042553191 0.03333333 0.028213166
[5,] 0.015957447 0.02222222 0.031347962
[6,] 0.042553191 0.00000000 0.025078370
[7,] 0.015957447 0.03333333 0.021943574
[8,] 0.031914894 0.02222222 0.031347962
[9,] 0.047872340 0.01111111 0.025078370
[10,] 0.015957447 0.02222222 0.009404389
[11,] 0.021276596 0.02222222 0.021943574
[12,] 0.021276596 0.03333333 0.018808777
[13,] 0.005319149 0.03333333 0.034482759
[14,] 0.031914894 0.02222222 0.021943574
[15,] 0.026595745 0.02222222 0.031347962
[16,] 0.026595745 0.02222222 0.034482759
[17,] 0.015957447 0.00000000 0.040752351
[18,] 0.021276596 0.00000000 0.021943574
[19,] 0.021276596 0.02222222 0.047021944
[20,] 0.021276596 0.03333333 0.031347962
[21,] 0.031914894 0.03333333 0.028213166
[22,] 0.026595745 0.03333333 0.006269592
[23,] 0.037234043 0.03333333 0.018808777
[24,] 0.015957447 0.05555556 0.028213166
[25,] 0.005319149 0.07777778 0.025078370
[26,] 0.005319149 0.03333333 0.021943574
[27,] 0.021276596 0.02222222 0.021943574
[28,] 0.021276596 0.01111111 0.015673981
[29,] 0.015957447 0.01111111 0.025078370
[30,] 0.042553191 0.01111111 0.031347962
[31,] 0.037234043 0.01111111 0.025078370
[32,] 0.026595745 0.00000000 0.015673981
[33,] 0.015957447 0.03333333 0.009404389
[34,] 0.010638298 0.02222222 0.028213166
[35,] 0.026595745 0.02222222 0.012539185
[36,] 0.031914894 0.04444444 0.028213166
[37,] 0.015957447 0.01111111 0.025078370
[38,] 0.037234043 0.04444444 0.034482759
[39,] 0.026595745 0.02222222 0.015673981
[40,] 0.031914894 0.00000000 0.034482759
Live Demo
y1<-rnorm(20)
y2<-rnorm(20)
df2<-data.frame(y1,y2)
df2
y1 y2
1 1.52398233 0.423204080
2 0.48580249 -0.902605575
3 2.67630858 0.007436699
4 0.68410093 0.147904838
5 -1.40680934 1.223015890
6 -2.58064644 1.573868810
7 -0.82872756 -1.663446039
8 0.62632080 -0.478541658
9 -0.52795034 -0.236118274
10 1.68900397 -1.692100343
11 -1.37090356 -0.693266887
12 0.27027656 1.206031106
13 -1.40924870 2.025970432
14 1.06878458 -0.421947510
15 -1.18499758 0.152058450
16 0.85252095 0.520451585
17 0.33823672 0.003101624
18 -0.01792139 0.160589590
19 0.50504901 -0.370946479
20 0.37809177 -1.276916712
Dividing each value by column total in df2 −
apply(df2,2,function(x){x/sum(x)})
y1 y2
[1,] 0.8603878 -1.44805767
[2,] 0.2742673 3.08840341
[3,] 1.5109514 -0.02544581
[4,] 0.3862198 -0.50607909
[5,] -0.7942360 -4.18473645
[6,] -1.4569439 -5.38523353
[7,] -0.4678710 5.69173576
[8,] 0.3535991 1.63740368
[9,] -0.2980625 0.80791489
[10,] 0.9535533 5.78978085
[11,] -0.7739648 2.37211898
[12,] 0.1525888 -4.12662041
[13,] -0.7956132 -6.93216857
[14,] 0.6033989 1.44375812
[15,] -0.6690087 -0.52029131
[16,] 0.4813039 -1.78080492
[17,] 0.1909568 -0.01061268
[18,] -0.0101178 -0.54948191
[19,] 0.2851332 1.26925027
[20,] 0.2134576 4.36916638
|
[
{
"code": null,
"e": 1373,
"s": 1062,
"text": "To divide each value in a data frame by column total, we can use apply function and define the function for the division. For example, if we have a data frame called df that contains five columns then we can divide each value of these columns by column total using the command apply(df,2,function(x){x/sum(x)})"
},
{
"code": null,
"e": 1405,
"s": 1373,
"text": "Consider the below data frame −"
},
{
"code": null,
"e": 1416,
"s": 1405,
"text": " Live Demo"
},
{
"code": null,
"e": 1494,
"s": 1416,
"text": "x1<-rpois(40,5)\nx2<-rpois(40,2)\nx3<-rpois(40,8)\ndf1<-data.frame(x1,x2,x3)\ndf1"
},
{
"code": null,
"e": 1987,
"s": 1494,
"text": " x1 x2 x3\n1 4 3 9\n2 9 5 8\n3 4 2 6\n4 8 3 9\n5 3 2 10\n6 8 0 8\n7 3 3 7\n8 6 2 10\n9 9 1 8\n10 3 2 3\n11 4 2 7\n12 4 3 6\n13 1 3 11\n14 6 2 7\n15 5 2 10\n16 5 2 11\n17 3 0 13\n18 4 0 7\n19 4 2 15\n20 4 3 10\n21 6 3 9\n22 5 3 2\n23 7 3 6\n24 3 5 9\n25 1 7 8\n26 1 3 7\n27 4 2 7\n28 4 1 5\n29 3 1 8\n30 8 1 10\n31 7 1 8\n32 5 0 5\n33 3 3 3\n34 2 2 9\n35 5 2 4\n36 6 4 9\n37 3 1 8\n38 7 4 11\n39 5 2 5\n40 6 0 11"
},
{
"code": null,
"e": 2032,
"s": 1987,
"text": "Dividing each value by column total in df1 −"
},
{
"code": null,
"e": 2067,
"s": 2032,
"text": "apply(df1,2,function(x){x/sum(x)})"
},
{
"code": null,
"e": 3824,
"s": 2067,
"text": " x1 x2 x3\n[1,] 0.021276596 0.03333333 0.028213166\n[2,] 0.047872340 0.05555556 0.025078370\n[3,] 0.021276596 0.02222222 0.018808777\n[4,] 0.042553191 0.03333333 0.028213166\n[5,] 0.015957447 0.02222222 0.031347962\n[6,] 0.042553191 0.00000000 0.025078370\n[7,] 0.015957447 0.03333333 0.021943574\n[8,] 0.031914894 0.02222222 0.031347962\n[9,] 0.047872340 0.01111111 0.025078370\n[10,] 0.015957447 0.02222222 0.009404389\n[11,] 0.021276596 0.02222222 0.021943574\n[12,] 0.021276596 0.03333333 0.018808777\n[13,] 0.005319149 0.03333333 0.034482759\n[14,] 0.031914894 0.02222222 0.021943574\n[15,] 0.026595745 0.02222222 0.031347962\n[16,] 0.026595745 0.02222222 0.034482759\n[17,] 0.015957447 0.00000000 0.040752351\n[18,] 0.021276596 0.00000000 0.021943574\n[19,] 0.021276596 0.02222222 0.047021944\n[20,] 0.021276596 0.03333333 0.031347962\n[21,] 0.031914894 0.03333333 0.028213166\n[22,] 0.026595745 0.03333333 0.006269592\n[23,] 0.037234043 0.03333333 0.018808777\n[24,] 0.015957447 0.05555556 0.028213166\n[25,] 0.005319149 0.07777778 0.025078370\n[26,] 0.005319149 0.03333333 0.021943574\n[27,] 0.021276596 0.02222222 0.021943574\n[28,] 0.021276596 0.01111111 0.015673981\n[29,] 0.015957447 0.01111111 0.025078370\n[30,] 0.042553191 0.01111111 0.031347962\n[31,] 0.037234043 0.01111111 0.025078370\n[32,] 0.026595745 0.00000000 0.015673981\n[33,] 0.015957447 0.03333333 0.009404389\n[34,] 0.010638298 0.02222222 0.028213166\n[35,] 0.026595745 0.02222222 0.012539185\n[36,] 0.031914894 0.04444444 0.028213166\n[37,] 0.015957447 0.01111111 0.025078370\n[38,] 0.037234043 0.04444444 0.034482759\n[39,] 0.026595745 0.02222222 0.015673981\n[40,] 0.031914894 0.00000000 0.034482759"
},
{
"code": null,
"e": 3835,
"s": 3824,
"text": " Live Demo"
},
{
"code": null,
"e": 3890,
"s": 3835,
"text": "y1<-rnorm(20)\ny2<-rnorm(20)\ndf2<-data.frame(y1,y2)\ndf2"
},
{
"code": null,
"e": 4493,
"s": 3890,
"text": " y1 y2\n1 1.52398233 0.423204080\n2 0.48580249 -0.902605575\n3 2.67630858 0.007436699\n4 0.68410093 0.147904838\n5 -1.40680934 1.223015890\n6 -2.58064644 1.573868810\n7 -0.82872756 -1.663446039\n8 0.62632080 -0.478541658\n9 -0.52795034 -0.236118274\n10 1.68900397 -1.692100343\n11 -1.37090356 -0.693266887\n12 0.27027656 1.206031106\n13 -1.40924870 2.025970432\n14 1.06878458 -0.421947510\n15 -1.18499758 0.152058450\n16 0.85252095 0.520451585\n17 0.33823672 0.003101624\n18 -0.01792139 0.160589590\n19 0.50504901 -0.370946479\n20 0.37809177 -1.276916712"
},
{
"code": null,
"e": 4538,
"s": 4493,
"text": "Dividing each value by column total in df2 −"
},
{
"code": null,
"e": 4573,
"s": 4538,
"text": "apply(df2,2,function(x){x/sum(x)})"
},
{
"code": null,
"e": 5199,
"s": 4573,
"text": " y1 y2\n[1,] 0.8603878 -1.44805767\n[2,] 0.2742673 3.08840341\n[3,] 1.5109514 -0.02544581\n[4,] 0.3862198 -0.50607909\n[5,] -0.7942360 -4.18473645\n[6,] -1.4569439 -5.38523353\n[7,] -0.4678710 5.69173576\n[8,] 0.3535991 1.63740368\n[9,] -0.2980625 0.80791489\n[10,] 0.9535533 5.78978085\n[11,] -0.7739648 2.37211898\n[12,] 0.1525888 -4.12662041\n[13,] -0.7956132 -6.93216857\n[14,] 0.6033989 1.44375812\n[15,] -0.6690087 -0.52029131\n[16,] 0.4813039 -1.78080492\n[17,] 0.1909568 -0.01061268\n[18,] -0.0101178 -0.54948191\n[19,] 0.2851332 1.26925027\n[20,] 0.2134576 4.36916638"
}
] |
Comparing the Feature Extraction Algorithms for Images | by Sam Bell | Towards Data Science
|
There are many algorithms out there dedicated to feature extraction of images. Many of them work similarly to a spirograph, or a Roomba. The little bot goes around the room bumping into walls until it, hopefully, covers every speck off the entire floor. Similarly, an algorithm will travel around an image picking up interesting bits and pieces of information from that image. This process is called feature detection.
A good example of feature detection can be seen with the ORB (Oriented FAST and Rotated BRIEF) algorithm. It is actually a hot combination of FAST and BRIEF.
Those markers indicate the important characteristics of that image. This algorithm can even match those features of the same image that has been distorted( grayed, rotated, and shrunk).
ORB essentially finds the “corners” of the image. The FAST component identifies features as areas of the image with a sharp contrast of brightness. If more than 8 surrounding pixels are brighter or darker than a given pixel, that spot is flagged as a feature. Now that we have detected our features, we must express them. BRIEF does this by converting the extracted points as binary feature vectors. These are strings of 128–526 0s and 1s. ORB is pretty useful. I ran into trouble though when it came to applying ORB to a full database of images, and then storing those features into a CSV that would then be used to compare to a given query image in order to find the most similar image. This method is great for any CBIR, but I had difficulty with proper implementation. If any of you have any pointers, please feel free to comment below! :)
Documentation: https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_feature2d/py_orb/py_orb.html
Beware! The code at the bottom of the page isn’t actually great. Be sure to use:
orb = cv2.ORB_create()
It may take some clever debugging for it to work correctly.
This method simply measures the proportions of red, green, and blue values of an image and finds an image with similar color proportions. Color gradient histograms can be tuned primarily through binning the values.
Adrian Rosebrock has a great tutorial of implementing this method of comparing images: https://www.pyimagesearch.com/2014/01/22/clever-girl-a-guide-to-utilizing-color-histograms-for-computer-vision-and-image-search-engines/
This method is fine, but it isn’t very detailed. If you query and image with blue skies, it can return ocean images, or images of a pool. Think of it like the color feature in Google Image Search.
A VP-Tree is great if you’re trying to find duplicate images in a database. This algorithm is able to find identical images to the query image, or near-identical images. Again, Adrian Rosebrock has a great tutorial on this: https://www.pyimagesearch.com/2019/08/26/building-an-image-hashing-search-engine-with-vp-trees-and-opencv/
This method essentially analyzes the contents of an image and compresses all that information in a 32-bit integer. Theoretically, the images that have similar compositions would be ordered similarly, and would be neighbors based on composition. This is called hashing, and below is an example.
As you can see, the two images of the sunflower have the same number up to 8 digits. That white text is responsible for the difference, but they would most likely be neighbors. So, if both images were in your dataset one query would result in the other. This algorithm is great for returning identical, or near-identical images. It does not account for the objects in the images being rotated or blurred.
This algorithm is interesting because it seems as though it isn’t an acronym. KAZE refers to the Japanese word for ‘wind.’ Wind flows through “nonlinear forces,” and so, this algorithm is composed of nonlinear diffusion processes in the image domain.
https://www.doc.ic.ac.uk/~ajd/Publications/alcantarilla_etal_eccv2012.pdf
This parallel is a bit of a stretch in my opinion. See these following videos to get a feel for the features KAZE uses.
The last video demonstrates how robust the KAZE model is. KAZE is a great model for identifying the same object in different images. If you had a database of images, like bottles of wine, this would be a good model for label detection, and finding matches based on the label of the wine.
This has been a quick overview of the many different forms of feature extraction for images. There are lots of options available, and each has a different strength to offer for different purposes.
If you are trying to find duplicate images, use VP-trees. KAZE and ORB are great at detecting similar objects in different images. Color histograms are ideal for making one of those pictures made up of thousands of pictures, or at least finding pictures with similar color composition.
Create your own content-based image retrieval system using some of these algorithms, or use a different algorithm! There are so many to choose from. I would love to hear what you come up with.
|
[
{
"code": null,
"e": 591,
"s": 172,
"text": "There are many algorithms out there dedicated to feature extraction of images. Many of them work similarly to a spirograph, or a Roomba. The little bot goes around the room bumping into walls until it, hopefully, covers every speck off the entire floor. Similarly, an algorithm will travel around an image picking up interesting bits and pieces of information from that image. This process is called feature detection."
},
{
"code": null,
"e": 749,
"s": 591,
"text": "A good example of feature detection can be seen with the ORB (Oriented FAST and Rotated BRIEF) algorithm. It is actually a hot combination of FAST and BRIEF."
},
{
"code": null,
"e": 935,
"s": 749,
"text": "Those markers indicate the important characteristics of that image. This algorithm can even match those features of the same image that has been distorted( grayed, rotated, and shrunk)."
},
{
"code": null,
"e": 1779,
"s": 935,
"text": "ORB essentially finds the “corners” of the image. The FAST component identifies features as areas of the image with a sharp contrast of brightness. If more than 8 surrounding pixels are brighter or darker than a given pixel, that spot is flagged as a feature. Now that we have detected our features, we must express them. BRIEF does this by converting the extracted points as binary feature vectors. These are strings of 128–526 0s and 1s. ORB is pretty useful. I ran into trouble though when it came to applying ORB to a full database of images, and then storing those features into a CSV that would then be used to compare to a given query image in order to find the most similar image. This method is great for any CBIR, but I had difficulty with proper implementation. If any of you have any pointers, please feel free to comment below! :)"
},
{
"code": null,
"e": 1876,
"s": 1779,
"text": "Documentation: https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_feature2d/py_orb/py_orb.html"
},
{
"code": null,
"e": 1957,
"s": 1876,
"text": "Beware! The code at the bottom of the page isn’t actually great. Be sure to use:"
},
{
"code": null,
"e": 1980,
"s": 1957,
"text": "orb = cv2.ORB_create()"
},
{
"code": null,
"e": 2040,
"s": 1980,
"text": "It may take some clever debugging for it to work correctly."
},
{
"code": null,
"e": 2255,
"s": 2040,
"text": "This method simply measures the proportions of red, green, and blue values of an image and finds an image with similar color proportions. Color gradient histograms can be tuned primarily through binning the values."
},
{
"code": null,
"e": 2479,
"s": 2255,
"text": "Adrian Rosebrock has a great tutorial of implementing this method of comparing images: https://www.pyimagesearch.com/2014/01/22/clever-girl-a-guide-to-utilizing-color-histograms-for-computer-vision-and-image-search-engines/"
},
{
"code": null,
"e": 2676,
"s": 2479,
"text": "This method is fine, but it isn’t very detailed. If you query and image with blue skies, it can return ocean images, or images of a pool. Think of it like the color feature in Google Image Search."
},
{
"code": null,
"e": 3007,
"s": 2676,
"text": "A VP-Tree is great if you’re trying to find duplicate images in a database. This algorithm is able to find identical images to the query image, or near-identical images. Again, Adrian Rosebrock has a great tutorial on this: https://www.pyimagesearch.com/2019/08/26/building-an-image-hashing-search-engine-with-vp-trees-and-opencv/"
},
{
"code": null,
"e": 3301,
"s": 3007,
"text": "This method essentially analyzes the contents of an image and compresses all that information in a 32-bit integer. Theoretically, the images that have similar compositions would be ordered similarly, and would be neighbors based on composition. This is called hashing, and below is an example."
},
{
"code": null,
"e": 3706,
"s": 3301,
"text": "As you can see, the two images of the sunflower have the same number up to 8 digits. That white text is responsible for the difference, but they would most likely be neighbors. So, if both images were in your dataset one query would result in the other. This algorithm is great for returning identical, or near-identical images. It does not account for the objects in the images being rotated or blurred."
},
{
"code": null,
"e": 3957,
"s": 3706,
"text": "This algorithm is interesting because it seems as though it isn’t an acronym. KAZE refers to the Japanese word for ‘wind.’ Wind flows through “nonlinear forces,” and so, this algorithm is composed of nonlinear diffusion processes in the image domain."
},
{
"code": null,
"e": 4031,
"s": 3957,
"text": "https://www.doc.ic.ac.uk/~ajd/Publications/alcantarilla_etal_eccv2012.pdf"
},
{
"code": null,
"e": 4151,
"s": 4031,
"text": "This parallel is a bit of a stretch in my opinion. See these following videos to get a feel for the features KAZE uses."
},
{
"code": null,
"e": 4439,
"s": 4151,
"text": "The last video demonstrates how robust the KAZE model is. KAZE is a great model for identifying the same object in different images. If you had a database of images, like bottles of wine, this would be a good model for label detection, and finding matches based on the label of the wine."
},
{
"code": null,
"e": 4636,
"s": 4439,
"text": "This has been a quick overview of the many different forms of feature extraction for images. There are lots of options available, and each has a different strength to offer for different purposes."
},
{
"code": null,
"e": 4922,
"s": 4636,
"text": "If you are trying to find duplicate images, use VP-trees. KAZE and ORB are great at detecting similar objects in different images. Color histograms are ideal for making one of those pictures made up of thousands of pictures, or at least finding pictures with similar color composition."
}
] |
Area of a Regular Pentagram - GeeksforGeeks
|
04 Aug, 2021
Given a Pentagram and it’s inner side length(d). The task is find out area of Pentagram. The Pentagram is a five-pointed star that is formed by drawing a continuous line in five straight segments.
Examples:
Input: d = 5 Output: Area = 139.187 Area of regular pentagram = 139.187
Input: d = 7 Output: Area = 272.807
Idea is to use Golden Ratio between a/b, b/c, and c/d which equals approximately 1.618 Inner side length d is given so c = 1.618 * d b = 1.618 * c a = 1.618 * bAB, BC and CD are equals(both side of regular pentagram) So AB = BC = CD = c and BD is given by d.
Area of pentagram = Area of Pentagon BDFHJ + 5 * (Area of triangle BCD) Area of Pentagon BDFHJ = (d^2 * 5)/ (4* tan 36) Area of triangle BCD = [s(s-d)(s-c)(s-c)]^(1/2) {Heron’s Formula} where s = (d + c + c)/2
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>#define PI 3.14159using namespace std; // Function to return the area of triangle BCDdouble areaOfTriangle(float d){ // Using Golden ratio float c = 1.618 * d; float s = (d + c + c) / 2; // Calculate area of triangle BCD double area = sqrt(s * (s - c) * (s - c) * (s - d)); // Return area of all 5 triangle are same return 5 * area;} // Function to return the area of regular pentagondouble areaOfRegPentagon(float d){ // Calculate the area of regular // pentagon using above formula double cal = 4 * tan(PI / 5); double area = (5 * d * d) / cal; // Return area of regular pentagon return area;} // Function to return the area of pentagramdouble areaOfPentagram(float d){ // Area of a pentagram is equal to the // area of regular pentagon and five times // the area of Triangle return areaOfRegPentagon(d) + areaOfTriangle(d);} // Driver codeint main(){ float d = 5; cout << areaOfPentagram(d) << endl; return 0;}
// Java implementation of above approachpublic class GFG{ static double PI = 3.14159; // Function to return the area of triangle BCD static double areaOfTriangle(float d) { // Using Golden ratio float c = (float) (1.618 * d); float s = (d + c + c) / 2; // Calculate area of triangle BCD double area = Math.sqrt(s * (s - c) * (s - c) * (s - d)); // Return area of all 5 triangle are same return 5 * area; } // Function to return the area of regular pentagon static double areaOfRegPentagon(float d) { // Calculate the area of regular // pentagon using above formula double cal = 4 * Math.tan(PI / 5); double area = (5 * d * d) / cal; // Return area of regular pentagon return area; } // Function to return the area of pentagram static double areaOfPentagram(float d) { // Area of a pentagram is equal to the // area of regular pentagon and five times // the area of Triangle return areaOfRegPentagon(d) + areaOfTriangle(d); } // Driver code public static void main(String[] args) { float d = 5; System.out.println(areaOfPentagram(d)); }} // This code has been contributed by 29AjayKumar
# Python3 implementation of the approach import math PI = 3.14159 # Function to return the area of triangle BCDdef areaOfTriangle(d) : # Using Golden ratio c = 1.618 * d s = (d + c + c) / 2 # Calculate area of triangle BCD area = math.sqrt(s * (s - c) * (s - c) * (s - d)) # Return area of all 5 triangles are the same return 5 * area # Function to return the area of regular pentagondef areaOfRegPentagon(d) : global PI # Calculate the area of regular # pentagon using above formula cal = 4 * math.tan(PI / 5) area = (5 * d * d) / cal # Return area of regular pentagon return area # Function to return the area of pentagramdef areaOfPentagram(d) : # Area of a pentagram is equal to the # area of regular pentagon and five times # the area of Triangle return areaOfRegPentagon(d) + areaOfTriangle(d) # Driver code d = 5print(areaOfPentagram(d)) # This code is contributed by ihritik
// C# implementation of the above approachusing System; class GFG{ static double PI = 3.14159; // Function to return the area of triangle BCD static double areaOfTriangle(float d) { // Using Golden ratio float c = (float) (1.618 * d); float s = (d + c + c) / 2; // Calculate area of triangle BCD double area = Math.Sqrt(s * (s - c) * (s - c) * (s - d)); // Return area of all 5 triangle are same return 5 * area; } // Function to return the area of regular pentagon static double areaOfRegPentagon(float d) { // Calculate the area of regular // pentagon using above formula double cal = 4 * Math.Tan(PI / 5); double area = (5 * d * d) / cal; // Return area of regular pentagon return area; } // Function to return the area of pentagram static double areaOfPentagram(float d) { // Area of a pentagram is equal to the // area of regular pentagon and five times // the area of Triangle return areaOfRegPentagon(d) + areaOfTriangle(d); } // Driver code public static void Main() { float d = 5; Console.WriteLine(areaOfPentagram(d)); }} // This code has been contributed by ihritik
<script>// Javascript implementation of the approachvar PI = 3.14159 // Function to return the area of triangle BCDfunction areaOfTriangle(d){ // Using Golden ratio var c = 1.618 * d; var s = (d + c + c) / 2; // Calculate area of triangle BCD var area = Math.sqrt(s * (s - c) * (s - c) * (s - d)); // Return area of all 5 triangle are same return 5 * area;} // Function to return the area of regular pentagonfunction areaOfRegPentagon( d){ // Calculate the area of regular // pentagon using above formula var cal = 4 * Math.tan(PI / 5); var area = (5 * d * d) / cal; // Return area of regular pentagon return area;} // Function to return the area of pentagramfunction areaOfPentagram(d){ // Area of a pentagram is equal to the // area of regular pentagon and five times // the area of Triangle return areaOfRegPentagon(d) + areaOfTriangle(d);} // Driver codevar d = 5;document.write(areaOfPentagram(d).toFixed(3)); // This code is contributed by ShubhamSingh10</script>
139.187
Time Complexity : O(1)
29AjayKumar
ihritik
ManasChhabra2
SHUBHAMSINGH10
sumitgumber28
anikakapoor
simmytarika5
area-volume-programs
C++ Programs
Geometric
Mathematical
Mathematical
Geometric
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++
Circle and Lattice Points
Closest Pair of Points using Divide and Conquer algorithm
How to check if two given line segments intersect?
Program for distance between two points on earth
How to check if a given point lies inside or outside a polygon?
|
[
{
"code": null,
"e": 24241,
"s": 24213,
"text": "\n04 Aug, 2021"
},
{
"code": null,
"e": 24438,
"s": 24241,
"text": "Given a Pentagram and it’s inner side length(d). The task is find out area of Pentagram. The Pentagram is a five-pointed star that is formed by drawing a continuous line in five straight segments."
},
{
"code": null,
"e": 24449,
"s": 24438,
"text": "Examples: "
},
{
"code": null,
"e": 24522,
"s": 24449,
"text": "Input: d = 5 Output: Area = 139.187 Area of regular pentagram = 139.187 "
},
{
"code": null,
"e": 24560,
"s": 24522,
"text": "Input: d = 7 Output: Area = 272.807 "
},
{
"code": null,
"e": 24819,
"s": 24560,
"text": "Idea is to use Golden Ratio between a/b, b/c, and c/d which equals approximately 1.618 Inner side length d is given so c = 1.618 * d b = 1.618 * c a = 1.618 * bAB, BC and CD are equals(both side of regular pentagram) So AB = BC = CD = c and BD is given by d."
},
{
"code": null,
"e": 25031,
"s": 24819,
"text": "Area of pentagram = Area of Pentagon BDFHJ + 5 * (Area of triangle BCD) Area of Pentagon BDFHJ = (d^2 * 5)/ (4* tan 36) Area of triangle BCD = [s(s-d)(s-c)(s-c)]^(1/2) {Heron’s Formula} where s = (d + c + c)/2 "
},
{
"code": null,
"e": 25083,
"s": 25031,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25087,
"s": 25083,
"text": "C++"
},
{
"code": null,
"e": 25092,
"s": 25087,
"text": "Java"
},
{
"code": null,
"e": 25100,
"s": 25092,
"text": "Python3"
},
{
"code": null,
"e": 25103,
"s": 25100,
"text": "C#"
},
{
"code": null,
"e": 25114,
"s": 25103,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>#define PI 3.14159using namespace std; // Function to return the area of triangle BCDdouble areaOfTriangle(float d){ // Using Golden ratio float c = 1.618 * d; float s = (d + c + c) / 2; // Calculate area of triangle BCD double area = sqrt(s * (s - c) * (s - c) * (s - d)); // Return area of all 5 triangle are same return 5 * area;} // Function to return the area of regular pentagondouble areaOfRegPentagon(float d){ // Calculate the area of regular // pentagon using above formula double cal = 4 * tan(PI / 5); double area = (5 * d * d) / cal; // Return area of regular pentagon return area;} // Function to return the area of pentagramdouble areaOfPentagram(float d){ // Area of a pentagram is equal to the // area of regular pentagon and five times // the area of Triangle return areaOfRegPentagon(d) + areaOfTriangle(d);} // Driver codeint main(){ float d = 5; cout << areaOfPentagram(d) << endl; return 0;}",
"e": 26207,
"s": 25114,
"text": null
},
{
"code": "// Java implementation of above approachpublic class GFG{ static double PI = 3.14159; // Function to return the area of triangle BCD static double areaOfTriangle(float d) { // Using Golden ratio float c = (float) (1.618 * d); float s = (d + c + c) / 2; // Calculate area of triangle BCD double area = Math.sqrt(s * (s - c) * (s - c) * (s - d)); // Return area of all 5 triangle are same return 5 * area; } // Function to return the area of regular pentagon static double areaOfRegPentagon(float d) { // Calculate the area of regular // pentagon using above formula double cal = 4 * Math.tan(PI / 5); double area = (5 * d * d) / cal; // Return area of regular pentagon return area; } // Function to return the area of pentagram static double areaOfPentagram(float d) { // Area of a pentagram is equal to the // area of regular pentagon and five times // the area of Triangle return areaOfRegPentagon(d) + areaOfTriangle(d); } // Driver code public static void main(String[] args) { float d = 5; System.out.println(areaOfPentagram(d)); }} // This code has been contributed by 29AjayKumar",
"e": 27515,
"s": 26207,
"text": null
},
{
"code": "# Python3 implementation of the approach import math PI = 3.14159 # Function to return the area of triangle BCDdef areaOfTriangle(d) : # Using Golden ratio c = 1.618 * d s = (d + c + c) / 2 # Calculate area of triangle BCD area = math.sqrt(s * (s - c) * (s - c) * (s - d)) # Return area of all 5 triangles are the same return 5 * area # Function to return the area of regular pentagondef areaOfRegPentagon(d) : global PI # Calculate the area of regular # pentagon using above formula cal = 4 * math.tan(PI / 5) area = (5 * d * d) / cal # Return area of regular pentagon return area # Function to return the area of pentagramdef areaOfPentagram(d) : # Area of a pentagram is equal to the # area of regular pentagon and five times # the area of Triangle return areaOfRegPentagon(d) + areaOfTriangle(d) # Driver code d = 5print(areaOfPentagram(d)) # This code is contributed by ihritik",
"e": 28497,
"s": 27515,
"text": null
},
{
"code": "// C# implementation of the above approachusing System; class GFG{ static double PI = 3.14159; // Function to return the area of triangle BCD static double areaOfTriangle(float d) { // Using Golden ratio float c = (float) (1.618 * d); float s = (d + c + c) / 2; // Calculate area of triangle BCD double area = Math.Sqrt(s * (s - c) * (s - c) * (s - d)); // Return area of all 5 triangle are same return 5 * area; } // Function to return the area of regular pentagon static double areaOfRegPentagon(float d) { // Calculate the area of regular // pentagon using above formula double cal = 4 * Math.Tan(PI / 5); double area = (5 * d * d) / cal; // Return area of regular pentagon return area; } // Function to return the area of pentagram static double areaOfPentagram(float d) { // Area of a pentagram is equal to the // area of regular pentagon and five times // the area of Triangle return areaOfRegPentagon(d) + areaOfTriangle(d); } // Driver code public static void Main() { float d = 5; Console.WriteLine(areaOfPentagram(d)); }} // This code has been contributed by ihritik",
"e": 29796,
"s": 28497,
"text": null
},
{
"code": "<script>// Javascript implementation of the approachvar PI = 3.14159 // Function to return the area of triangle BCDfunction areaOfTriangle(d){ // Using Golden ratio var c = 1.618 * d; var s = (d + c + c) / 2; // Calculate area of triangle BCD var area = Math.sqrt(s * (s - c) * (s - c) * (s - d)); // Return area of all 5 triangle are same return 5 * area;} // Function to return the area of regular pentagonfunction areaOfRegPentagon( d){ // Calculate the area of regular // pentagon using above formula var cal = 4 * Math.tan(PI / 5); var area = (5 * d * d) / cal; // Return area of regular pentagon return area;} // Function to return the area of pentagramfunction areaOfPentagram(d){ // Area of a pentagram is equal to the // area of regular pentagon and five times // the area of Triangle return areaOfRegPentagon(d) + areaOfTriangle(d);} // Driver codevar d = 5;document.write(areaOfPentagram(d).toFixed(3)); // This code is contributed by ShubhamSingh10</script>",
"e": 30874,
"s": 29796,
"text": null
},
{
"code": null,
"e": 30882,
"s": 30874,
"text": "139.187"
},
{
"code": null,
"e": 30908,
"s": 30884,
"text": "Time Complexity : O(1) "
},
{
"code": null,
"e": 30922,
"s": 30910,
"text": "29AjayKumar"
},
{
"code": null,
"e": 30930,
"s": 30922,
"text": "ihritik"
},
{
"code": null,
"e": 30944,
"s": 30930,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 30959,
"s": 30944,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 30973,
"s": 30959,
"text": "sumitgumber28"
},
{
"code": null,
"e": 30985,
"s": 30973,
"text": "anikakapoor"
},
{
"code": null,
"e": 30998,
"s": 30985,
"text": "simmytarika5"
},
{
"code": null,
"e": 31019,
"s": 30998,
"text": "area-volume-programs"
},
{
"code": null,
"e": 31032,
"s": 31019,
"text": "C++ Programs"
},
{
"code": null,
"e": 31042,
"s": 31032,
"text": "Geometric"
},
{
"code": null,
"e": 31055,
"s": 31042,
"text": "Mathematical"
},
{
"code": null,
"e": 31068,
"s": 31055,
"text": "Mathematical"
},
{
"code": null,
"e": 31078,
"s": 31068,
"text": "Geometric"
},
{
"code": null,
"e": 31176,
"s": 31078,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31185,
"s": 31176,
"text": "Comments"
},
{
"code": null,
"e": 31198,
"s": 31185,
"text": "Old Comments"
},
{
"code": null,
"e": 31239,
"s": 31198,
"text": "Passing a function as a parameter in C++"
},
{
"code": null,
"e": 31298,
"s": 31239,
"text": "Program to implement Singly Linked List in C++ using class"
},
{
"code": null,
"e": 31310,
"s": 31298,
"text": "cout in C++"
},
{
"code": null,
"e": 31337,
"s": 31310,
"text": "Pi(π) in C++ with Examples"
},
{
"code": null,
"e": 31358,
"s": 31337,
"text": "Const keyword in C++"
},
{
"code": null,
"e": 31384,
"s": 31358,
"text": "Circle and Lattice Points"
},
{
"code": null,
"e": 31442,
"s": 31384,
"text": "Closest Pair of Points using Divide and Conquer algorithm"
},
{
"code": null,
"e": 31493,
"s": 31442,
"text": "How to check if two given line segments intersect?"
},
{
"code": null,
"e": 31542,
"s": 31493,
"text": "Program for distance between two points on earth"
}
] |
How to Show Percentage in Pie Chart in Excel? - GeeksforGeeks
|
29 Jun, 2021
Pie charts are mostly used as it is more appealing and easy to understand for any type of audience. It is divided into various parts and each part of pie charts denotes a subcategory of the original data set. This sub-category data is sometimes shown using the original values or sometimes using percentages as each subcategory represents the proportion of data.
In this article, we are going to see how to show percentages in a pie chart using Excel.
Consider the example shown below :
Example: Consider the data set which consists of information about the number of students enrolled in our courses.
The steps are as follows :
Insert the data set in the form of a table as shown above in the cells of the Excel sheet.
Select the data set and go to the Insert tab at the top of the Excel window.
Now, select Insert Doughnut or Pie chart. A drop-down will appear.
Select a 2-D pie chart from the drop-down. A pie chart will be built.
Select -> Insert -> Doughnut or Pie Chart -> 2-D Pie
Initially, the pie chart will not have any data labels in it. To add data labels, select the chart and then click on the “+” button in the top right corner of the pie chart and check the Data Labels button.
Pie Chart
It can be observed that the pie chart contains the value in the labels but our aim is to show the data labels in terms of percentage.
The steps are as follows :
Select the pie chart.
Right-click on it. A pop-down menu will appear.
Click on the Format Data Labels option.
The Format Data Labels dialog box will appear.
In this dialog box check the “Percentage” button and uncheck the Value button. This will replace the data labels in pie chart from values to percentage.
The final pie chart with percentages in the data labels is now ready.
Picked
Excel
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Use Solver in Excel?
Macros in Excel
How to Find the Last Used Row and Column in Excel VBA?
How to Sum Values Based on Criteria in Another Column in Excel?
Introduction to Excel Spreadsheet
Java Program to Draw a Shape in Excel Sheet using Apache POI
How to Run a Macro Automatically When Workbook Opens in Excel?
How to Read Data From Text File in Excel VBA?
How to Check if the Number is Prime Number in Excel?
Using CHOOSE Function along with VLOOKUP in Excel
|
[
{
"code": null,
"e": 24897,
"s": 24869,
"text": "\n29 Jun, 2021"
},
{
"code": null,
"e": 25260,
"s": 24897,
"text": "Pie charts are mostly used as it is more appealing and easy to understand for any type of audience. It is divided into various parts and each part of pie charts denotes a subcategory of the original data set. This sub-category data is sometimes shown using the original values or sometimes using percentages as each subcategory represents the proportion of data."
},
{
"code": null,
"e": 25350,
"s": 25260,
"text": "In this article, we are going to see how to show percentages in a pie chart using Excel. "
},
{
"code": null,
"e": 25385,
"s": 25350,
"text": "Consider the example shown below :"
},
{
"code": null,
"e": 25501,
"s": 25385,
"text": "Example: Consider the data set which consists of information about the number of students enrolled in our courses. "
},
{
"code": null,
"e": 25528,
"s": 25501,
"text": "The steps are as follows :"
},
{
"code": null,
"e": 25619,
"s": 25528,
"text": "Insert the data set in the form of a table as shown above in the cells of the Excel sheet."
},
{
"code": null,
"e": 25696,
"s": 25619,
"text": "Select the data set and go to the Insert tab at the top of the Excel window."
},
{
"code": null,
"e": 25763,
"s": 25696,
"text": "Now, select Insert Doughnut or Pie chart. A drop-down will appear."
},
{
"code": null,
"e": 25833,
"s": 25763,
"text": "Select a 2-D pie chart from the drop-down. A pie chart will be built."
},
{
"code": null,
"e": 25886,
"s": 25833,
"text": "Select -> Insert -> Doughnut or Pie Chart -> 2-D Pie"
},
{
"code": null,
"e": 26093,
"s": 25886,
"text": "Initially, the pie chart will not have any data labels in it. To add data labels, select the chart and then click on the “+” button in the top right corner of the pie chart and check the Data Labels button."
},
{
"code": null,
"e": 26103,
"s": 26093,
"text": "Pie Chart"
},
{
"code": null,
"e": 26238,
"s": 26103,
"text": "It can be observed that the pie chart contains the value in the labels but our aim is to show the data labels in terms of percentage. "
},
{
"code": null,
"e": 26265,
"s": 26238,
"text": "The steps are as follows :"
},
{
"code": null,
"e": 26287,
"s": 26265,
"text": "Select the pie chart."
},
{
"code": null,
"e": 26335,
"s": 26287,
"text": "Right-click on it. A pop-down menu will appear."
},
{
"code": null,
"e": 26375,
"s": 26335,
"text": "Click on the Format Data Labels option."
},
{
"code": null,
"e": 26422,
"s": 26375,
"text": "The Format Data Labels dialog box will appear."
},
{
"code": null,
"e": 26575,
"s": 26422,
"text": "In this dialog box check the “Percentage” button and uncheck the Value button. This will replace the data labels in pie chart from values to percentage."
},
{
"code": null,
"e": 26645,
"s": 26575,
"text": "The final pie chart with percentages in the data labels is now ready."
},
{
"code": null,
"e": 26652,
"s": 26645,
"text": "Picked"
},
{
"code": null,
"e": 26658,
"s": 26652,
"text": "Excel"
},
{
"code": null,
"e": 26756,
"s": 26658,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26765,
"s": 26756,
"text": "Comments"
},
{
"code": null,
"e": 26778,
"s": 26765,
"text": "Old Comments"
},
{
"code": null,
"e": 26806,
"s": 26778,
"text": "How to Use Solver in Excel?"
},
{
"code": null,
"e": 26822,
"s": 26806,
"text": "Macros in Excel"
},
{
"code": null,
"e": 26877,
"s": 26822,
"text": "How to Find the Last Used Row and Column in Excel VBA?"
},
{
"code": null,
"e": 26941,
"s": 26877,
"text": "How to Sum Values Based on Criteria in Another Column in Excel?"
},
{
"code": null,
"e": 26975,
"s": 26941,
"text": "Introduction to Excel Spreadsheet"
},
{
"code": null,
"e": 27036,
"s": 26975,
"text": "Java Program to Draw a Shape in Excel Sheet using Apache POI"
},
{
"code": null,
"e": 27099,
"s": 27036,
"text": "How to Run a Macro Automatically When Workbook Opens in Excel?"
},
{
"code": null,
"e": 27145,
"s": 27099,
"text": "How to Read Data From Text File in Excel VBA?"
},
{
"code": null,
"e": 27198,
"s": 27145,
"text": "How to Check if the Number is Prime Number in Excel?"
}
] |
How can I generate random integers between 0 and 9 using Python?
|
The randint() function in a random module returns a randomly generated integer in the given range. To obtain a random integer between 0 to 9,
>>> import random
>>> random.randint(0,9)
0
>>> random.randint(0,9)
5
>>> random.randint(0,9)
6
>>> random.randint(0,9)
8
|
[
{
"code": null,
"e": 1204,
"s": 1062,
"text": "The randint() function in a random module returns a randomly generated integer in the given range. To obtain a random integer between 0 to 9,"
},
{
"code": null,
"e": 1326,
"s": 1204,
"text": ">>> import random\n>>> random.randint(0,9)\n0\n>>> random.randint(0,9)\n5\n>>> random.randint(0,9)\n6\n>>> random.randint(0,9)\n8"
}
] |
9 Tips That Helped Me Clear All HackerRank SQL Challenges in 2 Weeks | by Michael Li | Towards Data Science
|
Current projects at work require more SQL skills, so I took the time to brush up my SQL knowledge using the HackerRank coding challenges platform. It took me a bit more than two weeks (on and off between work, workout, and taking the kid to day school, etc.) to finish all the 58 SQL challenges on the site, and I gained quite some insights from the journey (and having quite some fun doing that!). This article could be read by anyone who wants to get into the data science world or prepare for your next SQL interview using a coding site like HackerRank or LeetCode, Even if you still don’t have any prior SQL knowledge. I did put a bit of code in there to show you straightforward examples. Most of the tips are about making full use of these SQL challenges so you can benefit the most from them, rather than teaching you how to crack the problems. So don’t worry if you don’t know squash about SQL or coding. Please sit down, relax, and let’s do this.
SQL is boring in that it does not boast clever algorithms or complicated data structures. There is nothing to brag about. It requires more rigid planning and step-by-step execution to close the gap between your tables and the final results. Yet, it is essential to every data analysis/data science professionals. It is how we get access to our gold mine🪙 (data). Today, people do most of their data exploration and manipulations using more powerful languages/modules or tools like Python/Pandas or Tableau. Yet, we still cannot live without SQL since we need to get the data out of those ‘dusted’ relational databases first.
SQL can be less boring, of course, when you are doing challenging coding problems on sites like HackerRank or LeetCode. Approaching it the right way, everyone with basic SQL knowledge could have some fun doing SQL coding challenges and upgrade their SQL skills while doing so. That’s what I will be talking about in the following sessions.
Obviously, you need to have some fundamental SQL knowledge to start the challenges, though you’ll learn much more along the way. Learning basic SQL is relatively easy these days since we have tons of resources online to help you out. Two good sources I used:
Mode: The SQL Tutorial for Data Analysis: It is very well-paced, from basic to advanced topics. It also comes with an online SQL environment that you can try in real-time with the databases already used in the tutorial — no need to resort to sqlfiddle, etc.
SQLZoo: In my opinion, more new learner-friendly. It holds your hands along the way from the most simple clauses like SELECT to the more complicated JOINS. If you’ve never learned SQL, you’ll feel more comfortable here. Facebook recruiters also recommend it.
Once you feel that you have gotten the hang of most commands, you can tackle the challenges. There is no need to over-study your basics. Doing all these challenges is a good way of practicing what you learned and learning new tricks along the way.
Looking at your data and taking notes along the way is halfway to solving the problem. Better yet, visualize your data in your mind or using a whiteboard (physical or digital) helps to put the query together. Our human thinks more efficiently when doing it visually. So whiteboard away, draw your tables, put in some sample data, and maybe draw lines to show relations. Some challenges are pretty complicated, and you have to put all pieces together in one big picture, either on a whiteboard or in your mind, to find the way out. It’s easier to do it on a whiteboard (unless you are Nikola Tesla, then you can solve problems using simply your brain).🤔
Another tip is to make good use of many small, thrown-away utility queries to gain familiarity with the data. Queries that won’t directly build data toward the end result, instead show you how your data looks, uncover valuable insights, and give you instant feedback on your ideas. You can start from: SELECT * FROM table LIMIT 10; to see how your table looks, then try aggregating on different columns and seeing if you can gain some insights.
SELECT *, COUNT(*) FROM table GROUP BY column;
Maybe organize data in a better way and put them in another intermediate table (CTE) to be used later.
WITH temp_table as ( SELECT xxx...)SELECT * FROM temp_table
The above code snippets are simple examples of what I meant by ‘thrown-away’ utility queries. Obviously, you can do much more, depending on what problems you are solving. This way of problem-solving is also used widely in real Data Scientist jobs and has a name: Exploratory Data Analysis. Why not start doing it now?
I can’t remember how many times I got stuck, wondering why my perfect code won’t work or why the problem just cannot be solved, and then find out I misread the question itself 😜. It was stupid, but you’ll be surprised how easy to fall for it when you’re in a rush of solving all your challenges within a short period (like when you are doing a certification test or in an interview).
So take it slow when reading the question. Don’t skip through seemingly minor statements. A well-designed challenge usually hides important clues in plain text, and carefully reading the question will uncover them. Get a firm understanding of the schemas, table relationships, and what the question is asking. The time you spent here will be compensated dearly later by avoiding horrible, stupid mistakes.
Sometimes slow is fast.
Once you have gained your basic SQL skills, understand the question clearly, and know your data in and out, now is the time to start your attack to the challenge by formulating a plan first. I can’t stress enough how important this is. If you only remember one tip from this article, remember this one, make a plan. It’s because the nature of a SQL challenge is complicated data manipulation and usually takes multiple aggregation/layers of abstraction to solve it. Thinking at a certain level of abstracting by planning things out makes it cognitively possible and prevents us from delving too deep to recall the big picture.
The usual way of thinking I use is to think out loud like this: The question is asking for data point A and B, I can get to A by aggregating these 3 columns, get to B by using window functions to print out an ordered list of column C. OK, so for A, we need to create the columns from scratch, which I’ll use inner join to put together. For B, the window function need to be partitioned by column D and ordered by column E, ....
You see, I start from the top level and gradually work my way down, all the way to the specific clause I pick. Talking it out allows it to be heard by myself and reinforces my memory of the problem and plan, thus help me think through it. Another benefit is: In an actual SQL interview, the recruiters usually expect you to think out loud, so they will know better your thinking process. Most of the time, showcasing the thought process when working on the problem is as important as solving it, if not more so. If you practice this through all the challenges, you’ll get very comfortable(and even a bit excited) doing it. Being comfortable with talking out loud will make you feel and look more confident to the interviewers.
Peeking the answer is nothing to be ashamed of when you are learning. Your goal is to practice your skills, not trying to pass a certification test. Sometimes you’ll find yourself stuck with one challenge for too long. Don’t overspend your time trying to tackle it. Instead, use the 15- minute rule:
“Take 15 minutes to solve the problem any way you can. However, if you don’t have an answer after 15 minutes, you must ask someone.”
One reason to apply the 15-minute-rule here is that you are still learning. And sometimes, a challenge will need to use some techniques or clauses that you don’t know yet. Like people say: You don’t know what you don’t know. Spending more time on it won’t help. Another reason is that problem solving sometimes needs you to step back, see the bigger picture again, and figure out whether you’re in a hole and need to get out and change course.
Developing your ability to switch abstraction levels freely will significantly help your coding/data analysis career.
After you get the hint from the Discussion Board and completed the challenge, stop a while and think about why you missed it in the first place? Any missing part in your knowledge? Blind spots of your thinking/approach? Again, take it slow here. You are learning. The contemplation time is when you will learn the MOST from these challenges by figuring out the weak spots in your knowledge and improve it accordingly.
Most algorithm/data structure coding challenges tend to be a bit ‘tricky,’ and rightfully so. Yet, for SQL, the problem to be solved in real life is more about simplifying complicated relationships than coming up with clever solutions to math problems. Overall, I find HackerRank’s SQL challenges to follow the real-world challenges mostly. However, occasionally you will still encounter problems that can be hard to find in real life, like the (in)famous challenge of Print Prime Numbers. It feels like someone put a Python coding challenge into a SQL form and forcing you to solve it. I might be biased here but ignore those kinds of challenges. You might as well do it in Python. Using SQL for what it is not designed to will help nothing except intelligent fun. Most of us don’t come to a site like HackerRank or LeetCode for that, do we?
Once you have cracked the challenge, resist the temptation to hit the juicy ‘Next Challenge’ button! I highly suggest you to reflect on your problem-solving process, ask high-quality questions to yourself:
What clauses did I use? Why did they work? Why did some of them not work? Any better alternatives? How did I approach the problem? How did I break it into smaller sub-problems? What intermediate data did I aggregate to get to the final results?
I know, sometimes in the excitement of having tackled a complex challenge, it’s hard to slow down and contemplate these tough questions, and it seems to slow us down, but trust me, this is the FASTER way to learn.
I’d say some of the ‘hard’ challenges could be pretty tricky. In that, you need to figure out some clever ways to put the data required together. I used to use 8 CTEs, two window functions, and multiple joins to get what I wanted. But the certification tests are more reasonable and closer to real-world problems. My experience is that the certification test requires more careful question reading, schema dissecting, and maybe white-boarding your tables than coming up with novel pivoting techniques. So even if you are stuck with some challenges, don’t let them discourage you! When you feel ready, take the certification test, you might still steam roller through it!
Now onto the coding part. I’ll list what I think helped me below:
An easy way to understand subquery and CTE(Common Table Expression) is to think of it as a function in other programming languages. If you use it in more than one place, why not put it into a function? Whereas subquery is like a lambda function, you write it on the go and throw it away after using it. They help make your code more readable and conceptually easier to digest, which has great value in solving complicated SQL challenges.
Aggregation is the primary way to distill raw data into something more meaningful, closer to what the question asks. GROUP BY helps to condense the data with SUM(), COUNT(), MIN/MAX(), or AVG(), whereas window functions do the aggregation function in the item level (Best for tackling ‘Top N’ kind of problems). Sometimes you’ll need many levels/steps of aggregations to get to where you want. Again, look at your data and challenge question, and carefully design your ‘aggregation map.’
JOIN vs. LEFT JOIN: Honestly, these two are the main JOINs you’ll ever need. Use JOIN when you want to return only rows having pairs on both tables, and use LEFT JOIN when you need all rows from the “left” table, no matter if they have pairs in the “right” table or not.
Order to write the query: The most natural way is to write the query as to how they execute: FROM > WHERE > GROUP BY > HAVING > SELECT > ORDER BY > LIMIT. Resist the urge to start from SELECT. Think like what the machine is thinking.
Work from both ends, your tables, and what the question asks to solve the problem. From the data/tables side: Ask yourself what it can build with the tables? What aggregation could further distill the data? From the end-result side: What data is required? What kind of table will help solve the problem? Imagine some middle-level tables that can help bridge the gap. Try to work on both sides and meet at the middle point. Again, think at different abstraction levels helps a lot.
Do your SQL Certification Test (both Basic and Intermediate) on HackerRank if you cracked all the challenges. You can do it!
SQL challenges are a bit different than their regular algorithm/data structure counterparts. It requires you to think in a more organized way, structure your code, and switch among different abstraction levels. Master these ‘slow’ skills, you will likely find yourself steam-rolling through the challenges much faster than you think, and most importantly, it will have you well prepared for that critical SQL interview!
I hope you find this article enjoyable to read and learned a thing or two from it. If you want to know more about what I think, practice, and write about data science, consider signing up to become a Medium member. It’s $5 a month, giving you unlimited access to stories on Medium. If you sign up using my link, I’ll earn a small commission.
|
[
{
"code": null,
"e": 1128,
"s": 172,
"text": "Current projects at work require more SQL skills, so I took the time to brush up my SQL knowledge using the HackerRank coding challenges platform. It took me a bit more than two weeks (on and off between work, workout, and taking the kid to day school, etc.) to finish all the 58 SQL challenges on the site, and I gained quite some insights from the journey (and having quite some fun doing that!). This article could be read by anyone who wants to get into the data science world or prepare for your next SQL interview using a coding site like HackerRank or LeetCode, Even if you still don’t have any prior SQL knowledge. I did put a bit of code in there to show you straightforward examples. Most of the tips are about making full use of these SQL challenges so you can benefit the most from them, rather than teaching you how to crack the problems. So don’t worry if you don’t know squash about SQL or coding. Please sit down, relax, and let’s do this."
},
{
"code": null,
"e": 1753,
"s": 1128,
"text": "SQL is boring in that it does not boast clever algorithms or complicated data structures. There is nothing to brag about. It requires more rigid planning and step-by-step execution to close the gap between your tables and the final results. Yet, it is essential to every data analysis/data science professionals. It is how we get access to our gold mine🪙 (data). Today, people do most of their data exploration and manipulations using more powerful languages/modules or tools like Python/Pandas or Tableau. Yet, we still cannot live without SQL since we need to get the data out of those ‘dusted’ relational databases first."
},
{
"code": null,
"e": 2093,
"s": 1753,
"text": "SQL can be less boring, of course, when you are doing challenging coding problems on sites like HackerRank or LeetCode. Approaching it the right way, everyone with basic SQL knowledge could have some fun doing SQL coding challenges and upgrade their SQL skills while doing so. That’s what I will be talking about in the following sessions."
},
{
"code": null,
"e": 2352,
"s": 2093,
"text": "Obviously, you need to have some fundamental SQL knowledge to start the challenges, though you’ll learn much more along the way. Learning basic SQL is relatively easy these days since we have tons of resources online to help you out. Two good sources I used:"
},
{
"code": null,
"e": 2610,
"s": 2352,
"text": "Mode: The SQL Tutorial for Data Analysis: It is very well-paced, from basic to advanced topics. It also comes with an online SQL environment that you can try in real-time with the databases already used in the tutorial — no need to resort to sqlfiddle, etc."
},
{
"code": null,
"e": 2869,
"s": 2610,
"text": "SQLZoo: In my opinion, more new learner-friendly. It holds your hands along the way from the most simple clauses like SELECT to the more complicated JOINS. If you’ve never learned SQL, you’ll feel more comfortable here. Facebook recruiters also recommend it."
},
{
"code": null,
"e": 3117,
"s": 2869,
"text": "Once you feel that you have gotten the hang of most commands, you can tackle the challenges. There is no need to over-study your basics. Doing all these challenges is a good way of practicing what you learned and learning new tricks along the way."
},
{
"code": null,
"e": 3770,
"s": 3117,
"text": "Looking at your data and taking notes along the way is halfway to solving the problem. Better yet, visualize your data in your mind or using a whiteboard (physical or digital) helps to put the query together. Our human thinks more efficiently when doing it visually. So whiteboard away, draw your tables, put in some sample data, and maybe draw lines to show relations. Some challenges are pretty complicated, and you have to put all pieces together in one big picture, either on a whiteboard or in your mind, to find the way out. It’s easier to do it on a whiteboard (unless you are Nikola Tesla, then you can solve problems using simply your brain).🤔"
},
{
"code": null,
"e": 4215,
"s": 3770,
"text": "Another tip is to make good use of many small, thrown-away utility queries to gain familiarity with the data. Queries that won’t directly build data toward the end result, instead show you how your data looks, uncover valuable insights, and give you instant feedback on your ideas. You can start from: SELECT * FROM table LIMIT 10; to see how your table looks, then try aggregating on different columns and seeing if you can gain some insights."
},
{
"code": null,
"e": 4262,
"s": 4215,
"text": "SELECT *, COUNT(*) FROM table GROUP BY column;"
},
{
"code": null,
"e": 4365,
"s": 4262,
"text": "Maybe organize data in a better way and put them in another intermediate table (CTE) to be used later."
},
{
"code": null,
"e": 4425,
"s": 4365,
"text": "WITH temp_table as ( SELECT xxx...)SELECT * FROM temp_table"
},
{
"code": null,
"e": 4743,
"s": 4425,
"text": "The above code snippets are simple examples of what I meant by ‘thrown-away’ utility queries. Obviously, you can do much more, depending on what problems you are solving. This way of problem-solving is also used widely in real Data Scientist jobs and has a name: Exploratory Data Analysis. Why not start doing it now?"
},
{
"code": null,
"e": 5127,
"s": 4743,
"text": "I can’t remember how many times I got stuck, wondering why my perfect code won’t work or why the problem just cannot be solved, and then find out I misread the question itself 😜. It was stupid, but you’ll be surprised how easy to fall for it when you’re in a rush of solving all your challenges within a short period (like when you are doing a certification test or in an interview)."
},
{
"code": null,
"e": 5533,
"s": 5127,
"text": "So take it slow when reading the question. Don’t skip through seemingly minor statements. A well-designed challenge usually hides important clues in plain text, and carefully reading the question will uncover them. Get a firm understanding of the schemas, table relationships, and what the question is asking. The time you spent here will be compensated dearly later by avoiding horrible, stupid mistakes."
},
{
"code": null,
"e": 5557,
"s": 5533,
"text": "Sometimes slow is fast."
},
{
"code": null,
"e": 6184,
"s": 5557,
"text": "Once you have gained your basic SQL skills, understand the question clearly, and know your data in and out, now is the time to start your attack to the challenge by formulating a plan first. I can’t stress enough how important this is. If you only remember one tip from this article, remember this one, make a plan. It’s because the nature of a SQL challenge is complicated data manipulation and usually takes multiple aggregation/layers of abstraction to solve it. Thinking at a certain level of abstracting by planning things out makes it cognitively possible and prevents us from delving too deep to recall the big picture."
},
{
"code": null,
"e": 6612,
"s": 6184,
"text": "The usual way of thinking I use is to think out loud like this: The question is asking for data point A and B, I can get to A by aggregating these 3 columns, get to B by using window functions to print out an ordered list of column C. OK, so for A, we need to create the columns from scratch, which I’ll use inner join to put together. For B, the window function need to be partitioned by column D and ordered by column E, ...."
},
{
"code": null,
"e": 7339,
"s": 6612,
"text": "You see, I start from the top level and gradually work my way down, all the way to the specific clause I pick. Talking it out allows it to be heard by myself and reinforces my memory of the problem and plan, thus help me think through it. Another benefit is: In an actual SQL interview, the recruiters usually expect you to think out loud, so they will know better your thinking process. Most of the time, showcasing the thought process when working on the problem is as important as solving it, if not more so. If you practice this through all the challenges, you’ll get very comfortable(and even a bit excited) doing it. Being comfortable with talking out loud will make you feel and look more confident to the interviewers."
},
{
"code": null,
"e": 7639,
"s": 7339,
"text": "Peeking the answer is nothing to be ashamed of when you are learning. Your goal is to practice your skills, not trying to pass a certification test. Sometimes you’ll find yourself stuck with one challenge for too long. Don’t overspend your time trying to tackle it. Instead, use the 15- minute rule:"
},
{
"code": null,
"e": 7772,
"s": 7639,
"text": "“Take 15 minutes to solve the problem any way you can. However, if you don’t have an answer after 15 minutes, you must ask someone.”"
},
{
"code": null,
"e": 8216,
"s": 7772,
"text": "One reason to apply the 15-minute-rule here is that you are still learning. And sometimes, a challenge will need to use some techniques or clauses that you don’t know yet. Like people say: You don’t know what you don’t know. Spending more time on it won’t help. Another reason is that problem solving sometimes needs you to step back, see the bigger picture again, and figure out whether you’re in a hole and need to get out and change course."
},
{
"code": null,
"e": 8334,
"s": 8216,
"text": "Developing your ability to switch abstraction levels freely will significantly help your coding/data analysis career."
},
{
"code": null,
"e": 8752,
"s": 8334,
"text": "After you get the hint from the Discussion Board and completed the challenge, stop a while and think about why you missed it in the first place? Any missing part in your knowledge? Blind spots of your thinking/approach? Again, take it slow here. You are learning. The contemplation time is when you will learn the MOST from these challenges by figuring out the weak spots in your knowledge and improve it accordingly."
},
{
"code": null,
"e": 9595,
"s": 8752,
"text": "Most algorithm/data structure coding challenges tend to be a bit ‘tricky,’ and rightfully so. Yet, for SQL, the problem to be solved in real life is more about simplifying complicated relationships than coming up with clever solutions to math problems. Overall, I find HackerRank’s SQL challenges to follow the real-world challenges mostly. However, occasionally you will still encounter problems that can be hard to find in real life, like the (in)famous challenge of Print Prime Numbers. It feels like someone put a Python coding challenge into a SQL form and forcing you to solve it. I might be biased here but ignore those kinds of challenges. You might as well do it in Python. Using SQL for what it is not designed to will help nothing except intelligent fun. Most of us don’t come to a site like HackerRank or LeetCode for that, do we?"
},
{
"code": null,
"e": 9801,
"s": 9595,
"text": "Once you have cracked the challenge, resist the temptation to hit the juicy ‘Next Challenge’ button! I highly suggest you to reflect on your problem-solving process, ask high-quality questions to yourself:"
},
{
"code": null,
"e": 10046,
"s": 9801,
"text": "What clauses did I use? Why did they work? Why did some of them not work? Any better alternatives? How did I approach the problem? How did I break it into smaller sub-problems? What intermediate data did I aggregate to get to the final results?"
},
{
"code": null,
"e": 10260,
"s": 10046,
"text": "I know, sometimes in the excitement of having tackled a complex challenge, it’s hard to slow down and contemplate these tough questions, and it seems to slow us down, but trust me, this is the FASTER way to learn."
},
{
"code": null,
"e": 10931,
"s": 10260,
"text": "I’d say some of the ‘hard’ challenges could be pretty tricky. In that, you need to figure out some clever ways to put the data required together. I used to use 8 CTEs, two window functions, and multiple joins to get what I wanted. But the certification tests are more reasonable and closer to real-world problems. My experience is that the certification test requires more careful question reading, schema dissecting, and maybe white-boarding your tables than coming up with novel pivoting techniques. So even if you are stuck with some challenges, don’t let them discourage you! When you feel ready, take the certification test, you might still steam roller through it!"
},
{
"code": null,
"e": 10997,
"s": 10931,
"text": "Now onto the coding part. I’ll list what I think helped me below:"
},
{
"code": null,
"e": 11435,
"s": 10997,
"text": "An easy way to understand subquery and CTE(Common Table Expression) is to think of it as a function in other programming languages. If you use it in more than one place, why not put it into a function? Whereas subquery is like a lambda function, you write it on the go and throw it away after using it. They help make your code more readable and conceptually easier to digest, which has great value in solving complicated SQL challenges."
},
{
"code": null,
"e": 11923,
"s": 11435,
"text": "Aggregation is the primary way to distill raw data into something more meaningful, closer to what the question asks. GROUP BY helps to condense the data with SUM(), COUNT(), MIN/MAX(), or AVG(), whereas window functions do the aggregation function in the item level (Best for tackling ‘Top N’ kind of problems). Sometimes you’ll need many levels/steps of aggregations to get to where you want. Again, look at your data and challenge question, and carefully design your ‘aggregation map.’"
},
{
"code": null,
"e": 12194,
"s": 11923,
"text": "JOIN vs. LEFT JOIN: Honestly, these two are the main JOINs you’ll ever need. Use JOIN when you want to return only rows having pairs on both tables, and use LEFT JOIN when you need all rows from the “left” table, no matter if they have pairs in the “right” table or not."
},
{
"code": null,
"e": 12428,
"s": 12194,
"text": "Order to write the query: The most natural way is to write the query as to how they execute: FROM > WHERE > GROUP BY > HAVING > SELECT > ORDER BY > LIMIT. Resist the urge to start from SELECT. Think like what the machine is thinking."
},
{
"code": null,
"e": 12909,
"s": 12428,
"text": "Work from both ends, your tables, and what the question asks to solve the problem. From the data/tables side: Ask yourself what it can build with the tables? What aggregation could further distill the data? From the end-result side: What data is required? What kind of table will help solve the problem? Imagine some middle-level tables that can help bridge the gap. Try to work on both sides and meet at the middle point. Again, think at different abstraction levels helps a lot."
},
{
"code": null,
"e": 13034,
"s": 12909,
"text": "Do your SQL Certification Test (both Basic and Intermediate) on HackerRank if you cracked all the challenges. You can do it!"
},
{
"code": null,
"e": 13454,
"s": 13034,
"text": "SQL challenges are a bit different than their regular algorithm/data structure counterparts. It requires you to think in a more organized way, structure your code, and switch among different abstraction levels. Master these ‘slow’ skills, you will likely find yourself steam-rolling through the challenges much faster than you think, and most importantly, it will have you well prepared for that critical SQL interview!"
}
] |
Java String toCharArray() with example - GeeksforGeeks
|
04 Dec, 2018
The java string toCharArray() method converts the given string into a sequence of characters. The returned array length is equal to the length of the string.
Syntax :
public char[] toCharArray()
Return : It returns a newly allocated character array.
// Java program to demonstrate// working of toCharArray() method class Gfg { public static void main(String args[]) { String s = "GeeksforGeeks"; char[] gfg = s.toCharArray(); for (int i = 0; i < gfg.length; i++) { System.out.println(gfg[i]); } }}
Output:
G
e
e
k
s
f
o
r
G
e
e
k
s
Java-Functions
Java-lang package
Java-Strings
Java
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
HashMap in Java with Examples
Interfaces in Java
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
ArrayList in Java
How to iterate any Map in Java
Multidimensional Arrays in Java
Overriding in Java
Stack Class in Java
Collections in Java
|
[
{
"code": null,
"e": 24955,
"s": 24927,
"text": "\n04 Dec, 2018"
},
{
"code": null,
"e": 25113,
"s": 24955,
"text": "The java string toCharArray() method converts the given string into a sequence of characters. The returned array length is equal to the length of the string."
},
{
"code": null,
"e": 25122,
"s": 25113,
"text": "Syntax :"
},
{
"code": null,
"e": 25209,
"s": 25122,
"text": "public char[] toCharArray() \nReturn : It returns a newly allocated character array.\n"
},
{
"code": "// Java program to demonstrate// working of toCharArray() method class Gfg { public static void main(String args[]) { String s = \"GeeksforGeeks\"; char[] gfg = s.toCharArray(); for (int i = 0; i < gfg.length; i++) { System.out.println(gfg[i]); } }}",
"e": 25506,
"s": 25209,
"text": null
},
{
"code": null,
"e": 25514,
"s": 25506,
"text": "Output:"
},
{
"code": null,
"e": 25541,
"s": 25514,
"text": "G\ne\ne\nk\ns\nf\no\nr\nG\ne\ne\nk\ns\n"
},
{
"code": null,
"e": 25556,
"s": 25541,
"text": "Java-Functions"
},
{
"code": null,
"e": 25574,
"s": 25556,
"text": "Java-lang package"
},
{
"code": null,
"e": 25587,
"s": 25574,
"text": "Java-Strings"
},
{
"code": null,
"e": 25592,
"s": 25587,
"text": "Java"
},
{
"code": null,
"e": 25605,
"s": 25592,
"text": "Java-Strings"
},
{
"code": null,
"e": 25610,
"s": 25605,
"text": "Java"
},
{
"code": null,
"e": 25708,
"s": 25610,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25717,
"s": 25708,
"text": "Comments"
},
{
"code": null,
"e": 25730,
"s": 25717,
"text": "Old Comments"
},
{
"code": null,
"e": 25760,
"s": 25730,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 25779,
"s": 25760,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 25811,
"s": 25779,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 25862,
"s": 25811,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 25880,
"s": 25862,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 25911,
"s": 25880,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 25943,
"s": 25911,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 25962,
"s": 25943,
"text": "Overriding in Java"
},
{
"code": null,
"e": 25982,
"s": 25962,
"text": "Stack Class in Java"
}
] |
Total length of string from given Array of strings composed using given characters - GeeksforGeeks
|
31 Oct, 2021
Given a list of characters and an array of strings, find the total length of all strings in the array of strings that can be composed using the given characters.Examples:
Input: string = [“mouse”, “me”, “bat”, “lion”], chars = “eusamotb” Output: 10 Explanation: The strings that can be formed using the characters “eusamotb” are “mouse” and “me” and “bat”. Length of “mouse” is 5, length of “me” is 2, and length of “bat” is 3 Sum of all lengths = 5 + 2 + 3 = 10.Input: string = [“hi”, “data”, “geeksforgeeks”], chars = “tiadha” Output: 6 Explanation: The strings that can be formed using the characters “tiadha” are “hi” and “data”. Where length of “hi” is 2, length of “data” is 4, the sum of all is 2 + 4 = 6.
Approach:To solve the problem mentioned above we have to follow the steps given below:
We can use characters from the given character string that is ‘chars’ while forming a string. We can also reuse the used characters for forming the next string
Maintain an unordered map with character as a key and the value by keeping track of the frequency of each character from the string of chars.
Every time we scan characters from the list of string we reduce the frequency of character from the unordered map but we have to maintain the copy of the original map so as to check the second string .
If the key is not present in the map it creates one with default value as zero rather than throwing an error.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to find total length// of string composed of given characters// formed from given Array of strings #include <bits/stdc++.h>using namespace std; // Function to count the total lengthint countCharacters( vector<string>& strings, string chars){ int res = 0; // Unordered_map for // keeping frequency of characters unordered_map<char, int> freq; // Calculate the frequency for (int i = 0; i < chars.length(); i++) freq[chars[i]] += 1; // Iterate in the N strings for (auto st : strings) { bool flag = true; // Iterates in the string for (auto c : st) { // Checks if given character of string // string appears in it or not if (!freq) { flag = false; break; } } // Adds the length of string // if all characters are present if (flag) res += st.length(); } // Return the final result return res;} // Driver codeint main(){ vector<string> strings = { "hi", "data", "geeksforgeeks" }; string chars = "tiadhae"; cout << countCharacters(strings, chars); return 0;}
// Java implementation to find total length// of string composed of given characters// formed from given Array of stringsimport java.util.*;class GFG { // Function to count the total lengthstatic int countCharacters(List<String> strings, String chars){ int res = 0; // Map for // keeping frequency of characters Map<Character, Integer> freq = new HashMap<>(); // Calculate the frequency for (int i = 0; i < chars.length(); i++) { freq.put(chars.charAt(i), freq.getOrDefault(chars.charAt(i), 0) + 1); } // Iterate in the N strings for (String st : strings) { boolean flag = true; // Iterates in the string for (char c : st.toCharArray()) { // Checks if given character of string // string appears in it or not if (!freq.containsKey(c)) { flag = false; break; } } // Adds the length of string // if all characters are present if (flag) res += st.length(); } // Return the final result return res;} // Driver codepublic static void main(String[] args){ List<String> strings = Arrays.asList("hi", "data", "geeksforgeeks"); String chars = "tiadhae"; System.out.println(countCharacters(strings, chars));}} // This code is contributed by offbeat
# Python3 implementation to find total length# of string composed of given characters# formed from given Array of strings # Function to count the total lengthdef countCharacters(arr, chars): res = 0 # Unordered_map for # keeping frequency of characters freq = dict() # Calculate the frequency for i in range(len(chars)): freq[chars[i]] = freq.get(chars[i], 0)+1 # Iterate in the N strings for st in arr: flag = True # Iterates in the string for c in st: # Checks if given character of string # string appears in it or not if (c not in freq): flag = False break # Adds the length of string # if all characters are present if (flag): res += len(st) # Return the final result return res # Driver codeif __name__ == '__main__': arr =["hi", "data", "geeksforgeeks"] chars = "tiadhae" print(countCharacters(arr, chars)) # This code is contributed by mohit kumar 29
// C# implementation to find total length// of string composed of given characters// formed from given Array of stringsusing System;using System.Collections.Generic;using System.Linq; class GFG{ // Function to count the total lengthstatic int countCharacters(List<string> strings, string chars){ int res = 0; // Dictionary for keeping frequency // of characters Dictionary<char, int> freq = new Dictionary<char, int>(); // Calculate the frequency for(int i = 0; i < chars.Length; i++) { if(freq.ContainsKey(chars[i])) { freq[chars[i]]++; } else { freq.Add(chars[i], freq.GetValueOrDefault( chars[i], 0) + 1); } } // Iterate in the N strings foreach(string st in strings) { bool flag = true; // Iterates in the string foreach (char c in st.ToCharArray()) { // Checks if given character of string // string appears in it or not if (!freq.ContainsKey(c)) { flag = false; break; } } // Adds the length of string // if all characters are present if (flag) res += st.Length; } // Return the final result return res;} // Driver codepublic static void Main(string[] args){ string []tmp = { "hi", "data", "geeksforgeeks" }; List<string> strings = tmp.ToList(); string chars = "tiadhae"; Console.Write(countCharacters(strings, chars));}} // This code is contributed by rutvik_56
<script> // Javascript implementation to find total length// of string composed of given characters// formed from given Array of strings // Function to count the total lengthfunction countCharacters( strings, chars){ var res = 0; // Unordered_map for // keeping frequency of characters var freq = new Map(); // Calculate the frequency for (var i = 0; i < chars.length; i++) { if(freq.has(chars[i])) freq.set(chars[i], freq.get(chars[i])+1) else freq.set(chars[i], 1) } // Iterate in the N strings strings.forEach(st => { var flag = true; // Iterates in the string st.split('').forEach(c => { // Checks if given character of string // string appears in it or not if (!freq.has(c)) { flag = false; } }); // Adds the length of string // if all characters are present if (flag) res += st.length; }); // Return the final result return res;} // Driver codevar strings = ["hi", "data", "geeksforgeeks"];var chars = "tiadhae";document.write( countCharacters(strings, chars)); // This code is contributed by noob2000.</script>
6
Time Complexity: O(n * m), where n is the length of the char and m is the length of the string.Auxiliary Space Complexity: O(1), as the unordered map will be of size 26 only.
mohit kumar 29
offbeat
rutvik_56
noob2000
adnanirshad158
cpp-map
cpp-unordered_map
frequency-counting
Pattern Searching
Strings
Strings
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to validate HTML tag using Regular Expression
Build a DFA to accept Binary strings that starts or ends with "01"
How to validate pin code of India using Regular Expression
How to check Aadhaar number is valid or not using Regular Expression
How to validate time in 24-hour format using Regular Expression
Reverse a string in Java
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
C++ Data Types
Write a program to print all permutations of a given string
|
[
{
"code": null,
"e": 25328,
"s": 25300,
"text": "\n31 Oct, 2021"
},
{
"code": null,
"e": 25501,
"s": 25328,
"text": "Given a list of characters and an array of strings, find the total length of all strings in the array of strings that can be composed using the given characters.Examples: "
},
{
"code": null,
"e": 26045,
"s": 25501,
"text": "Input: string = [“mouse”, “me”, “bat”, “lion”], chars = “eusamotb” Output: 10 Explanation: The strings that can be formed using the characters “eusamotb” are “mouse” and “me” and “bat”. Length of “mouse” is 5, length of “me” is 2, and length of “bat” is 3 Sum of all lengths = 5 + 2 + 3 = 10.Input: string = [“hi”, “data”, “geeksforgeeks”], chars = “tiadha” Output: 6 Explanation: The strings that can be formed using the characters “tiadha” are “hi” and “data”. Where length of “hi” is 2, length of “data” is 4, the sum of all is 2 + 4 = 6. "
},
{
"code": null,
"e": 26136,
"s": 26047,
"text": "Approach:To solve the problem mentioned above we have to follow the steps given below: "
},
{
"code": null,
"e": 26296,
"s": 26136,
"text": "We can use characters from the given character string that is ‘chars’ while forming a string. We can also reuse the used characters for forming the next string"
},
{
"code": null,
"e": 26438,
"s": 26296,
"text": "Maintain an unordered map with character as a key and the value by keeping track of the frequency of each character from the string of chars."
},
{
"code": null,
"e": 26640,
"s": 26438,
"text": "Every time we scan characters from the list of string we reduce the frequency of character from the unordered map but we have to maintain the copy of the original map so as to check the second string ."
},
{
"code": null,
"e": 26750,
"s": 26640,
"text": "If the key is not present in the map it creates one with default value as zero rather than throwing an error."
},
{
"code": null,
"e": 26803,
"s": 26750,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26807,
"s": 26803,
"text": "C++"
},
{
"code": null,
"e": 26812,
"s": 26807,
"text": "Java"
},
{
"code": null,
"e": 26820,
"s": 26812,
"text": "Python3"
},
{
"code": null,
"e": 26823,
"s": 26820,
"text": "C#"
},
{
"code": null,
"e": 26834,
"s": 26823,
"text": "Javascript"
},
{
"code": "// C++ implementation to find total length// of string composed of given characters// formed from given Array of strings #include <bits/stdc++.h>using namespace std; // Function to count the total lengthint countCharacters( vector<string>& strings, string chars){ int res = 0; // Unordered_map for // keeping frequency of characters unordered_map<char, int> freq; // Calculate the frequency for (int i = 0; i < chars.length(); i++) freq[chars[i]] += 1; // Iterate in the N strings for (auto st : strings) { bool flag = true; // Iterates in the string for (auto c : st) { // Checks if given character of string // string appears in it or not if (!freq) { flag = false; break; } } // Adds the length of string // if all characters are present if (flag) res += st.length(); } // Return the final result return res;} // Driver codeint main(){ vector<string> strings = { \"hi\", \"data\", \"geeksforgeeks\" }; string chars = \"tiadhae\"; cout << countCharacters(strings, chars); return 0;}",
"e": 28032,
"s": 26834,
"text": null
},
{
"code": "// Java implementation to find total length// of string composed of given characters// formed from given Array of stringsimport java.util.*;class GFG { // Function to count the total lengthstatic int countCharacters(List<String> strings, String chars){ int res = 0; // Map for // keeping frequency of characters Map<Character, Integer> freq = new HashMap<>(); // Calculate the frequency for (int i = 0; i < chars.length(); i++) { freq.put(chars.charAt(i), freq.getOrDefault(chars.charAt(i), 0) + 1); } // Iterate in the N strings for (String st : strings) { boolean flag = true; // Iterates in the string for (char c : st.toCharArray()) { // Checks if given character of string // string appears in it or not if (!freq.containsKey(c)) { flag = false; break; } } // Adds the length of string // if all characters are present if (flag) res += st.length(); } // Return the final result return res;} // Driver codepublic static void main(String[] args){ List<String> strings = Arrays.asList(\"hi\", \"data\", \"geeksforgeeks\"); String chars = \"tiadhae\"; System.out.println(countCharacters(strings, chars));}} // This code is contributed by offbeat",
"e": 29471,
"s": 28032,
"text": null
},
{
"code": "# Python3 implementation to find total length# of string composed of given characters# formed from given Array of strings # Function to count the total lengthdef countCharacters(arr, chars): res = 0 # Unordered_map for # keeping frequency of characters freq = dict() # Calculate the frequency for i in range(len(chars)): freq[chars[i]] = freq.get(chars[i], 0)+1 # Iterate in the N strings for st in arr: flag = True # Iterates in the string for c in st: # Checks if given character of string # string appears in it or not if (c not in freq): flag = False break # Adds the length of string # if all characters are present if (flag): res += len(st) # Return the final result return res # Driver codeif __name__ == '__main__': arr =[\"hi\", \"data\", \"geeksforgeeks\"] chars = \"tiadhae\" print(countCharacters(arr, chars)) # This code is contributed by mohit kumar 29",
"e": 30503,
"s": 29471,
"text": null
},
{
"code": "// C# implementation to find total length// of string composed of given characters// formed from given Array of stringsusing System;using System.Collections.Generic;using System.Linq; class GFG{ // Function to count the total lengthstatic int countCharacters(List<string> strings, string chars){ int res = 0; // Dictionary for keeping frequency // of characters Dictionary<char, int> freq = new Dictionary<char, int>(); // Calculate the frequency for(int i = 0; i < chars.Length; i++) { if(freq.ContainsKey(chars[i])) { freq[chars[i]]++; } else { freq.Add(chars[i], freq.GetValueOrDefault( chars[i], 0) + 1); } } // Iterate in the N strings foreach(string st in strings) { bool flag = true; // Iterates in the string foreach (char c in st.ToCharArray()) { // Checks if given character of string // string appears in it or not if (!freq.ContainsKey(c)) { flag = false; break; } } // Adds the length of string // if all characters are present if (flag) res += st.Length; } // Return the final result return res;} // Driver codepublic static void Main(string[] args){ string []tmp = { \"hi\", \"data\", \"geeksforgeeks\" }; List<string> strings = tmp.ToList(); string chars = \"tiadhae\"; Console.Write(countCharacters(strings, chars));}} // This code is contributed by rutvik_56",
"e": 32267,
"s": 30503,
"text": null
},
{
"code": "<script> // Javascript implementation to find total length// of string composed of given characters// formed from given Array of strings // Function to count the total lengthfunction countCharacters( strings, chars){ var res = 0; // Unordered_map for // keeping frequency of characters var freq = new Map(); // Calculate the frequency for (var i = 0; i < chars.length; i++) { if(freq.has(chars[i])) freq.set(chars[i], freq.get(chars[i])+1) else freq.set(chars[i], 1) } // Iterate in the N strings strings.forEach(st => { var flag = true; // Iterates in the string st.split('').forEach(c => { // Checks if given character of string // string appears in it or not if (!freq.has(c)) { flag = false; } }); // Adds the length of string // if all characters are present if (flag) res += st.length; }); // Return the final result return res;} // Driver codevar strings = [\"hi\", \"data\", \"geeksforgeeks\"];var chars = \"tiadhae\";document.write( countCharacters(strings, chars)); // This code is contributed by noob2000.</script> ",
"e": 33527,
"s": 32267,
"text": null
},
{
"code": null,
"e": 33529,
"s": 33527,
"text": "6"
},
{
"code": null,
"e": 33707,
"s": 33531,
"text": "Time Complexity: O(n * m), where n is the length of the char and m is the length of the string.Auxiliary Space Complexity: O(1), as the unordered map will be of size 26 only. "
},
{
"code": null,
"e": 33722,
"s": 33707,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 33730,
"s": 33722,
"text": "offbeat"
},
{
"code": null,
"e": 33740,
"s": 33730,
"text": "rutvik_56"
},
{
"code": null,
"e": 33749,
"s": 33740,
"text": "noob2000"
},
{
"code": null,
"e": 33764,
"s": 33749,
"text": "adnanirshad158"
},
{
"code": null,
"e": 33772,
"s": 33764,
"text": "cpp-map"
},
{
"code": null,
"e": 33790,
"s": 33772,
"text": "cpp-unordered_map"
},
{
"code": null,
"e": 33809,
"s": 33790,
"text": "frequency-counting"
},
{
"code": null,
"e": 33827,
"s": 33809,
"text": "Pattern Searching"
},
{
"code": null,
"e": 33835,
"s": 33827,
"text": "Strings"
},
{
"code": null,
"e": 33843,
"s": 33835,
"text": "Strings"
},
{
"code": null,
"e": 33861,
"s": 33843,
"text": "Pattern Searching"
},
{
"code": null,
"e": 33959,
"s": 33861,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33968,
"s": 33959,
"text": "Comments"
},
{
"code": null,
"e": 33981,
"s": 33968,
"text": "Old Comments"
},
{
"code": null,
"e": 34031,
"s": 33981,
"text": "How to validate HTML tag using Regular Expression"
},
{
"code": null,
"e": 34098,
"s": 34031,
"text": "Build a DFA to accept Binary strings that starts or ends with \"01\""
},
{
"code": null,
"e": 34157,
"s": 34098,
"text": "How to validate pin code of India using Regular Expression"
},
{
"code": null,
"e": 34226,
"s": 34157,
"text": "How to check Aadhaar number is valid or not using Regular Expression"
},
{
"code": null,
"e": 34290,
"s": 34226,
"text": "How to validate time in 24-hour format using Regular Expression"
},
{
"code": null,
"e": 34315,
"s": 34290,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 34361,
"s": 34315,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 34395,
"s": 34361,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 34410,
"s": 34395,
"text": "C++ Data Types"
}
] |
Basic Object Oriented Data Model - GeeksforGeeks
|
10 Dec, 2021
Need of Object Oriented Data Model : To represent the complex real world problems there was a need for a data model that is closely related to real world. Object Oriented Data Model represents the real world problems easily.
Object Oriented Data Model : In Object Oriented Data Model, data and their relationships are contained in a single structure which is referred as object in this data model. In this, real world problems are represented as objects with different attributes. All objects have multiple relationships between them. Basically, it is combination of Object Oriented programming and Relational Database Model as it is clear from the following figure :
Object Oriented Data Model
= Combination of Object Oriented Programming + Relational database model
Components of Object Oriented Data Model :
Basic Object Oriented Data Model
Objects – An object is an abstraction of a real world entity or we can say it is an instance of class. Objects encapsulates data and code into a single unit which provide data abstraction by hiding the implementation details from the user. For example: Instances of student, doctor, engineer in above figure.
Attribute – An attribute describes the properties of object. For example: Object is STUDENT and its attribute are Roll no, Branch, Setmarks() in the Student class.
Methods – Method represents the behavior of an object. Basically, it represents the real-world action. For example: Finding a STUDENT marks in above figure as Setmarks().
Class – A class is a collection of similar objects with shared structure i.e. attributes and behavior i.e. methods. An object is an instance of class. For example: Person, Student, Doctor, Engineer in above figure.
class student
{
char Name[20];
int roll_no;
--
--
public:
void search();
void update();
}
In this example, students refers to class and S1, S2 are the objects of class which can be created in main function.
Inheritance – By using inheritance, new class can inherit the attributes and methods of the old class i.e. base class. For example: as classes Student, Doctor and Engineer are inherited from the base class Person.
Advantages of Object Oriented Data Model :
Codes can be reused due to inheritance.
Easily understandable.
Cost of maintenance can reduced due to reusability of attributes and functions because of inheritance.
Disadvantages of Object Oriented Data Model :
It is not properly developed so not accepted by users easily.
adarshlondhe19
sunnyk23995
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Second Normal Form (2NF)
Introduction of Relational Algebra in DBMS
What is Temporary Table in SQL?
Types of Functional dependencies in DBMS
Difference between Where and Having Clause in SQL
Relational Model in DBMS
Difference between OLAP and OLTP in DBMS
KDD Process in Data Mining
MySQL | Regular expressions (Regexp)
Difference between File System and DBMS
|
[
{
"code": null,
"e": 23937,
"s": 23909,
"text": "\n10 Dec, 2021"
},
{
"code": null,
"e": 24163,
"s": 23937,
"text": "Need of Object Oriented Data Model : To represent the complex real world problems there was a need for a data model that is closely related to real world. Object Oriented Data Model represents the real world problems easily. "
},
{
"code": null,
"e": 24608,
"s": 24163,
"text": "Object Oriented Data Model : In Object Oriented Data Model, data and their relationships are contained in a single structure which is referred as object in this data model. In this, real world problems are represented as objects with different attributes. All objects have multiple relationships between them. Basically, it is combination of Object Oriented programming and Relational Database Model as it is clear from the following figure : "
},
{
"code": null,
"e": 24709,
"s": 24608,
"text": "Object Oriented Data Model \n= Combination of Object Oriented Programming + Relational database model"
},
{
"code": null,
"e": 24753,
"s": 24709,
"text": "Components of Object Oriented Data Model : "
},
{
"code": null,
"e": 24788,
"s": 24755,
"text": "Basic Object Oriented Data Model"
},
{
"code": null,
"e": 25101,
"s": 24790,
"text": "Objects – An object is an abstraction of a real world entity or we can say it is an instance of class. Objects encapsulates data and code into a single unit which provide data abstraction by hiding the implementation details from the user. For example: Instances of student, doctor, engineer in above figure. "
},
{
"code": null,
"e": 25267,
"s": 25101,
"text": "Attribute – An attribute describes the properties of object. For example: Object is STUDENT and its attribute are Roll no, Branch, Setmarks() in the Student class. "
},
{
"code": null,
"e": 25440,
"s": 25267,
"text": "Methods – Method represents the behavior of an object. Basically, it represents the real-world action. For example: Finding a STUDENT marks in above figure as Setmarks(). "
},
{
"code": null,
"e": 25657,
"s": 25440,
"text": "Class – A class is a collection of similar objects with shared structure i.e. attributes and behavior i.e. methods. An object is an instance of class. For example: Person, Student, Doctor, Engineer in above figure. "
},
{
"code": null,
"e": 25775,
"s": 25657,
"text": "class student\n{\n char Name[20];\n int roll_no;\n --\n --\n public:\n void search();\n void update();\n}"
},
{
"code": null,
"e": 25893,
"s": 25775,
"text": "In this example, students refers to class and S1, S2 are the objects of class which can be created in main function. "
},
{
"code": null,
"e": 26109,
"s": 25893,
"text": "Inheritance – By using inheritance, new class can inherit the attributes and methods of the old class i.e. base class. For example: as classes Student, Doctor and Engineer are inherited from the base class Person. "
},
{
"code": null,
"e": 26153,
"s": 26109,
"text": "Advantages of Object Oriented Data Model : "
},
{
"code": null,
"e": 26193,
"s": 26153,
"text": "Codes can be reused due to inheritance."
},
{
"code": null,
"e": 26216,
"s": 26193,
"text": "Easily understandable."
},
{
"code": null,
"e": 26319,
"s": 26216,
"text": "Cost of maintenance can reduced due to reusability of attributes and functions because of inheritance."
},
{
"code": null,
"e": 26366,
"s": 26319,
"text": "Disadvantages of Object Oriented Data Model : "
},
{
"code": null,
"e": 26428,
"s": 26366,
"text": "It is not properly developed so not accepted by users easily."
},
{
"code": null,
"e": 26443,
"s": 26428,
"text": "adarshlondhe19"
},
{
"code": null,
"e": 26455,
"s": 26443,
"text": "sunnyk23995"
},
{
"code": null,
"e": 26460,
"s": 26455,
"text": "DBMS"
},
{
"code": null,
"e": 26465,
"s": 26460,
"text": "DBMS"
},
{
"code": null,
"e": 26563,
"s": 26465,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26572,
"s": 26563,
"text": "Comments"
},
{
"code": null,
"e": 26585,
"s": 26572,
"text": "Old Comments"
},
{
"code": null,
"e": 26610,
"s": 26585,
"text": "Second Normal Form (2NF)"
},
{
"code": null,
"e": 26653,
"s": 26610,
"text": "Introduction of Relational Algebra in DBMS"
},
{
"code": null,
"e": 26685,
"s": 26653,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 26726,
"s": 26685,
"text": "Types of Functional dependencies in DBMS"
},
{
"code": null,
"e": 26776,
"s": 26726,
"text": "Difference between Where and Having Clause in SQL"
},
{
"code": null,
"e": 26801,
"s": 26776,
"text": "Relational Model in DBMS"
},
{
"code": null,
"e": 26842,
"s": 26801,
"text": "Difference between OLAP and OLTP in DBMS"
},
{
"code": null,
"e": 26869,
"s": 26842,
"text": "KDD Process in Data Mining"
},
{
"code": null,
"e": 26906,
"s": 26869,
"text": "MySQL | Regular expressions (Regexp)"
}
] |
Clicking an element using javascript vs actions vs webdriver?
|
We can click on an element using javascript, Actions class and webdriver methods. Selenium can execute commands in Javascript with the help of the execute_script() method.
We have to import org.openqa.selenium.JavascriptExecutor in our code to work with a javascript executor. In order to click an element, first we have to move to that element with mouse movements. We can execute mouse movement with the help of the Actions class in Selenium.
We have to use the moveToElement() method. This method shall perform mouse movement till the middle of the element and then perform click followed by build() and perform() methods. We have to import org.openqa.selenium.interactions.Actions for Action class in our code. For clicking an element with the webdriver method, we can use the click() method.
Code Implementation with click() method.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class ElementClk{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String url = "https://www.tutorialspoint.com/about/about_careers.htm";
driver.get(url);
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
// identify element and click()
WebElement l=driver.findElement(By.linkText("Terms of Use"));
l.click();
System.out.println("Current page title:" + driver.getTitle());
driver.quit();
}
}
Code Implementation with Javascript Executor.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class ElementClkJs{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String url = "https://www.tutorialspoint.com/about/about_careers.htm";
driver.get(url);
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
// identify element
WebElement l=driver.findElement(By.linkText("Terms of Use"));
// click with Javascript Executor
JavascriptExecutor j = (JavascriptExecutor) driver;
j.executeScript("arguments[0].click();", l);
System.out.println("Current page title:" + driver.getTitle());
driver.quit();
}
}
Code Implementation with Actions class.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions
public class ElementClkActs{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String url = "https://www.tutorialspoint.com/about/about_careers.htm";
driver.get(url);
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
// identify element
WebElement l=driver.findElement(By.linkText("Terms of Use"));
// Actions class with moveToElement() and click()
Actions a = new Actions(driver);
a.moveToElement(l).click();
a.build().perform();
System.out.println("Current page title:" + driver.getTitle());
driver.quit();
}
}
|
[
{
"code": null,
"e": 1234,
"s": 1062,
"text": "We can click on an element using javascript, Actions class and webdriver methods. Selenium can execute commands in Javascript with the help of the execute_script() method."
},
{
"code": null,
"e": 1507,
"s": 1234,
"text": "We have to import org.openqa.selenium.JavascriptExecutor in our code to work with a javascript executor. In order to click an element, first we have to move to that element with mouse movements. We can execute mouse movement with the help of the Actions class in Selenium."
},
{
"code": null,
"e": 1859,
"s": 1507,
"text": "We have to use the moveToElement() method. This method shall perform mouse movement till the middle of the element and then perform click followed by build() and perform() methods. We have to import org.openqa.selenium.interactions.Actions for Action class in our code. For clicking an element with the webdriver method, we can use the click() method."
},
{
"code": null,
"e": 1900,
"s": 1859,
"text": "Code Implementation with click() method."
},
{
"code": null,
"e": 2706,
"s": 1900,
"text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\npublic class ElementClk{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n String url = \"https://www.tutorialspoint.com/about/about_careers.htm\";\n driver.get(url);\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n // identify element and click()\n WebElement l=driver.findElement(By.linkText(\"Terms of Use\"));\n l.click();\n System.out.println(\"Current page title:\" + driver.getTitle());\n driver.quit();\n }\n}"
},
{
"code": null,
"e": 2752,
"s": 2706,
"text": "Code Implementation with Javascript Executor."
},
{
"code": null,
"e": 3727,
"s": 2752,
"text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\nimport org.openqa.selenium.JavascriptExecutor;\npublic class ElementClkJs{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n String url = \"https://www.tutorialspoint.com/about/about_careers.htm\";\n driver.get(url);\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n // identify element\n WebElement l=driver.findElement(By.linkText(\"Terms of Use\"));\n // click with Javascript Executor\n JavascriptExecutor j = (JavascriptExecutor) driver;\n j.executeScript(\"arguments[0].click();\", l);\n System.out.println(\"Current page title:\" + driver.getTitle());\n driver.quit();\n }\n}"
},
{
"code": null,
"e": 3767,
"s": 3727,
"text": "Code Implementation with Actions class."
},
{
"code": null,
"e": 4806,
"s": 3767,
"text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\nimport org.openqa.selenium.interactions.Action;\nimport org.openqa.selenium.interactions.Actions\npublic class ElementClkActs{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n String url = \"https://www.tutorialspoint.com/about/about_careers.htm\";\n driver.get(url);\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n // identify element\n WebElement l=driver.findElement(By.linkText(\"Terms of Use\"));\n // Actions class with moveToElement() and click()\n Actions a = new Actions(driver);\n a.moveToElement(l).click();\n a.build().perform();\n System.out.println(\"Current page title:\" + driver.getTitle());\n driver.quit();\n }\n}"
}
] |
Find the element at given index | Practice | GeeksforGeeks
|
Given an array Arr[] of N elements. Perform K right circular rotations on given ranges [L...R]. After performing these rotations, we need to find element at a given index X.
Example 1:
Input:
N = 5, X = 1, K = 2
Arr[] = {1, 2, 3, 4, 5}
Ranges[][] = {{0, 2}, {0, 3}}
Output: 3
Explanation: Rotating the elements in range
0-2 and 0-3, we have array as 4 3 1 2 5.
Element at first position is 3.
Example 2:
Input:
N = 3, X = 2, K = 1
Arr[] = {1, 2, 3}
Ranges[][] = {{0, 1}}
Output: 3
Your Task:
You don't need to read input or print anything. Your task is to complete the function findElement() which takes the array of integers arr, n, x, ranges and k as parameters and returns an integer denoting the answer.
Expected Time Complexity: O(K)
Expected Auxiliary Space: O(1)
Constraints:
2 <= N <= 105
1 <= Arr[i] <= 105
1 <= K <= 105
X < N
0 <= L <= R
0
AKSHAT AGGARWAL9 months ago
AKSHAT AGGARWAL
I have earned 110 geek bits and I want to redeem them.How can I do that please help!
0
abhikarsh gupta1 year ago
abhikarsh gupta
Problem statement is kind of confusing :- " Perform K right circular rotations on given ranges [L...R].".
Here K is the size of ranges array. what I initially thought was, for each range, we have to perform K rotations.. but that is not the case.
Had to see the hints as the brute force that i tried( rotating the array for all ranges gave TLE.
Anyhow, here is the code :-
int findElement(int arr[], int n, int x, int ranges[][2], int k) { for(int i = k - 1; i >= 0; i--) { if(x > ranges[i][0] && x <= ranges[i][1]) x--; else if(x == ranges[i][0]) x = ranges[i][1]; } return arr[x]; }
0
vishal jat2 years ago
vishal jat
simple c++ solution O(k) time complexity....using STLhttps://ide.geeksforgeeks.o...
0
Shivam Gohri2 years ago
Shivam Gohri
0.41 c++
#include <iostream>#include <vector>
using namespace std;
int main() {
int t;cin>> t;
while(t--){
int n, x, k; cin>> n >> x >> k;
vector<int> v(n,0);
for(int i=0; i<n; i++)="" cin="">> v[i];
int temp = k;
while(temp--){
int start, end; cin>> start >>end;
int x = v[end]; v.erase(v.begin()+end); v.insert(v.begin()+start, x);
}
cout<< v[x] <<endl; }="" return="" 0;="" }="">
-1
Bicky2 years ago
Bicky
simple cpp soln 0.09 s
https://ide.geeksforgeeks.o...
0
Shivanshu Tiwari2 years ago
Shivanshu Tiwari
Hint-idea is that you have to think in reverse direction.only consider given range and change accordingly.if the index is in given range decrement it by 1.only breakpoint is if index==left then convert it in to right;you can check my code here .https://ide.geeksforgeeks.org/B2BH4...
0
Astha Gupta2 years ago
Astha Gupta
@quandray:disqus can u help me with this? https://ide.geeksforgeeks.o...
0
Thomas White
This comment was deleted.
+1
Thomas White4 years ago
Thomas White
need to clarify this description. the rotation is occuring in the "sub arrays" given by the ranges NOT rotating the range within the entire array. For example,[1 2 3 4 5 6 7] given the range {0 2} means [1 2 3] becomes [3 1 2] and the array is then [3 1 2 4 5 6 7].
0
Astha Jindal4 years ago
Astha Jindal
How the test case is working?
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": 412,
"s": 238,
"text": "Given an array Arr[] of N elements. Perform K right circular rotations on given ranges [L...R]. After performing these rotations, we need to find element at a given index X."
},
{
"code": null,
"e": 423,
"s": 412,
"text": "Example 1:"
},
{
"code": null,
"e": 634,
"s": 423,
"text": "Input:\nN = 5, X = 1, K = 2\nArr[] = {1, 2, 3, 4, 5}\nRanges[][] = {{0, 2}, {0, 3}}\nOutput: 3\nExplanation: Rotating the elements in range \n0-2 and 0-3, we have array as 4 3 1 2 5. \nElement at first position is 3.\n"
},
{
"code": null,
"e": 645,
"s": 634,
"text": "Example 2:"
},
{
"code": null,
"e": 723,
"s": 645,
"text": "Input:\nN = 3, X = 2, K = 1\nArr[] = {1, 2, 3}\nRanges[][] = {{0, 1}}\nOutput: 3\n"
},
{
"code": null,
"e": 950,
"s": 723,
"text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function findElement() which takes the array of integers arr, n, x, ranges and k as parameters and returns an integer denoting the answer."
},
{
"code": null,
"e": 1012,
"s": 950,
"text": "Expected Time Complexity: O(K)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1090,
"s": 1012,
"text": "Constraints:\n2 <= N <= 105\n1 <= Arr[i] <= 105\n1 <= K <= 105\nX < N\n0 <= L <= R"
},
{
"code": null,
"e": 1094,
"s": 1092,
"text": "0"
},
{
"code": null,
"e": 1122,
"s": 1094,
"text": "AKSHAT AGGARWAL9 months ago"
},
{
"code": null,
"e": 1138,
"s": 1122,
"text": "AKSHAT AGGARWAL"
},
{
"code": null,
"e": 1223,
"s": 1138,
"text": "I have earned 110 geek bits and I want to redeem them.How can I do that please help!"
},
{
"code": null,
"e": 1225,
"s": 1223,
"text": "0"
},
{
"code": null,
"e": 1251,
"s": 1225,
"text": "abhikarsh gupta1 year ago"
},
{
"code": null,
"e": 1267,
"s": 1251,
"text": "abhikarsh gupta"
},
{
"code": null,
"e": 1374,
"s": 1267,
"text": "Problem statement is kind of confusing :- \" Perform K right circular rotations on given ranges [L...R].\"."
},
{
"code": null,
"e": 1515,
"s": 1374,
"text": "Here K is the size of ranges array. what I initially thought was, for each range, we have to perform K rotations.. but that is not the case."
},
{
"code": null,
"e": 1613,
"s": 1515,
"text": "Had to see the hints as the brute force that i tried( rotating the array for all ranges gave TLE."
},
{
"code": null,
"e": 1641,
"s": 1613,
"text": "Anyhow, here is the code :-"
},
{
"code": null,
"e": 1936,
"s": 1641,
"text": "int findElement(int arr[], int n, int x, int ranges[][2], int k) { for(int i = k - 1; i >= 0; i--) { if(x > ranges[i][0] && x <= ranges[i][1]) x--; else if(x == ranges[i][0]) x = ranges[i][1]; } return arr[x]; }"
},
{
"code": null,
"e": 1938,
"s": 1936,
"text": "0"
},
{
"code": null,
"e": 1960,
"s": 1938,
"text": "vishal jat2 years ago"
},
{
"code": null,
"e": 1971,
"s": 1960,
"text": "vishal jat"
},
{
"code": null,
"e": 2055,
"s": 1971,
"text": "simple c++ solution O(k) time complexity....using STLhttps://ide.geeksforgeeks.o..."
},
{
"code": null,
"e": 2057,
"s": 2055,
"text": "0"
},
{
"code": null,
"e": 2081,
"s": 2057,
"text": "Shivam Gohri2 years ago"
},
{
"code": null,
"e": 2094,
"s": 2081,
"text": "Shivam Gohri"
},
{
"code": null,
"e": 2103,
"s": 2094,
"text": "0.41 c++"
},
{
"code": null,
"e": 2140,
"s": 2103,
"text": "#include <iostream>#include <vector>"
},
{
"code": null,
"e": 2161,
"s": 2140,
"text": "using namespace std;"
},
{
"code": null,
"e": 2174,
"s": 2161,
"text": "int main() {"
},
{
"code": null,
"e": 2189,
"s": 2174,
"text": "int t;cin>> t;"
},
{
"code": null,
"e": 2201,
"s": 2189,
"text": "while(t--){"
},
{
"code": null,
"e": 2240,
"s": 2201,
"text": " int n, x, k; cin>> n >> x >> k;"
},
{
"code": null,
"e": 2264,
"s": 2240,
"text": " vector<int> v(n,0);"
},
{
"code": null,
"e": 2309,
"s": 2264,
"text": " for(int i=0; i<n; i++)=\"\" cin=\"\">> v[i];"
},
{
"code": null,
"e": 2331,
"s": 2309,
"text": " int temp = k;"
},
{
"code": null,
"e": 2354,
"s": 2331,
"text": " while(temp--){"
},
{
"code": null,
"e": 2412,
"s": 2354,
"text": " int start, end; cin>> start >>end;"
},
{
"code": null,
"e": 2516,
"s": 2412,
"text": " int x = v[end]; v.erase(v.begin()+end); v.insert(v.begin()+start, x);"
},
{
"code": null,
"e": 2526,
"s": 2516,
"text": " }"
},
{
"code": null,
"e": 2581,
"s": 2526,
"text": " cout<< v[x] <<endl; }=\"\" return=\"\" 0;=\"\" }=\"\">"
},
{
"code": null,
"e": 2584,
"s": 2581,
"text": "-1"
},
{
"code": null,
"e": 2601,
"s": 2584,
"text": "Bicky2 years ago"
},
{
"code": null,
"e": 2607,
"s": 2601,
"text": "Bicky"
},
{
"code": null,
"e": 2630,
"s": 2607,
"text": "simple cpp soln 0.09 s"
},
{
"code": null,
"e": 2661,
"s": 2630,
"text": "https://ide.geeksforgeeks.o..."
},
{
"code": null,
"e": 2663,
"s": 2661,
"text": "0"
},
{
"code": null,
"e": 2691,
"s": 2663,
"text": "Shivanshu Tiwari2 years ago"
},
{
"code": null,
"e": 2708,
"s": 2691,
"text": "Shivanshu Tiwari"
},
{
"code": null,
"e": 2992,
"s": 2708,
"text": "Hint-idea is that you have to think in reverse direction.only consider given range and change accordingly.if the index is in given range decrement it by 1.only breakpoint is if index==left then convert it in to right;you can check my code here .https://ide.geeksforgeeks.org/B2BH4..."
},
{
"code": null,
"e": 2994,
"s": 2992,
"text": "0"
},
{
"code": null,
"e": 3017,
"s": 2994,
"text": "Astha Gupta2 years ago"
},
{
"code": null,
"e": 3029,
"s": 3017,
"text": "Astha Gupta"
},
{
"code": null,
"e": 3102,
"s": 3029,
"text": "@quandray:disqus can u help me with this? https://ide.geeksforgeeks.o..."
},
{
"code": null,
"e": 3104,
"s": 3102,
"text": "0"
},
{
"code": null,
"e": 3117,
"s": 3104,
"text": "Thomas White"
},
{
"code": null,
"e": 3143,
"s": 3117,
"text": "This comment was deleted."
},
{
"code": null,
"e": 3146,
"s": 3143,
"text": "+1"
},
{
"code": null,
"e": 3170,
"s": 3146,
"text": "Thomas White4 years ago"
},
{
"code": null,
"e": 3183,
"s": 3170,
"text": "Thomas White"
},
{
"code": null,
"e": 3451,
"s": 3183,
"text": "need to clarify this description. the rotation is occuring in the \"sub arrays\" given by the ranges NOT rotating the range within the entire array. For example,[1 2 3 4 5 6 7] given the range {0 2} means [1 2 3] becomes [3 1 2] and the array is then [3 1 2 4 5 6 7]."
},
{
"code": null,
"e": 3453,
"s": 3451,
"text": "0"
},
{
"code": null,
"e": 3477,
"s": 3453,
"text": "Astha Jindal4 years ago"
},
{
"code": null,
"e": 3490,
"s": 3477,
"text": "Astha Jindal"
},
{
"code": null,
"e": 3522,
"s": 3490,
"text": "How the test case is working?"
},
{
"code": null,
"e": 3668,
"s": 3522,
"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": 3704,
"s": 3668,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 3714,
"s": 3704,
"text": "\nProblem\n"
},
{
"code": null,
"e": 3724,
"s": 3714,
"text": "\nContest\n"
},
{
"code": null,
"e": 3787,
"s": 3724,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 3935,
"s": 3787,
"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": 4143,
"s": 3935,
"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": 4249,
"s": 4143,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Easy Text-to-Speech with Python. Text to Speech | by Dhilip Subramanian | Towards Data Science
|
Text-to-speech (TTS) technology reads aloud digital text. It can take words on computers, smartphones, tablets and convert them into audio. Also, all kinds of text files can be read aloud, including Word, pages document, online web pages can be read aloud. TTS can help kids who struggle with reading. Many tools and apps are available to convert text into speech.
Python comes with a lot of handy and easily accessible libraries and we’re going to look at how we can deliver text-to-speech with Python in this article.
Different API’s are available in Python in order to convert text to speech. One of Such API’s is the Google Text to Speech commonly known as the gTTS API. It is very easy to use the library which converts the text entered, into an audio file which can be saved as a mp3 file. It supports several languages and the speech can be delivered in any one of the two available audio speeds, fast or slow. More details can be found here
Import gTTS library and “os” module in order to play the converted audio
from gtts import gTTS import os
Creating a text that we want to convert into audio
text = “Global warming is the long-term rise in the average temperature of the Earth’s climate system”
gTTS supports multiple languages. Please refer to the documentation here. Selected ‘en’ -> English and stored in the language variable
language = ‘en’
Creating an object called speech and passing the text and language to the engine. Marked slow = False which tells the module that the converted audio should have a high speed.
speech = gTTS(text = text, lang = language, slow = False)
Saving the converted audio in a mp3 file named called ‘text.mp3’
speech.save(“text.mp3”)
Playing the converted file, using Windows command ‘start’ followed by the name of the mp3 file.
os.system(“start text.mp3”)
The output of the above program saved as text.mp3 file. Mp3 file should be a voice saying, 'Global warming is the long-term rise in the average temperature of the Earth’s climate system'
Here, covert the text file into speech. Reading the text file and pass to gTTS module
Import gTTS and os library
from gtts import gTTS import os
Reading the text file and store into object called text. My file name is “draft.txt”
file = open("draft.txt", "r").read().replace("\n", " ")
Choosing language English
language = ‘en’
Passing the text file into gTTS module and store into speech
speech = gTTS(text = str(file), lang = language, slow = False)
Saving the converted audio in a mp3 file named called ‘voice.mp3’
speech.save("voice.mp3")
Playing the mp3 file
os.system("start voice.mp3")
Converted draft.txt file into voice.mp3
Draft.txt file saved as a voice.mp3 file.Play the Mp3 file to listen the text presented in the draft.txt file
GTTS is an easy tool to convert text to voice, but it requires an internet connection to operate because it depends entirely on Google to get the audio data.
Thanks for reading. Keep learning and stay tuned for more!
You can also read this article on KDnuggets.
|
[
{
"code": null,
"e": 537,
"s": 172,
"text": "Text-to-speech (TTS) technology reads aloud digital text. It can take words on computers, smartphones, tablets and convert them into audio. Also, all kinds of text files can be read aloud, including Word, pages document, online web pages can be read aloud. TTS can help kids who struggle with reading. Many tools and apps are available to convert text into speech."
},
{
"code": null,
"e": 692,
"s": 537,
"text": "Python comes with a lot of handy and easily accessible libraries and we’re going to look at how we can deliver text-to-speech with Python in this article."
},
{
"code": null,
"e": 1121,
"s": 692,
"text": "Different API’s are available in Python in order to convert text to speech. One of Such API’s is the Google Text to Speech commonly known as the gTTS API. It is very easy to use the library which converts the text entered, into an audio file which can be saved as a mp3 file. It supports several languages and the speech can be delivered in any one of the two available audio speeds, fast or slow. More details can be found here"
},
{
"code": null,
"e": 1194,
"s": 1121,
"text": "Import gTTS library and “os” module in order to play the converted audio"
},
{
"code": null,
"e": 1226,
"s": 1194,
"text": "from gtts import gTTS import os"
},
{
"code": null,
"e": 1277,
"s": 1226,
"text": "Creating a text that we want to convert into audio"
},
{
"code": null,
"e": 1380,
"s": 1277,
"text": "text = “Global warming is the long-term rise in the average temperature of the Earth’s climate system”"
},
{
"code": null,
"e": 1515,
"s": 1380,
"text": "gTTS supports multiple languages. Please refer to the documentation here. Selected ‘en’ -> English and stored in the language variable"
},
{
"code": null,
"e": 1531,
"s": 1515,
"text": "language = ‘en’"
},
{
"code": null,
"e": 1707,
"s": 1531,
"text": "Creating an object called speech and passing the text and language to the engine. Marked slow = False which tells the module that the converted audio should have a high speed."
},
{
"code": null,
"e": 1765,
"s": 1707,
"text": "speech = gTTS(text = text, lang = language, slow = False)"
},
{
"code": null,
"e": 1830,
"s": 1765,
"text": "Saving the converted audio in a mp3 file named called ‘text.mp3’"
},
{
"code": null,
"e": 1854,
"s": 1830,
"text": "speech.save(“text.mp3”)"
},
{
"code": null,
"e": 1950,
"s": 1854,
"text": "Playing the converted file, using Windows command ‘start’ followed by the name of the mp3 file."
},
{
"code": null,
"e": 1978,
"s": 1950,
"text": "os.system(“start text.mp3”)"
},
{
"code": null,
"e": 2165,
"s": 1978,
"text": "The output of the above program saved as text.mp3 file. Mp3 file should be a voice saying, 'Global warming is the long-term rise in the average temperature of the Earth’s climate system'"
},
{
"code": null,
"e": 2251,
"s": 2165,
"text": "Here, covert the text file into speech. Reading the text file and pass to gTTS module"
},
{
"code": null,
"e": 2278,
"s": 2251,
"text": "Import gTTS and os library"
},
{
"code": null,
"e": 2310,
"s": 2278,
"text": "from gtts import gTTS import os"
},
{
"code": null,
"e": 2395,
"s": 2310,
"text": "Reading the text file and store into object called text. My file name is “draft.txt”"
},
{
"code": null,
"e": 2451,
"s": 2395,
"text": "file = open(\"draft.txt\", \"r\").read().replace(\"\\n\", \" \")"
},
{
"code": null,
"e": 2477,
"s": 2451,
"text": "Choosing language English"
},
{
"code": null,
"e": 2493,
"s": 2477,
"text": "language = ‘en’"
},
{
"code": null,
"e": 2554,
"s": 2493,
"text": "Passing the text file into gTTS module and store into speech"
},
{
"code": null,
"e": 2617,
"s": 2554,
"text": "speech = gTTS(text = str(file), lang = language, slow = False)"
},
{
"code": null,
"e": 2683,
"s": 2617,
"text": "Saving the converted audio in a mp3 file named called ‘voice.mp3’"
},
{
"code": null,
"e": 2708,
"s": 2683,
"text": "speech.save(\"voice.mp3\")"
},
{
"code": null,
"e": 2729,
"s": 2708,
"text": "Playing the mp3 file"
},
{
"code": null,
"e": 2758,
"s": 2729,
"text": "os.system(\"start voice.mp3\")"
},
{
"code": null,
"e": 2798,
"s": 2758,
"text": "Converted draft.txt file into voice.mp3"
},
{
"code": null,
"e": 2908,
"s": 2798,
"text": "Draft.txt file saved as a voice.mp3 file.Play the Mp3 file to listen the text presented in the draft.txt file"
},
{
"code": null,
"e": 3066,
"s": 2908,
"text": "GTTS is an easy tool to convert text to voice, but it requires an internet connection to operate because it depends entirely on Google to get the audio data."
},
{
"code": null,
"e": 3125,
"s": 3066,
"text": "Thanks for reading. Keep learning and stay tuned for more!"
}
] |
Understanding Word Embeddings from scratch | LSTM model | | by Manik Soni | Towards Data Science
|
Yo reader! I am Manik. What’s up?.
Hope you’re doing great and working hard for your goals. If not, it’s never late. Start now, at this very moment.
With this piece of information, you’ll walk away with a clear explanation on Sequence and Text processing for Deep Neural Networks which includes:
What’s one-hot Encoding?OneHot Encoding with keras.What are word embeddings and their advantage over One-Hot encoding?What are word embeddings trying to say?A complete example of converting raw text to word embeddings in keras with an LSTM and GRU layer.
What’s one-hot Encoding?
OneHot Encoding with keras.
What are word embeddings and their advantage over One-Hot encoding?
What are word embeddings trying to say?
A complete example of converting raw text to word embeddings in keras with an LSTM and GRU layer.
if you want to learn about LSTMs, you can go here
binarykeys.in
“Yours and my ancestors had run after a mastodon or wild boar, like an Olympic sprinter, with a spear in hand covering themselves with leaves and tiger skin, for their breakfast” — History
The above sentence is in textual form and for neural networks to understand and ingest it, we need to convert it into some numeric form. Two ways of doing that are One-hot encoding and the other is Word embeddings.
This is a way of representing each word by an array of 0s and 1. In the array, only one index has ‘1’ present and rest all are 0s.
Example: The following vector represents only one word, in a sentence with 6 unique words.
Let’s find all the unique words in our sentence.
array(['Yours', 'a', 'after', 'an', 'ancestors', 'and', 'boar,', 'breakfast', 'covering', 'for', 'had', 'hand', 'in','leaves', 'like', 'mastodons', 'mine', 'olympic', 'or', 'run', 'skin,', 'spear', 'sprinter,', 'their', 'themselves', 'tiger', 'wild', 'with'], dtype='<U10')shape: (28,)
Now, give each of them an index i.e. create a word_index where each word has an index attached to it in a dictionary.
You might have observed above in the code that 0 is not assigned to any word. It’s a reserved index in Keras(We’ll get here later).
{'Yours': 1, 'a': 2, 'after': 3, 'an': 4, 'ancestors': 5, 'and': 6, 'boar,': 7, 'breakfast': 8, 'covering': 9, 'for': 10, 'had': 11, 'hand': 12, 'in': 13, 'leaves': 14, 'like': 15, 'mastodons': 16, 'mine': 17, 'olympic': 18, 'or': 19, 'run': 20, 'skin,': 21, 'spear': 22, 'sprinter,': 23, 'their': 24, 'themselves': 25, 'tiger': 26, 'wild': 27, 'with': 28}
Now, let’s create one-hot encoding for them.
Example output: This is how “yours” is represented.
Yours [0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
text_to_matrix is the method used to return one-hot encoding.
You can see that, to represent a word, we are actually wasting a lot of memory to just set 0s(sparse matrix). These one-hot encodings also doesn’t reflect any relation between similar words. They are just representation of some word with ‘1’. Two similar words such as “accurate” and “exact” might be at very different positions in one-hot encodings.
What if we can represent a word with less space and have a meaning of its representation with which we can learn something.
Word embeddings also represent words in an array, not in the form of 0s and 1s but continuous vectors.
They can represent any word in few dimensions, mostly based on the number of unique words in our text.
They are dense, low dimensional vectors
Not hardcoded but are “learned” through data.
Geometric relationship between words in a word embeddings can represent semantic relationship between words. Words closer to each other have a strong relation compared to words away from each other.
Vectors/words closer to each other means the cosine distance or geometric distance between them is less compared to others.
There could be vector “male to female” which represents the relation between a word and its feminine. That vector may help us in predicting “king” when “he” is used and “Queen” when she is used in the sentence.
Below is a single row of embedding matrix representing the word ‘the’ in 100 dimensions from a text having 100K unique words.
Such matrices are learned from data and can represent any text with millions of words in 100, 200, 1000 or more dimensions (The same would require 1MM dimensions if one-hot encoding is used).
Let’s see how to create embeddings of our text in keras with a recurrent neural network.
Load text data in array.Process the data.Convert the text to sequence and using the tokenizer and pad them with keras.preprocessing.text.pad_sequences method.Initialise a model with Embedding layer of dimensions (max_words, representation_dimensions, input_size))
Load text data in array.
Process the data.
Convert the text to sequence and using the tokenizer and pad them with keras.preprocessing.text.pad_sequences method.
Initialise a model with Embedding layer of dimensions (max_words, representation_dimensions, input_size))
max_words: It is the no. of unique words in your data
representation_dimension: It is the no. of dimensions in which you want to represent a word. Usually, it is number of (unique words)^(1/4)
input_size: size of your padded sequence(maxlen)
5 . Run the model
Let’s follow the above steps for IMDB raw data. All the code below is present in my Kaggle notebook.
loading the text data with pandas.
Marking 1 for positive movie review and 0 for negative review.
Creating an instance of keras’s Tokenizer class and padding the sequence to ‘maxlen’.
A simple recurrent neural network with embedding as first layer.
All the above code is present here.
If this piece of writing helped you in any way, do share your knowledge with others!
Thanks for reaching till here! Great!
|
[
{
"code": null,
"e": 207,
"s": 172,
"text": "Yo reader! I am Manik. What’s up?."
},
{
"code": null,
"e": 321,
"s": 207,
"text": "Hope you’re doing great and working hard for your goals. If not, it’s never late. Start now, at this very moment."
},
{
"code": null,
"e": 468,
"s": 321,
"text": "With this piece of information, you’ll walk away with a clear explanation on Sequence and Text processing for Deep Neural Networks which includes:"
},
{
"code": null,
"e": 723,
"s": 468,
"text": "What’s one-hot Encoding?OneHot Encoding with keras.What are word embeddings and their advantage over One-Hot encoding?What are word embeddings trying to say?A complete example of converting raw text to word embeddings in keras with an LSTM and GRU layer."
},
{
"code": null,
"e": 748,
"s": 723,
"text": "What’s one-hot Encoding?"
},
{
"code": null,
"e": 776,
"s": 748,
"text": "OneHot Encoding with keras."
},
{
"code": null,
"e": 844,
"s": 776,
"text": "What are word embeddings and their advantage over One-Hot encoding?"
},
{
"code": null,
"e": 884,
"s": 844,
"text": "What are word embeddings trying to say?"
},
{
"code": null,
"e": 982,
"s": 884,
"text": "A complete example of converting raw text to word embeddings in keras with an LSTM and GRU layer."
},
{
"code": null,
"e": 1032,
"s": 982,
"text": "if you want to learn about LSTMs, you can go here"
},
{
"code": null,
"e": 1046,
"s": 1032,
"text": "binarykeys.in"
},
{
"code": null,
"e": 1235,
"s": 1046,
"text": "“Yours and my ancestors had run after a mastodon or wild boar, like an Olympic sprinter, with a spear in hand covering themselves with leaves and tiger skin, for their breakfast” — History"
},
{
"code": null,
"e": 1450,
"s": 1235,
"text": "The above sentence is in textual form and for neural networks to understand and ingest it, we need to convert it into some numeric form. Two ways of doing that are One-hot encoding and the other is Word embeddings."
},
{
"code": null,
"e": 1581,
"s": 1450,
"text": "This is a way of representing each word by an array of 0s and 1. In the array, only one index has ‘1’ present and rest all are 0s."
},
{
"code": null,
"e": 1672,
"s": 1581,
"text": "Example: The following vector represents only one word, in a sentence with 6 unique words."
},
{
"code": null,
"e": 1721,
"s": 1672,
"text": "Let’s find all the unique words in our sentence."
},
{
"code": null,
"e": 2031,
"s": 1721,
"text": "array(['Yours', 'a', 'after', 'an', 'ancestors', 'and', 'boar,', 'breakfast', 'covering', 'for', 'had', 'hand', 'in','leaves', 'like', 'mastodons', 'mine', 'olympic', 'or', 'run', 'skin,', 'spear', 'sprinter,', 'their', 'themselves', 'tiger', 'wild', 'with'], dtype='<U10')shape: (28,)"
},
{
"code": null,
"e": 2149,
"s": 2031,
"text": "Now, give each of them an index i.e. create a word_index where each word has an index attached to it in a dictionary."
},
{
"code": null,
"e": 2281,
"s": 2149,
"text": "You might have observed above in the code that 0 is not assigned to any word. It’s a reserved index in Keras(We’ll get here later)."
},
{
"code": null,
"e": 2638,
"s": 2281,
"text": "{'Yours': 1, 'a': 2, 'after': 3, 'an': 4, 'ancestors': 5, 'and': 6, 'boar,': 7, 'breakfast': 8, 'covering': 9, 'for': 10, 'had': 11, 'hand': 12, 'in': 13, 'leaves': 14, 'like': 15, 'mastodons': 16, 'mine': 17, 'olympic': 18, 'or': 19, 'run': 20, 'skin,': 21, 'spear': 22, 'sprinter,': 23, 'their': 24, 'themselves': 25, 'tiger': 26, 'wild': 27, 'with': 28}"
},
{
"code": null,
"e": 2683,
"s": 2638,
"text": "Now, let’s create one-hot encoding for them."
},
{
"code": null,
"e": 2735,
"s": 2683,
"text": "Example output: This is how “yours” is represented."
},
{
"code": null,
"e": 2827,
"s": 2735,
"text": "Yours [0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]"
},
{
"code": null,
"e": 2889,
"s": 2827,
"text": "text_to_matrix is the method used to return one-hot encoding."
},
{
"code": null,
"e": 3240,
"s": 2889,
"text": "You can see that, to represent a word, we are actually wasting a lot of memory to just set 0s(sparse matrix). These one-hot encodings also doesn’t reflect any relation between similar words. They are just representation of some word with ‘1’. Two similar words such as “accurate” and “exact” might be at very different positions in one-hot encodings."
},
{
"code": null,
"e": 3364,
"s": 3240,
"text": "What if we can represent a word with less space and have a meaning of its representation with which we can learn something."
},
{
"code": null,
"e": 3467,
"s": 3364,
"text": "Word embeddings also represent words in an array, not in the form of 0s and 1s but continuous vectors."
},
{
"code": null,
"e": 3570,
"s": 3467,
"text": "They can represent any word in few dimensions, mostly based on the number of unique words in our text."
},
{
"code": null,
"e": 3610,
"s": 3570,
"text": "They are dense, low dimensional vectors"
},
{
"code": null,
"e": 3656,
"s": 3610,
"text": "Not hardcoded but are “learned” through data."
},
{
"code": null,
"e": 3855,
"s": 3656,
"text": "Geometric relationship between words in a word embeddings can represent semantic relationship between words. Words closer to each other have a strong relation compared to words away from each other."
},
{
"code": null,
"e": 3979,
"s": 3855,
"text": "Vectors/words closer to each other means the cosine distance or geometric distance between them is less compared to others."
},
{
"code": null,
"e": 4190,
"s": 3979,
"text": "There could be vector “male to female” which represents the relation between a word and its feminine. That vector may help us in predicting “king” when “he” is used and “Queen” when she is used in the sentence."
},
{
"code": null,
"e": 4316,
"s": 4190,
"text": "Below is a single row of embedding matrix representing the word ‘the’ in 100 dimensions from a text having 100K unique words."
},
{
"code": null,
"e": 4508,
"s": 4316,
"text": "Such matrices are learned from data and can represent any text with millions of words in 100, 200, 1000 or more dimensions (The same would require 1MM dimensions if one-hot encoding is used)."
},
{
"code": null,
"e": 4597,
"s": 4508,
"text": "Let’s see how to create embeddings of our text in keras with a recurrent neural network."
},
{
"code": null,
"e": 4861,
"s": 4597,
"text": "Load text data in array.Process the data.Convert the text to sequence and using the tokenizer and pad them with keras.preprocessing.text.pad_sequences method.Initialise a model with Embedding layer of dimensions (max_words, representation_dimensions, input_size))"
},
{
"code": null,
"e": 4886,
"s": 4861,
"text": "Load text data in array."
},
{
"code": null,
"e": 4904,
"s": 4886,
"text": "Process the data."
},
{
"code": null,
"e": 5022,
"s": 4904,
"text": "Convert the text to sequence and using the tokenizer and pad them with keras.preprocessing.text.pad_sequences method."
},
{
"code": null,
"e": 5128,
"s": 5022,
"text": "Initialise a model with Embedding layer of dimensions (max_words, representation_dimensions, input_size))"
},
{
"code": null,
"e": 5182,
"s": 5128,
"text": "max_words: It is the no. of unique words in your data"
},
{
"code": null,
"e": 5321,
"s": 5182,
"text": "representation_dimension: It is the no. of dimensions in which you want to represent a word. Usually, it is number of (unique words)^(1/4)"
},
{
"code": null,
"e": 5370,
"s": 5321,
"text": "input_size: size of your padded sequence(maxlen)"
},
{
"code": null,
"e": 5388,
"s": 5370,
"text": "5 . Run the model"
},
{
"code": null,
"e": 5489,
"s": 5388,
"text": "Let’s follow the above steps for IMDB raw data. All the code below is present in my Kaggle notebook."
},
{
"code": null,
"e": 5524,
"s": 5489,
"text": "loading the text data with pandas."
},
{
"code": null,
"e": 5587,
"s": 5524,
"text": "Marking 1 for positive movie review and 0 for negative review."
},
{
"code": null,
"e": 5673,
"s": 5587,
"text": "Creating an instance of keras’s Tokenizer class and padding the sequence to ‘maxlen’."
},
{
"code": null,
"e": 5738,
"s": 5673,
"text": "A simple recurrent neural network with embedding as first layer."
},
{
"code": null,
"e": 5774,
"s": 5738,
"text": "All the above code is present here."
},
{
"code": null,
"e": 5859,
"s": 5774,
"text": "If this piece of writing helped you in any way, do share your knowledge with others!"
}
] |
GATE CS 2012 - GeeksforGeeks
|
11 Oct, 2021
BCNF is a stronger version 3NF. So every relation in BCNF will also be in 3NF.
No choice
Choice A
Choice A
Choice B No choice
Program gives no output as it is erroneous
int main()
{
char inchar = 'A';
switch (inchar)
{
case 'A' :
printf ("choice A \n") ;
case 'B' :
{
printf ("choice B") ;
break;
}
case 'C' :
case 'D' :
case 'E' :
default:
printf ("No Choice") ;
}
}
Assuming P != NP, which of the following is true ?
(A) NP-complete = NP
(B) NP-complete P =
(C) NP-hard = NP
(D) P = NP-complete
The answer is B (no NP-Complete problem can be solved in polynomial time). Because, if one NP-Complete problem can be solved in polynomial time, then all NP problems can solved in polynomial time. If that is the case, then NP and P set become same which contradicts the given condition.
(A)
(B)
(C)
(D)
= XY’+XY
= X(Y’+Y)
= X *1
= X
Column x = f(x,y)
So ,
f(x,y)=x
fork();
fork();
fork();
fork (); // Line 1
fork (); // Line 2
fork (); // Line 3
L1 // There will be 1 child process created by line 1
/ \
L2 L2 // There will be 2 child processes created by line 2
/ \ / \
L3 L3 L3 L3 // There will be 4 child processes created by line 3
Consider the function f(x) = sin(x) in the interval [π/4, 7π/4]. The number and location(s) of the local minima of this function are
One, at π/2
One, at 3π/2
Two, at π/2 and 3π/2
Two, at π/4 and 3π/2
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Comments
Old Comments
Must Do Coding Questions for Product Based Companies
Microsoft Interview Experience for Internship (Via Engage)
Difference between var, let and const keywords in JavaScript
Array of Objects in C++ with Examples
How to Replace Values in Column Based on Condition in Pandas?
C Program to read contents of Whole File
Hash Functions and list/types of Hash functions
How to Replace Values in a List in Python?
Spring - REST Controller
How to Read Text Files with Pandas?
|
[
{
"code": null,
"e": 27219,
"s": 27191,
"text": "\n11 Oct, 2021"
},
{
"code": null,
"e": 27298,
"s": 27219,
"text": "BCNF is a stronger version 3NF. So every relation in BCNF will also be in 3NF."
},
{
"code": null,
"e": 27308,
"s": 27298,
"text": "No choice"
},
{
"code": null,
"e": 27317,
"s": 27308,
"text": "Choice A"
},
{
"code": null,
"e": 27345,
"s": 27317,
"text": "Choice A\nChoice B No choice"
},
{
"code": null,
"e": 27388,
"s": 27345,
"text": "Program gives no output as it is erroneous"
},
{
"code": null,
"e": 27667,
"s": 27388,
"text": "int main()\n{\n char inchar = 'A';\n switch (inchar)\n {\n case 'A' :\n printf (\"choice A \\n\") ;\n case 'B' :\n {\n printf (\"choice B\") ;\n break;\n }\n case 'C' :\n case 'D' :\n case 'E' :\n default:\n printf (\"No Choice\") ;\n }\n}"
},
{
"code": null,
"e": 27799,
"s": 27667,
"text": "Assuming P != NP, which of the following is true ?\n(A) NP-complete = NP\n(B) NP-complete P = \n(C) NP-hard = NP\n(D) P = NP-complete\n"
},
{
"code": null,
"e": 28086,
"s": 27799,
"text": "The answer is B (no NP-Complete problem can be solved in polynomial time). Because, if one NP-Complete problem can be solved in polynomial time, then all NP problems can solved in polynomial time. If that is the case, then NP and P set become same which contradicts the given condition."
},
{
"code": null,
"e": 28110,
"s": 28086,
"text": "(A) \n\n(B) \n\n(C) \n\n(D) "
},
{
"code": null,
"e": 28141,
"s": 28110,
"text": "= XY’+XY\n= X(Y’+Y)\n= X *1\n= X "
},
{
"code": null,
"e": 28177,
"s": 28141,
"text": "Column x = f(x,y) \nSo , \nf(x,y)=x \n"
},
{
"code": null,
"e": 28202,
"s": 28177,
"text": "fork();\nfork();\nfork(); "
},
{
"code": null,
"e": 28504,
"s": 28202,
"text": " fork (); // Line 1\n fork (); // Line 2\n fork (); // Line 3\n\n L1 // There will be 1 child process created by line 1\n / \\\n L2 L2 // There will be 2 child processes created by line 2\n / \\ / \\\nL3 L3 L3 L3 // There will be 4 child processes created by line 3"
},
{
"code": null,
"e": 28638,
"s": 28504,
"text": "Consider the function f(x) = sin(x) in the interval [π/4, 7π/4]. The number and location(s) of the local minima of this function are "
},
{
"code": null,
"e": 28650,
"s": 28638,
"text": "One, at π/2"
},
{
"code": null,
"e": 28663,
"s": 28650,
"text": "One, at 3π/2"
},
{
"code": null,
"e": 28684,
"s": 28663,
"text": "Two, at π/2 and 3π/2"
},
{
"code": null,
"e": 28705,
"s": 28684,
"text": "Two, at π/4 and 3π/2"
},
{
"code": null,
"e": 28803,
"s": 28705,
"text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here."
},
{
"code": null,
"e": 28812,
"s": 28803,
"text": "Comments"
},
{
"code": null,
"e": 28825,
"s": 28812,
"text": "Old Comments"
},
{
"code": null,
"e": 28878,
"s": 28825,
"text": "Must Do Coding Questions for Product Based Companies"
},
{
"code": null,
"e": 28937,
"s": 28878,
"text": "Microsoft Interview Experience for Internship (Via Engage)"
},
{
"code": null,
"e": 28998,
"s": 28937,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29036,
"s": 28998,
"text": "Array of Objects in C++ with Examples"
},
{
"code": null,
"e": 29098,
"s": 29036,
"text": "How to Replace Values in Column Based on Condition in Pandas?"
},
{
"code": null,
"e": 29139,
"s": 29098,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 29187,
"s": 29139,
"text": "Hash Functions and list/types of Hash functions"
},
{
"code": null,
"e": 29230,
"s": 29187,
"text": "How to Replace Values in a List in Python?"
},
{
"code": null,
"e": 29255,
"s": 29230,
"text": "Spring - REST Controller"
}
] |
SELECT where row value contains string in MySQL?
|
To select the row value containing string in MySQL, use the following syntax.
SELECT *FROM yourTableName where yourColumnName like ‘%yourPattern%’;
To understand the above syntax, let us first create a table. The query to create a table is as follows.
mysql> create table PatternDemo
-> (
-> Id int,
-> Name varchar(100),
-> Age int
-> );
Query OK, 0 rows affected (0.97 sec)
Insert records in the table using insert command. The query is as follows.
mysql> insert into PatternDemo values(1,'James',23);
Query OK, 1 row affected (0.11 sec)
mysql> insert into PatternDemo values(2,'Joseph',21);
Query OK, 1 row affected (0.18 sec)
mysql> insert into PatternDemo values(3,'Robert',20);
Query OK, 1 row affected (0.11 sec)
mysql> insert into PatternDemo values(4,'John',26);
Query OK, 1 row affected (0.10 sec)
mysql> insert into PatternDemo values(5,'Richard',24);
Query OK, 1 row affected (0.17 sec)
Now you can display all records from the table using select statement. The query is as follows.
mysql> select *from PatternDemo;
The following is the output.
+------+---------+------+
| Id | Name | Age |
+------+---------+------+
| 1 | James | 23 |
| 2 | Joseph | 21 |
| 3 | Robert | 20 |
| 4 | John | 26 |
| 5 | Richard | 24 |
+------+---------+------+
5 rows in set (0.00 sec)
Here is the query that will give all names with the characters “Jo”. The query is as follows.
mysql> select *from PatternDemo where Name like '%Jo%';
The following is the output.
+------+--------+------+
| Id | Name | Age |
+------+--------+------+
| 2 | Joseph | 21 |
| 4 | John | 26 |
+------+--------+------+
2 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1140,
"s": 1062,
"text": "To select the row value containing string in MySQL, use the following syntax."
},
{
"code": null,
"e": 1210,
"s": 1140,
"text": "SELECT *FROM yourTableName where yourColumnName like ‘%yourPattern%’;"
},
{
"code": null,
"e": 1314,
"s": 1210,
"text": "To understand the above syntax, let us first create a table. The query to create a table is as follows."
},
{
"code": null,
"e": 1438,
"s": 1314,
"text": "mysql> create table PatternDemo\n-> (\n-> Id int,\n-> Name varchar(100),\n-> Age int\n-> );\nQuery OK, 0 rows affected (0.97 sec)"
},
{
"code": null,
"e": 1513,
"s": 1438,
"text": "Insert records in the table using insert command. The query is as follows."
},
{
"code": null,
"e": 1965,
"s": 1513,
"text": "mysql> insert into PatternDemo values(1,'James',23);\nQuery OK, 1 row affected (0.11 sec)\n\nmysql> insert into PatternDemo values(2,'Joseph',21);\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into PatternDemo values(3,'Robert',20);\nQuery OK, 1 row affected (0.11 sec)\n\nmysql> insert into PatternDemo values(4,'John',26);\nQuery OK, 1 row affected (0.10 sec)\n\nmysql> insert into PatternDemo values(5,'Richard',24);\nQuery OK, 1 row affected (0.17 sec)"
},
{
"code": null,
"e": 2061,
"s": 1965,
"text": "Now you can display all records from the table using select statement. The query is as follows."
},
{
"code": null,
"e": 2094,
"s": 2061,
"text": "mysql> select *from PatternDemo;"
},
{
"code": null,
"e": 2123,
"s": 2094,
"text": "The following is the output."
},
{
"code": null,
"e": 2382,
"s": 2123,
"text": "+------+---------+------+\n| Id | Name | Age |\n+------+---------+------+\n| 1 | James | 23 |\n| 2 | Joseph | 21 |\n| 3 | Robert | 20 |\n| 4 | John | 26 |\n| 5 | Richard | 24 |\n+------+---------+------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2476,
"s": 2382,
"text": "Here is the query that will give all names with the characters “Jo”. The query is as follows."
},
{
"code": null,
"e": 2532,
"s": 2476,
"text": "mysql> select *from PatternDemo where Name like '%Jo%';"
},
{
"code": null,
"e": 2561,
"s": 2532,
"text": "The following is the output."
},
{
"code": null,
"e": 2736,
"s": 2561,
"text": "+------+--------+------+\n| Id | Name | Age |\n+------+--------+------+\n| 2 | Joseph | 21 |\n| 4 | John | 26 |\n+------+--------+------+\n2 rows in set (0.00 sec)"
}
] |
Data Analysis and Visualization Just Got Better — Mito Adds 5 Features You Should Try | by Dario Radečić | Towards Data Science
|
Disclaimer: This is not a sponsored article. I don’t have any affiliation with Mito or the creators of the library. The article shows an unbiased overview of the library, intending to make data science tools accessible to the broader masses.
Trying to keep up with the most recent data science libraries is like trying to read with your eyes closed. Nothing new can gain traction without solving a specific problem really well. That’s where Mito will grab your attention.
I’ve already written about Mito a couple of months back, but the library got some new features and updated the existing ones since then. These will be covered today.
First things first, let’s install Mito on your local machine.
The Mito package has two prerequisites:
Python 3.6 or newer
Node.js
Assuming you have both installed, I’ll continue by creating and activating a new virtual environment with Anaconda:
conda create --name mito_env python=3.8conda activate mito_env
And then by installing dependencies:
python -m pip install mitoinstallerpython -m mitoinstaller install
Once done, you can launch Jupyter Lab:
jupyter lab
Create a new notebook and you’re ready to proceed!
I love when a tool does its job well. But I won’t use it if it looks like shit. That might not be the case for you, but modern design beats unnecessary borders, shadows, and other Windows-XP-looking software every day of the week.
The new Mito version comes with an updated design that you’ll see in a second. However, it’s not technically a new feature, so I’m not counting it into the list.
First, let’s create a new Mito sheet. Execute the following code to do so, assuming you have a blank notebook open:
import mitosheetmitosheet.sheet()
You should see something similar:
You’ll have to enter your email to continue, but they won’t bother you with too many emails. Even if they do, there’s always an option to unsubscribe.
Once done, you’ll see a blank sheet in the notebook:
Yep — Mito definitely looks better than before, but that’s not why you’re reading this. Let’s continue with the first improved feature — easier data management.
One thing I dislike about Pandas is guessing how many times I have to write ../ to get at the correct data folder. That’s not the case with Mito.
Mito can now connect directly to your local file system, making dataset loading and management that much easier. We’ll use the Titanic dataset through the article, so make sure to download it if you’re following along.
You’ll see the option to import files after creating a new Mito sheet, like shown below:
You can select your dataset and hit the import button down below. That will instantly load the dataset:
The library will automatically generate the Python code for you in the cell below. Here’s how it looks like for now:
Neat, isn’t it? Let’s see how to calculate summary statistics next.
Calculating summary statistics — like mean, median, quartiles, and so on — would typically imply calling a describe() function on every column, not counting for graphical representation of the variable.
Mito does it in a single click.
Just click on a column of interest and explore the Summary Stats tab on the right side. It visualizes the data with the most appropriate chart type and tells you everything the describe() function would:
Needless to say, but exploring data this way is a must for any first encounter with the dataset.
Data isn’t always formatted correctly by default. To solve this problem, you can either change the data type or create a derived column. Mito does both with ease.
You can click on the little icon in the header column to open properties and change the data type from there:
For anything more complex, you’re better of creating a derived column. The example below shows you how to convert the Sex attribute into a binary column, where males have a value of 1:
The previous operation generates the following Python code:
# Set M in titanic_csv to =IF(Sex == ‘male’, 1, 0)titanic_csv[‘M’] = IF(titanic_csv[‘Sex’] == ‘male’, 1, 0)# Renamed M to IsMale in titanic_csvtitanic_csv.rename(columns={“M”: “IsMale”}, inplace=True)
This should feel familiar to anyone with basic Excel background.
One of the easiest ways to summarize data quickly is through pivot tables. In Mito, creating a pivot table creates a new Pandas DataFrame which you can then further modify (e.g., sort).
The best way to explain the concept is through a demonstration — the one that follows creates a DataFrame containing the number of survived passengers by the embarked point:
Here’s the code generated by the previous operation:
unused_columns = titanic_csv.columns.difference(set([‘Embarked’]).union(set([])).union(set({‘Survived’})))tmp_df = titanic_csv.drop(unused_columns, axis=1)pivot_table = tmp_df.pivot_table( index=[‘Embarked’], values=[‘Survived’], aggfunc={‘Survived’: [‘sum’]})# Flatten the column headerspivot_table.columns = [make_valid_header(col) for col in pivot_table.columns.values]# Reset the column name and the indexesdf2 = pivot_table.rename_axis(None, axis=1).reset_index()
Easy, right? As mentioned before, you can modify the pivot table after creation. Here’s how to sort it and rename a column:
The previous operation generated the following code:
# Sorted Survived_sum in df2 in descending orderdf2 = df2.sort_values(by=’Survived_sum’, ascending=False, na_position=’first’)df2 = df2.reset_index(drop=True)# Renamed Survived_sum to Total_survived in df2df2.rename(columns={“Survived_sum”: “Total_survived”}, inplace=True)
Finally, let’s cover data visualization.
I like to inspect data visually, but I’m not the biggest fan of writing visualization code. As you would assume, Mito has you covered.
All you have to do is click on the Graph option, select the visualization type and select the columns for X and Y axes — the library covers everything else.
Here’s how to draw a boxplot of the Age column:
It looks like Plotly is used behind the scenes, so visualizations are interactive by default. Neat!
And that does it for the top five new/upgraded features in the most recent Mito release. The official documentation isn’t updated yet — judging by the old design — but it’s just a matter of time until it is.
The question remains — should you use Mito?
My answer is the same as in the previous article. As a data scientist, I don’t see why you shouldn’t, especially if you’re skilled in Excel and want to get started with Python and Pandas. Mito can make the transition process that much easier.
To conclude — give Mito a try. It’s free, and you have nothing to lose. I’d love to hear your opinion on the library in the comment section below.
Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you.
medium.com
Top 5 Books to Learn Data Science in 2021
How to Schedule Python Scripts With Cron — The Only Guide You’ll Ever Need
Dask Delayed — How to Parallelize Your Python Code With Ease
How to Create PDF Reports With Python — The Essential Guide
Become a Data Scientist in 2021 Even Without a College Degree
Follow me on Medium for more stories like this
Sign up for my newsletter
Connect on LinkedIn
|
[
{
"code": null,
"e": 413,
"s": 171,
"text": "Disclaimer: This is not a sponsored article. I don’t have any affiliation with Mito or the creators of the library. The article shows an unbiased overview of the library, intending to make data science tools accessible to the broader masses."
},
{
"code": null,
"e": 643,
"s": 413,
"text": "Trying to keep up with the most recent data science libraries is like trying to read with your eyes closed. Nothing new can gain traction without solving a specific problem really well. That’s where Mito will grab your attention."
},
{
"code": null,
"e": 809,
"s": 643,
"text": "I’ve already written about Mito a couple of months back, but the library got some new features and updated the existing ones since then. These will be covered today."
},
{
"code": null,
"e": 871,
"s": 809,
"text": "First things first, let’s install Mito on your local machine."
},
{
"code": null,
"e": 911,
"s": 871,
"text": "The Mito package has two prerequisites:"
},
{
"code": null,
"e": 931,
"s": 911,
"text": "Python 3.6 or newer"
},
{
"code": null,
"e": 939,
"s": 931,
"text": "Node.js"
},
{
"code": null,
"e": 1055,
"s": 939,
"text": "Assuming you have both installed, I’ll continue by creating and activating a new virtual environment with Anaconda:"
},
{
"code": null,
"e": 1118,
"s": 1055,
"text": "conda create --name mito_env python=3.8conda activate mito_env"
},
{
"code": null,
"e": 1155,
"s": 1118,
"text": "And then by installing dependencies:"
},
{
"code": null,
"e": 1222,
"s": 1155,
"text": "python -m pip install mitoinstallerpython -m mitoinstaller install"
},
{
"code": null,
"e": 1261,
"s": 1222,
"text": "Once done, you can launch Jupyter Lab:"
},
{
"code": null,
"e": 1273,
"s": 1261,
"text": "jupyter lab"
},
{
"code": null,
"e": 1324,
"s": 1273,
"text": "Create a new notebook and you’re ready to proceed!"
},
{
"code": null,
"e": 1555,
"s": 1324,
"text": "I love when a tool does its job well. But I won’t use it if it looks like shit. That might not be the case for you, but modern design beats unnecessary borders, shadows, and other Windows-XP-looking software every day of the week."
},
{
"code": null,
"e": 1717,
"s": 1555,
"text": "The new Mito version comes with an updated design that you’ll see in a second. However, it’s not technically a new feature, so I’m not counting it into the list."
},
{
"code": null,
"e": 1833,
"s": 1717,
"text": "First, let’s create a new Mito sheet. Execute the following code to do so, assuming you have a blank notebook open:"
},
{
"code": null,
"e": 1867,
"s": 1833,
"text": "import mitosheetmitosheet.sheet()"
},
{
"code": null,
"e": 1901,
"s": 1867,
"text": "You should see something similar:"
},
{
"code": null,
"e": 2052,
"s": 1901,
"text": "You’ll have to enter your email to continue, but they won’t bother you with too many emails. Even if they do, there’s always an option to unsubscribe."
},
{
"code": null,
"e": 2105,
"s": 2052,
"text": "Once done, you’ll see a blank sheet in the notebook:"
},
{
"code": null,
"e": 2266,
"s": 2105,
"text": "Yep — Mito definitely looks better than before, but that’s not why you’re reading this. Let’s continue with the first improved feature — easier data management."
},
{
"code": null,
"e": 2412,
"s": 2266,
"text": "One thing I dislike about Pandas is guessing how many times I have to write ../ to get at the correct data folder. That’s not the case with Mito."
},
{
"code": null,
"e": 2631,
"s": 2412,
"text": "Mito can now connect directly to your local file system, making dataset loading and management that much easier. We’ll use the Titanic dataset through the article, so make sure to download it if you’re following along."
},
{
"code": null,
"e": 2720,
"s": 2631,
"text": "You’ll see the option to import files after creating a new Mito sheet, like shown below:"
},
{
"code": null,
"e": 2824,
"s": 2720,
"text": "You can select your dataset and hit the import button down below. That will instantly load the dataset:"
},
{
"code": null,
"e": 2941,
"s": 2824,
"text": "The library will automatically generate the Python code for you in the cell below. Here’s how it looks like for now:"
},
{
"code": null,
"e": 3009,
"s": 2941,
"text": "Neat, isn’t it? Let’s see how to calculate summary statistics next."
},
{
"code": null,
"e": 3212,
"s": 3009,
"text": "Calculating summary statistics — like mean, median, quartiles, and so on — would typically imply calling a describe() function on every column, not counting for graphical representation of the variable."
},
{
"code": null,
"e": 3244,
"s": 3212,
"text": "Mito does it in a single click."
},
{
"code": null,
"e": 3448,
"s": 3244,
"text": "Just click on a column of interest and explore the Summary Stats tab on the right side. It visualizes the data with the most appropriate chart type and tells you everything the describe() function would:"
},
{
"code": null,
"e": 3545,
"s": 3448,
"text": "Needless to say, but exploring data this way is a must for any first encounter with the dataset."
},
{
"code": null,
"e": 3708,
"s": 3545,
"text": "Data isn’t always formatted correctly by default. To solve this problem, you can either change the data type or create a derived column. Mito does both with ease."
},
{
"code": null,
"e": 3818,
"s": 3708,
"text": "You can click on the little icon in the header column to open properties and change the data type from there:"
},
{
"code": null,
"e": 4003,
"s": 3818,
"text": "For anything more complex, you’re better of creating a derived column. The example below shows you how to convert the Sex attribute into a binary column, where males have a value of 1:"
},
{
"code": null,
"e": 4063,
"s": 4003,
"text": "The previous operation generates the following Python code:"
},
{
"code": null,
"e": 4264,
"s": 4063,
"text": "# Set M in titanic_csv to =IF(Sex == ‘male’, 1, 0)titanic_csv[‘M’] = IF(titanic_csv[‘Sex’] == ‘male’, 1, 0)# Renamed M to IsMale in titanic_csvtitanic_csv.rename(columns={“M”: “IsMale”}, inplace=True)"
},
{
"code": null,
"e": 4329,
"s": 4264,
"text": "This should feel familiar to anyone with basic Excel background."
},
{
"code": null,
"e": 4515,
"s": 4329,
"text": "One of the easiest ways to summarize data quickly is through pivot tables. In Mito, creating a pivot table creates a new Pandas DataFrame which you can then further modify (e.g., sort)."
},
{
"code": null,
"e": 4689,
"s": 4515,
"text": "The best way to explain the concept is through a demonstration — the one that follows creates a DataFrame containing the number of survived passengers by the embarked point:"
},
{
"code": null,
"e": 4742,
"s": 4689,
"text": "Here’s the code generated by the previous operation:"
},
{
"code": null,
"e": 5220,
"s": 4742,
"text": "unused_columns = titanic_csv.columns.difference(set([‘Embarked’]).union(set([])).union(set({‘Survived’})))tmp_df = titanic_csv.drop(unused_columns, axis=1)pivot_table = tmp_df.pivot_table( index=[‘Embarked’], values=[‘Survived’], aggfunc={‘Survived’: [‘sum’]})# Flatten the column headerspivot_table.columns = [make_valid_header(col) for col in pivot_table.columns.values]# Reset the column name and the indexesdf2 = pivot_table.rename_axis(None, axis=1).reset_index()"
},
{
"code": null,
"e": 5344,
"s": 5220,
"text": "Easy, right? As mentioned before, you can modify the pivot table after creation. Here’s how to sort it and rename a column:"
},
{
"code": null,
"e": 5397,
"s": 5344,
"text": "The previous operation generated the following code:"
},
{
"code": null,
"e": 5671,
"s": 5397,
"text": "# Sorted Survived_sum in df2 in descending orderdf2 = df2.sort_values(by=’Survived_sum’, ascending=False, na_position=’first’)df2 = df2.reset_index(drop=True)# Renamed Survived_sum to Total_survived in df2df2.rename(columns={“Survived_sum”: “Total_survived”}, inplace=True)"
},
{
"code": null,
"e": 5712,
"s": 5671,
"text": "Finally, let’s cover data visualization."
},
{
"code": null,
"e": 5847,
"s": 5712,
"text": "I like to inspect data visually, but I’m not the biggest fan of writing visualization code. As you would assume, Mito has you covered."
},
{
"code": null,
"e": 6004,
"s": 5847,
"text": "All you have to do is click on the Graph option, select the visualization type and select the columns for X and Y axes — the library covers everything else."
},
{
"code": null,
"e": 6052,
"s": 6004,
"text": "Here’s how to draw a boxplot of the Age column:"
},
{
"code": null,
"e": 6152,
"s": 6052,
"text": "It looks like Plotly is used behind the scenes, so visualizations are interactive by default. Neat!"
},
{
"code": null,
"e": 6360,
"s": 6152,
"text": "And that does it for the top five new/upgraded features in the most recent Mito release. The official documentation isn’t updated yet — judging by the old design — but it’s just a matter of time until it is."
},
{
"code": null,
"e": 6404,
"s": 6360,
"text": "The question remains — should you use Mito?"
},
{
"code": null,
"e": 6647,
"s": 6404,
"text": "My answer is the same as in the previous article. As a data scientist, I don’t see why you shouldn’t, especially if you’re skilled in Excel and want to get started with Python and Pandas. Mito can make the transition process that much easier."
},
{
"code": null,
"e": 6794,
"s": 6647,
"text": "To conclude — give Mito a try. It’s free, and you have nothing to lose. I’d love to hear your opinion on the library in the comment section below."
},
{
"code": null,
"e": 6977,
"s": 6794,
"text": "Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you."
},
{
"code": null,
"e": 6988,
"s": 6977,
"text": "medium.com"
},
{
"code": null,
"e": 7030,
"s": 6988,
"text": "Top 5 Books to Learn Data Science in 2021"
},
{
"code": null,
"e": 7105,
"s": 7030,
"text": "How to Schedule Python Scripts With Cron — The Only Guide You’ll Ever Need"
},
{
"code": null,
"e": 7166,
"s": 7105,
"text": "Dask Delayed — How to Parallelize Your Python Code With Ease"
},
{
"code": null,
"e": 7226,
"s": 7166,
"text": "How to Create PDF Reports With Python — The Essential Guide"
},
{
"code": null,
"e": 7288,
"s": 7226,
"text": "Become a Data Scientist in 2021 Even Without a College Degree"
},
{
"code": null,
"e": 7335,
"s": 7288,
"text": "Follow me on Medium for more stories like this"
},
{
"code": null,
"e": 7361,
"s": 7335,
"text": "Sign up for my newsletter"
}
] |
How to move one DIV element inside another using jQuery ? - GeeksforGeeks
|
23 Apr, 2021
In this article, we will learn to move one HTML div element inside another using jQuery.
The HTML div element is used to define a division or a section in an HTML document.
Method used:
parent(): This method is used to get the parent of each element in the current set of matched elements, optionally filtered by a selector.
detach(): This method is used to removes the selected elements from the DOM tree including its all text and child nodes but it keeps the data and the events.
attr(): This method is used to set or return attributes and values of the selected elements.
appendTo(): This method is used to insert HTML elements at the end of the selected elements.
Approach:
Create the HTML page with the various division within the division element.
Next, create a function using the above methods to move the inner division element onclick event.
Example:
HTML
<!DOCTYPE html><html> <head> <script src="https://code.jquery.com/jquery-git.js"> </script> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width" /> <style> body { text-align: center; } #nonSelected { position: absolute; top: 150px; left: 350px; width: 250px; height: 280px; background-color: lightblue; border-width: 2px; border-style: dotted; border-color: black; padding: 10px; } #selected { position: absolute; top: 150px; left: 20px; width: 250px; height: 280px; background-color: lightgreen; font-style: italic; border-width: 2px; border-style: solid; border-color: black; padding: 10px; } </style> </head> <body> <h2 style="color: green">GeeksforGeeks</h2> <b>Make groups of three colors.</b> <div id="nonSelected"> <div id="div1" onclick="move(this)" style="background-color: green"> Inner division one </div> <div id="div2" onclick="move(this)" style="background-color: blue"> Inner division two </div> <div id="div3" onclick="move(this)" style="background-color: red"> Inner division three </div> <div id="div1" onclick="move(this)" style="background-color: green"> Inner division one </div> <div id="div2" onclick="move(this)" style="background-color: blue"> Inner division two </div> <div id="div3" onclick="move(this)" style="background-color: red"> Inner division three </div> <div id="div1" onclick="move(this)" style="background-color: green"> Inner division one </div> <div id="div2" onclick="move(this)" style="background-color: blue"> Inner division two </div> <div id="div3" onclick="move(this)" style="background-color: red"> Inner division three </div> <div id="div1" onclick="move(this)" style="background-color: green"> Inner division one </div> <div id="div2" onclick="move(this)" style="background-color: blue"> Inner division two </div> <div id="div3" onclick="move(this)" style="background-color: red"> Inner division three </div> <div id="div1" onclick="move(this)" style="background-color: green"> Inner division one </div> <div id="div2" onclick="move(this)" style="background-color: blue"> Inner division two </div> <div id="div3" onclick="move(this)" style="background-color: red"> Inner division three </div> </div> <div id="selected"></div> <script> function move(elem) { if ($(elem).parent().attr("id") == "nonSelected") { $(elem).detach().appendTo("#selected"); } else { $(elem).detach().appendTo("#nonSelected"); } } </script> </body></html>
Output:
one div to another
jQuery-Methods
jQuery-Questions
Picked
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Show and Hide div elements using radio buttons?
How to prevent Body from scrolling when a modal is opened using jQuery ?
jQuery | ajax() Method
jQuery | removeAttr() with Examples
How to get the value in an input text box using jQuery ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 27064,
"s": 27036,
"text": "\n23 Apr, 2021"
},
{
"code": null,
"e": 27154,
"s": 27064,
"text": "In this article, we will learn to move one HTML div element inside another using jQuery. "
},
{
"code": null,
"e": 27238,
"s": 27154,
"text": "The HTML div element is used to define a division or a section in an HTML document."
},
{
"code": null,
"e": 27253,
"s": 27238,
"text": "Method used: "
},
{
"code": null,
"e": 27392,
"s": 27253,
"text": "parent(): This method is used to get the parent of each element in the current set of matched elements, optionally filtered by a selector."
},
{
"code": null,
"e": 27550,
"s": 27392,
"text": "detach(): This method is used to removes the selected elements from the DOM tree including its all text and child nodes but it keeps the data and the events."
},
{
"code": null,
"e": 27643,
"s": 27550,
"text": "attr(): This method is used to set or return attributes and values of the selected elements."
},
{
"code": null,
"e": 27736,
"s": 27643,
"text": "appendTo(): This method is used to insert HTML elements at the end of the selected elements."
},
{
"code": null,
"e": 27747,
"s": 27736,
"text": "Approach: "
},
{
"code": null,
"e": 27823,
"s": 27747,
"text": "Create the HTML page with the various division within the division element."
},
{
"code": null,
"e": 27921,
"s": 27823,
"text": "Next, create a function using the above methods to move the inner division element onclick event."
},
{
"code": null,
"e": 27930,
"s": 27921,
"text": "Example:"
},
{
"code": null,
"e": 27935,
"s": 27930,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <script src=\"https://code.jquery.com/jquery-git.js\"> </script> <meta charset=\"utf-8\" /> <meta name=\"viewport\" content=\"width=device-width\" /> <style> body { text-align: center; } #nonSelected { position: absolute; top: 150px; left: 350px; width: 250px; height: 280px; background-color: lightblue; border-width: 2px; border-style: dotted; border-color: black; padding: 10px; } #selected { position: absolute; top: 150px; left: 20px; width: 250px; height: 280px; background-color: lightgreen; font-style: italic; border-width: 2px; border-style: solid; border-color: black; padding: 10px; } </style> </head> <body> <h2 style=\"color: green\">GeeksforGeeks</h2> <b>Make groups of three colors.</b> <div id=\"nonSelected\"> <div id=\"div1\" onclick=\"move(this)\" style=\"background-color: green\"> Inner division one </div> <div id=\"div2\" onclick=\"move(this)\" style=\"background-color: blue\"> Inner division two </div> <div id=\"div3\" onclick=\"move(this)\" style=\"background-color: red\"> Inner division three </div> <div id=\"div1\" onclick=\"move(this)\" style=\"background-color: green\"> Inner division one </div> <div id=\"div2\" onclick=\"move(this)\" style=\"background-color: blue\"> Inner division two </div> <div id=\"div3\" onclick=\"move(this)\" style=\"background-color: red\"> Inner division three </div> <div id=\"div1\" onclick=\"move(this)\" style=\"background-color: green\"> Inner division one </div> <div id=\"div2\" onclick=\"move(this)\" style=\"background-color: blue\"> Inner division two </div> <div id=\"div3\" onclick=\"move(this)\" style=\"background-color: red\"> Inner division three </div> <div id=\"div1\" onclick=\"move(this)\" style=\"background-color: green\"> Inner division one </div> <div id=\"div2\" onclick=\"move(this)\" style=\"background-color: blue\"> Inner division two </div> <div id=\"div3\" onclick=\"move(this)\" style=\"background-color: red\"> Inner division three </div> <div id=\"div1\" onclick=\"move(this)\" style=\"background-color: green\"> Inner division one </div> <div id=\"div2\" onclick=\"move(this)\" style=\"background-color: blue\"> Inner division two </div> <div id=\"div3\" onclick=\"move(this)\" style=\"background-color: red\"> Inner division three </div> </div> <div id=\"selected\"></div> <script> function move(elem) { if ($(elem).parent().attr(\"id\") == \"nonSelected\") { $(elem).detach().appendTo(\"#selected\"); } else { $(elem).detach().appendTo(\"#nonSelected\"); } } </script> </body></html>",
"e": 31039,
"s": 27935,
"text": null
},
{
"code": null,
"e": 31047,
"s": 31039,
"text": "Output:"
},
{
"code": null,
"e": 31066,
"s": 31047,
"text": "one div to another"
},
{
"code": null,
"e": 31081,
"s": 31066,
"text": "jQuery-Methods"
},
{
"code": null,
"e": 31098,
"s": 31081,
"text": "jQuery-Questions"
},
{
"code": null,
"e": 31105,
"s": 31098,
"text": "Picked"
},
{
"code": null,
"e": 31112,
"s": 31105,
"text": "JQuery"
},
{
"code": null,
"e": 31129,
"s": 31112,
"text": "Web Technologies"
},
{
"code": null,
"e": 31227,
"s": 31129,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31282,
"s": 31227,
"text": "How to Show and Hide div elements using radio buttons?"
},
{
"code": null,
"e": 31355,
"s": 31282,
"text": "How to prevent Body from scrolling when a modal is opened using jQuery ?"
},
{
"code": null,
"e": 31378,
"s": 31355,
"text": "jQuery | ajax() Method"
},
{
"code": null,
"e": 31414,
"s": 31378,
"text": "jQuery | removeAttr() with Examples"
},
{
"code": null,
"e": 31471,
"s": 31414,
"text": "How to get the value in an input text box using jQuery ?"
},
{
"code": null,
"e": 31511,
"s": 31471,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 31544,
"s": 31511,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 31589,
"s": 31544,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 31632,
"s": 31589,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Display Images on Terminal using Python - GeeksforGeeks
|
04 Jul, 2021
In this article, we will discuss how to display images on a terminal using Python. We will be using the climage module for the same. This module has the following features –
It helps to convert images to its ANSI Escape Codes to be able to convert be printable on Command-Line Interfaces.
It allows 8/16/256 bit color codings for vivid images.
It provides ASCII/Unicode support for more detail and adjustable pallets for different terminal themes
This module does not come built-in with Python. To install this type the below command in the terminal.
pip install climage
After the installation, the next step is to import convert() and to_file() functions, where the former performs the task of conversion and the latter performs the task of conversion and saving to the output file if needed.
Syntax:
convert(filename, is_unicode=False, is_truecolor=False, is_256color=True, is_16color=False, is_8color=False, width=80, palette=”default”)
Parameters:filename : Name of image file.is_unicode : If true, conversion is done in unicode format, otherwise ASCII characters will be used.is_truecolor : Whether to use RGB colors in generation, if supported by terminal. Defaults False.is_256color : Whether to use 256 colors encoding. Defaults True.is_16color : Whether to use 16 colors encoding. Defaults False.is_8color : Whether to use first 8 System colors. Defaults False.width : Number of blocks of console to be used. Defaults to 80.palette : Sets mapping of RGB colors scheme to system colors. Options are : [“default”, “xterm”, “linuxconsole”, “solarized”, “rxvt”, “tango”, “gruvbox”, “gruvboxdark”]. Default is “default”.
to_file(infile, outfile, is_unicode=False, is_truecolor=False, is_256color=True, is_16color=False, is_8color=False, width=80, palette=”default”)
Parameters:infile : The name/path of image file.outfile : File in which to store ANSI encoded string.
Example 1: Printing on Terminal
Image Used:
Python3
import climage # converts the image to print in terminal# inform of ANSI Escape codesoutput = climage.convert('banana.png') # prints output on console.print(output)
Output :
Example 2: Saving Encoding to file.
Python3
import climage # saves the converted encoded string# to banana_ansi file.output = climage.to_file('banana.png', 'banana_ansi')
Output :
u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[0m ...
Example 3: Working using command line
A similar function can also be used to work with the command line using similar constructs, parameters explained in previous part.
Syntax :
climage [-h] [-v] [–unicode | –ascii] [–truecolor | –256color | –16color | –8color] [–palette {default,xterm,linuxconsole,solarized,rxvt,tango,gruvbox,gruvboxdark}] [-w width] [-o outfile] inputfile
Working:
Example 4: Custom examples using command line
Below example show working with customized examples setting different possible parameters.
Example 5: Custom examples using Python code.
Extending to previous part, this section shows how custom parameters can be used from the code to construct different images.
Python3
import climage # converts the image to print in terminal# with 8 color encoding and palette tangooutput = climage.convert('banana.png', is_8color=True, palette='tango', is_256color=False) # prints output on console.print(output)
Output:
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
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
Python Classes and Objects
Python | os.path.join() method
Python | Pandas dataframe.groupby()
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list
|
[
{
"code": null,
"e": 25647,
"s": 25619,
"text": "\n04 Jul, 2021"
},
{
"code": null,
"e": 25822,
"s": 25647,
"text": "In this article, we will discuss how to display images on a terminal using Python. We will be using the climage module for the same. This module has the following features – "
},
{
"code": null,
"e": 25937,
"s": 25822,
"text": "It helps to convert images to its ANSI Escape Codes to be able to convert be printable on Command-Line Interfaces."
},
{
"code": null,
"e": 25992,
"s": 25937,
"text": "It allows 8/16/256 bit color codings for vivid images."
},
{
"code": null,
"e": 26095,
"s": 25992,
"text": "It provides ASCII/Unicode support for more detail and adjustable pallets for different terminal themes"
},
{
"code": null,
"e": 26199,
"s": 26095,
"text": "This module does not come built-in with Python. To install this type the below command in the terminal."
},
{
"code": null,
"e": 26219,
"s": 26199,
"text": "pip install climage"
},
{
"code": null,
"e": 26442,
"s": 26219,
"text": "After the installation, the next step is to import convert() and to_file() functions, where the former performs the task of conversion and the latter performs the task of conversion and saving to the output file if needed."
},
{
"code": null,
"e": 26450,
"s": 26442,
"text": "Syntax:"
},
{
"code": null,
"e": 26588,
"s": 26450,
"text": "convert(filename, is_unicode=False, is_truecolor=False, is_256color=True, is_16color=False, is_8color=False, width=80, palette=”default”)"
},
{
"code": null,
"e": 27276,
"s": 26588,
"text": "Parameters:filename : Name of image file.is_unicode : If true, conversion is done in unicode format, otherwise ASCII characters will be used.is_truecolor : Whether to use RGB colors in generation, if supported by terminal. Defaults False.is_256color : Whether to use 256 colors encoding. Defaults True.is_16color : Whether to use 16 colors encoding. Defaults False.is_8color : Whether to use first 8 System colors. Defaults False.width : Number of blocks of console to be used. Defaults to 80.palette : Sets mapping of RGB colors scheme to system colors. Options are : [“default”, “xterm”, “linuxconsole”, “solarized”, “rxvt”, “tango”, “gruvbox”, “gruvboxdark”]. Default is “default”. "
},
{
"code": null,
"e": 27421,
"s": 27276,
"text": "to_file(infile, outfile, is_unicode=False, is_truecolor=False, is_256color=True, is_16color=False, is_8color=False, width=80, palette=”default”)"
},
{
"code": null,
"e": 27525,
"s": 27421,
"text": "Parameters:infile : The name/path of image file.outfile : File in which to store ANSI encoded string."
},
{
"code": null,
"e": 27557,
"s": 27525,
"text": "Example 1: Printing on Terminal"
},
{
"code": null,
"e": 27569,
"s": 27557,
"text": "Image Used:"
},
{
"code": null,
"e": 27577,
"s": 27569,
"text": "Python3"
},
{
"code": "import climage # converts the image to print in terminal# inform of ANSI Escape codesoutput = climage.convert('banana.png') # prints output on console.print(output)",
"e": 27744,
"s": 27577,
"text": null
},
{
"code": null,
"e": 27754,
"s": 27744,
"text": "Output : "
},
{
"code": null,
"e": 27791,
"s": 27754,
"text": "Example 2: Saving Encoding to file. "
},
{
"code": null,
"e": 27799,
"s": 27791,
"text": "Python3"
},
{
"code": "import climage # saves the converted encoded string# to banana_ansi file.output = climage.to_file('banana.png', 'banana_ansi')",
"e": 27927,
"s": 27799,
"text": null
},
{
"code": null,
"e": 27938,
"s": 27927,
"text": "Output : "
},
{
"code": null,
"e": 28591,
"s": 27938,
"text": "u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[48;5;15m u001b[0m ..."
},
{
"code": null,
"e": 28630,
"s": 28591,
"text": "Example 3: Working using command line "
},
{
"code": null,
"e": 28761,
"s": 28630,
"text": "A similar function can also be used to work with the command line using similar constructs, parameters explained in previous part."
},
{
"code": null,
"e": 28771,
"s": 28761,
"text": "Syntax : "
},
{
"code": null,
"e": 28970,
"s": 28771,
"text": "climage [-h] [-v] [–unicode | –ascii] [–truecolor | –256color | –16color | –8color] [–palette {default,xterm,linuxconsole,solarized,rxvt,tango,gruvbox,gruvboxdark}] [-w width] [-o outfile] inputfile"
},
{
"code": null,
"e": 28979,
"s": 28970,
"text": "Working:"
},
{
"code": null,
"e": 29026,
"s": 28979,
"text": "Example 4: Custom examples using command line "
},
{
"code": null,
"e": 29118,
"s": 29026,
"text": "Below example show working with customized examples setting different possible parameters. "
},
{
"code": null,
"e": 29165,
"s": 29118,
"text": "Example 5: Custom examples using Python code. "
},
{
"code": null,
"e": 29291,
"s": 29165,
"text": "Extending to previous part, this section shows how custom parameters can be used from the code to construct different images."
},
{
"code": null,
"e": 29299,
"s": 29291,
"text": "Python3"
},
{
"code": "import climage # converts the image to print in terminal# with 8 color encoding and palette tangooutput = climage.convert('banana.png', is_8color=True, palette='tango', is_256color=False) # prints output on console.print(output)",
"e": 29555,
"s": 29299,
"text": null
},
{
"code": null,
"e": 29564,
"s": 29555,
"text": "Output: "
},
{
"code": null,
"e": 29579,
"s": 29564,
"text": "python-modules"
},
{
"code": null,
"e": 29586,
"s": 29579,
"text": "Python"
},
{
"code": null,
"e": 29684,
"s": 29586,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29716,
"s": 29684,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29758,
"s": 29716,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 29800,
"s": 29758,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 29856,
"s": 29800,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 29883,
"s": 29856,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 29914,
"s": 29883,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 29950,
"s": 29914,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 29979,
"s": 29950,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 30001,
"s": 29979,
"text": "Defaultdict in Python"
}
] |
GATE | GATE-CS-2015 (Set 3) | Question 41 - GeeksforGeeks
|
07 Sep, 2021
Consider the following grammar G.
S → F ⎪ H
F → p ⎪ c
H → d ⎪ c
Where S, F and H are non-terminal symbols, p, d and c are terminal symbols. Which of the following statement(s) is/are correct?
S1: LL(1) can parse all strings that are generated using grammar G.
S2: LR(1) can parse all strings that are generated using grammar G.
(A) Only S1(B) Only S2(C) Both S1 and S2(D) Neither S1 and S2Answer: (D)Explanation: The given grammar is ambiguous as there are two possible leftmost derivations for string “c”.
First Leftmost Derivation
S → F
F → c
Second Leftmost Derivation
S → H
H → c
An Ambiguous grammar can neither be LL(1) nor LR(1)
YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersPYQ - Parsing and SDT (Continued) with Joyojyoti Acharya | GeeksforGeeks GATEWatch 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:0021:42 / 44:16•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=9LF8Bby1Qhc" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE-CS-2015 (Set 3)
GATE-GATE-CS-2015 (Set 3)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE CS 2018 | Question 37
GATE | GATE-IT-2004 | Question 83
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2016 (Set 1) | Question 63
GATE | GATE-IT-2004 | Question 12
GATE | GATE-CS-2007 | Question 17
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2007 | Question 64
GATE | GATE CS 2010 | Question 33
|
[
{
"code": null,
"e": 24386,
"s": 24358,
"text": "\n07 Sep, 2021"
},
{
"code": null,
"e": 24420,
"s": 24386,
"text": "Consider the following grammar G."
},
{
"code": null,
"e": 24457,
"s": 24420,
"text": " S → F ⎪ H\n F → p ⎪ c\n H → d ⎪ c "
},
{
"code": null,
"e": 24585,
"s": 24457,
"text": "Where S, F and H are non-terminal symbols, p, d and c are terminal symbols. Which of the following statement(s) is/are correct?"
},
{
"code": null,
"e": 24722,
"s": 24585,
"text": "S1: LL(1) can parse all strings that are generated using grammar G.\nS2: LR(1) can parse all strings that are generated using grammar G. "
},
{
"code": null,
"e": 24901,
"s": 24722,
"text": "(A) Only S1(B) Only S2(C) Both S1 and S2(D) Neither S1 and S2Answer: (D)Explanation: The given grammar is ambiguous as there are two possible leftmost derivations for string “c”."
},
{
"code": null,
"e": 24991,
"s": 24901,
"text": "\nFirst Leftmost Derivation\n S → F \n F → c\n\nSecond Leftmost Derivation\n S → H\n H → c "
},
{
"code": null,
"e": 25043,
"s": 24991,
"text": "An Ambiguous grammar can neither be LL(1) nor LR(1)"
},
{
"code": null,
"e": 25949,
"s": 25043,
"text": "YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersPYQ - Parsing and SDT (Continued) with Joyojyoti Acharya | GeeksforGeeks GATEWatch 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:0021:42 / 44:16•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=9LF8Bby1Qhc\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question"
},
{
"code": null,
"e": 25970,
"s": 25949,
"text": "GATE-CS-2015 (Set 3)"
},
{
"code": null,
"e": 25996,
"s": 25970,
"text": "GATE-GATE-CS-2015 (Set 3)"
},
{
"code": null,
"e": 26001,
"s": 25996,
"text": "GATE"
},
{
"code": null,
"e": 26099,
"s": 26001,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26108,
"s": 26099,
"text": "Comments"
},
{
"code": null,
"e": 26121,
"s": 26108,
"text": "Old Comments"
},
{
"code": null,
"e": 26163,
"s": 26121,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 38"
},
{
"code": null,
"e": 26197,
"s": 26163,
"text": "GATE | GATE CS 2018 | Question 37"
},
{
"code": null,
"e": 26231,
"s": 26197,
"text": "GATE | GATE-IT-2004 | Question 83"
},
{
"code": null,
"e": 26273,
"s": 26231,
"text": "GATE | GATE-CS-2016 (Set 1) | Question 65"
},
{
"code": null,
"e": 26315,
"s": 26273,
"text": "GATE | GATE-CS-2016 (Set 1) | Question 63"
},
{
"code": null,
"e": 26349,
"s": 26315,
"text": "GATE | GATE-IT-2004 | Question 12"
},
{
"code": null,
"e": 26383,
"s": 26349,
"text": "GATE | GATE-CS-2007 | Question 17"
},
{
"code": null,
"e": 26425,
"s": 26383,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
},
{
"code": null,
"e": 26459,
"s": 26425,
"text": "GATE | GATE-CS-2007 | Question 64"
}
] |
Checking MySQL Database Size in Linux - GeeksforGeeks
|
11 Feb, 2021
Mysql is the most popular open-source database among developers. It is developed and managed by Oracle Corporation and initially released on 23 May 1995. It is compatible with each operating system, Like(Linux, Windows, and macOS) which is major support for web-based applications. In this article, we are going to see how to get the size of a database in MySQL in Linux. Every operating system follows the same approach(Syntax) to check the size of a database.
So let’s see the approach in step-wise:
Step 1: Check your MySql is installed or not.
mysql --version
Step 2: Start MySql.
sudo mysql
Step 3: Check the databases.
show databases;
Step 4: Check the all databases.
Here we define the table_schema and show the size of our database in a new column by following commands:
SELECT table_schema "Database_Name"
SUM(data_length + index_length) / (1024 * 1024) "Database Size in MB"
FROM information_schema.TABLES
GROUP BY table_schema;
Output:
Step 5: Check single databases.
Here we define the table_schema and show the size of any one database (students) in a new column by following commands:
SELECT table_schema "Database_Name",
SUM(data_length + index_length) / (1024 * 1024) "Database Size in MB"
FROM information_schema.TABLES
WHERE table_schema = "students"
ORDER BY (data_length + index_length) DESC;
mysql
Picked
How To
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install FFmpeg on Windows?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Set Git Username and Password in GitBash?
How to create a nested RecyclerView in Android
How to Create and Setup Spring Boot Project in Eclipse IDE?
Sed Command in Linux/Unix with examples
AWK command in Unix/Linux with examples
grep command in Unix/Linux
cut command in Linux with examples
cp command in Linux with examples
|
[
{
"code": null,
"e": 26307,
"s": 26279,
"text": "\n11 Feb, 2021"
},
{
"code": null,
"e": 26770,
"s": 26307,
"text": "Mysql is the most popular open-source database among developers. It is developed and managed by Oracle Corporation and initially released on 23 May 1995. It is compatible with each operating system, Like(Linux, Windows, and macOS) which is major support for web-based applications. In this article, we are going to see how to get the size of a database in MySQL in Linux. Every operating system follows the same approach(Syntax) to check the size of a database. "
},
{
"code": null,
"e": 26810,
"s": 26770,
"text": "So let’s see the approach in step-wise:"
},
{
"code": null,
"e": 26856,
"s": 26810,
"text": "Step 1: Check your MySql is installed or not."
},
{
"code": null,
"e": 26872,
"s": 26856,
"text": "mysql --version"
},
{
"code": null,
"e": 26893,
"s": 26872,
"text": "Step 2: Start MySql."
},
{
"code": null,
"e": 26904,
"s": 26893,
"text": "sudo mysql"
},
{
"code": null,
"e": 26933,
"s": 26904,
"text": "Step 3: Check the databases."
},
{
"code": null,
"e": 26949,
"s": 26933,
"text": "show databases;"
},
{
"code": null,
"e": 26982,
"s": 26949,
"text": "Step 4: Check the all databases."
},
{
"code": null,
"e": 27087,
"s": 26982,
"text": "Here we define the table_schema and show the size of our database in a new column by following commands:"
},
{
"code": null,
"e": 27247,
"s": 27087,
"text": "SELECT table_schema \"Database_Name\"\nSUM(data_length + index_length) / (1024 * 1024) \"Database Size in MB\"\nFROM information_schema.TABLES\nGROUP BY table_schema;"
},
{
"code": null,
"e": 27255,
"s": 27247,
"text": "Output:"
},
{
"code": null,
"e": 27287,
"s": 27255,
"text": "Step 5: Check single databases."
},
{
"code": null,
"e": 27407,
"s": 27287,
"text": "Here we define the table_schema and show the size of any one database (students) in a new column by following commands:"
},
{
"code": null,
"e": 27621,
"s": 27407,
"text": "SELECT table_schema \"Database_Name\",\nSUM(data_length + index_length) / (1024 * 1024) \"Database Size in MB\"\nFROM information_schema.TABLES\nWHERE table_schema = \"students\"\nORDER BY (data_length + index_length) DESC;"
},
{
"code": null,
"e": 27627,
"s": 27621,
"text": "mysql"
},
{
"code": null,
"e": 27634,
"s": 27627,
"text": "Picked"
},
{
"code": null,
"e": 27641,
"s": 27634,
"text": "How To"
},
{
"code": null,
"e": 27652,
"s": 27641,
"text": "Linux-Unix"
},
{
"code": null,
"e": 27750,
"s": 27652,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27784,
"s": 27750,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 27842,
"s": 27784,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
},
{
"code": null,
"e": 27891,
"s": 27842,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 27938,
"s": 27891,
"text": "How to create a nested RecyclerView in Android"
},
{
"code": null,
"e": 27998,
"s": 27938,
"text": "How to Create and Setup Spring Boot Project in Eclipse IDE?"
},
{
"code": null,
"e": 28038,
"s": 27998,
"text": "Sed Command in Linux/Unix with examples"
},
{
"code": null,
"e": 28078,
"s": 28038,
"text": "AWK command in Unix/Linux with examples"
},
{
"code": null,
"e": 28105,
"s": 28078,
"text": "grep command in Unix/Linux"
},
{
"code": null,
"e": 28140,
"s": 28105,
"text": "cut command in Linux with examples"
}
] |
C program to Count the digits of a number - GeeksforGeeks
|
29 Apr, 2020
Given a number N, write a C program to find the count of digits in number N.
Examples:
Input: N = 12345Output: 5Explanation:The count of digit in 12345 = 5.
Input: N = 23451452Output: 8Explanation:The count of digits in 23451452 = 8.
Approach: Count of digits in a number can be found efficiently in few steps:
Remove the last digit of number by dividing it with 10.Increment the count of digit by 1.Keep repeating steps 1 and 2 until the value of N becomes 0. In this case, there will be no more digit left in the number to count
Remove the last digit of number by dividing it with 10.
Increment the count of digit by 1.
Keep repeating steps 1 and 2 until the value of N becomes 0. In this case, there will be no more digit left in the number to count
C
// C Program to find count of// digits in a number #include <stdio.h> // Find the count of digitsint findCount(int n){ int count = 0; // Remove last digit from number // till number is 0 while (n != 0) { //Increment count count++; n /= 10; } // return the count of digit return count;} // Driver programint main(){ int n = 98562; printf("Count of digits in %d = %d\n", n, findCount(n)); return 0;}
Count of digits in 98562 = 5
Time complexity: O(D), where D is the count of digits in number N.Auxiliary Space complexity: O(1)
number-digits
C Programs
Mathematical
School Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C Program to read contents of Whole File
Producer Consumer Problem in C
C program to find the length of a string
C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7
Regular expressions in C
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)
Program to find GCD or HCF of two numbers
|
[
{
"code": null,
"e": 25032,
"s": 25004,
"text": "\n29 Apr, 2020"
},
{
"code": null,
"e": 25109,
"s": 25032,
"text": "Given a number N, write a C program to find the count of digits in number N."
},
{
"code": null,
"e": 25119,
"s": 25109,
"text": "Examples:"
},
{
"code": null,
"e": 25189,
"s": 25119,
"text": "Input: N = 12345Output: 5Explanation:The count of digit in 12345 = 5."
},
{
"code": null,
"e": 25266,
"s": 25189,
"text": "Input: N = 23451452Output: 8Explanation:The count of digits in 23451452 = 8."
},
{
"code": null,
"e": 25343,
"s": 25266,
"text": "Approach: Count of digits in a number can be found efficiently in few steps:"
},
{
"code": null,
"e": 25563,
"s": 25343,
"text": "Remove the last digit of number by dividing it with 10.Increment the count of digit by 1.Keep repeating steps 1 and 2 until the value of N becomes 0. In this case, there will be no more digit left in the number to count"
},
{
"code": null,
"e": 25619,
"s": 25563,
"text": "Remove the last digit of number by dividing it with 10."
},
{
"code": null,
"e": 25654,
"s": 25619,
"text": "Increment the count of digit by 1."
},
{
"code": null,
"e": 25785,
"s": 25654,
"text": "Keep repeating steps 1 and 2 until the value of N becomes 0. In this case, there will be no more digit left in the number to count"
},
{
"code": null,
"e": 25787,
"s": 25785,
"text": "C"
},
{
"code": "// C Program to find count of// digits in a number #include <stdio.h> // Find the count of digitsint findCount(int n){ int count = 0; // Remove last digit from number // till number is 0 while (n != 0) { //Increment count count++; n /= 10; } // return the count of digit return count;} // Driver programint main(){ int n = 98562; printf(\"Count of digits in %d = %d\\n\", n, findCount(n)); return 0;}",
"e": 26239,
"s": 25787,
"text": null
},
{
"code": null,
"e": 26269,
"s": 26239,
"text": "Count of digits in 98562 = 5\n"
},
{
"code": null,
"e": 26368,
"s": 26269,
"text": "Time complexity: O(D), where D is the count of digits in number N.Auxiliary Space complexity: O(1)"
},
{
"code": null,
"e": 26382,
"s": 26368,
"text": "number-digits"
},
{
"code": null,
"e": 26393,
"s": 26382,
"text": "C Programs"
},
{
"code": null,
"e": 26406,
"s": 26393,
"text": "Mathematical"
},
{
"code": null,
"e": 26425,
"s": 26406,
"text": "School Programming"
},
{
"code": null,
"e": 26438,
"s": 26425,
"text": "Mathematical"
},
{
"code": null,
"e": 26536,
"s": 26438,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26545,
"s": 26536,
"text": "Comments"
},
{
"code": null,
"e": 26558,
"s": 26545,
"text": "Old Comments"
},
{
"code": null,
"e": 26599,
"s": 26558,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 26630,
"s": 26599,
"text": "Producer Consumer Problem in C"
},
{
"code": null,
"e": 26671,
"s": 26630,
"text": "C program to find the length of a string"
},
{
"code": null,
"e": 26742,
"s": 26671,
"text": "C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 26767,
"s": 26742,
"text": "Regular expressions in C"
},
{
"code": null,
"e": 26797,
"s": 26767,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 26857,
"s": 26797,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 26872,
"s": 26857,
"text": "C++ Data Types"
},
{
"code": null,
"e": 26915,
"s": 26872,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Draw a moving car using computer graphics programming in C - GeeksforGeeks
|
07 Oct, 2021
In computer graphics, use graphics.h which provide direct functions to draw different coordinate shapes (like circle, rectangle etc). By using these functions we can draw different objects like car, hut, trees, etc. In this program, we will draw a moving car using line and circles.
Functions used in program:
delay(n): This function is used for holding the program output for a small period of time since processing is very fast so use it to see the result.
setcolor(n): A function from graphics.h header file which set the color of the pointer (cursor). There are some predefined colors in computer graphics. Here n is color number.
line(x1, y1, x2, y2): A function from graphics.h header file which draw a line with (x1, y1) as first coordinate of line and (x2, y2) as second coordinate of the line.
circle(x, y, r): A function from graphics.h header file which draw a circle with center (x, y) and radius r.
Example 1: This example create a moving car without using cleardevice() method.
C++
// C program to draw a moving car. This// program run in gcc compiler having// graphics.h library installed#include <graphics.h>#include <stdio.h> // Function to draw moving carvoid draw_moving_car(void) { int i, j = 0, gd = DETECT, gm; // Passed three arguments to initgraph // function to initialize graphics mode initgraph(&gd, &gm, ""); for (i = 0; i <= 420; i = i + 10) { // Set color of car as red setcolor(RED); // Thease lines for bonnet and // body of car line(0 + i, 300, 210 + i, 300); line(50 + i, 300, 75 + i, 270); line(75 + i, 270, 150 + i, 270); line(150 + i, 270, 165 + i, 300); line(0 + i, 300, 0 + i, 330); line(210 + i, 300, 210 + i, 330); // For left wheel of car circle(65 + i, 330, 15); circle(65 + i, 330, 2); // For right wheel of car circle(145 + i, 330, 15); circle(145 + i, 330, 2); // Line left of left wheel line(0 + i, 330, 50 + i, 330); // Line middle of both wheel line(80 + i, 330, 130 + i, 330); // Line right of right wheel line(210 + i, 330, 160 + i, 330); delay(100); // To erase previous drawn car, draw // the whole car at same position // but color using black setcolor(BLACK); // Lines for bonnet and body of car line(0 + i, 300, 210 + i, 300); line(50 + i, 300, 75 + i, 270); line(75 + i, 270, 150 + i, 270); line(150 + i, 270, 165 + i, 300); line(0 + i, 300, 0 + i, 330); line(210 + i, 300, 210 + i, 330); // For left wheel of car circle(65 + i, 330, 15); circle(65 + i, 330, 2); // For right wheel of car circle(145 + i, 330, 15); circle(145 + i, 330, 2); // Line left of left wheel line(0 + i, 330, 50 + i, 330); // Line middle of both wheel line(80 + i, 330, 130 + i, 330); // Line right of right wheel line(210 + i, 330, 160 + i, 330); } getch(); closegraph();} // Driver codeint main(){ draw_moving_car(); return 0;}
Output:
Example 2: This example uses cleardevice() method to clear the screen.
C
// C program to draw a moving car. This// program run in gcc compiler having// graphics.h library installed#include <graphics.h>#include <stdio.h> // Function to draw moving carvoid draw_moving_car(void) { int i, j = 0, gd = DETECT, gm; // Passed three arguments to initgraph // function to initialize graphics mode initgraph(&gd, &gm, ""); for (i = 0; i <= 420; i = i + 10) { // Set color of car as red setcolor(RED); // Thease lines for bonnet and // body of car line(0 + i, 300, 210 + i, 300); line(50 + i, 300, 75 + i, 270); line(75 + i, 270, 150 + i, 270); line(150 + i, 270, 165 + i, 300); line(0 + i, 300, 0 + i, 330); line(210 + i, 300, 210 + i, 330); // For left wheel of car circle(65 + i, 330, 15); circle(65 + i, 330, 2); // For right wheel of car circle(145 + i, 330, 15); circle(145 + i, 330, 2); // Line left of left wheel line(0 + i, 330, 50 + i, 330); // Line middle of both wheel line(80 + i, 330, 130 + i, 330); // Line right of right wheel line(210 + i, 330, 160 + i, 330); delay(100); // To erase previous drawn car // use cleardevice() function cleardevice(); } getch(); closegraph();} // Driver codeint main(){ draw_moving_car(); return 0;}
Output:
surinderdawra388
computer-graphics
C Programs
Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C Program to read contents of Whole File
Header files in C/C++ and its uses
How to return multiple values from a function in C or C++?
How to Append a Character to a String in C
Program to print ASCII Value of a character
SDE SHEET - A Complete Guide for SDE Preparation
Introduction to Algorithms
Software Engineering | Coupling and Cohesion
Software Engineering | Prototyping Model
Difference between NP hard and NP complete problem
|
[
{
"code": null,
"e": 24253,
"s": 24225,
"text": "\n07 Oct, 2021"
},
{
"code": null,
"e": 24536,
"s": 24253,
"text": "In computer graphics, use graphics.h which provide direct functions to draw different coordinate shapes (like circle, rectangle etc). By using these functions we can draw different objects like car, hut, trees, etc. In this program, we will draw a moving car using line and circles."
},
{
"code": null,
"e": 24564,
"s": 24536,
"text": "Functions used in program: "
},
{
"code": null,
"e": 24713,
"s": 24564,
"text": "delay(n): This function is used for holding the program output for a small period of time since processing is very fast so use it to see the result."
},
{
"code": null,
"e": 24889,
"s": 24713,
"text": "setcolor(n): A function from graphics.h header file which set the color of the pointer (cursor). There are some predefined colors in computer graphics. Here n is color number."
},
{
"code": null,
"e": 25057,
"s": 24889,
"text": "line(x1, y1, x2, y2): A function from graphics.h header file which draw a line with (x1, y1) as first coordinate of line and (x2, y2) as second coordinate of the line."
},
{
"code": null,
"e": 25166,
"s": 25057,
"text": "circle(x, y, r): A function from graphics.h header file which draw a circle with center (x, y) and radius r."
},
{
"code": null,
"e": 25247,
"s": 25166,
"text": "Example 1: This example create a moving car without using cleardevice() method. "
},
{
"code": null,
"e": 25251,
"s": 25247,
"text": "C++"
},
{
"code": "// C program to draw a moving car. This// program run in gcc compiler having// graphics.h library installed#include <graphics.h>#include <stdio.h> // Function to draw moving carvoid draw_moving_car(void) { int i, j = 0, gd = DETECT, gm; // Passed three arguments to initgraph // function to initialize graphics mode initgraph(&gd, &gm, \"\"); for (i = 0; i <= 420; i = i + 10) { // Set color of car as red setcolor(RED); // Thease lines for bonnet and // body of car line(0 + i, 300, 210 + i, 300); line(50 + i, 300, 75 + i, 270); line(75 + i, 270, 150 + i, 270); line(150 + i, 270, 165 + i, 300); line(0 + i, 300, 0 + i, 330); line(210 + i, 300, 210 + i, 330); // For left wheel of car circle(65 + i, 330, 15); circle(65 + i, 330, 2); // For right wheel of car circle(145 + i, 330, 15); circle(145 + i, 330, 2); // Line left of left wheel line(0 + i, 330, 50 + i, 330); // Line middle of both wheel line(80 + i, 330, 130 + i, 330); // Line right of right wheel line(210 + i, 330, 160 + i, 330); delay(100); // To erase previous drawn car, draw // the whole car at same position // but color using black setcolor(BLACK); // Lines for bonnet and body of car line(0 + i, 300, 210 + i, 300); line(50 + i, 300, 75 + i, 270); line(75 + i, 270, 150 + i, 270); line(150 + i, 270, 165 + i, 300); line(0 + i, 300, 0 + i, 330); line(210 + i, 300, 210 + i, 330); // For left wheel of car circle(65 + i, 330, 15); circle(65 + i, 330, 2); // For right wheel of car circle(145 + i, 330, 15); circle(145 + i, 330, 2); // Line left of left wheel line(0 + i, 330, 50 + i, 330); // Line middle of both wheel line(80 + i, 330, 130 + i, 330); // Line right of right wheel line(210 + i, 330, 160 + i, 330); } getch(); closegraph();} // Driver codeint main(){ draw_moving_car(); return 0;}",
"e": 27398,
"s": 25251,
"text": null
},
{
"code": null,
"e": 27407,
"s": 27398,
"text": "Output: "
},
{
"code": null,
"e": 27479,
"s": 27407,
"text": "Example 2: This example uses cleardevice() method to clear the screen. "
},
{
"code": null,
"e": 27481,
"s": 27479,
"text": "C"
},
{
"code": "// C program to draw a moving car. This// program run in gcc compiler having// graphics.h library installed#include <graphics.h>#include <stdio.h> // Function to draw moving carvoid draw_moving_car(void) { int i, j = 0, gd = DETECT, gm; // Passed three arguments to initgraph // function to initialize graphics mode initgraph(&gd, &gm, \"\"); for (i = 0; i <= 420; i = i + 10) { // Set color of car as red setcolor(RED); // Thease lines for bonnet and // body of car line(0 + i, 300, 210 + i, 300); line(50 + i, 300, 75 + i, 270); line(75 + i, 270, 150 + i, 270); line(150 + i, 270, 165 + i, 300); line(0 + i, 300, 0 + i, 330); line(210 + i, 300, 210 + i, 330); // For left wheel of car circle(65 + i, 330, 15); circle(65 + i, 330, 2); // For right wheel of car circle(145 + i, 330, 15); circle(145 + i, 330, 2); // Line left of left wheel line(0 + i, 330, 50 + i, 330); // Line middle of both wheel line(80 + i, 330, 130 + i, 330); // Line right of right wheel line(210 + i, 330, 160 + i, 330); delay(100); // To erase previous drawn car // use cleardevice() function cleardevice(); } getch(); closegraph();} // Driver codeint main(){ draw_moving_car(); return 0;}",
"e": 28872,
"s": 27481,
"text": null
},
{
"code": null,
"e": 28881,
"s": 28872,
"text": "Output: "
},
{
"code": null,
"e": 28900,
"s": 28883,
"text": "surinderdawra388"
},
{
"code": null,
"e": 28918,
"s": 28900,
"text": "computer-graphics"
},
{
"code": null,
"e": 28929,
"s": 28918,
"text": "C Programs"
},
{
"code": null,
"e": 28946,
"s": 28929,
"text": "Computer Subject"
},
{
"code": null,
"e": 29044,
"s": 28946,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29053,
"s": 29044,
"text": "Comments"
},
{
"code": null,
"e": 29066,
"s": 29053,
"text": "Old Comments"
},
{
"code": null,
"e": 29107,
"s": 29066,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 29142,
"s": 29107,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 29201,
"s": 29142,
"text": "How to return multiple values from a function in C or C++?"
},
{
"code": null,
"e": 29244,
"s": 29201,
"text": "How to Append a Character to a String in C"
},
{
"code": null,
"e": 29288,
"s": 29244,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 29337,
"s": 29288,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 29364,
"s": 29337,
"text": "Introduction to Algorithms"
},
{
"code": null,
"e": 29409,
"s": 29364,
"text": "Software Engineering | Coupling and Cohesion"
},
{
"code": null,
"e": 29450,
"s": 29409,
"text": "Software Engineering | Prototyping Model"
}
] |
Fizz Buzz in Python
|
Suppose we have a number n. We have to display a string representation of all numbers from 1 to n, but there are some constraints.
If the number is divisible by 3, write Fizz instead of the number
If the number is divisible by 5, write Buzz instead of the number
If the number is divisible by 3 and 5 both, write FizzBuzz instead of the number
To solve this, we will follow these steps −
For all number from 1 to n,if a number is divisible by 3 and 5 both, print “FizzBuzz”otherwise when the number is divisible by 3, print “Fizz”otherwise when the number is divisible by 5, print “Buzz”otherwise, write the number as a string
if a number is divisible by 3 and 5 both, print “FizzBuzz”
otherwise when the number is divisible by 3, print “Fizz”
otherwise when the number is divisible by 5, print “Buzz”
otherwise, write the number as a string
Let us see the following implementation to get a better understanding −
Live Demo
class Solution(object):
def fizzBuzz(self, n):
"""
:type n: int
:rtype: List[str]
"""
result = []
for i in range(1,n+1):
if i% 3== 0 and i%5==0:
result.append("FizzBuzz")
elif i %3==0:
result.append("Fizz")
elif i% 5 == 0:
result.append("Buzz")
else:
result.append(str(i))
return result
ob1 = Solution()
print(ob1.fizzBuzz(30))
30
["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz",
"13","14","FizzBuzz","16","17","Fizz","19","Buzz","Fizz","22","23",
"Fizz","Buzz","26","Fizz","28","29","FizzBuzz"]
|
[
{
"code": null,
"e": 1193,
"s": 1062,
"text": "Suppose we have a number n. We have to display a string representation of all numbers from 1 to n, but there are some constraints."
},
{
"code": null,
"e": 1259,
"s": 1193,
"text": "If the number is divisible by 3, write Fizz instead of the number"
},
{
"code": null,
"e": 1325,
"s": 1259,
"text": "If the number is divisible by 5, write Buzz instead of the number"
},
{
"code": null,
"e": 1406,
"s": 1325,
"text": "If the number is divisible by 3 and 5 both, write FizzBuzz instead of the number"
},
{
"code": null,
"e": 1450,
"s": 1406,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1689,
"s": 1450,
"text": "For all number from 1 to n,if a number is divisible by 3 and 5 both, print “FizzBuzz”otherwise when the number is divisible by 3, print “Fizz”otherwise when the number is divisible by 5, print “Buzz”otherwise, write the number as a string"
},
{
"code": null,
"e": 1748,
"s": 1689,
"text": "if a number is divisible by 3 and 5 both, print “FizzBuzz”"
},
{
"code": null,
"e": 1806,
"s": 1748,
"text": "otherwise when the number is divisible by 3, print “Fizz”"
},
{
"code": null,
"e": 1864,
"s": 1806,
"text": "otherwise when the number is divisible by 5, print “Buzz”"
},
{
"code": null,
"e": 1904,
"s": 1864,
"text": "otherwise, write the number as a string"
},
{
"code": null,
"e": 1976,
"s": 1904,
"text": "Let us see the following implementation to get a better understanding −"
},
{
"code": null,
"e": 1987,
"s": 1976,
"text": " Live Demo"
},
{
"code": null,
"e": 2444,
"s": 1987,
"text": "class Solution(object):\n def fizzBuzz(self, n):\n \"\"\"\n :type n: int\n :rtype: List[str]\n \"\"\"\n result = []\n for i in range(1,n+1):\n if i% 3== 0 and i%5==0:\n result.append(\"FizzBuzz\")\n elif i %3==0:\n result.append(\"Fizz\")\n elif i% 5 == 0:\n result.append(\"Buzz\")\n else:\n result.append(str(i))\n return result\nob1 = Solution()\nprint(ob1.fizzBuzz(30))"
},
{
"code": null,
"e": 2447,
"s": 2444,
"text": "30"
},
{
"code": null,
"e": 2632,
"s": 2447,
"text": "[\"1\",\"2\",\"Fizz\",\"4\",\"Buzz\",\"Fizz\",\"7\",\"8\",\"Fizz\",\"Buzz\",\"11\",\"Fizz\",\n\"13\",\"14\",\"FizzBuzz\",\"16\",\"17\",\"Fizz\",\"19\",\"Buzz\",\"Fizz\",\"22\",\"23\",\n\"Fizz\",\"Buzz\",\"26\",\"Fizz\",\"28\",\"29\",\"FizzBuzz\"]"
}
] |
CSS - Bounce Effect
|
Bounce Animation effect is used to move the element quick up, back, or away from a surface after hitting it.
@keyframes bounce {
0%, 20%, 50%, 80%, 100% {transform: translateY(0);}
40% {transform: translateY(-30px);}
60% {transform: translateY(-15px);}
}
Transform − Transform applies to 2d and 3d transformation to an element.
<html>
<head>
<style>
.animated {
background-image: url(/css/images/logo.png);
background-repeat: no-repeat;
background-position: left top;
padding-top:95px;
margin-bottom:60px;
-webkit-animation-duration: 1s;
animation-duration: 1s;
-webkit-animation-fill-mode: both;
animation-fill-mode: both;
}
@-webkit-keyframes bounce {
0%, 20%, 50%, 80%, 100% {-webkit-transform: translateY(0);}
40% {-webkit-transform: translateY(-30px);}
60% {-webkit-transform: translateY(-15px);}
}
@keyframes bounce {
0%, 20%, 50%, 80%, 100% {transform: translateY(0);}
40% {transform: translateY(-30px);}
60% {transform: translateY(-15px);}
}
.bounce {
-webkit-animation-name: bounce;
animation-name: bounce;
}
</style>
</head>
<body>
<div id = "animated-example" class = "animated bounce"></div>
<button onclick = "myFunction()">Reload page</button>
<script>
function myFunction() {
location.reload();
}
</script>
</body>
</html>
It will produce the following result −
Academic Tutorials
Big Data & Analytics
Computer Programming
Computer Science
Databases
DevOps
Digital Marketing
Engineering Tutorials
Exams Syllabus
Famous Monuments
GATE Exams Tutorials
Latest Technologies
Machine Learning
Mainframe Development
Management Tutorials
Mathematics Tutorials
Microsoft Technologies
Misc tutorials
Mobile Development
Java Technologies
Python Technologies
SAP Tutorials
Programming Scripts
Selected Reading
Software Quality
Soft Skills
Telecom Tutorials
UPSC IAS Exams
Web Development
Sports Tutorials
XML Technologies
Multi-Language
Interview Questions
Academic Tutorials
Big Data & Analytics
Computer Programming
Computer Science
Databases
DevOps
Digital Marketing
Engineering Tutorials
Exams Syllabus
Famous Monuments
GATE Exams Tutorials
Latest Technologies
Machine Learning
Mainframe Development
Management Tutorials
Mathematics Tutorials
Microsoft Technologies
Misc tutorials
Mobile Development
Java Technologies
Python Technologies
SAP Tutorials
Programming Scripts
Selected Reading
Software Quality
Soft Skills
Telecom Tutorials
UPSC IAS Exams
Web Development
Sports Tutorials
XML Technologies
Multi-Language
Interview Questions
Selected Reading
UPSC IAS Exams Notes
Developer's Best Practices
Questions and Answers
Effective Resume Writing
HR Interview Questions
Computer Glossary
Who is Who
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2735,
"s": 2626,
"text": "Bounce Animation effect is used to move the element quick up, back, or away from a surface after hitting it."
},
{
"code": null,
"e": 2894,
"s": 2735,
"text": "@keyframes bounce {\n 0%, 20%, 50%, 80%, 100% {transform: translateY(0);} \n 40% {transform: translateY(-30px);} \n 60% {transform: translateY(-15px);} \n} "
},
{
"code": null,
"e": 2967,
"s": 2894,
"text": "Transform − Transform applies to 2d and 3d transformation to an element."
},
{
"code": null,
"e": 4298,
"s": 2967,
"text": "<html>\n <head>\n <style>\n .animated { \n background-image: url(/css/images/logo.png); \n background-repeat: no-repeat;\n background-position: left top; \n padding-top:95px;\n margin-bottom:60px;\n -webkit-animation-duration: 1s;\n animation-duration: 1s; \n -webkit-animation-fill-mode: both; \n animation-fill-mode: both; \n }\n \n @-webkit-keyframes bounce { \n 0%, 20%, 50%, 80%, 100% {-webkit-transform: translateY(0);} \n 40% {-webkit-transform: translateY(-30px);} \n 60% {-webkit-transform: translateY(-15px);} \n } \n \n @keyframes bounce { \n 0%, 20%, 50%, 80%, 100% {transform: translateY(0);} \n 40% {transform: translateY(-30px);} \n 60% {transform: translateY(-15px);} \n }\n \n .bounce { \n -webkit-animation-name: bounce; \n animation-name: bounce; \n }\n </style>\n </head>\n\n <body>\n \n <div id = \"animated-example\" class = \"animated bounce\"></div>\n <button onclick = \"myFunction()\">Reload page</button>\n \n <script>\n function myFunction() {\n location.reload();\n }\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 4337,
"s": 4298,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 4984,
"s": 4337,
"text": "\n\n Academic Tutorials\n Big Data & Analytics \n Computer Programming \n Computer Science \n Databases \n DevOps \n Digital Marketing \n Engineering Tutorials \n Exams Syllabus \n Famous Monuments \n GATE Exams Tutorials\n Latest Technologies \n Machine Learning \n Mainframe Development \n Management Tutorials \n Mathematics Tutorials\n Microsoft Technologies \n Misc tutorials \n Mobile Development \n Java Technologies \n Python Technologies \n SAP Tutorials \nProgramming Scripts \n Selected Reading \n Software Quality \n Soft Skills \n Telecom Tutorials \n UPSC IAS Exams \n Web Development \n Sports Tutorials \n XML Technologies \n Multi-Language\n Interview Questions\n\n"
},
{
"code": null,
"e": 5004,
"s": 4984,
"text": " Academic Tutorials"
},
{
"code": null,
"e": 5027,
"s": 5004,
"text": " Big Data & Analytics "
},
{
"code": null,
"e": 5050,
"s": 5027,
"text": " Computer Programming "
},
{
"code": null,
"e": 5069,
"s": 5050,
"text": " Computer Science "
},
{
"code": null,
"e": 5081,
"s": 5069,
"text": " Databases "
},
{
"code": null,
"e": 5090,
"s": 5081,
"text": " DevOps "
},
{
"code": null,
"e": 5110,
"s": 5090,
"text": " Digital Marketing "
},
{
"code": null,
"e": 5134,
"s": 5110,
"text": " Engineering Tutorials "
},
{
"code": null,
"e": 5151,
"s": 5134,
"text": " Exams Syllabus "
},
{
"code": null,
"e": 5170,
"s": 5151,
"text": " Famous Monuments "
},
{
"code": null,
"e": 5192,
"s": 5170,
"text": " GATE Exams Tutorials"
},
{
"code": null,
"e": 5214,
"s": 5192,
"text": " Latest Technologies "
},
{
"code": null,
"e": 5233,
"s": 5214,
"text": " Machine Learning "
},
{
"code": null,
"e": 5257,
"s": 5233,
"text": " Mainframe Development "
},
{
"code": null,
"e": 5280,
"s": 5257,
"text": " Management Tutorials "
},
{
"code": null,
"e": 5303,
"s": 5280,
"text": " Mathematics Tutorials"
},
{
"code": null,
"e": 5328,
"s": 5303,
"text": " Microsoft Technologies "
},
{
"code": null,
"e": 5345,
"s": 5328,
"text": " Misc tutorials "
},
{
"code": null,
"e": 5366,
"s": 5345,
"text": " Mobile Development "
},
{
"code": null,
"e": 5386,
"s": 5366,
"text": " Java Technologies "
},
{
"code": null,
"e": 5408,
"s": 5386,
"text": " Python Technologies "
},
{
"code": null,
"e": 5424,
"s": 5408,
"text": " SAP Tutorials "
},
{
"code": null,
"e": 5445,
"s": 5424,
"text": "Programming Scripts "
},
{
"code": null,
"e": 5464,
"s": 5445,
"text": " Selected Reading "
},
{
"code": null,
"e": 5483,
"s": 5464,
"text": " Software Quality "
},
{
"code": null,
"e": 5497,
"s": 5483,
"text": " Soft Skills "
},
{
"code": null,
"e": 5517,
"s": 5497,
"text": " Telecom Tutorials "
},
{
"code": null,
"e": 5534,
"s": 5517,
"text": " UPSC IAS Exams "
},
{
"code": null,
"e": 5552,
"s": 5534,
"text": " Web Development "
},
{
"code": null,
"e": 5571,
"s": 5552,
"text": " Sports Tutorials "
},
{
"code": null,
"e": 5590,
"s": 5571,
"text": " XML Technologies "
},
{
"code": null,
"e": 5606,
"s": 5590,
"text": " Multi-Language"
},
{
"code": null,
"e": 5627,
"s": 5606,
"text": " Interview Questions"
},
{
"code": null,
"e": 5644,
"s": 5627,
"text": "Selected Reading"
},
{
"code": null,
"e": 5665,
"s": 5644,
"text": "UPSC IAS Exams Notes"
},
{
"code": null,
"e": 5692,
"s": 5665,
"text": "Developer's Best Practices"
},
{
"code": null,
"e": 5714,
"s": 5692,
"text": "Questions and Answers"
},
{
"code": null,
"e": 5739,
"s": 5714,
"text": "Effective Resume Writing"
},
{
"code": null,
"e": 5762,
"s": 5739,
"text": "HR Interview Questions"
},
{
"code": null,
"e": 5780,
"s": 5762,
"text": "Computer Glossary"
},
{
"code": null,
"e": 5791,
"s": 5780,
"text": "Who is Who"
},
{
"code": null,
"e": 5798,
"s": 5791,
"text": " Print"
},
{
"code": null,
"e": 5809,
"s": 5798,
"text": " Add Notes"
}
] |
Extract Content from XML
|
How to extract content from an XML document using java.
Following is the program to extract content from an XML document using java.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.html.HtmlParser;
import org.apache.tika.sax.BodyContentHandler;
import org.xml.sax.SAXException;
public class ExtractContentFromXMLDoc {
public static void main(String[] args) throws IOException,SAXException, TikaException {
//detecting the file type
BodyContentHandler handler = new BodyContentHandler();
Metadata metadata = new Metadata();
FileInputStream inputstream = new FileInputStream(new File(
"C:/tika/xmlExample.xml"));
ParseContext pcontext = new ParseContext();
//Html parser
HtmlParser htmlparser = new HtmlParser();
htmlparser.parse(inputstream, handler, metadata,pcontext);
System.out.println("Contents of the document:" + handler.toString());
System.out.println("Metadata of the document:");
String[] metadataNames = metadata.names();
for(String name : metadataNames) {
System.out.println(name + ": " + metadata.get(name));
}
}
}
Contents of the document:
Tanmay Patil
TutorialsPoint
(011) 123-4567
Metadata of the document:
Content-Encoding: windows-1252
Content-Type: text/html; charset = windows-1252
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2124,
"s": 2068,
"text": "How to extract content from an XML document using java."
},
{
"code": null,
"e": 2201,
"s": 2124,
"text": "Following is the program to extract content from an XML document using java."
},
{
"code": null,
"e": 3419,
"s": 2201,
"text": "import java.io.File;\nimport java.io.FileInputStream;\nimport java.io.IOException;\n\nimport org.apache.tika.exception.TikaException;\nimport org.apache.tika.metadata.Metadata;\nimport org.apache.tika.parser.ParseContext;\nimport org.apache.tika.parser.html.HtmlParser;\nimport org.apache.tika.sax.BodyContentHandler;\nimport org.xml.sax.SAXException;\n\npublic class ExtractContentFromXMLDoc {\n public static void main(String[] args) throws IOException,SAXException, TikaException {\n \n //detecting the file type\n BodyContentHandler handler = new BodyContentHandler();\n \n Metadata metadata = new Metadata();\n FileInputStream inputstream = new FileInputStream(new File(\n \"C:/tika/xmlExample.xml\"));\n ParseContext pcontext = new ParseContext();\n\n //Html parser\n HtmlParser htmlparser = new HtmlParser();\n \n htmlparser.parse(inputstream, handler, metadata,pcontext);\n System.out.println(\"Contents of the document:\" + handler.toString());\n System.out.println(\"Metadata of the document:\");\n String[] metadataNames = metadata.names();\n\n for(String name : metadataNames) {\n System.out.println(name + \": \" + metadata.get(name));\n }\n }\n}"
},
{
"code": null,
"e": 3613,
"s": 3419,
"text": "Contents of the document: \n Tanmay Patil \n TutorialsPoint \n (011) 123-4567 \n\nMetadata of the document: \nContent-Encoding: windows-1252 \nContent-Type: text/html; charset = windows-1252 \n"
},
{
"code": null,
"e": 3620,
"s": 3613,
"text": " Print"
},
{
"code": null,
"e": 3631,
"s": 3620,
"text": " Add Notes"
}
] |
Java Program to Find a triplet that sum to a given value - GeeksforGeeks
|
21 Dec, 2021
Given an array and a value, find if there is a triplet in array whose sum is equal to the given value. If there is such a triplet present in array, then print the triplet and return true. Else return false.
Examples:
Input: array = {12, 3, 4, 1, 6, 9}, sum = 24; Output: 12, 3, 9 Explanation: There is a triplet (12, 3 and 9) present in the array whose sum is 24. Input: array = {1, 2, 3, 4, 5}, sum = 9 Output: 5, 3, 1 Explanation: There is a triplet (5, 3 and 1) present in the array whose sum is 9.
Method 1: This is the naive approach towards solving the above problem.
Approach: A simple method is to generate all possible triplets and compare the sum of every triplet with the given value. The following code implements this simple method using three nested loops.
Algorithm: Given an array of length n and a sum sCreate three nested loop first loop runs from start to end (loop counter i), second loop runs from i+1 to end (loop counter j) and third loop runs from j+1 to end (loop counter k)The counter of these loops represents the index of 3 elements of the triplets.Find the sum of ith, jth and kth element. If the sum is equal to given sum. Print the triplet and break.If there is no triplet, then print that no triplet exist.
Given an array of length n and a sum sCreate three nested loop first loop runs from start to end (loop counter i), second loop runs from i+1 to end (loop counter j) and third loop runs from j+1 to end (loop counter k)The counter of these loops represents the index of 3 elements of the triplets.Find the sum of ith, jth and kth element. If the sum is equal to given sum. Print the triplet and break.If there is no triplet, then print that no triplet exist.
Given an array of length n and a sum s
Create three nested loop first loop runs from start to end (loop counter i), second loop runs from i+1 to end (loop counter j) and third loop runs from j+1 to end (loop counter k)
The counter of these loops represents the index of 3 elements of the triplets.
Find the sum of ith, jth and kth element. If the sum is equal to given sum. Print the triplet and break.
If there is no triplet, then print that no triplet exist.
Implementation:
Java
// Java program to find a tripletclass FindTriplet { // returns true if there is triplet with sum equal // to 'sum' present in A[]. Also, prints the triplet boolean find3Numbers(int A[], int arr_size, int sum) { int l, r; // Fix the first element as A[i] for (int i = 0; i < arr_size - 2; i++) { // Fix the second element as A[j] for (int j = i + 1; j < arr_size - 1; j++) { // Now look for the third number for (int k = j + 1; k < arr_size; k++) { if (A[i] + A[j] + A[k] == sum) { System.out.print("Triplet is " + A[i] + ", " + A[j] + ", " + A[k]); return true; } } } } // If we reach here, then no triplet was found return false; } // Driver program to test above functions public static void main(String[] args) { FindTriplet triplet = new FindTriplet(); int A[] = { 1, 4, 45, 6, 10, 8 }; int sum = 22; int arr_size = A.length; triplet.find3Numbers(A, arr_size, sum); }}
Triplet is 4, 10, 8
Complexity Analysis: Time Complexity: O(n3). There are three nested loops traversing the array, so the time complexity is O(n^3)Space Complexity: O(1). As no extra space is required.
Time Complexity: O(n3). There are three nested loops traversing the array, so the time complexity is O(n^3)
Space Complexity: O(1). As no extra space is required.
Method 2: This method uses sorting to increase the efficiency of the code.
Approach: By Sorting the array the efficiency of the algorithm can be improved. This efficient approach uses the two-pointer technique. Traverse the array and fix the first element of the triplet. Now use the Two Pointers algorithm to find if there is a pair whose sum is equal to x – array[i]. Two pointers algorithm take linear time so it is better than a nested loop.
Algorithm : Sort the given array.Loop over the array and fix the first element of the possible triplet, arr[i].Then fix two pointers, one at i + 1 and the other at n – 1. And look at the sum, If the sum is smaller than the required sum, increment the first pointer.Else, If the sum is bigger, Decrease the end pointer to reduce the sum.Else, if the sum of elements at two-pointer is equal to given sum then print the triplet and break.
Sort the given array.Loop over the array and fix the first element of the possible triplet, arr[i].Then fix two pointers, one at i + 1 and the other at n – 1. And look at the sum, If the sum is smaller than the required sum, increment the first pointer.Else, If the sum is bigger, Decrease the end pointer to reduce the sum.Else, if the sum of elements at two-pointer is equal to given sum then print the triplet and break.
Sort the given array.
Loop over the array and fix the first element of the possible triplet, arr[i].
Then fix two pointers, one at i + 1 and the other at n – 1. And look at the sum, If the sum is smaller than the required sum, increment the first pointer.Else, If the sum is bigger, Decrease the end pointer to reduce the sum.Else, if the sum of elements at two-pointer is equal to given sum then print the triplet and break.
If the sum is smaller than the required sum, increment the first pointer.Else, If the sum is bigger, Decrease the end pointer to reduce the sum.Else, if the sum of elements at two-pointer is equal to given sum then print the triplet and break.
If the sum is smaller than the required sum, increment the first pointer.
Else, If the sum is bigger, Decrease the end pointer to reduce the sum.
Else, if the sum of elements at two-pointer is equal to given sum then print the triplet and break.
Implementation:
Java
// Java program to find a tripletclass FindTriplet { // returns true if there is triplet with sum equal // to 'sum' present in A[]. Also, prints the triplet boolean find3Numbers(int A[], int arr_size, int sum) { int l, r; /* Sort the elements */ quickSort(A, 0, arr_size - 1); /* Now fix the first element one by one and find the other two elements */ for (int i = 0; i < arr_size - 2; i++) { // To find the other two elements, start two index variables // from two corners of the array and move them toward each // other l = i + 1; // index of the first element in the remaining elements r = arr_size - 1; // index of the last element while (l < r) { if (A[i] + A[l] + A[r] == sum) { System.out.print("Triplet is " + A[i] + ", " + A[l] + ", " + A[r]); return true; } else if (A[i] + A[l] + A[r] < sum) l++; else // A[i] + A[l] + A[r] > sum r--; } } // If we reach here, then no triplet was found return false; } int partition(int A[], int si, int ei) { int x = A[ei]; int i = (si - 1); int j; for (j = si; j <= ei - 1; j++) { if (A[j] <= x) { i++; int temp = A[i]; A[i] = A[j]; A[j] = temp; } } int temp = A[i + 1]; A[i + 1] = A[ei]; A[ei] = temp; return (i + 1); } /* Implementation of Quick Sort A[] --> Array to be sorted si --> Starting index ei --> Ending index */ void quickSort(int A[], int si, int ei) { int pi; /* Partitioning index */ if (si < ei) { pi = partition(A, si, ei); quickSort(A, si, pi - 1); quickSort(A, pi + 1, ei); } } // Driver program to test above functions public static void main(String[] args) { FindTriplet triplet = new FindTriplet(); int A[] = { 1, 4, 45, 6, 10, 8 }; int sum = 22; int arr_size = A.length; triplet.find3Numbers(A, arr_size, sum); }}
Triplet is 4, 8, 10
Complexity Analysis: Time complexity: O(N^2). There are only two nested loops traversing the array, so time complexity is O(n^2). Two pointers algorithm takes O(n) time and the first element can be fixed using another nested traversal.Space Complexity: O(1). As no extra space is required.
Time complexity: O(N^2). There are only two nested loops traversing the array, so time complexity is O(n^2). Two pointers algorithm takes O(n) time and the first element can be fixed using another nested traversal.
Space Complexity: O(1). As no extra space is required.
Method 3: This is a Hashing-based solution.
Approach: This approach uses extra space but is simpler than the two-pointers approach. Run two loops outer loop from start to end and inner loop from i+1 to end. Create a hashmap or set to store the elements in between i+1 to j-1. So if the given sum is x, check if there is a number in the set which is equal to x – arr[i] – arr[j]. If yes print the triplet.
Algorithm: Traverse the array from start to end. (loop counter i)Create a HashMap or set to store unique pairs.Run another loop from i+1 to end of the array. (loop counter j)If there is an element in the set which is equal to x- arr[i] – arr[j], then print the triplet (arr[i], arr[j], x-arr[i]-arr[j]) and breakInsert the jth element in the set.
Traverse the array from start to end. (loop counter i)Create a HashMap or set to store unique pairs.Run another loop from i+1 to end of the array. (loop counter j)If there is an element in the set which is equal to x- arr[i] – arr[j], then print the triplet (arr[i], arr[j], x-arr[i]-arr[j]) and breakInsert the jth element in the set.
Traverse the array from start to end. (loop counter i)
Create a HashMap or set to store unique pairs.
Run another loop from i+1 to end of the array. (loop counter j)
If there is an element in the set which is equal to x- arr[i] – arr[j], then print the triplet (arr[i], arr[j], x-arr[i]-arr[j]) and break
Insert the jth element in the set.
Implementation:
Java
// Java program to find a triplet using Hashingimport java.util.*; class GFG { // returns true if there is triplet // with sum equal to 'sum' present // in A[]. Also, prints the triplet static boolean find3Numbers(int A[], int arr_size, int sum) { // Fix the first element as A[i] for (int i = 0; i < arr_size - 2; i++) { // Find pair in subarray A[i+1..n-1] // with sum equal to sum - A[i] HashSet<Integer> s = new HashSet<Integer>(); int curr_sum = sum - A[i]; for (int j = i + 1; j < arr_size; j++) { if (s.contains(curr_sum - A[j])) { System.out.printf("Triplet is %d, %d, %d", A[i], A[j], curr_sum - A[j]); return true; } s.add(A[j]); } } // If we reach here, then no triplet was found return false; } /* Driver code */ public static void main(String[] args) { int A[] = { 1, 4, 45, 6, 10, 8 }; int sum = 22; int arr_size = A.length; find3Numbers(A, arr_size, sum); }} // This code has been contributed by 29AjayKumar
Output:
Triplet is 4, 8, 10
Time complexity: O(N^2) Auxiliary Space: O(N)
Please refer complete article on Find a triplet that sum to a given value for more details!
Accolite
Amazon
CarWale
Morgan Stanley
Samsung
two-pointer-algorithm
Arrays
Java
Java Programs
Sorting
Morgan Stanley
Accolite
Amazon
Samsung
CarWale
two-pointer-algorithm
Arrays
Sorting
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Window Sliding Technique
Program to find sum of elements in a given array
Reversal algorithm for array rotation
Trapping Rain Water
Move all negative numbers to beginning and positive to end with constant extra space
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Reverse a string in Java
HashMap in Java with Examples
|
[
{
"code": null,
"e": 24796,
"s": 24768,
"text": "\n21 Dec, 2021"
},
{
"code": null,
"e": 25003,
"s": 24796,
"text": "Given an array and a value, find if there is a triplet in array whose sum is equal to the given value. If there is such a triplet present in array, then print the triplet and return true. Else return false."
},
{
"code": null,
"e": 25015,
"s": 25003,
"text": "Examples: "
},
{
"code": null,
"e": 25300,
"s": 25015,
"text": "Input: array = {12, 3, 4, 1, 6, 9}, sum = 24; Output: 12, 3, 9 Explanation: There is a triplet (12, 3 and 9) present in the array whose sum is 24. Input: array = {1, 2, 3, 4, 5}, sum = 9 Output: 5, 3, 1 Explanation: There is a triplet (5, 3 and 1) present in the array whose sum is 9."
},
{
"code": null,
"e": 25378,
"s": 25304,
"text": "Method 1: This is the naive approach towards solving the above problem. "
},
{
"code": null,
"e": 25577,
"s": 25380,
"text": "Approach: A simple method is to generate all possible triplets and compare the sum of every triplet with the given value. The following code implements this simple method using three nested loops."
},
{
"code": null,
"e": 26045,
"s": 25577,
"text": "Algorithm: Given an array of length n and a sum sCreate three nested loop first loop runs from start to end (loop counter i), second loop runs from i+1 to end (loop counter j) and third loop runs from j+1 to end (loop counter k)The counter of these loops represents the index of 3 elements of the triplets.Find the sum of ith, jth and kth element. If the sum is equal to given sum. Print the triplet and break.If there is no triplet, then print that no triplet exist."
},
{
"code": null,
"e": 26502,
"s": 26045,
"text": "Given an array of length n and a sum sCreate three nested loop first loop runs from start to end (loop counter i), second loop runs from i+1 to end (loop counter j) and third loop runs from j+1 to end (loop counter k)The counter of these loops represents the index of 3 elements of the triplets.Find the sum of ith, jth and kth element. If the sum is equal to given sum. Print the triplet and break.If there is no triplet, then print that no triplet exist."
},
{
"code": null,
"e": 26541,
"s": 26502,
"text": "Given an array of length n and a sum s"
},
{
"code": null,
"e": 26721,
"s": 26541,
"text": "Create three nested loop first loop runs from start to end (loop counter i), second loop runs from i+1 to end (loop counter j) and third loop runs from j+1 to end (loop counter k)"
},
{
"code": null,
"e": 26800,
"s": 26721,
"text": "The counter of these loops represents the index of 3 elements of the triplets."
},
{
"code": null,
"e": 26905,
"s": 26800,
"text": "Find the sum of ith, jth and kth element. If the sum is equal to given sum. Print the triplet and break."
},
{
"code": null,
"e": 26963,
"s": 26905,
"text": "If there is no triplet, then print that no triplet exist."
},
{
"code": null,
"e": 26979,
"s": 26963,
"text": "Implementation:"
},
{
"code": null,
"e": 26984,
"s": 26979,
"text": "Java"
},
{
"code": "// Java program to find a tripletclass FindTriplet { // returns true if there is triplet with sum equal // to 'sum' present in A[]. Also, prints the triplet boolean find3Numbers(int A[], int arr_size, int sum) { int l, r; // Fix the first element as A[i] for (int i = 0; i < arr_size - 2; i++) { // Fix the second element as A[j] for (int j = i + 1; j < arr_size - 1; j++) { // Now look for the third number for (int k = j + 1; k < arr_size; k++) { if (A[i] + A[j] + A[k] == sum) { System.out.print(\"Triplet is \" + A[i] + \", \" + A[j] + \", \" + A[k]); return true; } } } } // If we reach here, then no triplet was found return false; } // Driver program to test above functions public static void main(String[] args) { FindTriplet triplet = new FindTriplet(); int A[] = { 1, 4, 45, 6, 10, 8 }; int sum = 22; int arr_size = A.length; triplet.find3Numbers(A, arr_size, sum); }}",
"e": 28138,
"s": 26984,
"text": null
},
{
"code": null,
"e": 28158,
"s": 28138,
"text": "Triplet is 4, 10, 8"
},
{
"code": null,
"e": 28343,
"s": 28160,
"text": "Complexity Analysis: Time Complexity: O(n3). There are three nested loops traversing the array, so the time complexity is O(n^3)Space Complexity: O(1). As no extra space is required."
},
{
"code": null,
"e": 28451,
"s": 28343,
"text": "Time Complexity: O(n3). There are three nested loops traversing the array, so the time complexity is O(n^3)"
},
{
"code": null,
"e": 28506,
"s": 28451,
"text": "Space Complexity: O(1). As no extra space is required."
},
{
"code": null,
"e": 28582,
"s": 28506,
"text": "Method 2: This method uses sorting to increase the efficiency of the code. "
},
{
"code": null,
"e": 28953,
"s": 28582,
"text": "Approach: By Sorting the array the efficiency of the algorithm can be improved. This efficient approach uses the two-pointer technique. Traverse the array and fix the first element of the triplet. Now use the Two Pointers algorithm to find if there is a pair whose sum is equal to x – array[i]. Two pointers algorithm take linear time so it is better than a nested loop."
},
{
"code": null,
"e": 29389,
"s": 28953,
"text": "Algorithm : Sort the given array.Loop over the array and fix the first element of the possible triplet, arr[i].Then fix two pointers, one at i + 1 and the other at n – 1. And look at the sum, If the sum is smaller than the required sum, increment the first pointer.Else, If the sum is bigger, Decrease the end pointer to reduce the sum.Else, if the sum of elements at two-pointer is equal to given sum then print the triplet and break."
},
{
"code": null,
"e": 29813,
"s": 29389,
"text": "Sort the given array.Loop over the array and fix the first element of the possible triplet, arr[i].Then fix two pointers, one at i + 1 and the other at n – 1. And look at the sum, If the sum is smaller than the required sum, increment the first pointer.Else, If the sum is bigger, Decrease the end pointer to reduce the sum.Else, if the sum of elements at two-pointer is equal to given sum then print the triplet and break."
},
{
"code": null,
"e": 29835,
"s": 29813,
"text": "Sort the given array."
},
{
"code": null,
"e": 29914,
"s": 29835,
"text": "Loop over the array and fix the first element of the possible triplet, arr[i]."
},
{
"code": null,
"e": 30239,
"s": 29914,
"text": "Then fix two pointers, one at i + 1 and the other at n – 1. And look at the sum, If the sum is smaller than the required sum, increment the first pointer.Else, If the sum is bigger, Decrease the end pointer to reduce the sum.Else, if the sum of elements at two-pointer is equal to given sum then print the triplet and break."
},
{
"code": null,
"e": 30483,
"s": 30239,
"text": "If the sum is smaller than the required sum, increment the first pointer.Else, If the sum is bigger, Decrease the end pointer to reduce the sum.Else, if the sum of elements at two-pointer is equal to given sum then print the triplet and break."
},
{
"code": null,
"e": 30557,
"s": 30483,
"text": "If the sum is smaller than the required sum, increment the first pointer."
},
{
"code": null,
"e": 30629,
"s": 30557,
"text": "Else, If the sum is bigger, Decrease the end pointer to reduce the sum."
},
{
"code": null,
"e": 30729,
"s": 30629,
"text": "Else, if the sum of elements at two-pointer is equal to given sum then print the triplet and break."
},
{
"code": null,
"e": 30745,
"s": 30729,
"text": "Implementation:"
},
{
"code": null,
"e": 30750,
"s": 30745,
"text": "Java"
},
{
"code": "// Java program to find a tripletclass FindTriplet { // returns true if there is triplet with sum equal // to 'sum' present in A[]. Also, prints the triplet boolean find3Numbers(int A[], int arr_size, int sum) { int l, r; /* Sort the elements */ quickSort(A, 0, arr_size - 1); /* Now fix the first element one by one and find the other two elements */ for (int i = 0; i < arr_size - 2; i++) { // To find the other two elements, start two index variables // from two corners of the array and move them toward each // other l = i + 1; // index of the first element in the remaining elements r = arr_size - 1; // index of the last element while (l < r) { if (A[i] + A[l] + A[r] == sum) { System.out.print(\"Triplet is \" + A[i] + \", \" + A[l] + \", \" + A[r]); return true; } else if (A[i] + A[l] + A[r] < sum) l++; else // A[i] + A[l] + A[r] > sum r--; } } // If we reach here, then no triplet was found return false; } int partition(int A[], int si, int ei) { int x = A[ei]; int i = (si - 1); int j; for (j = si; j <= ei - 1; j++) { if (A[j] <= x) { i++; int temp = A[i]; A[i] = A[j]; A[j] = temp; } } int temp = A[i + 1]; A[i + 1] = A[ei]; A[ei] = temp; return (i + 1); } /* Implementation of Quick Sort A[] --> Array to be sorted si --> Starting index ei --> Ending index */ void quickSort(int A[], int si, int ei) { int pi; /* Partitioning index */ if (si < ei) { pi = partition(A, si, ei); quickSort(A, si, pi - 1); quickSort(A, pi + 1, ei); } } // Driver program to test above functions public static void main(String[] args) { FindTriplet triplet = new FindTriplet(); int A[] = { 1, 4, 45, 6, 10, 8 }; int sum = 22; int arr_size = A.length; triplet.find3Numbers(A, arr_size, sum); }}",
"e": 33041,
"s": 30750,
"text": null
},
{
"code": null,
"e": 33061,
"s": 33041,
"text": "Triplet is 4, 8, 10"
},
{
"code": null,
"e": 33351,
"s": 33061,
"text": "Complexity Analysis: Time complexity: O(N^2). There are only two nested loops traversing the array, so time complexity is O(n^2). Two pointers algorithm takes O(n) time and the first element can be fixed using another nested traversal.Space Complexity: O(1). As no extra space is required."
},
{
"code": null,
"e": 33566,
"s": 33351,
"text": "Time complexity: O(N^2). There are only two nested loops traversing the array, so time complexity is O(n^2). Two pointers algorithm takes O(n) time and the first element can be fixed using another nested traversal."
},
{
"code": null,
"e": 33621,
"s": 33566,
"text": "Space Complexity: O(1). As no extra space is required."
},
{
"code": null,
"e": 33666,
"s": 33621,
"text": "Method 3: This is a Hashing-based solution. "
},
{
"code": null,
"e": 34029,
"s": 33666,
"text": "Approach: This approach uses extra space but is simpler than the two-pointers approach. Run two loops outer loop from start to end and inner loop from i+1 to end. Create a hashmap or set to store the elements in between i+1 to j-1. So if the given sum is x, check if there is a number in the set which is equal to x – arr[i] – arr[j]. If yes print the triplet. "
},
{
"code": null,
"e": 34376,
"s": 34029,
"text": "Algorithm: Traverse the array from start to end. (loop counter i)Create a HashMap or set to store unique pairs.Run another loop from i+1 to end of the array. (loop counter j)If there is an element in the set which is equal to x- arr[i] – arr[j], then print the triplet (arr[i], arr[j], x-arr[i]-arr[j]) and breakInsert the jth element in the set."
},
{
"code": null,
"e": 34712,
"s": 34376,
"text": "Traverse the array from start to end. (loop counter i)Create a HashMap or set to store unique pairs.Run another loop from i+1 to end of the array. (loop counter j)If there is an element in the set which is equal to x- arr[i] – arr[j], then print the triplet (arr[i], arr[j], x-arr[i]-arr[j]) and breakInsert the jth element in the set."
},
{
"code": null,
"e": 34767,
"s": 34712,
"text": "Traverse the array from start to end. (loop counter i)"
},
{
"code": null,
"e": 34814,
"s": 34767,
"text": "Create a HashMap or set to store unique pairs."
},
{
"code": null,
"e": 34878,
"s": 34814,
"text": "Run another loop from i+1 to end of the array. (loop counter j)"
},
{
"code": null,
"e": 35017,
"s": 34878,
"text": "If there is an element in the set which is equal to x- arr[i] – arr[j], then print the triplet (arr[i], arr[j], x-arr[i]-arr[j]) and break"
},
{
"code": null,
"e": 35052,
"s": 35017,
"text": "Insert the jth element in the set."
},
{
"code": null,
"e": 35068,
"s": 35052,
"text": "Implementation:"
},
{
"code": null,
"e": 35073,
"s": 35068,
"text": "Java"
},
{
"code": "// Java program to find a triplet using Hashingimport java.util.*; class GFG { // returns true if there is triplet // with sum equal to 'sum' present // in A[]. Also, prints the triplet static boolean find3Numbers(int A[], int arr_size, int sum) { // Fix the first element as A[i] for (int i = 0; i < arr_size - 2; i++) { // Find pair in subarray A[i+1..n-1] // with sum equal to sum - A[i] HashSet<Integer> s = new HashSet<Integer>(); int curr_sum = sum - A[i]; for (int j = i + 1; j < arr_size; j++) { if (s.contains(curr_sum - A[j])) { System.out.printf(\"Triplet is %d, %d, %d\", A[i], A[j], curr_sum - A[j]); return true; } s.add(A[j]); } } // If we reach here, then no triplet was found return false; } /* Driver code */ public static void main(String[] args) { int A[] = { 1, 4, 45, 6, 10, 8 }; int sum = 22; int arr_size = A.length; find3Numbers(A, arr_size, sum); }} // This code has been contributed by 29AjayKumar",
"e": 36386,
"s": 35073,
"text": null
},
{
"code": null,
"e": 36394,
"s": 36386,
"text": "Output:"
},
{
"code": null,
"e": 36414,
"s": 36394,
"text": "Triplet is 4, 8, 10"
},
{
"code": null,
"e": 36461,
"s": 36414,
"text": "Time complexity: O(N^2) Auxiliary Space: O(N) "
},
{
"code": null,
"e": 36553,
"s": 36461,
"text": "Please refer complete article on Find a triplet that sum to a given value for more details!"
},
{
"code": null,
"e": 36562,
"s": 36553,
"text": "Accolite"
},
{
"code": null,
"e": 36569,
"s": 36562,
"text": "Amazon"
},
{
"code": null,
"e": 36577,
"s": 36569,
"text": "CarWale"
},
{
"code": null,
"e": 36592,
"s": 36577,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 36600,
"s": 36592,
"text": "Samsung"
},
{
"code": null,
"e": 36622,
"s": 36600,
"text": "two-pointer-algorithm"
},
{
"code": null,
"e": 36629,
"s": 36622,
"text": "Arrays"
},
{
"code": null,
"e": 36634,
"s": 36629,
"text": "Java"
},
{
"code": null,
"e": 36648,
"s": 36634,
"text": "Java Programs"
},
{
"code": null,
"e": 36656,
"s": 36648,
"text": "Sorting"
},
{
"code": null,
"e": 36671,
"s": 36656,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 36680,
"s": 36671,
"text": "Accolite"
},
{
"code": null,
"e": 36687,
"s": 36680,
"text": "Amazon"
},
{
"code": null,
"e": 36695,
"s": 36687,
"text": "Samsung"
},
{
"code": null,
"e": 36703,
"s": 36695,
"text": "CarWale"
},
{
"code": null,
"e": 36725,
"s": 36703,
"text": "two-pointer-algorithm"
},
{
"code": null,
"e": 36732,
"s": 36725,
"text": "Arrays"
},
{
"code": null,
"e": 36740,
"s": 36732,
"text": "Sorting"
},
{
"code": null,
"e": 36745,
"s": 36740,
"text": "Java"
},
{
"code": null,
"e": 36843,
"s": 36745,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36852,
"s": 36843,
"text": "Comments"
},
{
"code": null,
"e": 36865,
"s": 36852,
"text": "Old Comments"
},
{
"code": null,
"e": 36890,
"s": 36865,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 36939,
"s": 36890,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 36977,
"s": 36939,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 36997,
"s": 36977,
"text": "Trapping Rain Water"
},
{
"code": null,
"e": 37082,
"s": 36997,
"text": "Move all negative numbers to beginning and positive to end with constant extra space"
},
{
"code": null,
"e": 37126,
"s": 37082,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 37148,
"s": 37126,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 37184,
"s": 37148,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 37209,
"s": 37184,
"text": "Reverse a string in Java"
}
] |
Write your own memcpy() and memmove() - GeeksforGeeks
|
10 Dec, 2021
The memcpy function is used to copy a block of data from a source address to a destination address. Below is its prototype.
void * memcpy(void * destination, const void * source, size_t num);
The idea is to simply typecast given addresses to char *(char takes 1 byte). Then one by one copy data from source to destination. Below is implementation of this idea.
// A C implementation of memcpy()#include<stdio.h>#include<string.h> void myMemCpy(void *dest, void *src, size_t n){ // Typecast src and dest addresses to (char *) char *csrc = (char *)src; char *cdest = (char *)dest; // Copy contents of src[] to dest[] for (int i=0; i<n; i++) cdest[i] = csrc[i];} // Driver programint main(){ char csrc[] = "GeeksforGeeks"; char cdest[100]; myMemCpy(cdest, csrc, strlen(csrc)+1); printf("Copied string is %s", cdest); int isrc[] = {10, 20, 30, 40, 50}; int n = sizeof(isrc)/sizeof(isrc[0]); int idest[n], i; myMemCpy(idest, isrc, sizeof(isrc)); printf("\nCopied array is "); for (i=0; i<n; i++) printf("%d ", idest[i]); return 0;}
Output:
Copied string is GeeksforGeeks
Copied array is 10 20 30 40 50
memmove() is similar to memcpy() as it also copies data from a source to destination. memcpy() leads to problems when source and destination addresses overlap as memcpy() simply copies data one by one from one location to another. For example consider below program.
// Sample program to show that memcpy() can lose data.#include <stdio.h>#include <string.h>int main(){ char csrc[100] = "Geeksfor"; memcpy(csrc+5, csrc, strlen(csrc)+1); printf("%s", csrc); return 0;}
Output:
GeeksGeeksfor
Since the input addresses are overlapping, the above program overwrites the original string and causes data loss.
// Sample program to show that memmove() is better than memcpy()// when addresses overlap.#include <stdio.h>#include <string.h>int main(){ char csrc[100] = "Geeksfor"; memmove(csrc+5, csrc, strlen(csrc)+1); printf("%s", csrc); return 0;}
Output:
GeeksGeeksfor
The trick here is to use a temp array instead of directly copying from src to dest. The use of temp array is important to handle cases when source and destination addresses are overlapping.
//C++ program to demonstrate implementation of memmove()#include<stdio.h>#include<string.h> // A function to copy block of 'n' bytes from source// address 'src' to destination address 'dest'.void myMemMove(void *dest, void *src, size_t n){ // Typecast src and dest addresses to (char *) char *csrc = (char *)src; char *cdest = (char *)dest; // Create a temporary array to hold data of src char *temp = new char[n]; // Copy data from csrc[] to temp[] for (int i=0; i<n; i++) temp[i] = csrc[i]; // Copy data from temp[] to cdest[] for (int i=0; i<n; i++) cdest[i] = temp[i]; delete [] temp;} // Driver programint main(){ char csrc[100] = "Geeksfor"; myMemMove(csrc+5, csrc, strlen(csrc)+1); printf("%s", csrc); return 0;}
Output:
GeeksGeeksfor
Optimizations:The algorithm is inefficient (and honestly double the time if you use a temporary array). Double copies should be avoided unless if it is really impossible.
In this case though it is easily possible to avoid double copies by picking a direction of copy. In fact this is what the memmove() library function does.
By comparing the src and the dst addresses you should be able to find if they overlap.
– If they do not overlap, you can copy in any direction– If they do overlap, find which end of dest overlaps with the source and choose the direction of copy accordingly.– If the beginning of dest overlaps, copy from end to beginning– If the end of dest overlaps, copy from beginning to end– Another optimization would be to copy by word size. Just be careful to handle the boundary conditions.– A further optimization would be to use vector instructions for the copy since they’re contiguous.
This article is contributed by Saurabh Jain. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
SwatiGangwar
rkbhola5
CPP-Library
cpp-pointer
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
Core Dump (Segmentation fault) in C/C++
fork() in C
Command line arguments in C/C++
Initialize a vector in C++ (6 different ways)
Inheritance in C++
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
Operator Overloading in C++
|
[
{
"code": null,
"e": 24366,
"s": 24338,
"text": "\n10 Dec, 2021"
},
{
"code": null,
"e": 24490,
"s": 24366,
"text": "The memcpy function is used to copy a block of data from a source address to a destination address. Below is its prototype."
},
{
"code": null,
"e": 24558,
"s": 24490,
"text": "void * memcpy(void * destination, const void * source, size_t num);"
},
{
"code": null,
"e": 24727,
"s": 24558,
"text": "The idea is to simply typecast given addresses to char *(char takes 1 byte). Then one by one copy data from source to destination. Below is implementation of this idea."
},
{
"code": "// A C implementation of memcpy()#include<stdio.h>#include<string.h> void myMemCpy(void *dest, void *src, size_t n){ // Typecast src and dest addresses to (char *) char *csrc = (char *)src; char *cdest = (char *)dest; // Copy contents of src[] to dest[] for (int i=0; i<n; i++) cdest[i] = csrc[i];} // Driver programint main(){ char csrc[] = \"GeeksforGeeks\"; char cdest[100]; myMemCpy(cdest, csrc, strlen(csrc)+1); printf(\"Copied string is %s\", cdest); int isrc[] = {10, 20, 30, 40, 50}; int n = sizeof(isrc)/sizeof(isrc[0]); int idest[n], i; myMemCpy(idest, isrc, sizeof(isrc)); printf(\"\\nCopied array is \"); for (i=0; i<n; i++) printf(\"%d \", idest[i]); return 0;}",
"e": 25442,
"s": 24727,
"text": null
},
{
"code": null,
"e": 25450,
"s": 25442,
"text": "Output:"
},
{
"code": null,
"e": 25512,
"s": 25450,
"text": "Copied string is GeeksforGeeks\nCopied array is 10 20 30 40 50"
},
{
"code": null,
"e": 25779,
"s": 25512,
"text": "memmove() is similar to memcpy() as it also copies data from a source to destination. memcpy() leads to problems when source and destination addresses overlap as memcpy() simply copies data one by one from one location to another. For example consider below program."
},
{
"code": "// Sample program to show that memcpy() can lose data.#include <stdio.h>#include <string.h>int main(){ char csrc[100] = \"Geeksfor\"; memcpy(csrc+5, csrc, strlen(csrc)+1); printf(\"%s\", csrc); return 0;}",
"e": 25988,
"s": 25779,
"text": null
},
{
"code": null,
"e": 25996,
"s": 25988,
"text": "Output:"
},
{
"code": null,
"e": 26010,
"s": 25996,
"text": "GeeksGeeksfor"
},
{
"code": null,
"e": 26124,
"s": 26010,
"text": "Since the input addresses are overlapping, the above program overwrites the original string and causes data loss."
},
{
"code": "// Sample program to show that memmove() is better than memcpy()// when addresses overlap.#include <stdio.h>#include <string.h>int main(){ char csrc[100] = \"Geeksfor\"; memmove(csrc+5, csrc, strlen(csrc)+1); printf(\"%s\", csrc); return 0;}",
"e": 26370,
"s": 26124,
"text": null
},
{
"code": null,
"e": 26378,
"s": 26370,
"text": "Output:"
},
{
"code": null,
"e": 26392,
"s": 26378,
"text": "GeeksGeeksfor"
},
{
"code": null,
"e": 26582,
"s": 26392,
"text": "The trick here is to use a temp array instead of directly copying from src to dest. The use of temp array is important to handle cases when source and destination addresses are overlapping."
},
{
"code": "//C++ program to demonstrate implementation of memmove()#include<stdio.h>#include<string.h> // A function to copy block of 'n' bytes from source// address 'src' to destination address 'dest'.void myMemMove(void *dest, void *src, size_t n){ // Typecast src and dest addresses to (char *) char *csrc = (char *)src; char *cdest = (char *)dest; // Create a temporary array to hold data of src char *temp = new char[n]; // Copy data from csrc[] to temp[] for (int i=0; i<n; i++) temp[i] = csrc[i]; // Copy data from temp[] to cdest[] for (int i=0; i<n; i++) cdest[i] = temp[i]; delete [] temp;} // Driver programint main(){ char csrc[100] = \"Geeksfor\"; myMemMove(csrc+5, csrc, strlen(csrc)+1); printf(\"%s\", csrc); return 0;}",
"e": 27352,
"s": 26582,
"text": null
},
{
"code": null,
"e": 27360,
"s": 27352,
"text": "Output:"
},
{
"code": null,
"e": 27374,
"s": 27360,
"text": "GeeksGeeksfor"
},
{
"code": null,
"e": 27545,
"s": 27374,
"text": "Optimizations:The algorithm is inefficient (and honestly double the time if you use a temporary array). Double copies should be avoided unless if it is really impossible."
},
{
"code": null,
"e": 27700,
"s": 27545,
"text": "In this case though it is easily possible to avoid double copies by picking a direction of copy. In fact this is what the memmove() library function does."
},
{
"code": null,
"e": 27787,
"s": 27700,
"text": "By comparing the src and the dst addresses you should be able to find if they overlap."
},
{
"code": null,
"e": 28281,
"s": 27787,
"text": "– If they do not overlap, you can copy in any direction– If they do overlap, find which end of dest overlaps with the source and choose the direction of copy accordingly.– If the beginning of dest overlaps, copy from end to beginning– If the end of dest overlaps, copy from beginning to end– Another optimization would be to copy by word size. Just be careful to handle the boundary conditions.– A further optimization would be to use vector instructions for the copy since they’re contiguous."
},
{
"code": null,
"e": 28451,
"s": 28281,
"text": "This article is contributed by Saurabh Jain. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 28464,
"s": 28451,
"text": "SwatiGangwar"
},
{
"code": null,
"e": 28473,
"s": 28464,
"text": "rkbhola5"
},
{
"code": null,
"e": 28485,
"s": 28473,
"text": "CPP-Library"
},
{
"code": null,
"e": 28497,
"s": 28485,
"text": "cpp-pointer"
},
{
"code": null,
"e": 28508,
"s": 28497,
"text": "C Language"
},
{
"code": null,
"e": 28512,
"s": 28508,
"text": "C++"
},
{
"code": null,
"e": 28516,
"s": 28512,
"text": "CPP"
},
{
"code": null,
"e": 28614,
"s": 28516,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28642,
"s": 28614,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 28688,
"s": 28642,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 28728,
"s": 28688,
"text": "Core Dump (Segmentation fault) in C/C++"
},
{
"code": null,
"e": 28740,
"s": 28728,
"text": "fork() in C"
},
{
"code": null,
"e": 28772,
"s": 28740,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 28818,
"s": 28772,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 28837,
"s": 28818,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 28880,
"s": 28837,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 28904,
"s": 28880,
"text": "C++ Classes and Objects"
}
] |
Counting Inversions using Ordered Set and GNU C++ PBDS - GeeksforGeeks
|
22 Mar, 2022
Given an array arr[] of N integers. The task is to find the number of inversion. Two elements arr[i] and arr[j] form an inversion if arr[i] > arr[j] and i < j.
Examples
Input: arr[] = {8, 4, 2, 1} Output: 6 Explanation: Given array has six inversions:
(8, 4): arr[0] > arr[1] and 0 < 1
(8, 2): arr[0] > arr[2] and 0 < 2
(8, 1): arr[0] > arr[3] and 0 < 3
(4, 2): arr[1] > arr[2] and 1 < 2
(4, 1): arr[1] > arr[3] and 1 < 3
(2, 1): arr[2] > arr[3] and 2 < 3
Input: arr[] = {2, 3} Output: 0 Explanation: There is no such pair exists such that arr[i] > arr[j] and i < j.
We have already discussed below approaches:
Count Inversions in an array | Set 1 (Using Merge Sort)
Count inversions in an array | Set 2 (Using Self-Balancing BST)
Counting Inversions using Set in C++ STL
Count inversions in an array | Set 3 (Using BIT)
In this post, we will be discussing an approach using Ordered Set and GNU C++ PBDS.
Approach: We will be using the function order_of_key(K) which returns number of elements strictly smaller than K in log N time.
Insert the first element of the array in the Ordered_Set.For all the remaining element in arr[] do the following: Insert the current element in the Ordered_Set.Find the number of element strictly less than current element + 1 in Ordered_Set using function order_of_key(arr[i]+1).The difference between size of Ordered_Set and order_of_key(current_element + 1) will give the inversion count for the current element.
Insert the first element of the array in the Ordered_Set.
For all the remaining element in arr[] do the following: Insert the current element in the Ordered_Set.Find the number of element strictly less than current element + 1 in Ordered_Set using function order_of_key(arr[i]+1).The difference between size of Ordered_Set and order_of_key(current_element + 1) will give the inversion count for the current element.
Insert the current element in the Ordered_Set.
Find the number of element strictly less than current element + 1 in Ordered_Set using function order_of_key(arr[i]+1).
The difference between size of Ordered_Set and order_of_key(current_element + 1) will give the inversion count for the current element.
For Example:
arr[] = {8, 4, 2, 1}
Ordered_Set S = {8}
For remaining element in arr[]:
At index 1, the element is 4
S = {4, 8}
key = order_of_key(5) = 1
The difference between size of S and key gives the total
number of inversion count for that current element.
inversion_count = S.size() - key = 2 - 1 = 1
Inversion Pairs are: (8, 4)
At index 2, the element is 2
S = {2, 4, 8}
key = order_of_key(3) = 1
inversion_count = S.size() - key = 3 - 1 = 2
Inversion Pairs are: (8, 2) and (4, 2)
At index 3, the element is 1
S = {1, 2, 4, 8}
key = order_of_key(2) = 1
inversion_count = S.size() - key = 4 - 1 = 3
Inversion Pairs are: (8, 1), (4, 1) and (2, 1)
Total inversion count = 1 + 2 + 3 = 6
Below is the implementation of the above approach:
C++
// Ordered set in GNU C++ based// approach for inversion count#include <bits/stdc++.h>#include <ext/pb_ds/assoc_container.hpp>#include <ext/pb_ds/tree_policy.hpp>using namespace __gnu_pbds;using namespace std; // Ordered Set Treetypedef tree<int, null_type, less_equal<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set; // Returns inversion count in// arr[0..n-1]int getInvCount(int arr[], int n){ int key; // Initialise the ordered_set ordered_set set1; // Insert the first // element in set set1.insert(arr[0]); // Initialise inversion // count to zero int invcount = 0; // Finding the inversion // count for current element for (int i = 1; i < n; i++) { set1.insert(arr[i]); // Number of elements strictly // less than arr[i]+1 key = set1.order_of_key(arr[i] + 1); // Difference between set size // and key will give the // inversion count invcount += set1.size() - key; } return invcount;} // Driver's Codeint main(){ int arr[] = { 8, 4, 2, 1 }; int n = sizeof(arr) / sizeof(int); // Function call to count // inversion cout << getInvCount(arr, n); return 0;}
6
Time Complexity: O(Nlog N)
saurabh1990aror
panchalpranav01
Advanced Data Structure
Algorithms
Arrays
Competitive Programming
Arrays
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Proof that Dominant Set of a Graph is NP-Complete
2-3 Trees | (Search, Insert and Deletion)
Extendible Hashing (Dynamic approach to DBMS)
Advantages of Trie Data Structure
Cartesian Tree
SDE SHEET - A Complete Guide for SDE Preparation
Top 50 Array Coding Problems for Interviews
DSA Sheet by Love Babbar
Difference between BFS and DFS
A* Search Algorithm
|
[
{
"code": null,
"e": 24488,
"s": 24460,
"text": "\n22 Mar, 2022"
},
{
"code": null,
"e": 24649,
"s": 24488,
"text": "Given an array arr[] of N integers. The task is to find the number of inversion. Two elements arr[i] and arr[j] form an inversion if arr[i] > arr[j] and i < j. "
},
{
"code": null,
"e": 24659,
"s": 24649,
"text": "Examples "
},
{
"code": null,
"e": 24744,
"s": 24659,
"text": "Input: arr[] = {8, 4, 2, 1} Output: 6 Explanation: Given array has six inversions: "
},
{
"code": null,
"e": 24778,
"s": 24744,
"text": "(8, 4): arr[0] > arr[1] and 0 < 1"
},
{
"code": null,
"e": 24812,
"s": 24778,
"text": "(8, 2): arr[0] > arr[2] and 0 < 2"
},
{
"code": null,
"e": 24846,
"s": 24812,
"text": "(8, 1): arr[0] > arr[3] and 0 < 3"
},
{
"code": null,
"e": 24880,
"s": 24846,
"text": "(4, 2): arr[1] > arr[2] and 1 < 2"
},
{
"code": null,
"e": 24914,
"s": 24880,
"text": "(4, 1): arr[1] > arr[3] and 1 < 3"
},
{
"code": null,
"e": 24948,
"s": 24914,
"text": "(2, 1): arr[2] > arr[3] and 2 < 3"
},
{
"code": null,
"e": 25060,
"s": 24948,
"text": "Input: arr[] = {2, 3} Output: 0 Explanation: There is no such pair exists such that arr[i] > arr[j] and i < j. "
},
{
"code": null,
"e": 25106,
"s": 25060,
"text": "We have already discussed below approaches: "
},
{
"code": null,
"e": 25162,
"s": 25106,
"text": "Count Inversions in an array | Set 1 (Using Merge Sort)"
},
{
"code": null,
"e": 25226,
"s": 25162,
"text": "Count inversions in an array | Set 2 (Using Self-Balancing BST)"
},
{
"code": null,
"e": 25267,
"s": 25226,
"text": "Counting Inversions using Set in C++ STL"
},
{
"code": null,
"e": 25316,
"s": 25267,
"text": "Count inversions in an array | Set 3 (Using BIT)"
},
{
"code": null,
"e": 25400,
"s": 25316,
"text": "In this post, we will be discussing an approach using Ordered Set and GNU C++ PBDS."
},
{
"code": null,
"e": 25530,
"s": 25400,
"text": "Approach: We will be using the function order_of_key(K) which returns number of elements strictly smaller than K in log N time. "
},
{
"code": null,
"e": 25945,
"s": 25530,
"text": "Insert the first element of the array in the Ordered_Set.For all the remaining element in arr[] do the following: Insert the current element in the Ordered_Set.Find the number of element strictly less than current element + 1 in Ordered_Set using function order_of_key(arr[i]+1).The difference between size of Ordered_Set and order_of_key(current_element + 1) will give the inversion count for the current element."
},
{
"code": null,
"e": 26003,
"s": 25945,
"text": "Insert the first element of the array in the Ordered_Set."
},
{
"code": null,
"e": 26361,
"s": 26003,
"text": "For all the remaining element in arr[] do the following: Insert the current element in the Ordered_Set.Find the number of element strictly less than current element + 1 in Ordered_Set using function order_of_key(arr[i]+1).The difference between size of Ordered_Set and order_of_key(current_element + 1) will give the inversion count for the current element."
},
{
"code": null,
"e": 26408,
"s": 26361,
"text": "Insert the current element in the Ordered_Set."
},
{
"code": null,
"e": 26528,
"s": 26408,
"text": "Find the number of element strictly less than current element + 1 in Ordered_Set using function order_of_key(arr[i]+1)."
},
{
"code": null,
"e": 26664,
"s": 26528,
"text": "The difference between size of Ordered_Set and order_of_key(current_element + 1) will give the inversion count for the current element."
},
{
"code": null,
"e": 26677,
"s": 26664,
"text": "For Example:"
},
{
"code": null,
"e": 27362,
"s": 26677,
"text": "arr[] = {8, 4, 2, 1}\nOrdered_Set S = {8}\nFor remaining element in arr[]:\nAt index 1, the element is 4\nS = {4, 8}\nkey = order_of_key(5) = 1\nThe difference between size of S and key gives the total \nnumber of inversion count for that current element.\ninversion_count = S.size() - key = 2 - 1 = 1\nInversion Pairs are: (8, 4)\n\nAt index 2, the element is 2\nS = {2, 4, 8}\nkey = order_of_key(3) = 1\ninversion_count = S.size() - key = 3 - 1 = 2\nInversion Pairs are: (8, 2) and (4, 2)\n\nAt index 3, the element is 1\nS = {1, 2, 4, 8}\nkey = order_of_key(2) = 1\ninversion_count = S.size() - key = 4 - 1 = 3\nInversion Pairs are: (8, 1), (4, 1) and (2, 1)\n\nTotal inversion count = 1 + 2 + 3 = 6"
},
{
"code": null,
"e": 27414,
"s": 27362,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27418,
"s": 27414,
"text": "C++"
},
{
"code": "// Ordered set in GNU C++ based// approach for inversion count#include <bits/stdc++.h>#include <ext/pb_ds/assoc_container.hpp>#include <ext/pb_ds/tree_policy.hpp>using namespace __gnu_pbds;using namespace std; // Ordered Set Treetypedef tree<int, null_type, less_equal<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set; // Returns inversion count in// arr[0..n-1]int getInvCount(int arr[], int n){ int key; // Initialise the ordered_set ordered_set set1; // Insert the first // element in set set1.insert(arr[0]); // Initialise inversion // count to zero int invcount = 0; // Finding the inversion // count for current element for (int i = 1; i < n; i++) { set1.insert(arr[i]); // Number of elements strictly // less than arr[i]+1 key = set1.order_of_key(arr[i] + 1); // Difference between set size // and key will give the // inversion count invcount += set1.size() - key; } return invcount;} // Driver's Codeint main(){ int arr[] = { 8, 4, 2, 1 }; int n = sizeof(arr) / sizeof(int); // Function call to count // inversion cout << getInvCount(arr, n); return 0;}",
"e": 28647,
"s": 27418,
"text": null
},
{
"code": null,
"e": 28649,
"s": 28647,
"text": "6"
},
{
"code": null,
"e": 28679,
"s": 28651,
"text": "Time Complexity: O(Nlog N) "
},
{
"code": null,
"e": 28695,
"s": 28679,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 28711,
"s": 28695,
"text": "panchalpranav01"
},
{
"code": null,
"e": 28735,
"s": 28711,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 28746,
"s": 28735,
"text": "Algorithms"
},
{
"code": null,
"e": 28753,
"s": 28746,
"text": "Arrays"
},
{
"code": null,
"e": 28777,
"s": 28753,
"text": "Competitive Programming"
},
{
"code": null,
"e": 28784,
"s": 28777,
"text": "Arrays"
},
{
"code": null,
"e": 28795,
"s": 28784,
"text": "Algorithms"
},
{
"code": null,
"e": 28893,
"s": 28795,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28902,
"s": 28893,
"text": "Comments"
},
{
"code": null,
"e": 28915,
"s": 28902,
"text": "Old Comments"
},
{
"code": null,
"e": 28965,
"s": 28915,
"text": "Proof that Dominant Set of a Graph is NP-Complete"
},
{
"code": null,
"e": 29007,
"s": 28965,
"text": "2-3 Trees | (Search, Insert and Deletion)"
},
{
"code": null,
"e": 29053,
"s": 29007,
"text": "Extendible Hashing (Dynamic approach to DBMS)"
},
{
"code": null,
"e": 29087,
"s": 29053,
"text": "Advantages of Trie Data Structure"
},
{
"code": null,
"e": 29102,
"s": 29087,
"text": "Cartesian Tree"
},
{
"code": null,
"e": 29151,
"s": 29102,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 29195,
"s": 29151,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 29220,
"s": 29195,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 29251,
"s": 29220,
"text": "Difference between BFS and DFS"
}
] |
How do I remove a substring from the end of a string in Python?
|
If you want to remove a substring from the end of a string, you should fisrt check if the string ends with that substring. If it does, then slice the string keeping only the part without substring. For example,
def rchop(string, ending):
if string.endswith(ending):
return string[:-len(ending)]
return string
chopped_str = rchop('Hello world', 'orld')
print chopped_str
This will give the output:
Hello w
If speed is not important, you can also use a regex here. For example,
>>> import re
>>> re.sub('orld$', '', 'Hello world')
Hello w
|
[
{
"code": null,
"e": 1273,
"s": 1062,
"text": "If you want to remove a substring from the end of a string, you should fisrt check if the string ends with that substring. If it does, then slice the string keeping only the part without substring. For example,"
},
{
"code": null,
"e": 1440,
"s": 1273,
"text": "def rchop(string, ending):\n if string.endswith(ending):\n return string[:-len(ending)]\n return string\nchopped_str = rchop('Hello world', 'orld')\nprint chopped_str"
},
{
"code": null,
"e": 1467,
"s": 1440,
"text": "This will give the output:"
},
{
"code": null,
"e": 1475,
"s": 1467,
"text": "Hello w"
},
{
"code": null,
"e": 1546,
"s": 1475,
"text": "If speed is not important, you can also use a regex here. For example,"
},
{
"code": null,
"e": 1607,
"s": 1546,
"text": ">>> import re\n>>> re.sub('orld$', '', 'Hello world')\nHello w"
}
] |
1 to n bit numbers with no consecutive 1s in binary representation - GeeksforGeeks
|
30 Apr, 2021
Given a number n, our task is to find all 1 to n bit numbers with no consecutive 1s in their binary representation.Examples:
Input: N = 4
Output: 1 2 4 5 8 9 10
These are numbers with 1 to 4
bits and no consecutive ones in
binary representation.
Input: n = 3
Output: 1 2 4 5
Approach:
There will be 2n numbers with number of bits from 1 to n.Iterate through all 2n numbers. For every number check if it contains consecutive set bits or not. To check, we do bitwise and of current number i and left-shifted i. If the bitwise and contains a non-zero bit (or its value is non-zero), then the given number contains consecutive set bits.
There will be 2n numbers with number of bits from 1 to n.
Iterate through all 2n numbers. For every number check if it contains consecutive set bits or not. To check, we do bitwise and of current number i and left-shifted i. If the bitwise and contains a non-zero bit (or its value is non-zero), then the given number contains consecutive set bits.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// Print all numbers upto n bits// with no consecutive set bits.#include<iostream>using namespace std; void printNonConsecutive(int n){ // Let us first compute // 2 raised to power n. int p = (1 << n); // loop 1 to n to check // all the numbers for (int i = 1; i < p; i++) // A number i doesn't contain // consecutive set bits if // bitwise and of i and left // shifted i do't contain a // commons set bit. if ((i & (i << 1)) == 0) cout << i << " ";} // Driver codeint main(){ int n = 3; printNonConsecutive(n); return 0;}
// Java Code to Print all numbers upto// n bits with no consecutive set bits.import java.util.*; class GFG{ static void printNonConsecutive(int n) { // Let us first compute // 2 raised to power n. int p = (1 << n); // loop 1 to n to check // all the numbers for (int i = 1; i < p; i++) // A number i doesn't contain // consecutive set bits if // bitwise and of i and left // shifted i do't contain a // commons set bit. if ((i & (i << 1)) == 0) System.out.print(i + " "); } // Driver codepublic static void main(String[] args) { int n = 3; printNonConsecutive(n); }} // This code is contributed by Mr. Somesh Awasthi
# Python3 program to print all numbers upto# n bits with no consecutive set bits. def printNonConsecutive(n): # Let us first compute # 2 raised to power n. p = (1 << n) # loop 1 to n to check # all the numbers for i in range(1, p): # A number i doesn't contain # consecutive set bits if # bitwise and of i and left # shifted i do't contain a # common set bit. if ((i & (i << 1)) == 0): print(i, end = " ") # Driver coden = 3printNonConsecutive(n) # This code is contributed by Anant Agarwal.
// C# Code to Print all numbers upto// n bits with no consecutive set bits.using System; class GFG{ static void printNonConsecutive(int n) { // Let us first compute // 2 raised to power n. int p = (1 << n); // loop 1 to n to check // all the numbers for (int i = 1; i < p; i++) // A number i doesn't contain // consecutive set bits if // bitwise and of i and left // shifted i do't contain a // commons set bit. if ((i & (i << 1)) == 0) Console.Write(i + " "); } // Driver codepublic static void Main() { int n = 3; printNonConsecutive(n); }}// This code is contributed by nitin mittal.
<?php// Print all numbers upto n bits// with no consecutive set bits. function printNonConsecutive($n){ // Let us first compute // 2 raised to power n. $p = (1 << $n); // loop 1 to n to check // all the numbers for ($i = 1; $i < $p; $i++) // A number i doesn't contain // consecutive set bits if // bitwise and of i and left // shifted i do't contain a // commons set bit. if (($i & ($i << 1)) == 0) echo $i . " ";} // Driver code $n = 3; printNonConsecutive($n); // This code is contributed by Sam007?>
<script> // Javascript Code to Print all numbers upto// n bits with no consecutive set bits. function printNonConsecutive(n) { // Let us first compute // 2 raised to power n. let p = (1 << n); // loop 1 to n to check // all the numbers for (let i = 1; i < p; i++) // A number i doesn't contain // consecutive set bits if // bitwise and of i and left // shifted i do't contain a // commons set bit. if ((i & (i << 1)) == 0) document.write(i + " "); } // driver program let n = 3; printNonConsecutive(n); </script>
1 2 4 5
Time Complexity: O(2N)Auxiliary Space: O(1)
This article is contributed by Devanshu 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 contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nitin mittal
Sam007
PawanGupta
sanjoy_62
Bit Magic
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Set, Clear and Toggle a given bit of a number in C
Program to find parity
Hamming code Implementation in C/C++
Check whether K-th bit is set or not
Write an Efficient Method to Check if a Number is Multiple of 3
Implementation of Bit Stuffing and Bit Destuffing
Builtin functions of GCC compiler
Find XOR of all elements in an Array
Swap bits in a given number
Count total bits in a number
|
[
{
"code": null,
"e": 25014,
"s": 24986,
"text": "\n30 Apr, 2021"
},
{
"code": null,
"e": 25139,
"s": 25014,
"text": "Given a number n, our task is to find all 1 to n bit numbers with no consecutive 1s in their binary representation.Examples:"
},
{
"code": null,
"e": 25290,
"s": 25139,
"text": "Input: N = 4\nOutput: 1 2 4 5 8 9 10\nThese are numbers with 1 to 4\nbits and no consecutive ones in\nbinary representation.\n\nInput: n = 3\nOutput: 1 2 4 5"
},
{
"code": null,
"e": 25300,
"s": 25290,
"text": "Approach:"
},
{
"code": null,
"e": 25648,
"s": 25300,
"text": "There will be 2n numbers with number of bits from 1 to n.Iterate through all 2n numbers. For every number check if it contains consecutive set bits or not. To check, we do bitwise and of current number i and left-shifted i. If the bitwise and contains a non-zero bit (or its value is non-zero), then the given number contains consecutive set bits."
},
{
"code": null,
"e": 25706,
"s": 25648,
"text": "There will be 2n numbers with number of bits from 1 to n."
},
{
"code": null,
"e": 25997,
"s": 25706,
"text": "Iterate through all 2n numbers. For every number check if it contains consecutive set bits or not. To check, we do bitwise and of current number i and left-shifted i. If the bitwise and contains a non-zero bit (or its value is non-zero), then the given number contains consecutive set bits."
},
{
"code": null,
"e": 26048,
"s": 25997,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26052,
"s": 26048,
"text": "C++"
},
{
"code": null,
"e": 26057,
"s": 26052,
"text": "Java"
},
{
"code": null,
"e": 26065,
"s": 26057,
"text": "Python3"
},
{
"code": null,
"e": 26068,
"s": 26065,
"text": "C#"
},
{
"code": null,
"e": 26072,
"s": 26068,
"text": "PHP"
},
{
"code": null,
"e": 26083,
"s": 26072,
"text": "Javascript"
},
{
"code": "// Print all numbers upto n bits// with no consecutive set bits.#include<iostream>using namespace std; void printNonConsecutive(int n){ // Let us first compute // 2 raised to power n. int p = (1 << n); // loop 1 to n to check // all the numbers for (int i = 1; i < p; i++) // A number i doesn't contain // consecutive set bits if // bitwise and of i and left // shifted i do't contain a // commons set bit. if ((i & (i << 1)) == 0) cout << i << \" \";} // Driver codeint main(){ int n = 3; printNonConsecutive(n); return 0;}",
"e": 26688,
"s": 26083,
"text": null
},
{
"code": "// Java Code to Print all numbers upto// n bits with no consecutive set bits.import java.util.*; class GFG{ static void printNonConsecutive(int n) { // Let us first compute // 2 raised to power n. int p = (1 << n); // loop 1 to n to check // all the numbers for (int i = 1; i < p; i++) // A number i doesn't contain // consecutive set bits if // bitwise and of i and left // shifted i do't contain a // commons set bit. if ((i & (i << 1)) == 0) System.out.print(i + \" \"); } // Driver codepublic static void main(String[] args) { int n = 3; printNonConsecutive(n); }} // This code is contributed by Mr. Somesh Awasthi",
"e": 27500,
"s": 26688,
"text": null
},
{
"code": "# Python3 program to print all numbers upto# n bits with no consecutive set bits. def printNonConsecutive(n): # Let us first compute # 2 raised to power n. p = (1 << n) # loop 1 to n to check # all the numbers for i in range(1, p): # A number i doesn't contain # consecutive set bits if # bitwise and of i and left # shifted i do't contain a # common set bit. if ((i & (i << 1)) == 0): print(i, end = \" \") # Driver coden = 3printNonConsecutive(n) # This code is contributed by Anant Agarwal.",
"e": 28067,
"s": 27500,
"text": null
},
{
"code": "// C# Code to Print all numbers upto// n bits with no consecutive set bits.using System; class GFG{ static void printNonConsecutive(int n) { // Let us first compute // 2 raised to power n. int p = (1 << n); // loop 1 to n to check // all the numbers for (int i = 1; i < p; i++) // A number i doesn't contain // consecutive set bits if // bitwise and of i and left // shifted i do't contain a // commons set bit. if ((i & (i << 1)) == 0) Console.Write(i + \" \"); } // Driver codepublic static void Main() { int n = 3; printNonConsecutive(n); }}// This code is contributed by nitin mittal.",
"e": 28817,
"s": 28067,
"text": null
},
{
"code": "<?php// Print all numbers upto n bits// with no consecutive set bits. function printNonConsecutive($n){ // Let us first compute // 2 raised to power n. $p = (1 << $n); // loop 1 to n to check // all the numbers for ($i = 1; $i < $p; $i++) // A number i doesn't contain // consecutive set bits if // bitwise and of i and left // shifted i do't contain a // commons set bit. if (($i & ($i << 1)) == 0) echo $i . \" \";} // Driver code $n = 3; printNonConsecutive($n); // This code is contributed by Sam007?>",
"e": 29421,
"s": 28817,
"text": null
},
{
"code": "<script> // Javascript Code to Print all numbers upto// n bits with no consecutive set bits. function printNonConsecutive(n) { // Let us first compute // 2 raised to power n. let p = (1 << n); // loop 1 to n to check // all the numbers for (let i = 1; i < p; i++) // A number i doesn't contain // consecutive set bits if // bitwise and of i and left // shifted i do't contain a // commons set bit. if ((i & (i << 1)) == 0) document.write(i + \" \"); } // driver program let n = 3; printNonConsecutive(n); </script>",
"e": 30129,
"s": 29421,
"text": null
},
{
"code": null,
"e": 30138,
"s": 30129,
"text": "1 2 4 5 "
},
{
"code": null,
"e": 30182,
"s": 30138,
"text": "Time Complexity: O(2N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 30605,
"s": 30182,
"text": "This article is contributed by Devanshu 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 contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 30618,
"s": 30605,
"text": "nitin mittal"
},
{
"code": null,
"e": 30625,
"s": 30618,
"text": "Sam007"
},
{
"code": null,
"e": 30636,
"s": 30625,
"text": "PawanGupta"
},
{
"code": null,
"e": 30646,
"s": 30636,
"text": "sanjoy_62"
},
{
"code": null,
"e": 30656,
"s": 30646,
"text": "Bit Magic"
},
{
"code": null,
"e": 30666,
"s": 30656,
"text": "Bit Magic"
},
{
"code": null,
"e": 30764,
"s": 30666,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30773,
"s": 30764,
"text": "Comments"
},
{
"code": null,
"e": 30786,
"s": 30773,
"text": "Old Comments"
},
{
"code": null,
"e": 30837,
"s": 30786,
"text": "Set, Clear and Toggle a given bit of a number in C"
},
{
"code": null,
"e": 30860,
"s": 30837,
"text": "Program to find parity"
},
{
"code": null,
"e": 30897,
"s": 30860,
"text": "Hamming code Implementation in C/C++"
},
{
"code": null,
"e": 30934,
"s": 30897,
"text": "Check whether K-th bit is set or not"
},
{
"code": null,
"e": 30998,
"s": 30934,
"text": "Write an Efficient Method to Check if a Number is Multiple of 3"
},
{
"code": null,
"e": 31048,
"s": 30998,
"text": "Implementation of Bit Stuffing and Bit Destuffing"
},
{
"code": null,
"e": 31082,
"s": 31048,
"text": "Builtin functions of GCC compiler"
},
{
"code": null,
"e": 31119,
"s": 31082,
"text": "Find XOR of all elements in an Array"
},
{
"code": null,
"e": 31147,
"s": 31119,
"text": "Swap bits in a given number"
}
] |
HTMLCollection item() Method - GeeksforGeeks
|
26 Jul, 2019
The item() method is used to return the content of element at the given index of the collection of all HTML element. The index starts from zero(0). The elements in the collection are sorted in the order as they appear in the sourcecode.
Syntax:
HTMLCollection.item(index)
OR
HTMLCollection[index]
Parameters: It contains a number that represents the index of the element that the user wants to return. The index starts from 0.
Example-1:
<!DOCTYPE html><html> <head> <style> h1 { color: green; } </style></head> <body> <center> <h1>GeeksForGeeks</h1> <h2>HTMLCollection item() Method</h2> <button onclick="Geeks()">Submit</button> <script> function Geeks() { var w = document.getElementsByTagName("h1"); alert(w.item(0).innerHTML); } </script> </body> </html>
Output:Before clicking on the button:After clicking on the button:
Example-2: To change the content of an HTML Element.
<!DOCTYPE html><html> <head> <style> h1 { color: green; } </style></head> <body> <center> <h1>GeeksForGeeks</h1> <h2>HTMLCollection item() Method</h2> <p>geeforgeefs</p> <button onclick="Geeks()">Submit</button> <script> function Geeks() { document.getElementsByTagName("P")[0].innerHTML = "GeeksForGeeks"; } </script> </body> </html>
Output:Before clicking on the button:After clicking on the button:
Supported Browsers: The browser supported by HTMLCollection item() Method are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
HTML-Methods
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to update Node.js and NPM to next version ?
How to Insert Form Data into Database using PHP ?
Types of CSS (Cascading Style Sheet)
REST API (Introduction)
Form validation using HTML and JavaScript
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Top 10 Angular Libraries For Web Developers
|
[
{
"code": null,
"e": 24314,
"s": 24286,
"text": "\n26 Jul, 2019"
},
{
"code": null,
"e": 24551,
"s": 24314,
"text": "The item() method is used to return the content of element at the given index of the collection of all HTML element. The index starts from zero(0). The elements in the collection are sorted in the order as they appear in the sourcecode."
},
{
"code": null,
"e": 24559,
"s": 24551,
"text": "Syntax:"
},
{
"code": null,
"e": 24587,
"s": 24559,
"text": "HTMLCollection.item(index) "
},
{
"code": null,
"e": 24590,
"s": 24587,
"text": "OR"
},
{
"code": null,
"e": 24613,
"s": 24590,
"text": "HTMLCollection[index] "
},
{
"code": null,
"e": 24743,
"s": 24613,
"text": "Parameters: It contains a number that represents the index of the element that the user wants to return. The index starts from 0."
},
{
"code": null,
"e": 24754,
"s": 24743,
"text": "Example-1:"
},
{
"code": "<!DOCTYPE html><html> <head> <style> h1 { color: green; } </style></head> <body> <center> <h1>GeeksForGeeks</h1> <h2>HTMLCollection item() Method</h2> <button onclick=\"Geeks()\">Submit</button> <script> function Geeks() { var w = document.getElementsByTagName(\"h1\"); alert(w.item(0).innerHTML); } </script> </body> </html>",
"e": 25205,
"s": 24754,
"text": null
},
{
"code": null,
"e": 25272,
"s": 25205,
"text": "Output:Before clicking on the button:After clicking on the button:"
},
{
"code": null,
"e": 25325,
"s": 25272,
"text": "Example-2: To change the content of an HTML Element."
},
{
"code": "<!DOCTYPE html><html> <head> <style> h1 { color: green; } </style></head> <body> <center> <h1>GeeksForGeeks</h1> <h2>HTMLCollection item() Method</h2> <p>geeforgeefs</p> <button onclick=\"Geeks()\">Submit</button> <script> function Geeks() { document.getElementsByTagName(\"P\")[0].innerHTML = \"GeeksForGeeks\"; } </script> </body> </html>",
"e": 25829,
"s": 25325,
"text": null
},
{
"code": null,
"e": 25896,
"s": 25829,
"text": "Output:Before clicking on the button:After clicking on the button:"
},
{
"code": null,
"e": 25988,
"s": 25896,
"text": "Supported Browsers: The browser supported by HTMLCollection item() Method are listed below:"
},
{
"code": null,
"e": 26002,
"s": 25988,
"text": "Google Chrome"
},
{
"code": null,
"e": 26020,
"s": 26002,
"text": "Internet Explorer"
},
{
"code": null,
"e": 26028,
"s": 26020,
"text": "Firefox"
},
{
"code": null,
"e": 26034,
"s": 26028,
"text": "Opera"
},
{
"code": null,
"e": 26041,
"s": 26034,
"text": "Safari"
},
{
"code": null,
"e": 26178,
"s": 26041,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 26191,
"s": 26178,
"text": "HTML-Methods"
},
{
"code": null,
"e": 26196,
"s": 26191,
"text": "HTML"
},
{
"code": null,
"e": 26213,
"s": 26196,
"text": "Web Technologies"
},
{
"code": null,
"e": 26218,
"s": 26213,
"text": "HTML"
},
{
"code": null,
"e": 26316,
"s": 26218,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26325,
"s": 26316,
"text": "Comments"
},
{
"code": null,
"e": 26338,
"s": 26325,
"text": "Old Comments"
},
{
"code": null,
"e": 26386,
"s": 26338,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 26436,
"s": 26386,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 26473,
"s": 26436,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 26497,
"s": 26473,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 26539,
"s": 26497,
"text": "Form validation using HTML and JavaScript"
},
{
"code": null,
"e": 26581,
"s": 26539,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 26614,
"s": 26581,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26657,
"s": 26614,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 26702,
"s": 26657,
"text": "Convert a string to an integer in JavaScript"
}
] |
JasmineJS - Quick Guide
|
Jasmine is an open-source JavaScript framework, capable of testing any kind of JavaScript application. Jasmine follows Behavior Driven Development (BDD) procedure to ensure that each line of JavaScript statement is properly unit tested. By following BDD procedure, Jasmine provides a small syntax to test the smallest unit of the entire application instead of testing it as a whole.
Following are the advantages of using Jasmine over other available JavaScript testing frameworks −
Jasmine does not depend on any other JavaScript framework.
Jasmine does not depend on any other JavaScript framework.
Jasmine does not require any DOM.
Jasmine does not require any DOM.
All the syntax used in Jasmine framework is clean and obvious.
All the syntax used in Jasmine framework is clean and obvious.
Jasmine is heavily influenced by Rspec, JS Spec, and Jspec.
Jasmine is heavily influenced by Rspec, JS Spec, and Jspec.
Jasmine is an open-source framework and easily available in different versions like stand-alone, ruby gem, Node.js, etc.
Jasmine is an open-source framework and easily available in different versions like stand-alone, ruby gem, Node.js, etc.
Jasmine is very easy to implement in any kind of development methodology. All you need to download is the standalone library files from the official website https://jasmine.github.io/ and implement the same in your application.
The detailed environment setup will be described in the next chapter named “Environment setup”. Once you successfully download and unzip the zip file, then you will find the following sub-folders inside that zip file.
In this chapter, we will discuss the step-by-step procedure of how to set up a Jasmine based BDD testing application.
Step 1 − Go to the official website of jasmine https://jasmine.github.io/
Step 2 − Click on any of the version link. It is preferable to use the most recent version that is “Edge”. You will be redirected to the homepage of the selected version.
Step 3 − Go to the Download section of the homepage and click on the standalone release page.
Step 4 − Once you are redirected to github release page, download the Zip file from there.
Step 5 − Unzip the downloaded jasmine-standalone-2.4.1 folder. You will see the following folder structure.
Step 6 − Now Create a web application project in your favorite IDE and add this downloaded library files into the application. Here, we have used netbeans IDE. Following is the Directory structure of our application after adding Jasmine framework.
Our environment setup is done. Now our application is ready to be tested by Jasmine framework.
In this chapter, we will create a hello world app which will test our “helloworld.js” file. Before developing the hello world app, go back to the previous chapter and make sure that your environment is ready to be tested using Jasmine.
Step 1 − Create a Web application in your IDE
Here we are using NetBeans 8.1 to develop our hello world app in Jasmine. In NetBeans, go to File → New Project → Html5/JS application and create a project. After creating the project, the project directory should look like the following screenshot. We named our project as Jasmine_Demo.
Step 2 − Include the Jasmine lib file into the application
After creating the demo project all you need to do is include the unzip folder of Jasmine library in the Unit Tests folder of the created application. After adding all the library files to our application folder, the structure of our project will look like as shown in the following screenshot.
Files given under spec and src folders are demo files provided by the Jasmine team. Delete these files as we are going to create our own test file and test case. While deleting those JavaScript file, we need to delete the reference of those files inside our output html file that is SpecRunner.html.
Following is the screenshot of SpecRunner.html file where the reference of different JavaScript files inside spec and src will be deleted.
Step 3 − Create a JavaScript file
In this step, we will create a JavaScript file named helloworld.js under src folder. This is the file which we will test through Jasmine. After creating a JavaScript file append the following set of code inside the file.
/*
* This is the JavaScript file that need to be tested through jasmine
* Below is the helloworld function that will return 'Hello World'
*
*/
var helloworld = function() {
return 'Hello World';
};
Step 4 − Create a test case
In this step, we will create another JavaScript file which will contain the test case for the above-mentioned JavaScript file. Go ahead and create a JavaScript file under “Spec” folder and name it as “HelloWorldsSpec.js”. Add the following line of code into this js file.
/*
* This is the file which will call our java script file that need to be tested.
* Each describe block is equivalent to one test case
*
*/
describe("Hello World", function() {
it("should Return Hello world",function() {
expect(helloworld()).toEqual('Hello World');
});
});
Step 5 − Add reference to the output file
We successfully created our own file to be tested and the corresponding test case. We kept it under two different folders. In this step, we will modify “SpecRunner.html” to include the reference of these two newly created file.
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>Jasmine Spec Runner v2.4.1</title>
<link rel = "shortcut icon" type = "image/png" href =
"lib/jasmine2.4.1/jasmine_favicon.png">
<link rel = "stylesheet" href = "lib/jasmine-2.4.1/jasmine.css">
<script src = "lib/jasmine-2.4.1/jasmine.js"></script>
<script src = "lib/jasmine-2.4.1/jasmine-html.js"></script>
<script src = "lib/jasmine-2.4.1/boot.js"></script>
<!--Lines to be deleted
<script src = "src/Player.js"></script>
<script src = "src/Song.js"></script>
<script src = "spec/SpecHelper.js"></script>
<script src = "spec/PlayerSpec.js"></script> -->
<!--adding the reference of our newly created file --->
<script src = "src/helloworld.js"></script>
<script src = "spec/HelloWorldsSpec.js"></script>
</head>
<body>
</body>
</html>
Step 6 − Execute by running SpecRunner.html
This is the final step of our application development. Run SpecRunner.html in any of your favorite browser. The following screenshot will appear as a result. The green screen indicates success, whereas red indicates failure in test case.
Step 7 − Understand the failure case
Till now we have seen the success test case of the hello world application. Now let us see what if something goes wrong and the test fails. To implement a failure case we need to write a failure test case. To do the same, we are going to modify the helloworld.js file using the following code.
var helloworld = function () {
return '';
};
// we are not returning any string whereas in the spec file
//we are expecting a // string as “Hello World”
The above code is definitely going to fail because our spec file is not getting the expected string as an output of the helloworld(). The following screenshot of the specRunner.html file depicts that there is an error with its red indicator.
Jasmine follows the Behavioral Driven Development (BDD) framework. Before learning the working principle of Jasmine, let us know what is the BDD framework.
The following flowchart depicts the different phases of BDD framework.
Step 1 − Start
In this phase, we will make our environment ready for Jasmine application.
Step 2 − Write a failing test
In this step, we will write our first ever test case. It is obvious that this test is going to fail because there is no such file or function to be tested.
Step 3 − Write a code to make it pass
In this phase, we will prepare our JavaScript file or function that needs to be tested. This phase is crucial as we need to make sure that all the test cases we had prepared in the early stage will be successful.
Step 4 − Refactor
Refactor is a very important phase of BDD model where we need to prepare as many test cases as we can for that particular application or function.
Step 5 − Stop
If everything is going well then your application must be ready and up. So we can consider this step as an end of our BDD application.
We have now gathered some knowledge about the working principle of BDD framework. Let us see how Jasmine follows this BDD framework in the line of JavaScript testing.
As the screenshot depicts we need to test Abc.js using Jasmine framework. SpecRunner.html is the output file that will take Spec.js(Test case file ), Abc.js(file to be tested), LIB as an input and run all the test cases present in the spec file and render the result into the browser.
Lib − These are the inbuilt JavaScript files that will be helpful to test different functions and other JavaScript files used in our project.
Spec.js(Test case file) − This is the JavaScript file that contains all the test cases which is required to test any JavaScript function or file. In the BDD methodology, we are going to write the test first, hence this is the file that needs to be updated first. Definitely this is going to be fail as there is no such file or function present in our project that can be tested. This file can be refactored unlimited times until all the functionalities are tested.
Abc.js(File to be tested) − This is the file that contains your functionalities which will be unit tested using Spec.js and Lib file.
SpecRunner.html − SpecRunner.html is a normal html file which will render the output of the unit test with the help of embedded JavaScript codes in it.
In this chapter, we will discuss the building blocks of test by Jasmine.
Jasmine is a testing framework for JavaScript. Suite is the basic building block of Jasmine framework. The collection of similar type test cases written for a specific file or function is known as one suite. It contains two other blocks, one is “Describe()” and another one is “It()”.
One Suite block can have only two parameters, one “name of that suite” and another “Function declaration” that actually makes a call to our unit functionality that is to be tested.
In the following example, we will create a suite that will unit test add function in add.js file. In this example, we have our JS file named “calculator.js” which will be tested through Jasmine, and the corresponding Jasmine spec file is “CalCulatorSpec.js”.
window.Calculator = {
currentVal:0,
varAfterEachExmaple:0,
add:function (num1) {
this.currentVal += num1;
return this.currentVal;
},
addAny:function () {
var sum = this.currentVal;
for(var i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
this.currentVal = sum;
Return this.currentVal;
},
};
describe("calculator",function() {
//test case: 1
it("Should retain the current value of all time", function () {
expect(Calculator.currentVal).toBeDefined();
expect(Calculator.currentVal).toEqual(0);
});
//test case: 2
it("should add numbers",function() {
expect(Calculator.add(5)).toEqual(5);
expect(Calculator.add(5)).toEqual(10);
});
//test case :3
it("Should add any number of numbers",function () {
expect(Calculator.addAny(1,2,3)).toEqual(6);
});
});
In the above function, we have declared two functions. Function add will add two numbers given as an argument to that function and another function addAny should add any numbers given as an argument.
After creating this file, we need to add this file in “SpecRunner.html” inside the head section. On successful compilation, this will generate the following output as a result.
Suite block can have many suite blocks inside another suite block. The following example will show you how we can create a different suite block inside another suite block. We will create two JavaScript files, one named as “NestedSpec.js” and another named as “nested.js”.
describe("nested",function() {
// Starting of first suite block
// First block
describe("Retaining values ",function () {
//test case:1
it ("Should retain the current value of all time", function () {
expect(nested.currentVal).toBeDefined();
expect(nested.currentVal).toEqual(0);
});
}); //end of the suite block
//second suite block
describe("Adding single number ",function () {
//test case:2
it("should add numbers",function() {
expect(nested.add(5)).toEqual(5);
expect(nested.add(5)).toEqual(10);
});
}); //end of the suite block
//third suite block
describe("Adding Different Numbers",function () {
//test case:3
it("Should add any number of numbers",function() {
expect(nested.addAny(1,2,3)).toEqual(6);
});
}); //end of the suite block
});
window.nested = {
currentVal: 0,
add:function (num1) {
this.currentVal += num1;
return this.currentVal;
},
addAny:function () {
Var sum = this.currentVal;
for(var i = 0;i < arguments.length; i++) {
sum += arguments[i];
}
this.currentVal = sum;
return this.currentVal;
}
};
The above piece of code will generate the following output as a result of running specRunner.html file after adding this file inside the head section.
As discussed earlier describe block is a part of Suite block. Like Suite block, it contains two parameters, one “the name of the describe block” and another “function declaration”. In our upcoming examples, we will go through many describe blocks to understand the working flow of Jasmine suite block. Following is an example of a complete describe block.
describe("Adding single number ",function () {
it("should add numbers",function() {
expect(nested.add(5)).toEqual(5);
expect(nested.add(5)).toEqual(10);
});
}
Like describe block we have been introduced to IT block too. It goes within a describe block. This is the block which actually contains each unit test case. In the following code, there are pieces of IT block inside one describe block.
describe("Adding single number ",function () {
// test case : 1
it("should add numbers",function() {
expect(nested.add(5)).toEqual(5);
expect(nested.add(5)).toEqual(10);
});
//test case : 2
it("should add numbers",function() {
expect(nested.addAny(1,2,3)).toEqual(6);
});
}
Jasmine Expect allows you to write your expectation from the required function or JavaScript file. It comes under IT block. One IT block can have more than one Expect block.
Following is an example of Expect block. This expect block provides a wide variety of methods to unit test your JavaScript function or JavaScript file. Each of the Expect block is also known as a matcher. There are two different types of matchers, one inbuilt matcher and another user defined matchers.
describe("Adding single number ",function () {
// test case : 1
it("should add numbers",function() {
expect(nested.add(5)).toEqual(5);
expect(nested.add(5)).toEqual(10);
});
//test case : 2
it("should add numbers",function() {
expect(nested.addAny(1,2,3)).toEqual(6);
});
}
In the upcoming chapters, we will discuss various uses of different inbuilt methods of the Expect block.
Jasmine is a testing framework, hence it always aims to compare the result of the JavaScript file or function with the expected result. Matcher works similarly in Jasmine framework.
Matchers are the JavaScript function that does a Boolean comparison between an actual output and an expected output. There are two type of matchers Inbuilt matcher and Custom matchers.
The matchers which are inbuilt in the Jasmine framework are called inbuilt matcher. The user can easily use it implicitly.
The following example shows how Inbuilt Matcher works in Jasmine framework. We have already used some matchers in the previous chapter.
describe("Adding single number ", function () {
//example of toEqual() matcher
it("should add numbers",function() {
expect(nested.add(5)).toEqual(5);
expect(nested.add(5)).toEqual(10);
});
it("should add numbers",function() {
expect(nested.addAny(1,2,3)).toEqual(6);
});
}
In the example toEqual() is the inbuilt matcher which will compare the result of the add() and addAny() methods with the arguments passed to toEqual() matchers.
The matchers which are not present in the inbuilt system library of Jasmine is called as custom matcher. Custom matcher needs to be defined explicitly(). In the following example, we will see how the custom matcher works.
describe('This custom matcher example', function() {
beforeEach(function() {
// We should add custom matched in beforeEach() function.
jasmine.addMatchers ({
validateAge: function() {
Return {
compare: function(actual,expected) {
var result = {};
result.pass = (actual > = 13 && actual < = 19);
result.message = 'sorry u are not a teen ';
return result;
}
};
}
});
});
it('Lets see whether u are teen or not', function() {
var myAge = 14;
expect(myAge).validateAge();
});
it('Lets see whether u are teen or not ', function() {
var yourAge = 18;
expect(yourAge).validateAge();
});
});
In the above example, validateAge() works as a matcher which is actually validating your age with some range. In this example, validateAge() works as a custom matcher. Add this JS file into SpecRunner.html and run the same. It will generate the following output.
Jasmine also allows the developers to skip one or more than one test cases. These techniques can be applied at the Spec level or the Suite level. Depending on the level of application, this block can be called as a Skipping Spec and Skipping Suite respectively.
In the following example, we will learn how to skip a specific Spec or Suite using “x” character.
We will modify the previous example using “x” just before it statement.
describe('This custom matcher example ', function() {
beforeEach(function() {
// We should add custom matched in beforeEach() function.
jasmine.addMatchers({
validateAge: function() {
return {
compare: function(actual,expected) {
var result = {};
result.pass = (actual > = 13 && actual < = 19);
result.message = 'sorry u are not a teen ';
return result;
}
};
}
});
});
it('Lets see whether u are teen or not', function() {
var myAge = 14;
expect(myAge).validateAge();
});
xit('Lets see whether u are teen or not ', function() {
//Skipping this Spec
var yourAge = 18;
});
});
If we run this JavaScript code, we will receive the following output as a result in the browser. Jasmine itself will notify the user that the specific it block is disabled temporarily using “xit”.
In the same way, we can disable the describe block in order to implement the technique of Skipping Suite. In the following example, we will learn about the process of skipping suite block.
xdescribe('This custom matcher example ', function() {
//Skipping the entire describe block
beforeEach(function() {
// We should add custom matched in beforeEach() function.
jasmine.addMatchers({
validateAge: function() {
return {
compare: function(actual,expected) {
var result = {};
result.pass = (actual >=13 && actual<=19);
result.message ='sorry u are not a teen ';
return result;
}
};
}
});
});
it('Lets see whether u are teen or not', function() {
var myAge = 14;
expect(myAge).validateAge();
});
it('Lets see whether u are teen or not ', function() {
var yourAge = 18;
expect(yourAge).validateAge();
});
});
The above code will generate the following screenshot as an output.
As we can see in the message bar, it shows two spec blocks in pending status, which means these two Spec blocks is disabled using “x” character. In the upcoming chapter, we will discuss different types of Jasmine test scenarios.
Jasmine provides plenty of methods which help us check the equality of any JavaScript function and file. Following are some examples to check equality conditions.
ToEqual() is the simplest matcher present in the inbuilt library of Jasmine. It just matches whether the result of the operation given as an argument to this method matches with the result of it or not.
The following example will help you understand how this matcher works. We have two files to be tested named as “expectexam.js” and another one through which we need to test is “expectSpec.js”.
window.expectexam = {
currentVal: 0,
};
describe("Different Methods of Expect Block",function () {
it("The Example of toEqual() method",function () {
//this will check whether the value of the variable
// currentVal is equal to 0 or not.
expect(expectexam.currentVal).toEqual(0);
});
});
On successful execution, these pieces of code will yield the following output. Remember you need to add these files into the header section of specRunner.html file as directed in the earlier example.
not.toEqual() works exactly opposite to toEqual(). not.toEqual() is used when we need to check if the value does not match with the output of any function.
We will modify the above example to show how this works.
describe("Different Methods of Expect Block",function () {
it("The Example of toEqual() method",function () {
expect(expectexam.currentVal).toEqual(0);
});
it("The Example of not.toEqual() method",function () {
//negation testing expect(expectexam.currentVal).not.toEqual(5);
});
});
window.expectexam = {
currentVal: 0,
};
In the second expect block, we are checking whether the value of the currentVal is equal to 5 as the value of currentVal is zero hence our test passes and provides us with a green output.
toBe() matcher works in a similar way as toEqual(), however they are technically different from each other. toBe() matcher matches with the type of the object whereas toEqual() matches with the equivalency of the result.
The following example will help you understand the working principle of the toBe() matcher. This matcher is exactly equivalent to the “===” operator of JavaScript whereas toEqual() is similar to the “==” operator of JavaScript.
describe("Different Methods of Expect Block",function () {
it("The Example of toBe() method",function () {
expect(expectexam.name).toBe(expectexam.name1);
});
});
window.expectexam = {
currentVal: 0,
name:"tutorialspoint",
name1:tutorialspoint
};
We will slightly modify our expectexam JavaScript file. We added two new variables, name and name1. Please find the difference between these two added variables - one is of string type and another one is not a string type.
Following screenshot is our test result where the red cross depicts that these two values are not equal, whereas it is expected to be equal. Hence our test fails.
Let us turn both the variables, name and name1 as String type variables and run the same SpecRunner.html again. Now check the output. It will prove that toBe() not only matches with the equivalency of the variable, but it also matches with the data type or object type of the variable.
As seen earlier, not is nothing but a negation of the toBe() method. It fails when the expected result matches with the actual output of the function or JavaScript file.
Following is a simple example that will help you understand how not.toBe() matcher works.
describe("Different Methods of Expect Block",function () {
it("The Example of not.toBe() method",function () {
expect(true).not.toBe(false);
});
});
Here Jasmine will try to match up true with false. As true cannot be same as false, this test case will be valid and pass through.
Apart from equality check, Jasmine provides some methods to check Boolean conditions too. Following are the methods that help us check Boolean conditions.
This Boolean matcher is used in Jasmine to check whether the result is equal to true or false.
The following example will help us understand the working principle of the toBeTruthy() function.
describe("Different Methods of Expect Block",function () {
it("The Example of toBeTruthy() method",function () {
expect(expectexam.exampleoftrueFalse(5)).toBeTruthy();
});
});
window.expectexam = {
exampleoftrueFalse: function (num) {
if(num < 10)
return true;
else
return false;
},
};
As we are passing number 5, which is smaller than 10, this test case will pass and give us the following output.
If we pass a number which is larger than 10, then this green test will change to red. In the second screenshot, you can see that on passing some value which is greater than 10, the expected test case fails and generates red output stating that “Expected false to be truthy”.
toBeFalsy() also works the same way as toBeTruthy() method. It matches the output to be false whereas toBeTruthy matches the output to be true. The following example will help you understand the basic working principles of toBeFalsy().
describe("Different Methods of Expect Block",function() {
it("The Example of toBeTruthy() method",function () {
expect(expectexam.exampleoftrueFalse(15)).toBeFalsy();
});
});
window.expectexam = {
exampleoftrueFalse: function (num) {
if(num < 10)
Return true;
else
return false;
},
};
The above code will pass the Jasmine test case as we are passing value more than 10 and expected the output to be false. Hence, the browser will show us a green sign which means it has passed.
Jasmine also provides different methods to provide sequentiality of the JS output. Following examples show how to implement sequential check using Jasmine.
toContain() matchers provide us the facility to check whether any element is a part of the same array or some other sequential objects. The following example will help us understand the working methodology of Jasmine toContain() method. Let's add the following piece of code in previously created customerMatcherSpec.js file.
describe("Different Methods of Expect Block",function () {
it("The Example of toContain() method",function () {
expect([1,2, 3, 4]).toContain(3);
});
});
In the above example, we are checking whether 3 is present in that array or not. We get a green output as 3 is present in the array.
In the above example, let's change the value of 3 with 15 and run the spec again. We will get the following red screen as 15 does not belong to that array we are passing as a parameter of that function.
toBeCloseTo() matcher matches whether the actual value is close to the expected value. In the following example, we will modify our customerMatcherSpec.js file and see how this actually works.
describe("Different Methods of Expect Block", function () {
it("Example of toBeCloseTo()", function () {
expect(12.34).toBeCloseTo(12.3, 1);
});
});
In the above Describe block, we are checking whether the actual result “12.3” is closer to the expected output “12.34” or not. As this satisfies our requirement, we will have the following green screenshot as our output. The second parameter of this method is the count of the decimal place to be compared with.
In the above code, let's modify the expected value to 15 and run SpecRunner.html.
describe("Different Methods of Expect Block",function () {
it("Example of toBeCloseTo()", function () {
expect(12.34).toBeCloseTo(15, 1);
});
});
In this scenario, 15 is nowhere close to 15, hence it will generate an error and present a red screenshot as an error.
ToMatch() matcher works on String type variable. It is helpful to find whether a specific String is present in the expected output or not. Following is what our customerMatcherSpec.js looks like.
describe("Different Methods of Expect Block",function () {
it("Example of toMatch()", function () {
expect("Jasmine tutorial in tutorials.com").toMatch(/com/);
});
});
This piece of code will test whether “com” is present in the expected String given. As com exists in the string, it will generate a green screenshot and pass the test condition.
Now let us change the output to some other string, which is not present in the expected value. Then our customerMatcherSpec.js will look like the following.
describe("Different Methods of Expect Block",function () {
it("Example of toMatch()", function () {
expect("Jasmine tutorial in tutorials.com").toMatch(/XYZ/);
});
});
The above code will find “XYZ” string in the expected value. As it does not exist in the expected string, it will throw an error and the output screen will be red accordingly.
Jasmine provides a different variety of method to check whether the actual output is Null, defined or undefined. In this chapter, we will learn how to implement different Jasmine methods to check the above-mentioned scenarios.
This matcher is used to check whether any variable in the code is predefined or not. Let us modify our customerMatcherSpec.js file according to this example.
currentVal = 0;
describe("Different Methods of Expect Block",function () {
it("Example of toBeDefined", function () {
expect(currentVal).toBeDefined();
});
});
In the above code, toBeDefined() will check whether the variable currentVal is defined in the system or not. As currentVal is defined to 0 in the beginning, this test will pass and generate a green screenshot as an output.
Again in the above example, let us remove the first line, where we actually define “currentVal” and run again. Then we will get a red screen, which means the test actually fails because we are expecting an undefined value to be defined. The following screenshot will be the output file.
This matcher helps to check whether any variable is previously undefined or not, basically it works simply opposite to the previous matcher that is toBeDefined. In the following example, we will learn how to use this matcher. Let us modify our Spec file, i.e. customerMatcher.js file with the following entry.
describe("Different Methods of Expect Block",function () {
it("Example of toBeUndefine()", function () {
var undefineValue;
expect(undefineValue).toBeUndefined();
});
});
In the above section, we will verify whether our variable “undefineValue” is actually undefined or not. After adding this file into the SpecRunner, we will receive a green color screenshot as an output, which tells us that this value is actually not defined previously.
Again let us define the variable with some predefined value and see whether it will throw an error or not. The new customerMatcher.js looks like the following.
describe("Different Methods of Expect Block",function () {
it("Example oftoBeUndefine()", function () {
var undefineValue = 0;
expect(undefineValue).toBeUndefined();
});
});
The above piece of code will throw an error and generate a red color screenshot because we have already defined the “undefineValue” value to “0” and expecting it to be not defined. The following screenshot will be generated on run SpecRunner.html file.
As the name signifies this matcher helps to check null values. Let us again modify our customerMatcherSpec.js file with the following piece of code.
describe("Different Methods of Expect Block",function () {
var value = null;
it("Example of toBeNull()", function () {
expect(value).toBeNull();
});
});
In the above code, we have mentioned one variable ”value” and we have explicitly mentioned this value as null. In the expect block, the toBeNull() matcher will check this value and give us the result accordingly. Following is the output of the above-mentioned code when it is run through the help of the SpecRunner.html file.
Now let us test by providing some defined value other than null. Please modify the customerMatcher.js file accordingly.
describe("Different Methods of Expect Block",function () {
var value = "TutorialsPoint";
it("Example of toBeNull()", function () {
expect(value).toBeNull();
});
});
In the above example, we have modified the variable value with “TutorialsPoint” which is not a null value. Hence, this test will fail and produce a red screenshot as an output.
Till now, we have discussed different methods in Jasmine which help us test different scenarios based on our requirements. In this chapter, we will learn about different matchers that will help us check the inequality condition in JS file. Following are the matchers used for this purpose.
As the name suggests this matcher helps to check greater than condition. Let us modify our customerMatcher.js using the following piece of code.
describe("Different Methods of Expect Block",function () {
var exp = 8;
it("Example of toBeGreaterThan()", function () {
expect(exp).toBeGreaterThan(5);
});
});
In the above piece of code, we are expecting that the value of the variable “exp” will be greater than 5. Now as the value of the variable “exp” is “8” which is greater than “5”, this piece of code will generate a green screenshot.
Now again let us modify the value of the variable to “4” and make this test fail. To do that we need to modify the js file using the following piece of code.
describe("Different Methods of Expect Block",function () {
var exp = 4;
it ("Example of toBeGreaterThan()", function () {
expect(exp).toBeGreaterThan(5);
});
});
This code will fail because value 4 cannot be greater than 5. Hence it will produce the following output.
This matcher helps to check the less than condition of the test scenario. It behaves exactly opposite to that of toBeGreaterThan() matcher. Now let us see how this matcher works. Let us modify the customerMatcher.js file accordingly.
describe("Different Methodsof Expect Block",function () {
var exp = 4;
it("Example of toBeLessThan()", function() {
expect(exp).toBeLessThan(5);
});
});
Like the previous example, we have one variable having value as “4”. In this piece of code, we are checking whether the value of this variable is less than 5 or not. This piece of code will generate the following output.
Now to make this fail, we need to assign some bigger number to the variable exp. Let us do that and test the application. We will assign 25 as the value to the exp, which will definitely throw an error and yield the following screenshot in red.
Jasmine provides a special matcher to check this special type of testing scenario that is toBeNaN().
Let us modify our customerMatcher.js with the following code.
describe("Different Methods of Expect Block",function () {
it("Example of toBeNaN()", function () {
expect(0 / 0).toBeNaN();
});
});
Here we want to test what is the value of “0/0” which cannot be determined. Hence, this piece of code will generate the following green screenshot.
Now let us again modify the code with the following logic, where we will assign one variable exp to 25 and expect the result is not a number one dividing it with 5.
describe("Different Methods of Expect Block",function () {
var exp = 25;
it("Example of toBeNaN()", function () {
expect(exp/5).toBeNaN();
});
});
This piece of code will yield the following output.
Apart from different computational matchers, Jasmine provides some useful matchers to check exception of the program. Let us modify our JavaScript with the following set of code.
var throwMeAnError = function() {
throw new Error();
};
describe("Different Methods of Expect Block", function() {
var exp = 25;
it ("Hey this will throw an Error ", function() {
expect(throwMeAnError).toThrow();
});
});
In the above example, we have created one method which deliberately throws an exception from that method and in the expect block we expect to catch the error. If everything goes well then this piece of code will yield the following output.
Now, for this test case to fail, we need to omit that throw statement in the function throwMeAnError. Following is the code which will yield a red screenshot as an output since the code does not satisfy our requirement.
var throwMeAnError = function() {
//throw new Error();
};
describe("Different Methods of Expect Block",function() {
var exp = 25;
it("Hey this will throw an Error ", function() {
expect(throwMeAnError).toThrow();
});
});
As can be seen, we have commented that line from where our method was throwing the exception. Following is the output of the above code on successful execution of the SpecRunner.html.
Any is the special matcher that is used when we are not sure about the output. In the following example, we will learn how this works. Let us modify the customerMatcher.js with the following piece of code.
var addAny = function() {
var sum = this.currentVal;
for (var i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
this.currentVal = sum;
return this.currentVal;
}
describe("Different Methods of Expect Block",function () {
it("Example of any()", function() {
expect(addAny(9,9)).toEqual(jasmine.any(Number));
});
});
Here we have declared one function that will give us the summation of the numbers provided as arguments. In the expect block, we are expecting that the result can be anything but it should be a Number.
As both 9 and 9 after sum yield 18 is a number, this test will pass and it will generate the following green screenshot as an output.
Now let us change the code according to the following piece of code, where we are expecting a string type variable as an output of the function AddAny().
var addAny = function() {
var sum = this.currentVal;
for(var i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
this.currentVal = sum;
return this.currentVal;
}
describe("Different Methodsof Expect Block",function () {
it("Example of any()", function () {
expect(addAny(9,9)).toEqual(jasmine.any(String));
});
});
Following is the output of the above code.
Another notable feature of Jasmine is before and after each function. Using these two functionalities, we can execute some pieces of code before and after execution of each spec. This functionality is very useful for running the common code in the application. Let us create one spec file like the following.
var currentVal = 0;
beforeEach(function() {
currentVal = 5;
});
describe("Different Methods of Expect Block",function() {
it("after each function ", function() {
expect(currentVal).toEqual(5);
});
});
Here although we have declared one variable as “0” in the beginning, we are expecting this value should be equal to 5 in the expectation block. The above code will generate the following output.
In the above code, 5 will be assigned to a variable currentVal before the execution of the expect block. Hence, it generates a green screenshot with no error.
Like beforeEach(), afterEach() works exactly the same way. It executes after the execution of the spec block. Let us modify the previous example using the following code.
var currentVal = 0;
afterEach(function() {
currentVal = 5;
});
describe("Different Methods of Expect Block",function() {
it("first call ", function() {
expect(currentVal).toEqual(0);
});
it("second call ", function() {
expect(currentVal).toEqual(5);
});
});
In the above example, while running the first spec block the value of the currentVal is 0. Hence, it will pass the test case but after running the first it block, Jasmine compile ran the afterEach() block, which makes the value of the currentVal to 5. Hence it also satisfies the second case and yields a green screenshot as an output.
Jasmine spy is another functionality which does the exact same as its name specifies. It will allow you to spy on your application function calls. There are two types of spying technology available in Jasmine. The first methodology can be implemented by using spyOn() and the second methodology can be implemented using createSpy(). In this chapter, we will learn more about these two methodologies.
spyOn() is inbuilt into the Jasmine library which allows you to spy on a definite piece of code. Let us create a new spec file “spyJasmineSpec.js” and another js file named as “spyJasmine.js”. Following is the entry of these two files.
var Person = function() {};
Person.prototype.sayHelloWorld = function(dict) {
return dict.hello() + " " + dict.world();
};
var Dictionary = function() {};
Dictionary.prototype.hello = function() {
return "hello";
};
Dictionary.prototype.world = function() {
return "world";
};
describe("Example Of jasmine Spy using spyOn()", function() {
it('uses the dictionary to say "hello world"', function() {
var dictionary = new Dictionary;
var person = new Person;
spyOn(dictionary, "hello"); // replace hello function with a spy
spyOn(dictionary, "world"); // replace world function with another spy
person.sayHelloWorld(dictionary);
expect(dictionary.hello).toHaveBeenCalled();
// not possible without first spy
expect(dictionary.world).toHaveBeenCalled();
// not possible withoutsecond spy
});
});
In the above piece of code, we want person object to say “Hello world” but we also want that person object should consult with dictionary object to give us the output literal “Hello world”.
Take a look at the Spec file where you can see that we have used spyOn() function, which actually mimics the functionality of the hello and world function. Hence, we are not actually calling the function but mimicking the function call. That is the specialty of Spies. The above piece of code will yield the following output.
Another method of obtaining the spying functionality is using createSpy(). Let us modify our two js files using the following code.
var Person = function() {};
Person.prototype.sayHelloWorld = function(dict) {
return dict.hello() + " " + dict.world();
};
var Dictionary = function() {};
Dictionary.prototype.hello = function() {
return "hello";
};
Dictionary.prototype.world = function() {
return "world";
};
describe("Example Of jasmine Spy using Create Spy", function() {
it("can have a spy function", function() {
var person = new Person();
person.getName11 = jasmine.createSpy("Name spy");
person.getName11();
expect(person.getName11).toHaveBeenCalled();
});
});
Take a look at the spec file, we are calling the getName11() of the Person object. Although this function is not present in the person object in spy Jasmine.js, we are not getting any error and hence the output is green and positive. In this example, createSpy() method actually mimics the functionality of the getName11().
The above code will generate the following output.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2433,
"s": 2050,
"text": "Jasmine is an open-source JavaScript framework, capable of testing any kind of JavaScript application. Jasmine follows Behavior Driven Development (BDD) procedure to ensure that each line of JavaScript statement is properly unit tested. By following BDD procedure, Jasmine provides a small syntax to test the smallest unit of the entire application instead of testing it as a whole."
},
{
"code": null,
"e": 2532,
"s": 2433,
"text": "Following are the advantages of using Jasmine over other available JavaScript testing frameworks −"
},
{
"code": null,
"e": 2591,
"s": 2532,
"text": "Jasmine does not depend on any other JavaScript framework."
},
{
"code": null,
"e": 2650,
"s": 2591,
"text": "Jasmine does not depend on any other JavaScript framework."
},
{
"code": null,
"e": 2684,
"s": 2650,
"text": "Jasmine does not require any DOM."
},
{
"code": null,
"e": 2718,
"s": 2684,
"text": "Jasmine does not require any DOM."
},
{
"code": null,
"e": 2781,
"s": 2718,
"text": "All the syntax used in Jasmine framework is clean and obvious."
},
{
"code": null,
"e": 2844,
"s": 2781,
"text": "All the syntax used in Jasmine framework is clean and obvious."
},
{
"code": null,
"e": 2904,
"s": 2844,
"text": "Jasmine is heavily influenced by Rspec, JS Spec, and Jspec."
},
{
"code": null,
"e": 2964,
"s": 2904,
"text": "Jasmine is heavily influenced by Rspec, JS Spec, and Jspec."
},
{
"code": null,
"e": 3085,
"s": 2964,
"text": "Jasmine is an open-source framework and easily available in different versions like stand-alone, ruby gem, Node.js, etc."
},
{
"code": null,
"e": 3206,
"s": 3085,
"text": "Jasmine is an open-source framework and easily available in different versions like stand-alone, ruby gem, Node.js, etc."
},
{
"code": null,
"e": 3434,
"s": 3206,
"text": "Jasmine is very easy to implement in any kind of development methodology. All you need to download is the standalone library files from the official website https://jasmine.github.io/ and implement the same in your application."
},
{
"code": null,
"e": 3652,
"s": 3434,
"text": "The detailed environment setup will be described in the next chapter named “Environment setup”. Once you successfully download and unzip the zip file, then you will find the following sub-folders inside that zip file."
},
{
"code": null,
"e": 3770,
"s": 3652,
"text": "In this chapter, we will discuss the step-by-step procedure of how to set up a Jasmine based BDD testing application."
},
{
"code": null,
"e": 3844,
"s": 3770,
"text": "Step 1 − Go to the official website of jasmine https://jasmine.github.io/"
},
{
"code": null,
"e": 4015,
"s": 3844,
"text": "Step 2 − Click on any of the version link. It is preferable to use the most recent version that is “Edge”. You will be redirected to the homepage of the selected version."
},
{
"code": null,
"e": 4109,
"s": 4015,
"text": "Step 3 − Go to the Download section of the homepage and click on the standalone release page."
},
{
"code": null,
"e": 4200,
"s": 4109,
"text": "Step 4 − Once you are redirected to github release page, download the Zip file from there."
},
{
"code": null,
"e": 4308,
"s": 4200,
"text": "Step 5 − Unzip the downloaded jasmine-standalone-2.4.1 folder. You will see the following folder structure."
},
{
"code": null,
"e": 4556,
"s": 4308,
"text": "Step 6 − Now Create a web application project in your favorite IDE and add this downloaded library files into the application. Here, we have used netbeans IDE. Following is the Directory structure of our application after adding Jasmine framework."
},
{
"code": null,
"e": 4651,
"s": 4556,
"text": "Our environment setup is done. Now our application is ready to be tested by Jasmine framework."
},
{
"code": null,
"e": 4887,
"s": 4651,
"text": "In this chapter, we will create a hello world app which will test our “helloworld.js” file. Before developing the hello world app, go back to the previous chapter and make sure that your environment is ready to be tested using Jasmine."
},
{
"code": null,
"e": 4933,
"s": 4887,
"text": "Step 1 − Create a Web application in your IDE"
},
{
"code": null,
"e": 5221,
"s": 4933,
"text": "Here we are using NetBeans 8.1 to develop our hello world app in Jasmine. In NetBeans, go to File → New Project → Html5/JS application and create a project. After creating the project, the project directory should look like the following screenshot. We named our project as Jasmine_Demo."
},
{
"code": null,
"e": 5280,
"s": 5221,
"text": "Step 2 − Include the Jasmine lib file into the application"
},
{
"code": null,
"e": 5575,
"s": 5280,
"text": "After creating the demo project all you need to do is include the unzip folder of Jasmine library in the Unit Tests folder of the created application. After adding all the library files to our application folder, the structure of our project will look like as shown in the following screenshot."
},
{
"code": null,
"e": 5875,
"s": 5575,
"text": "Files given under spec and src folders are demo files provided by the Jasmine team. Delete these files as we are going to create our own test file and test case. While deleting those JavaScript file, we need to delete the reference of those files inside our output html file that is SpecRunner.html."
},
{
"code": null,
"e": 6014,
"s": 5875,
"text": "Following is the screenshot of SpecRunner.html file where the reference of different JavaScript files inside spec and src will be deleted."
},
{
"code": null,
"e": 6048,
"s": 6014,
"text": "Step 3 − Create a JavaScript file"
},
{
"code": null,
"e": 6269,
"s": 6048,
"text": "In this step, we will create a JavaScript file named helloworld.js under src folder. This is the file which we will test through Jasmine. After creating a JavaScript file append the following set of code inside the file."
},
{
"code": null,
"e": 6505,
"s": 6269,
"text": "/* \n* This is the JavaScript file that need to be tested through jasmine \n* Below is the helloworld function that will return 'Hello World' \n* \n*/ \n\nvar helloworld = function() { \n return 'Hello World'; \n}; "
},
{
"code": null,
"e": 6533,
"s": 6505,
"text": "Step 4 − Create a test case"
},
{
"code": null,
"e": 6805,
"s": 6533,
"text": "In this step, we will create another JavaScript file which will contain the test case for the above-mentioned JavaScript file. Go ahead and create a JavaScript file under “Spec” folder and name it as “HelloWorldsSpec.js”. Add the following line of code into this js file."
},
{
"code": null,
"e": 7128,
"s": 6805,
"text": "/* \n* This is the file which will call our java script file that need to be tested. \n* Each describe block is equivalent to one test case \n* \n*/ \n\ndescribe(\"Hello World\", function() { \n \n it(\"should Return Hello world\",function() { \n expect(helloworld()).toEqual('Hello World'); \n }); \n\n});"
},
{
"code": null,
"e": 7170,
"s": 7128,
"text": "Step 5 − Add reference to the output file"
},
{
"code": null,
"e": 7398,
"s": 7170,
"text": "We successfully created our own file to be tested and the corresponding test case. We kept it under two different folders. In this step, we will modify “SpecRunner.html” to include the reference of these two newly created file."
},
{
"code": null,
"e": 8365,
"s": 7398,
"text": "<!DOCTYPE html> \n \n<html> \n <head> \n <meta charset = \"utf-8\"> \n \n <title>Jasmine Spec Runner v2.4.1</title> \n\t\t\n <link rel = \"shortcut icon\" type = \"image/png\" href = \n \"lib/jasmine2.4.1/jasmine_favicon.png\"> \n <link rel = \"stylesheet\" href = \"lib/jasmine-2.4.1/jasmine.css\"> \n\t\t\n <script src = \"lib/jasmine-2.4.1/jasmine.js\"></script>\n <script src = \"lib/jasmine-2.4.1/jasmine-html.js\"></script>\n <script src = \"lib/jasmine-2.4.1/boot.js\"></script> \n\n <!--Lines to be deleted \n <script src = \"src/Player.js\"></script> \n <script src = \"src/Song.js\"></script> \n <script src = \"spec/SpecHelper.js\"></script> \n <script src = \"spec/PlayerSpec.js\"></script> --> \n\n <!--adding the reference of our newly created file ---> \n\n <script src = \"src/helloworld.js\"></script> \n <script src = \"spec/HelloWorldsSpec.js\"></script> \n </head> \n\n <body> \n </body> \n\n</html>"
},
{
"code": null,
"e": 8409,
"s": 8365,
"text": "Step 6 − Execute by running SpecRunner.html"
},
{
"code": null,
"e": 8647,
"s": 8409,
"text": "This is the final step of our application development. Run SpecRunner.html in any of your favorite browser. The following screenshot will appear as a result. The green screen indicates success, whereas red indicates failure in test case."
},
{
"code": null,
"e": 8684,
"s": 8647,
"text": "Step 7 − Understand the failure case"
},
{
"code": null,
"e": 8978,
"s": 8684,
"text": "Till now we have seen the success test case of the hello world application. Now let us see what if something goes wrong and the test fails. To implement a failure case we need to write a failure test case. To do the same, we are going to modify the helloworld.js file using the following code."
},
{
"code": null,
"e": 9141,
"s": 8978,
"text": "var helloworld = function () { \n return ''; \n}; \n\n// we are not returning any string whereas in the spec file \n//we are expecting a // string as “Hello World” "
},
{
"code": null,
"e": 9383,
"s": 9141,
"text": "The above code is definitely going to fail because our spec file is not getting the expected string as an output of the helloworld(). The following screenshot of the specRunner.html file depicts that there is an error with its red indicator."
},
{
"code": null,
"e": 9539,
"s": 9383,
"text": "Jasmine follows the Behavioral Driven Development (BDD) framework. Before learning the working principle of Jasmine, let us know what is the BDD framework."
},
{
"code": null,
"e": 9610,
"s": 9539,
"text": "The following flowchart depicts the different phases of BDD framework."
},
{
"code": null,
"e": 9625,
"s": 9610,
"text": "Step 1 − Start"
},
{
"code": null,
"e": 9700,
"s": 9625,
"text": "In this phase, we will make our environment ready for Jasmine application."
},
{
"code": null,
"e": 9730,
"s": 9700,
"text": "Step 2 − Write a failing test"
},
{
"code": null,
"e": 9886,
"s": 9730,
"text": "In this step, we will write our first ever test case. It is obvious that this test is going to fail because there is no such file or function to be tested."
},
{
"code": null,
"e": 9924,
"s": 9886,
"text": "Step 3 − Write a code to make it pass"
},
{
"code": null,
"e": 10137,
"s": 9924,
"text": "In this phase, we will prepare our JavaScript file or function that needs to be tested. This phase is crucial as we need to make sure that all the test cases we had prepared in the early stage will be successful."
},
{
"code": null,
"e": 10155,
"s": 10137,
"text": "Step 4 − Refactor"
},
{
"code": null,
"e": 10302,
"s": 10155,
"text": "Refactor is a very important phase of BDD model where we need to prepare as many test cases as we can for that particular application or function."
},
{
"code": null,
"e": 10316,
"s": 10302,
"text": "Step 5 − Stop"
},
{
"code": null,
"e": 10451,
"s": 10316,
"text": "If everything is going well then your application must be ready and up. So we can consider this step as an end of our BDD application."
},
{
"code": null,
"e": 10618,
"s": 10451,
"text": "We have now gathered some knowledge about the working principle of BDD framework. Let us see how Jasmine follows this BDD framework in the line of JavaScript testing."
},
{
"code": null,
"e": 10903,
"s": 10618,
"text": "As the screenshot depicts we need to test Abc.js using Jasmine framework. SpecRunner.html is the output file that will take Spec.js(Test case file ), Abc.js(file to be tested), LIB as an input and run all the test cases present in the spec file and render the result into the browser."
},
{
"code": null,
"e": 11045,
"s": 10903,
"text": "Lib − These are the inbuilt JavaScript files that will be helpful to test different functions and other JavaScript files used in our project."
},
{
"code": null,
"e": 11510,
"s": 11045,
"text": "Spec.js(Test case file) − This is the JavaScript file that contains all the test cases which is required to test any JavaScript function or file. In the BDD methodology, we are going to write the test first, hence this is the file that needs to be updated first. Definitely this is going to be fail as there is no such file or function present in our project that can be tested. This file can be refactored unlimited times until all the functionalities are tested."
},
{
"code": null,
"e": 11644,
"s": 11510,
"text": "Abc.js(File to be tested) − This is the file that contains your functionalities which will be unit tested using Spec.js and Lib file."
},
{
"code": null,
"e": 11796,
"s": 11644,
"text": "SpecRunner.html − SpecRunner.html is a normal html file which will render the output of the unit test with the help of embedded JavaScript codes in it."
},
{
"code": null,
"e": 11869,
"s": 11796,
"text": "In this chapter, we will discuss the building blocks of test by Jasmine."
},
{
"code": null,
"e": 12154,
"s": 11869,
"text": "Jasmine is a testing framework for JavaScript. Suite is the basic building block of Jasmine framework. The collection of similar type test cases written for a specific file or function is known as one suite. It contains two other blocks, one is “Describe()” and another one is “It()”."
},
{
"code": null,
"e": 12335,
"s": 12154,
"text": "One Suite block can have only two parameters, one “name of that suite” and another “Function declaration” that actually makes a call to our unit functionality that is to be tested."
},
{
"code": null,
"e": 12594,
"s": 12335,
"text": "In the following example, we will create a suite that will unit test add function in add.js file. In this example, we have our JS file named “calculator.js” which will be tested through Jasmine, and the corresponding Jasmine spec file is “CalCulatorSpec.js”."
},
{
"code": null,
"e": 13013,
"s": 12594,
"text": "window.Calculator = { \n \n currentVal:0, \n varAfterEachExmaple:0, \n \n add:function (num1) { \n this.currentVal += num1; \n return this.currentVal; \n }, \n \n addAny:function () { \n var sum = this.currentVal; \n\t\t\n for(var i = 0; i < arguments.length; i++) { \n sum += arguments[i]; \n } \n \n this.currentVal = sum; \n Return this.currentVal; \n }, \n};"
},
{
"code": null,
"e": 13567,
"s": 13013,
"text": "describe(\"calculator\",function() { \n \n //test case: 1 \n it(\"Should retain the current value of all time\", function () {\n expect(Calculator.currentVal).toBeDefined();\n expect(Calculator.currentVal).toEqual(0); \n }); \n \n //test case: 2 \n it(\"should add numbers\",function() {\n expect(Calculator.add(5)).toEqual(5); \n expect(Calculator.add(5)).toEqual(10); \n }); \n \n //test case :3 \n it(\"Should add any number of numbers\",function () {\n expect(Calculator.addAny(1,2,3)).toEqual(6); \n }); \n}); "
},
{
"code": null,
"e": 13767,
"s": 13567,
"text": "In the above function, we have declared two functions. Function add will add two numbers given as an argument to that function and another function addAny should add any numbers given as an argument."
},
{
"code": null,
"e": 13944,
"s": 13767,
"text": "After creating this file, we need to add this file in “SpecRunner.html” inside the head section. On successful compilation, this will generate the following output as a result."
},
{
"code": null,
"e": 14217,
"s": 13944,
"text": "Suite block can have many suite blocks inside another suite block. The following example will show you how we can create a different suite block inside another suite block. We will create two JavaScript files, one named as “NestedSpec.js” and another named as “nested.js”."
},
{
"code": null,
"e": 15172,
"s": 14217,
"text": "describe(\"nested\",function() { \n \n // Starting of first suite block \n // First block \n\t\n describe(\"Retaining values \",function () {\n \n //test case:1 \n it (\"Should retain the current value of all time\", function () { \n expect(nested.currentVal).toBeDefined(); \n expect(nested.currentVal).toEqual(0); \n }); \n }); //end of the suite block \n\n //second suite block \n describe(\"Adding single number \",function () { \n \n //test case:2 \n it(\"should add numbers\",function() { \n expect(nested.add(5)).toEqual(5); \n expect(nested.add(5)).toEqual(10); \n }); \n }); //end of the suite block \n\n //third suite block \n describe(\"Adding Different Numbers\",function () { \n \n //test case:3 \n it(\"Should add any number of numbers\",function() { \n expect(nested.addAny(1,2,3)).toEqual(6); \n }); \n }); //end of the suite block \n});"
},
{
"code": null,
"e": 15551,
"s": 15172,
"text": "window.nested = { \n \n currentVal: 0,\n\t\n add:function (num1) { \n this.currentVal += num1; \n return this.currentVal; \n },\n \n addAny:function () { \n Var sum = this.currentVal; \n\t\t\n for(var i = 0;i < arguments.length; i++) { \n sum += arguments[i]; \n } \n\t\t\n this.currentVal = sum; \n return this.currentVal; \n } \n};"
},
{
"code": null,
"e": 15702,
"s": 15551,
"text": "The above piece of code will generate the following output as a result of running specRunner.html file after adding this file inside the head section."
},
{
"code": null,
"e": 16058,
"s": 15702,
"text": "As discussed earlier describe block is a part of Suite block. Like Suite block, it contains two parameters, one “the name of the describe block” and another “function declaration”. In our upcoming examples, we will go through many describe blocks to understand the working flow of Jasmine suite block. Following is an example of a complete describe block."
},
{
"code": null,
"e": 16248,
"s": 16058,
"text": "describe(\"Adding single number \",function () { \n \n it(\"should add numbers\",function() { \n expect(nested.add(5)).toEqual(5); \n expect(nested.add(5)).toEqual(10); \n }); \n}"
},
{
"code": null,
"e": 16484,
"s": 16248,
"text": "Like describe block we have been introduced to IT block too. It goes within a describe block. This is the block which actually contains each unit test case. In the following code, there are pieces of IT block inside one describe block."
},
{
"code": null,
"e": 16828,
"s": 16484,
"text": "describe(\"Adding single number \",function () { \n \n // test case : 1 \n it(\"should add numbers\",function() { \n expect(nested.add(5)).toEqual(5); \n expect(nested.add(5)).toEqual(10); \n }); \n \n //test case : 2 \n it(\"should add numbers\",function() { \n expect(nested.addAny(1,2,3)).toEqual(6); \n }); \n}"
},
{
"code": null,
"e": 17002,
"s": 16828,
"text": "Jasmine Expect allows you to write your expectation from the required function or JavaScript file. It comes under IT block. One IT block can have more than one Expect block."
},
{
"code": null,
"e": 17305,
"s": 17002,
"text": "Following is an example of Expect block. This expect block provides a wide variety of methods to unit test your JavaScript function or JavaScript file. Each of the Expect block is also known as a matcher. There are two different types of matchers, one inbuilt matcher and another user defined matchers."
},
{
"code": null,
"e": 17645,
"s": 17305,
"text": "describe(\"Adding single number \",function () { \n \n // test case : 1 \n it(\"should add numbers\",function() {\n expect(nested.add(5)).toEqual(5); \n expect(nested.add(5)).toEqual(10);\n }); \n \n //test case : 2 \n it(\"should add numbers\",function() {\n expect(nested.addAny(1,2,3)).toEqual(6); \n }); \n}"
},
{
"code": null,
"e": 17750,
"s": 17645,
"text": "In the upcoming chapters, we will discuss various uses of different inbuilt methods of the Expect block."
},
{
"code": null,
"e": 17932,
"s": 17750,
"text": "Jasmine is a testing framework, hence it always aims to compare the result of the JavaScript file or function with the expected result. Matcher works similarly in Jasmine framework."
},
{
"code": null,
"e": 18117,
"s": 17932,
"text": "Matchers are the JavaScript function that does a Boolean comparison between an actual output and an expected output. There are two type of matchers Inbuilt matcher and Custom matchers."
},
{
"code": null,
"e": 18240,
"s": 18117,
"text": "The matchers which are inbuilt in the Jasmine framework are called inbuilt matcher. The user can easily use it implicitly."
},
{
"code": null,
"e": 18376,
"s": 18240,
"text": "The following example shows how Inbuilt Matcher works in Jasmine framework. We have already used some matchers in the previous chapter."
},
{
"code": null,
"e": 18701,
"s": 18376,
"text": "describe(\"Adding single number \", function () { \n\n //example of toEqual() matcher \n it(\"should add numbers\",function() { \n expect(nested.add(5)).toEqual(5); \n expect(nested.add(5)).toEqual(10); \n }); \n \n it(\"should add numbers\",function() { \n expect(nested.addAny(1,2,3)).toEqual(6); \n });\n}"
},
{
"code": null,
"e": 18862,
"s": 18701,
"text": "In the example toEqual() is the inbuilt matcher which will compare the result of the add() and addAny() methods with the arguments passed to toEqual() matchers."
},
{
"code": null,
"e": 19084,
"s": 18862,
"text": "The matchers which are not present in the inbuilt system library of Jasmine is called as custom matcher. Custom matcher needs to be defined explicitly(). In the following example, we will see how the custom matcher works."
},
{
"code": null,
"e": 19928,
"s": 19084,
"text": "describe('This custom matcher example', function() {\n \n beforeEach(function() { \n // We should add custom matched in beforeEach() function. \n jasmine.addMatchers ({ \n validateAge: function() { \n Return { \n compare: function(actual,expected) {\n var result = {}; \n result.pass = (actual > = 13 && actual < = 19);\n result.message = 'sorry u are not a teen ';\n return result; \n } \n }; \n } \n }); \n }); \n \n it('Lets see whether u are teen or not', function() { \n var myAge = 14; \n expect(myAge).validateAge(); \n }); \n \n it('Lets see whether u are teen or not ', function() { \n var yourAge = 18;\n expect(yourAge).validateAge(); \n });\n});"
},
{
"code": null,
"e": 20191,
"s": 19928,
"text": "In the above example, validateAge() works as a matcher which is actually validating your age with some range. In this example, validateAge() works as a custom matcher. Add this JS file into SpecRunner.html and run the same. It will generate the following output."
},
{
"code": null,
"e": 20453,
"s": 20191,
"text": "Jasmine also allows the developers to skip one or more than one test cases. These techniques can be applied at the Spec level or the Suite level. Depending on the level of application, this block can be called as a Skipping Spec and Skipping Suite respectively."
},
{
"code": null,
"e": 20551,
"s": 20453,
"text": "In the following example, we will learn how to skip a specific Spec or Suite using “x” character."
},
{
"code": null,
"e": 20623,
"s": 20551,
"text": "We will modify the previous example using “x” just before it statement."
},
{
"code": null,
"e": 21453,
"s": 20623,
"text": "describe('This custom matcher example ', function() { \n \n beforeEach(function() { \n // We should add custom matched in beforeEach() function. \n \n jasmine.addMatchers({ \n validateAge: function() { \n return { \n compare: function(actual,expected) { \n var result = {}; \n result.pass = (actual > = 13 && actual < = 19); \n result.message = 'sorry u are not a teen '; \n return result; \n } \n }; \n } \n }); \n }); \n \n it('Lets see whether u are teen or not', function() { \n var myAge = 14; \n expect(myAge).validateAge(); \n });\n \n xit('Lets see whether u are teen or not ', function() { \n //Skipping this Spec \n var yourAge = 18; \n });\n});"
},
{
"code": null,
"e": 21650,
"s": 21453,
"text": "If we run this JavaScript code, we will receive the following output as a result in the browser. Jasmine itself will notify the user that the specific it block is disabled temporarily using “xit”."
},
{
"code": null,
"e": 21839,
"s": 21650,
"text": "In the same way, we can disable the describe block in order to implement the technique of Skipping Suite. In the following example, we will learn about the process of skipping suite block."
},
{
"code": null,
"e": 22713,
"s": 21839,
"text": "xdescribe('This custom matcher example ', function() { \n \n //Skipping the entire describe block \n beforeEach(function() { \n \n // We should add custom matched in beforeEach() function. \n jasmine.addMatchers({ \n validateAge: function() { \n return { \n compare: function(actual,expected) { \n var result = {}; \n result.pass = (actual >=13 && actual<=19); \n result.message ='sorry u are not a teen '; \n return result; \n } \n }; \n } \n }); \n });\n\n it('Lets see whether u are teen or not', function() { \n var myAge = 14; \n expect(myAge).validateAge(); \n }); \n\n it('Lets see whether u are teen or not ', function() { \n var yourAge = 18; \n expect(yourAge).validateAge(); \n });\n});"
},
{
"code": null,
"e": 22781,
"s": 22713,
"text": "The above code will generate the following screenshot as an output."
},
{
"code": null,
"e": 23010,
"s": 22781,
"text": "As we can see in the message bar, it shows two spec blocks in pending status, which means these two Spec blocks is disabled using “x” character. In the upcoming chapter, we will discuss different types of Jasmine test scenarios."
},
{
"code": null,
"e": 23173,
"s": 23010,
"text": "Jasmine provides plenty of methods which help us check the equality of any JavaScript function and file. Following are some examples to check equality conditions."
},
{
"code": null,
"e": 23376,
"s": 23173,
"text": "ToEqual() is the simplest matcher present in the inbuilt library of Jasmine. It just matches whether the result of the operation given as an argument to this method matches with the result of it or not."
},
{
"code": null,
"e": 23569,
"s": 23376,
"text": "The following example will help you understand how this matcher works. We have two files to be tested named as “expectexam.js” and another one through which we need to test is “expectSpec.js”."
},
{
"code": null,
"e": 23619,
"s": 23569,
"text": "window.expectexam = { \n currentVal: 0, \n};"
},
{
"code": null,
"e": 23905,
"s": 23619,
"text": "describe(\"Different Methods of Expect Block\",function () { \n \n it(\"The Example of toEqual() method\",function () { \n //this will check whether the value of the variable \n // currentVal is equal to 0 or not. \n expect(expectexam.currentVal).toEqual(0); \n });\n});"
},
{
"code": null,
"e": 24105,
"s": 23905,
"text": "On successful execution, these pieces of code will yield the following output. Remember you need to add these files into the header section of specRunner.html file as directed in the earlier example."
},
{
"code": null,
"e": 24261,
"s": 24105,
"text": "not.toEqual() works exactly opposite to toEqual(). not.toEqual() is used when we need to check if the value does not match with the output of any function."
},
{
"code": null,
"e": 24318,
"s": 24261,
"text": "We will modify the above example to show how this works."
},
{
"code": null,
"e": 24642,
"s": 24318,
"text": "describe(\"Different Methods of Expect Block\",function () { \n\n it(\"The Example of toEqual() method\",function () {\n expect(expectexam.currentVal).toEqual(0); \n }); \n \n it(\"The Example of not.toEqual() method\",function () { \n //negation testing expect(expectexam.currentVal).not.toEqual(5); \n }); \n});"
},
{
"code": null,
"e": 24689,
"s": 24642,
"text": "window.expectexam = { \n currentVal: 0, \n}; "
},
{
"code": null,
"e": 24877,
"s": 24689,
"text": "In the second expect block, we are checking whether the value of the currentVal is equal to 5 as the value of currentVal is zero hence our test passes and provides us with a green output."
},
{
"code": null,
"e": 25098,
"s": 24877,
"text": "toBe() matcher works in a similar way as toEqual(), however they are technically different from each other. toBe() matcher matches with the type of the object whereas toEqual() matches with the equivalency of the result."
},
{
"code": null,
"e": 25326,
"s": 25098,
"text": "The following example will help you understand the working principle of the toBe() matcher. This matcher is exactly equivalent to the “===” operator of JavaScript whereas toEqual() is similar to the “==” operator of JavaScript."
},
{
"code": null,
"e": 25510,
"s": 25326,
"text": "describe(\"Different Methods of Expect Block\",function () { \n\n it(\"The Example of toBe() method\",function () { \n expect(expectexam.name).toBe(expectexam.name1); \n });\n});"
},
{
"code": null,
"e": 25607,
"s": 25510,
"text": "window.expectexam = {\n currentVal: 0, \n name:\"tutorialspoint\", \n name1:tutorialspoint \n};"
},
{
"code": null,
"e": 25830,
"s": 25607,
"text": "We will slightly modify our expectexam JavaScript file. We added two new variables, name and name1. Please find the difference between these two added variables - one is of string type and another one is not a string type."
},
{
"code": null,
"e": 25993,
"s": 25830,
"text": "Following screenshot is our test result where the red cross depicts that these two values are not equal, whereas it is expected to be equal. Hence our test fails."
},
{
"code": null,
"e": 26279,
"s": 25993,
"text": "Let us turn both the variables, name and name1 as String type variables and run the same SpecRunner.html again. Now check the output. It will prove that toBe() not only matches with the equivalency of the variable, but it also matches with the data type or object type of the variable."
},
{
"code": null,
"e": 26449,
"s": 26279,
"text": "As seen earlier, not is nothing but a negation of the toBe() method. It fails when the expected result matches with the actual output of the function or JavaScript file."
},
{
"code": null,
"e": 26539,
"s": 26449,
"text": "Following is a simple example that will help you understand how not.toBe() matcher works."
},
{
"code": null,
"e": 26706,
"s": 26539,
"text": "describe(\"Different Methods of Expect Block\",function () { \n it(\"The Example of not.toBe() method\",function () { \n expect(true).not.toBe(false); \n });\n});"
},
{
"code": null,
"e": 26837,
"s": 26706,
"text": "Here Jasmine will try to match up true with false. As true cannot be same as false, this test case will be valid and pass through."
},
{
"code": null,
"e": 26992,
"s": 26837,
"text": "Apart from equality check, Jasmine provides some methods to check Boolean conditions too. Following are the methods that help us check Boolean conditions."
},
{
"code": null,
"e": 27087,
"s": 26992,
"text": "This Boolean matcher is used in Jasmine to check whether the result is equal to true or false."
},
{
"code": null,
"e": 27185,
"s": 27087,
"text": "The following example will help us understand the working principle of the toBeTruthy() function."
},
{
"code": null,
"e": 27381,
"s": 27185,
"text": "describe(\"Different Methods of Expect Block\",function () {\n it(\"The Example of toBeTruthy() method\",function () { \n expect(expectexam.exampleoftrueFalse(5)).toBeTruthy(); \n });\n}); "
},
{
"code": null,
"e": 27544,
"s": 27381,
"text": "window.expectexam = { \n exampleoftrueFalse: function (num) { \n if(num < 10) \n return true; \n else \n return false; \n }, \n};"
},
{
"code": null,
"e": 27657,
"s": 27544,
"text": "As we are passing number 5, which is smaller than 10, this test case will pass and give us the following output."
},
{
"code": null,
"e": 27932,
"s": 27657,
"text": "If we pass a number which is larger than 10, then this green test will change to red. In the second screenshot, you can see that on passing some value which is greater than 10, the expected test case fails and generates red output stating that “Expected false to be truthy”."
},
{
"code": null,
"e": 28168,
"s": 27932,
"text": "toBeFalsy() also works the same way as toBeTruthy() method. It matches the output to be false whereas toBeTruthy matches the output to be true. The following example will help you understand the basic working principles of toBeFalsy()."
},
{
"code": null,
"e": 28359,
"s": 28168,
"text": "describe(\"Different Methods of Expect Block\",function() { \n it(\"The Example of toBeTruthy() method\",function () {\n expect(expectexam.exampleoftrueFalse(15)).toBeFalsy(); \n });\n});"
},
{
"code": null,
"e": 28520,
"s": 28359,
"text": "window.expectexam = { \n exampleoftrueFalse: function (num) { \n if(num < 10) \n Return true; \n else \n return false; \n },\n}; "
},
{
"code": null,
"e": 28713,
"s": 28520,
"text": "The above code will pass the Jasmine test case as we are passing value more than 10 and expected the output to be false. Hence, the browser will show us a green sign which means it has passed."
},
{
"code": null,
"e": 28869,
"s": 28713,
"text": "Jasmine also provides different methods to provide sequentiality of the JS output. Following examples show how to implement sequential check using Jasmine."
},
{
"code": null,
"e": 29195,
"s": 28869,
"text": "toContain() matchers provide us the facility to check whether any element is a part of the same array or some other sequential objects. The following example will help us understand the working methodology of Jasmine toContain() method. Let's add the following piece of code in previously created customerMatcherSpec.js file."
},
{
"code": null,
"e": 29366,
"s": 29195,
"text": "describe(\"Different Methods of Expect Block\",function () { \n it(\"The Example of toContain() method\",function () { \n expect([1,2, 3, 4]).toContain(3);\n });\n}); "
},
{
"code": null,
"e": 29499,
"s": 29366,
"text": "In the above example, we are checking whether 3 is present in that array or not. We get a green output as 3 is present in the array."
},
{
"code": null,
"e": 29702,
"s": 29499,
"text": "In the above example, let's change the value of 3 with 15 and run the spec again. We will get the following red screen as 15 does not belong to that array we are passing as a parameter of that function."
},
{
"code": null,
"e": 29895,
"s": 29702,
"text": "toBeCloseTo() matcher matches whether the actual value is close to the expected value. In the following example, we will modify our customerMatcherSpec.js file and see how this actually works."
},
{
"code": null,
"e": 30063,
"s": 29895,
"text": "describe(\"Different Methods of Expect Block\", function () { \n it(\"Example of toBeCloseTo()\", function () { \n expect(12.34).toBeCloseTo(12.3, 1); \n });\n});"
},
{
"code": null,
"e": 30375,
"s": 30063,
"text": "In the above Describe block, we are checking whether the actual result “12.3” is closer to the expected output “12.34” or not. As this satisfies our requirement, we will have the following green screenshot as our output. The second parameter of this method is the count of the decimal place to be compared with."
},
{
"code": null,
"e": 30457,
"s": 30375,
"text": "In the above code, let's modify the expected value to 15 and run SpecRunner.html."
},
{
"code": null,
"e": 30619,
"s": 30457,
"text": "describe(\"Different Methods of Expect Block\",function () { \n it(\"Example of toBeCloseTo()\", function () { \n expect(12.34).toBeCloseTo(15, 1);\n });\n}); "
},
{
"code": null,
"e": 30738,
"s": 30619,
"text": "In this scenario, 15 is nowhere close to 15, hence it will generate an error and present a red screenshot as an error."
},
{
"code": null,
"e": 30934,
"s": 30738,
"text": "ToMatch() matcher works on String type variable. It is helpful to find whether a specific String is present in the expected output or not. Following is what our customerMatcherSpec.js looks like."
},
{
"code": null,
"e": 31119,
"s": 30934,
"text": "describe(\"Different Methods of Expect Block\",function () { \n it(\"Example of toMatch()\", function () { \n expect(\"Jasmine tutorial in tutorials.com\").toMatch(/com/); \n });\n});"
},
{
"code": null,
"e": 31297,
"s": 31119,
"text": "This piece of code will test whether “com” is present in the expected String given. As com exists in the string, it will generate a green screenshot and pass the test condition."
},
{
"code": null,
"e": 31454,
"s": 31297,
"text": "Now let us change the output to some other string, which is not present in the expected value. Then our customerMatcherSpec.js will look like the following."
},
{
"code": null,
"e": 31638,
"s": 31454,
"text": "describe(\"Different Methods of Expect Block\",function () { \n it(\"Example of toMatch()\", function () { \n expect(\"Jasmine tutorial in tutorials.com\").toMatch(/XYZ/);\n });\n}); "
},
{
"code": null,
"e": 31814,
"s": 31638,
"text": "The above code will find “XYZ” string in the expected value. As it does not exist in the expected string, it will throw an error and the output screen will be red accordingly."
},
{
"code": null,
"e": 32041,
"s": 31814,
"text": "Jasmine provides a different variety of method to check whether the actual output is Null, defined or undefined. In this chapter, we will learn how to implement different Jasmine methods to check the above-mentioned scenarios."
},
{
"code": null,
"e": 32199,
"s": 32041,
"text": "This matcher is used to check whether any variable in the code is predefined or not. Let us modify our customerMatcherSpec.js file according to this example."
},
{
"code": null,
"e": 32377,
"s": 32199,
"text": "currentVal = 0; \n\ndescribe(\"Different Methods of Expect Block\",function () { \n it(\"Example of toBeDefined\", function () {\n expect(currentVal).toBeDefined();\n });\n});"
},
{
"code": null,
"e": 32601,
"s": 32377,
"text": "In the above code, toBeDefined() will check whether the variable currentVal is defined in the system or not. As currentVal is defined to 0 in the beginning, this test will pass and generate a green screenshot as an output."
},
{
"code": null,
"e": 32888,
"s": 32601,
"text": "Again in the above example, let us remove the first line, where we actually define “currentVal” and run again. Then we will get a red screen, which means the test actually fails because we are expecting an undefined value to be defined. The following screenshot will be the output file."
},
{
"code": null,
"e": 33198,
"s": 32888,
"text": "This matcher helps to check whether any variable is previously undefined or not, basically it works simply opposite to the previous matcher that is toBeDefined. In the following example, we will learn how to use this matcher. Let us modify our Spec file, i.e. customerMatcher.js file with the following entry."
},
{
"code": null,
"e": 33392,
"s": 33198,
"text": "describe(\"Different Methods of Expect Block\",function () { \n it(\"Example of toBeUndefine()\", function () { \n var undefineValue; \n expect(undefineValue).toBeUndefined(); \n });\n}); "
},
{
"code": null,
"e": 33662,
"s": 33392,
"text": "In the above section, we will verify whether our variable “undefineValue” is actually undefined or not. After adding this file into the SpecRunner, we will receive a green color screenshot as an output, which tells us that this value is actually not defined previously."
},
{
"code": null,
"e": 33822,
"s": 33662,
"text": "Again let us define the variable with some predefined value and see whether it will throw an error or not. The new customerMatcher.js looks like the following."
},
{
"code": null,
"e": 34015,
"s": 33822,
"text": "describe(\"Different Methods of Expect Block\",function () {\n it(\"Example oftoBeUndefine()\", function () { \n var undefineValue = 0;\n expect(undefineValue).toBeUndefined();\n });\n});"
},
{
"code": null,
"e": 34268,
"s": 34015,
"text": "The above piece of code will throw an error and generate a red color screenshot because we have already defined the “undefineValue” value to “0” and expecting it to be not defined. The following screenshot will be generated on run SpecRunner.html file."
},
{
"code": null,
"e": 34417,
"s": 34268,
"text": "As the name signifies this matcher helps to check null values. Let us again modify our customerMatcherSpec.js file with the following piece of code."
},
{
"code": null,
"e": 34591,
"s": 34417,
"text": "describe(\"Different Methods of Expect Block\",function () { \n var value = null; \n\t\n it(\"Example of toBeNull()\", function () { \n expect(value).toBeNull();\n });\n}); "
},
{
"code": null,
"e": 34917,
"s": 34591,
"text": "In the above code, we have mentioned one variable ”value” and we have explicitly mentioned this value as null. In the expect block, the toBeNull() matcher will check this value and give us the result accordingly. Following is the output of the above-mentioned code when it is run through the help of the SpecRunner.html file."
},
{
"code": null,
"e": 35037,
"s": 34917,
"text": "Now let us test by providing some defined value other than null. Please modify the customerMatcher.js file accordingly."
},
{
"code": null,
"e": 35223,
"s": 35037,
"text": "describe(\"Different Methods of Expect Block\",function () {\n var value = \"TutorialsPoint\"; \n\t\n it(\"Example of toBeNull()\", function () { \n expect(value).toBeNull();\n });\n}); "
},
{
"code": null,
"e": 35400,
"s": 35223,
"text": "In the above example, we have modified the variable value with “TutorialsPoint” which is not a null value. Hence, this test will fail and produce a red screenshot as an output."
},
{
"code": null,
"e": 35690,
"s": 35400,
"text": "Till now, we have discussed different methods in Jasmine which help us test different scenarios based on our requirements. In this chapter, we will learn about different matchers that will help us check the inequality condition in JS file. Following are the matchers used for this purpose."
},
{
"code": null,
"e": 35835,
"s": 35690,
"text": "As the name suggests this matcher helps to check greater than condition. Let us modify our customerMatcher.js using the following piece of code."
},
{
"code": null,
"e": 36018,
"s": 35835,
"text": "describe(\"Different Methods of Expect Block\",function () { \n var exp = 8; \n\t\n it(\"Example of toBeGreaterThan()\", function () {\n expect(exp).toBeGreaterThan(5);\n });\n}); "
},
{
"code": null,
"e": 36250,
"s": 36018,
"text": "In the above piece of code, we are expecting that the value of the variable “exp” will be greater than 5. Now as the value of the variable “exp” is “8” which is greater than “5”, this piece of code will generate a green screenshot."
},
{
"code": null,
"e": 36408,
"s": 36250,
"text": "Now again let us modify the value of the variable to “4” and make this test fail. To do that we need to modify the js file using the following piece of code."
},
{
"code": null,
"e": 36592,
"s": 36408,
"text": "describe(\"Different Methods of Expect Block\",function () { \n var exp = 4; \n\t\n it (\"Example of toBeGreaterThan()\", function () {\n expect(exp).toBeGreaterThan(5); \n });\n});"
},
{
"code": null,
"e": 36698,
"s": 36592,
"text": "This code will fail because value 4 cannot be greater than 5. Hence it will produce the following output."
},
{
"code": null,
"e": 36932,
"s": 36698,
"text": "This matcher helps to check the less than condition of the test scenario. It behaves exactly opposite to that of toBeGreaterThan() matcher. Now let us see how this matcher works. Let us modify the customerMatcher.js file accordingly."
},
{
"code": null,
"e": 37111,
"s": 36932,
"text": "describe(\"Different Methodsof Expect Block\",function () { \n var exp = 4; \n\t\n it(\"Example of toBeLessThan()\", function() { \n expect(exp).toBeLessThan(5); \n });\n}); "
},
{
"code": null,
"e": 37332,
"s": 37111,
"text": "Like the previous example, we have one variable having value as “4”. In this piece of code, we are checking whether the value of this variable is less than 5 or not. This piece of code will generate the following output."
},
{
"code": null,
"e": 37577,
"s": 37332,
"text": "Now to make this fail, we need to assign some bigger number to the variable exp. Let us do that and test the application. We will assign 25 as the value to the exp, which will definitely throw an error and yield the following screenshot in red."
},
{
"code": null,
"e": 37678,
"s": 37577,
"text": "Jasmine provides a special matcher to check this special type of testing scenario that is toBeNaN()."
},
{
"code": null,
"e": 37740,
"s": 37678,
"text": "Let us modify our customerMatcher.js with the following code."
},
{
"code": null,
"e": 37888,
"s": 37740,
"text": "describe(\"Different Methods of Expect Block\",function () { \n it(\"Example of toBeNaN()\", function () { \n expect(0 / 0).toBeNaN(); \n });\n});"
},
{
"code": null,
"e": 38036,
"s": 37888,
"text": "Here we want to test what is the value of “0/0” which cannot be determined. Hence, this piece of code will generate the following green screenshot."
},
{
"code": null,
"e": 38201,
"s": 38036,
"text": "Now let us again modify the code with the following logic, where we will assign one variable exp to 25 and expect the result is not a number one dividing it with 5."
},
{
"code": null,
"e": 38369,
"s": 38201,
"text": "describe(\"Different Methods of Expect Block\",function () { \n var exp = 25; \n\t\n it(\"Example of toBeNaN()\", function () { \n expect(exp/5).toBeNaN(); \n });\n});"
},
{
"code": null,
"e": 38421,
"s": 38369,
"text": "This piece of code will yield the following output."
},
{
"code": null,
"e": 38600,
"s": 38421,
"text": "Apart from different computational matchers, Jasmine provides some useful matchers to check exception of the program. Let us modify our JavaScript with the following set of code."
},
{
"code": null,
"e": 38853,
"s": 38600,
"text": "var throwMeAnError = function() { \n throw new Error(); \n}; \n\ndescribe(\"Different Methods of Expect Block\", function() { \n var exp = 25; \n\n it (\"Hey this will throw an Error \", function() { \n expect(throwMeAnError).toThrow(); \n }); \n});"
},
{
"code": null,
"e": 39093,
"s": 38853,
"text": "In the above example, we have created one method which deliberately throws an exception from that method and in the expect block we expect to catch the error. If everything goes well then this piece of code will yield the following output."
},
{
"code": null,
"e": 39313,
"s": 39093,
"text": "Now, for this test case to fail, we need to omit that throw statement in the function throwMeAnError. Following is the code which will yield a red screenshot as an output since the code does not satisfy our requirement."
},
{
"code": null,
"e": 39574,
"s": 39313,
"text": "var throwMeAnError = function() { \n //throw new Error(); \n}; \n\ndescribe(\"Different Methods of Expect Block\",function() { \n var exp = 25; \n \n it(\"Hey this will throw an Error \", function() { \n expect(throwMeAnError).toThrow(); \n }); \n});"
},
{
"code": null,
"e": 39758,
"s": 39574,
"text": "As can be seen, we have commented that line from where our method was throwing the exception. Following is the output of the above code on successful execution of the SpecRunner.html."
},
{
"code": null,
"e": 39964,
"s": 39758,
"text": "Any is the special matcher that is used when we are not sure about the output. In the following example, we will learn how this works. Let us modify the customerMatcher.js with the following piece of code."
},
{
"code": null,
"e": 40340,
"s": 39964,
"text": "var addAny = function() {\n var sum = this.currentVal; \n\t\n for (var i = 0; i < arguments.length; i++) { \n sum += arguments[i]; \n } \n\t\n this.currentVal = sum; \n return this.currentVal; \n} \n\ndescribe(\"Different Methods of Expect Block\",function () { \n \n it(\"Example of any()\", function() { \n expect(addAny(9,9)).toEqual(jasmine.any(Number)); \n });\n});"
},
{
"code": null,
"e": 40542,
"s": 40340,
"text": "Here we have declared one function that will give us the summation of the numbers provided as arguments. In the expect block, we are expecting that the result can be anything but it should be a Number."
},
{
"code": null,
"e": 40676,
"s": 40542,
"text": "As both 9 and 9 after sum yield 18 is a number, this test will pass and it will generate the following green screenshot as an output."
},
{
"code": null,
"e": 40830,
"s": 40676,
"text": "Now let us change the code according to the following piece of code, where we are expecting a string type variable as an output of the function AddAny()."
},
{
"code": null,
"e": 41205,
"s": 40830,
"text": "var addAny = function() { \n var sum = this.currentVal; \n\t\n for(var i = 0; i < arguments.length; i++) { \n sum += arguments[i]; \n } \n\t\n this.currentVal = sum; \n return this.currentVal; \n} \n\ndescribe(\"Different Methodsof Expect Block\",function () { \n it(\"Example of any()\", function () { \n expect(addAny(9,9)).toEqual(jasmine.any(String)); \n });\n});"
},
{
"code": null,
"e": 41248,
"s": 41205,
"text": "Following is the output of the above code."
},
{
"code": null,
"e": 41557,
"s": 41248,
"text": "Another notable feature of Jasmine is before and after each function. Using these two functionalities, we can execute some pieces of code before and after execution of each spec. This functionality is very useful for running the common code in the application. Let us create one spec file like the following."
},
{
"code": null,
"e": 41786,
"s": 41557,
"text": "var currentVal = 0; \n\nbeforeEach(function() { \n currentVal = 5; \n}); \n\ndescribe(\"Different Methods of Expect Block\",function() { \n it(\"after each function \", function() {\n expect(currentVal).toEqual(5); \n });\n});"
},
{
"code": null,
"e": 41981,
"s": 41786,
"text": "Here although we have declared one variable as “0” in the beginning, we are expecting this value should be equal to 5 in the expectation block. The above code will generate the following output."
},
{
"code": null,
"e": 42140,
"s": 41981,
"text": "In the above code, 5 will be assigned to a variable currentVal before the execution of the expect block. Hence, it generates a green screenshot with no error."
},
{
"code": null,
"e": 42311,
"s": 42140,
"text": "Like beforeEach(), afterEach() works exactly the same way. It executes after the execution of the spec block. Let us modify the previous example using the following code."
},
{
"code": null,
"e": 42627,
"s": 42311,
"text": "var currentVal = 0; \n\nafterEach(function() { \n currentVal = 5; \n}); \n\ndescribe(\"Different Methods of Expect Block\",function() { \n it(\"first call \", function() { \n expect(currentVal).toEqual(0); \n }); \n \n it(\"second call \", function() { \n expect(currentVal).toEqual(5); \n });\n});"
},
{
"code": null,
"e": 42963,
"s": 42627,
"text": "In the above example, while running the first spec block the value of the currentVal is 0. Hence, it will pass the test case but after running the first it block, Jasmine compile ran the afterEach() block, which makes the value of the currentVal to 5. Hence it also satisfies the second case and yields a green screenshot as an output."
},
{
"code": null,
"e": 43363,
"s": 42963,
"text": "Jasmine spy is another functionality which does the exact same as its name specifies. It will allow you to spy on your application function calls. There are two types of spying technology available in Jasmine. The first methodology can be implemented by using spyOn() and the second methodology can be implemented using createSpy(). In this chapter, we will learn more about these two methodologies."
},
{
"code": null,
"e": 43599,
"s": 43363,
"text": "spyOn() is inbuilt into the Jasmine library which allows you to spy on a definite piece of code. Let us create a new spec file “spyJasmineSpec.js” and another js file named as “spyJasmine.js”. Following is the entry of these two files."
},
{
"code": null,
"e": 43900,
"s": 43599,
"text": "var Person = function() {}; \n\nPerson.prototype.sayHelloWorld = function(dict) { \n return dict.hello() + \" \" + dict.world(); \n}; \n\nvar Dictionary = function() {}; \n\nDictionary.prototype.hello = function() { \n return \"hello\"; \n}; \n\nDictionary.prototype.world = function() { \n return \"world\"; \n}; "
},
{
"code": null,
"e": 44503,
"s": 43900,
"text": "describe(\"Example Of jasmine Spy using spyOn()\", function() { \n \n it('uses the dictionary to say \"hello world\"', function() { \n var dictionary = new Dictionary; \n var person = new Person; \n\t\t\n spyOn(dictionary, \"hello\"); // replace hello function with a spy \n spyOn(dictionary, \"world\"); // replace world function with another spy \n\t\t\n person.sayHelloWorld(dictionary);\n expect(dictionary.hello).toHaveBeenCalled(); \n // not possible without first spy \n \n expect(dictionary.world).toHaveBeenCalled(); \n // not possible withoutsecond spy \n }); \n});"
},
{
"code": null,
"e": 44693,
"s": 44503,
"text": "In the above piece of code, we want person object to say “Hello world” but we also want that person object should consult with dictionary object to give us the output literal “Hello world”."
},
{
"code": null,
"e": 45019,
"s": 44693,
"text": "Take a look at the Spec file where you can see that we have used spyOn() function, which actually mimics the functionality of the hello and world function. Hence, we are not actually calling the function but mimicking the function call. That is the specialty of Spies. The above piece of code will yield the following output."
},
{
"code": null,
"e": 45151,
"s": 45019,
"text": "Another method of obtaining the spying functionality is using createSpy(). Let us modify our two js files using the following code."
},
{
"code": null,
"e": 45455,
"s": 45151,
"text": "var Person = function() {}; \n\nPerson.prototype.sayHelloWorld = function(dict) { \n return dict.hello() + \" \" + dict.world(); \n}; \n\nvar Dictionary = function() {}; \n\nDictionary.prototype.hello = function() { \n return \"hello\"; \n}; \n\nDictionary.prototype.world = function() { \n return \"world\"; \n}; "
},
{
"code": null,
"e": 45755,
"s": 45455,
"text": "describe(\"Example Of jasmine Spy using Create Spy\", function() { \n \n it(\"can have a spy function\", function() { \n var person = new Person(); \n person.getName11 = jasmine.createSpy(\"Name spy\"); \n person.getName11(); \n expect(person.getName11).toHaveBeenCalled(); \n }); \n}); "
},
{
"code": null,
"e": 46079,
"s": 45755,
"text": "Take a look at the spec file, we are calling the getName11() of the Person object. Although this function is not present in the person object in spy Jasmine.js, we are not getting any error and hence the output is green and positive. In this example, createSpy() method actually mimics the functionality of the getName11()."
},
{
"code": null,
"e": 46130,
"s": 46079,
"text": "The above code will generate the following output."
},
{
"code": null,
"e": 46137,
"s": 46130,
"text": " Print"
},
{
"code": null,
"e": 46148,
"s": 46137,
"text": " Add Notes"
}
] |
Analyzing Employee Exit Surveys. Analyze statistical rigor and latent... | by Kamil Mysiak | Towards Data Science
|
When analyzing employee sentiment data, which in our case is an employee exit survey, we have to look at four topics.
Statistical rigor of the surveyDemographical composition of survey respondentsOverall sentiment for defined latent constructsSentiment scores by respondents’ characteristics (ie. gender, location, department, etc.)
Statistical rigor of the survey
Demographical composition of survey respondents
Overall sentiment for defined latent constructs
Sentiment scores by respondents’ characteristics (ie. gender, location, department, etc.)
First, keeping to this methodology will enable us to determine how well our survey is measuring what it is meant to measure. Secondly, by understanding who answered the survey from a respondent characteristics perspective (ie. gender, departments, etc) we can provide context to our analysis and results. Thirdly, this methodology will help us determine the general sentiment of the responders. Last but not least, it will help us determine not only what organization initiatives might be useful to increase sentiment but also where these initiatives should be implemented.
The dataset we’ll be using is a fictional employee exit survey which asks the employee a series of questions regarding their organizational demographics (ie. department) and 5-point Likert (ie. Strongly Disagree, Disagree, Neutral, Agree, Strongly Agree) sentiment questions (ie. the organization offered plenty of promotional opportunities). No open-ended questions were utilized.
import pandas as pdimport numpy as npimport scipy.stats as statsimport matplotlib.pyplot as pltimport seaborn as snsimport warningswarnings.filterwarnings('ignore')pd.set_option('display.max_columns', None)%matplotlib inlinewith open('exit_data_final.csv') as f: df = pd.read_csv(f)f.close()df.info()
We have 33 items or questions which were asked of the employees. Before we can begin our analysis we have a bit of data cleaning to perform.
df.drop('Unnamed: 0', axis=1, inplace=True)
Let’s drop this odd “Unnamed” column as it services no purpose.
for var in df.columns: print(var, df[var].unique())
By examining the unique values for each item we can see a few issues.
Some items have missing values labeled correctly as np.nan but others are simply null.Based on df.info() we need to transform the item types for our Likert items as they are currently formatted as ‘objects’.Finally, we need to transform some of the values in order to improve the readability of our visualizations.
Some items have missing values labeled correctly as np.nan but others are simply null.
Based on df.info() we need to transform the item types for our Likert items as they are currently formatted as ‘objects’.
Finally, we need to transform some of the values in order to improve the readability of our visualizations.
# Replacing nulls with np.nanfor var in df.columns: df[var].replace(to_replace=' ', value=np.nan, inplace=True)# Converting feature typeslikert_items = df[['promotional_opportunities', 'performance_recognized', 'feedback_offered', 'coaching_offered', 'mgmt_clear_mission', 'mgmt_support_me', 'mgmt_support_team', 'mgmt_clear_comm', 'direct_mgmt_satisfaction', 'job_stimulating', 'initiative_encouraged', 'skill_variety', 'knowledge_variety', 'task_variety', 'fair_salary', 'teamwork', 'team_support', 'team_comm', 'team_culture', 'job_train_satisfaction', 'personal_train_satisfaction', 'org_culture', 'grievances_resolution', 'co-worker_interaction', 'workplace_conditions', 'job_stress', 'work/life_balance']]for col in likert_items: df[col] = pd.to_numeric(df[col], errors='coerce').astype('float64')# Discretization of tenurebins = [0,4,9,14,19,24]labels = ['0-4yrs', '5-9yrs', '10-14yrs', '15-19yrs', '20+yrs']df['tenure'] = pd.cut(df['tenure'], bins = bins, labels=labels)
In my previous article, we reviewed the process of analyzing the statistical rigor (ie. validity, reliability, factor analysis) of our survey. Feel free to review the but let’s quickly review what latent survey constructs are and how they are derived.
In order to develop survey items or questions which maintain good statistical rigor, we have to begin with scholarly literature. We want to find a theoretical model that describes the phenomena we wish to measure. For example, personality surveys very often will use the Big-5 model (ie. openness, conscientiousness, extraversion, agreeableness, and neuroticism) to develop the survey items. The survey developer will carefully craft 2–10 (depending on the length of the survey) items for each component of the model. The items which are meant to assess the same component are said to be measuring a “latent construct”. In order words, we are not measuring “extraversion” explicitly as that would be an “observed construct” but indirectly through the individual survey items. The survey is pilot tested with multiple samples of respondents until a certain level of rigor is attained. Once again, if you’re interested in the statistical analyses used to determine rigor take a look at my previous article.
# Calculating latent variablesdf['employee_valued'] = np.nanmean(df[['promotional_opportunities', 'performance_recognized', 'feedback_offered', 'coaching_offered']], axis=1)df['mgmt_sati'] = np.nanmean(df[['mgmt_clear_mission', 'mgmt_support_me', 'mgmt_support_team', 'mgmt_clear_comm', 'direct_mgmt_satisfaction']], axis=1)df['job_satisfaction'] = np.nanmean(df[['job_stimulating','initiative_encouraged','skill_variety','knowledge_variety', 'task_variety']], axis=1)df['team_satisfaction'] = np.nanmean(df[['teamwork','team_support', 'team_comm','team_culture']], axis=1)df['training_satisfaction'] = np.nanmean(df[['job_train_satisfaction','personal_train_satisfaction']], axis=1)df['org_environment'] = np.nanmean(df[['org_culture','grievances_resolution','co-worker_interaction','workplace_conditions']], axis=1)df['work_life_balance'] = np.nanmean(df[['job_stress','work/life_balance']], axis=1)df['overall_sati'] = np.nanmean(df[['promotional_opportunities', 'performance_recognized','feedback_offered', 'coaching_offered', 'mgmt_clear_mission','mgmt_support_me', 'mgmt_support_team', 'mgmt_clear_comm','direct_mgmt_satisfaction', 'job_stimulating', 'initiative_encouraged','skill_variety', 'knowledge_variety', 'task_variety', 'fair_salary','teamwork', 'team_support', 'team_comm', 'team_culture', 'job_train_satisfaction', 'personal_train_satisfaction', 'org_culture', 'grievances_resolution', 'co-worker_interaction', 'workplace_conditions', 'job_stress', 'work/life_balance']], axis=1)
Our exit survey has also been developed to assess certain latent constructs. Each survey item is averaged in accordance with the latent factor is it meant to measure. Finally, we have calculated an “overall_sati” feature which calculates the grand average across all items/latent factors for each respondent.
Below is a list of the survey items and the latent construct they are meant to measure. Keep in mind each label for each item has been shortened significantly in order to help facilitate visualizations. You can imagine the items asking questions such as “On a scale of 1–5, I find my job stimulating”.
mappings = {1:'1) Dissatisfied', 2:'1) Dissatisfied', 3:'2) Neutral', 4:'3) Satisfied', 5:'3) Satisfied'}likert = ['promotional_opportunities', 'performance_recognized', 'feedback_offered', 'coaching_offered', 'mgmt_clear_mission', 'mgmt_support_me', 'mgmt_support_team', 'mgmt_clear_comm', 'direct_mgmt_satisfaction', 'job_stimulating', 'initiative_encouraged', 'skill_variety', 'knowledge_variety', 'task_variety', 'fair_salary', 'teamwork', 'team_support', 'team_comm', 'team_culture', 'job_train_satisfaction', 'personal_train_satisfaction', 'org_culture', 'grievances_resolution', 'co-worker_interaction', 'workplace_conditions', 'job_stress', 'work/life_balance']for col in likert: df[col+'_short'] = df[col].map(mappings) df.head()
In order to aid with visualizations, we are going to create new features which will aggregate ratings of 1 and 2 into Dissatisfied, 3 into neutral, and 4 and 5 into Satisfied. This will enable us to create stacked bar plots with 3 unique portions.
Understanding the demographics of survey respondents’ helps to provide contextual information for our analysis. We also have to keep in mind that most employee exit surveys are completed on a volunteer basis. Due to this confounding variable, we need to take any insights gleaned from the data as “evidence” of organizational affairs instead of definitive “proof”. Employees might have been extremely happy or angry with the organization and their attitude will surely be represented in their answers. Finally, the survey consists of roughly 600 respondents and we need to be careful not to consider these as the total number of all termination which occurred in the last 4 years. 600 terminations might only be a small percentage of all terminations which have occurred.
In other words, our analysis hopes to determine the level satisfaction on several organizational factors for those employees who RESPONDED to the survey. We should not generalize our results to the broader organization or all terminated employees.
def uni_plots(feature, text): tmp_count = df[feature].dropna().value_counts().values tmp_percent = ((df[feature].dropna().value_counts()/len(df))*100).values df1 = pd.DataFrame({feature: df[feature].value_counts().index, 'Number of Employees': tmp_count, 'Percent of Employees': tmp_percent}) f, ax = plt.subplots(figsize=(20,10)) plt.title(text, fontsize=25, pad=30) plt.tick_params(axis='both', labelsize=15, pad=10) plt.xlabel(feature, fontsize=20) plt.xticks(size=18) plt.yticks(size=18) sns.set_color_codes('pastel') count = sns.barplot(x=feature, y='Number of Employees', color='b', data=df1, label='Number of Employees') for p in count.patches: count.annotate(format(p.get_height(), '.1f'), (p.get_x() + p.get_width() / 2., p.get_height()), ha = 'center', va = 'center', xytext = (0, 9), textcoords = 'offset points', size = 20) sns.set_color_codes('muted') percent = sns.barplot(x=feature, y='Percent of Employees', color='b', data=df1, label='Percent of Employees') for i in percent.patches: percent.annotate(format(i.get_height(), '.1f'), (i.get_x() + i.get_width() / 2., i.get_height()), ha = 'center', va = 'center', xytext = (0, 9), size = 20, textcoords = 'offset points') ax.set_ylabel('') ax.legend(ncol=2, loc="upper right", fontsize=15, frameon=True) sns.despine(left=False, bottom=False) ax.set_xticklabels(ax.get_xticklabels(), rotation=45) plt.show()def bi_cat_plot(feature1, feature2): ax = pd.crosstab(df[feature1], df[feature2], normalize='index')*100 ax1 = ax.plot(kind='barh', stacked=True, figsize=(25,15), fontsize=25) for i in ax1.patches: width, height = i.get_width(), i.get_height() x, y = i.get_xy() ax1.text(x+width/2, y+height/2, '{:.0f} %'.format(width), horizontalalignment='center', verticalalignment='center', size=25) plt.title('Percentage of Termination Reasons by {}'.format(feature1), fontsize=30, pad=25) plt.ylabel(' ') plt.legend(prop={'size':20})
The production, customer service, and sales departments make up over 65% of the survey respondents across 4 years (2017–2020) of data collection. We have a large discrepancy in survey respondents across all four years. 2018 saw 342 terminations whereas 2020 has only seen 37.
A major insight stems from the fact that almost 50% of the respondents were voluntary terminations. Once again it is difficult to generalize our results to the broader organization without conclusive HRIS data but this size of discrepancy in termination reasons points us to the possibility that the company may have a problem with voluntary terminations. We don’t have any employee performance data to determine constructive or regrettable voluntary turnover as this would allow us to specifically focus our analysis on regrettable voluntary turnover.
The largest age group of respondents is 56 and older which makes up almost 20% of the respondents. Slicing age by reason for termination we can see that this age group makes up 87% of retirements which would make sense. If we look at voluntary turnover and age, we can see an even distribution across all age groups.
Variables with a low number of categories such as gender typically don’t provide us with many insights unless we see major skewness to the data. It seems females responded to the survey at almost 2:1 ratio compared to males. Looking at gender by reason for termination we see percentages that mirror the ratio we see for gender overall.
We have a fairly even distribution of respondents based on job type. We do see managerial and executive job types to make up a significantly smaller portion but these positions make up smaller portions of the organization in general. What is more interesting that we see a spike in involuntary terminations (38%) for executives. We typically see lower sentiment for involuntary terminations compared to other reasons of termination, therefore, we can expect executives to score fairly low on overall sentiment.
Overall, we see voluntary terminations make up the majority of respondents who mainly come from the production, customer service and sales departments and fall towards the latter years of their careers (41 and older).
The overall respondent sentiment is calculated by first taking the average of all the individual sentiment items (ie. Likert items) for each respondent. Finally, a grand average is calculated depending on how the data is sliced.
def overall_plot(feature): ax = round(df.groupby(feature)['overall_sati'].mean(),2).sort_values().plot(kind='barh', stacked=True, figsize=(25,15), fontsize=25) for i in ax.patches: width, height = i.get_width(), i.get_height() x, y = i.get_xy() ax.text(x+width/2, y+height/2, '{:.2f}'.format(width), horizontalalignment='center', verticalalignment='center', size=25) plt.title('Overall Employee Sentiment by {}'.format(feature), fontsize=30, pad=25) plt.ylabel(' ')
Overall, HR has the lowest overall sentiment but it also makes up the smallest percentage of respondents (5.8%). This is problematic because the average can be quickly swayed by just a few respondents who rated the Likert items very low. That said, we cannot ignore this low overall average sentiment. On the other hand, production and sales make up the two largest portion of the respondents and they score 2nd and 3rd lowest. We will have to take a look into these three departments to determine which factors score particularly low.
The fact involuntary terminations scored the lowest on overall sentiment is not surprising. Being terminated (fired/laid off) by the organization typically produces adverse emotions which can affect how you respond to the survey. What is more interesting is that voluntary terminations, which is the number one reason in response rate, scored second-lowest on overall sentiment. Understanding the potential causes of voluntary turnover can pay enormous dividends in keeping your high performing workforce.
We can see that 46–50 age group scored the lowest.
As expected, executives scores particularly low on overall sentiment as 38% of them were terminated involuntarily but we also have to remember that 33% were terminated voluntarily. We definitely have to look into which specific factors executives score particularly low on. Finally, machine_ops scored equally low (3.39) on overall sentiment, also this population has a 52% voluntary termination response rate.
Finally, we don’t see any particular differences in general sentiment between tenure groups.
In summary, HR, production, and sales had the lowest overall sentiment with HR scoring (3.39). Since production and sales maintain the highest number of survey respondents we need to examine which specific factors these departments score the lowest on. Involuntary terminations had the lowest sentiment (3.42) which is of no surprise but voluntary turnover had the second-lowest average sentiment while being having the highest number of survey respondents. Finally, we saw executives and machine ops job types to have the lowest sentiment (3.39). Yet again additional analyses are required to ascertain the nature of this relationship.
emp_value_avg = round(np.mean(df['employee_valued']),2)mgmt_sati_avg = round(np.mean(df['mgmt_sati']),2)job_sati_avg = round(np.mean(df['job_satisfaction']),2)team_sati_avg = round(np.mean(df['team_satisfaction']),2)training_sati_avg = round(np.mean(df['training_satisfaction']),2)org_env_avg = round(np.mean(df['org_environment']),2)work_life_avg = round(np.mean(df['work_life_balance']),2)overall_sati = round(np.mean([emp_value_avg, mgmt_sati_avg, job_sati_avg, team_sati_avg, training_sati_avg, org_env_avg, work_life_avg]), 2)temp_dict = {'emp_value_avg': emp_value_avg, 'mgmt_sati_avg': mgmt_sati_avg, 'job_sati_avg': job_sati_avg, 'team_sati_avg': team_sati_avg, 'training_sati_avg': training_sati_avg, 'org_env_avg': org_env_avg, 'work_life_avg': work_life_avg, 'overall_sati': overall_sati}tmp_df = pd.DataFrame.from_dict(temp_dict, orient='index', columns=['average']).sort_values(by='average')plt.figure(figsize=(25,15))plt.title('Overall Latent Factor Averages', fontsize=28)plt.ylabel('Average Employee Rating', fontsize=25)ax = tmp_df['average'].plot(kind='barh', fontsize=25)for i in ax.patches: width, height = i.get_width(), i.get_height() x, y = i.get_xy() ax.text(x+width/2, y+height/2, '{:.2f}'.format(width), horizontalalignment='center', verticalalignment='center', size=25)plt.grid(False)plt.show()
If we disregard any respondent demographics and look at our latent sentiment factors we see that fair_salary, emp_value, and org_env have scored the lowest. It is important to focus our analysis on these factors in order to understand why these factors are low but also where in the organization they are the lowest (ie. department, job type, etc.). Our results are confirmed for voluntary termination as well.
likert = ['promotional_opportunities', 'performance_recognized', 'feedback_offered', 'coaching_offered', 'mgmt_clear_mission', 'mgmt_support_me', 'mgmt_support_team', 'mgmt_clear_comm', 'direct_mgmt_satisfaction', 'job_stimulating', 'initiative_encouraged', 'skill_variety', 'knowledge_variety', 'task_variety', 'fair_salary', 'teamwork', 'team_support', 'team_comm', 'team_culture', 'job_train_satisfaction', 'personal_train_satisfaction', 'org_culture', 'grievances_resolution', 'co-worker_interaction', 'workplace_conditions', 'job_stress', 'work/life_balance']likert_avgs = []for col in likert: likert_avgs.append(round(np.nanmean(df[col]),2))likert_avgs_df = pd.DataFrame(list(zip(likert, likert_avgs)), columns=['likert_item', 'avg_sentiment'])likert_avgs_df.set_index('likert_item', inplace=True)plt.figure()ax = likert_avgs_df.plot(kind='bar', figsize=(25,15), fontsize=20)for i in ax.patches: width, height = i.get_width(), i.get_height() x, y = i.get_xy() ax.text(x+width-0.25, y+height+.1, '{:.2f}'.format(height), horizontalalignment='center', verticalalignment='center', size=20)plt.title('Average Overall Likert Item Sentiment', fontsize=30, pad=25)plt.legend().remove()plt.xlabel(' ')
By examining the individual Likert items which make up each latent factor we can see that promotional opportunities and performance_recognized contribute the most to the low sentiment of emp_value. Although we would have liked to see more than one Likert item to assess salary satisfaction we can examine fair_salary in greater detail to determine where this sentiment is particularly low. Finally, it seems org_culture and grievances_resolution contribute the most to the low sentiment of org_environment.
When analyzing survey data it is quite easy to end-up down a proverbial rabbit-hole of charts and plots only to lose sight of your goal. In other words, we need to narrow our focus. The ultimate goal of analyzing sentiment surveys is to identify areas of weakness where organizational initiatives can be implemented to improve those identified areas. The area we will mainly focus our efforts on are voluntary terminations. First, they make up almost 50% of the respondents. Secondly, this is the employee population where we can make the most significant impact on using organizational initiatives. Finally, we want to limit the amount of voluntary turnover in order to limit the knowledge drain from the organization and minimize the recruiting and training cost associated with hiring replacement employees.
# plotting average likert sentiment by respondent characteristics for voluntary terminationsdef bi_volterm_plot(feature1, feature2): tmp_df = df.loc[(df['reason_of_term']=='vol_term')] ax = round(tmp_df.groupby(feature1)[feature2].mean(),2).sort_values().plot(kind='barh', stacked=True, figsize=(25,15), fontsize=25) for i in ax.patches: width, height = i.get_width(), i.get_height() x, y = i.get_xy() ax.text(x+width/2, y+height/2, '{:.2f}'.format(width), horizontalalignment='center', verticalalignment='center', size=25) plt.title('Average {} Sentiment of Voluntary Terminations by {}'.format(feature2, feature1),fontsize=30, pad=25) plt.ylabel(' ') plt.legend(prop={'size':20})
Not surprisingly voluntary termination from the HR department had the lowest score on emp_value as HR has the lowest overall sentiment. Additionally, purchasing, customer service, and production also scored relatively low. This is important as production and customer service have the largest number of survey respondents.
Since we know promotional opportunities and performance recognized are the main drivers behind low emp_value sentiment we are plotting these Likert items against department, age, and job type.
Filtering the data for only voluntary terminations, we can see that most departments score low on promotional opportunities but customer_service, HR, and purchasing score particularly low. Age scores especially low as voluntarily terminated employees between the ages of 21–50 score very low on promotional opportunities sentiment. Age group 46–50 yrs old scores very low (2.62) on this Likert item. Voluntarily terminated executives, managerial, machine ops, and service workers job types scored low on promotional opportunities sentiment with executives scoring very low (2.17). Finally, all tenure groups besides 1–14 yrs score low on promotional opportunities but 5–9 yrs scored especially low (2.80).
Once again we see purchasing and HR score the lowest on performance recognized but IT and production have fairly low sentiment as well. From an employee age perspective, 26–50 have scored the lowest, plus these age groups also scored very low on promotional opportunities. Again we see executive, managerial, and machine ops job types score the lowest. Finally, much like we saw with promotional opportunities, tenure group 5–9 yrs has scored the lowest on performance recognized.
Fair_salary scored second-lowest on overall respondent sentiment. Now that we have filtered our data for voluntary terminations let’s take a look where salary sentiment is the lowest. Not surprisingly, HR and purchasing departments scored the lowest. However, production which has a tendency to score low as well on many Likert items actually scored relatively well. That said, we do see R&D and IT scoring low on this Likert item. 46–50 yr olds again score low as they record an average sentiment of (2.76). Executives, managerial, and administrative job types score the lowest on fair_salary. Finally, tenure group 5–9 yrs scored the lowest.
We know that the organizational environment factor scored third lowest in terms of overall sentiment. As we filter for voluntary terminations we see that HR and purchasing scored the lowest on this factor. Let’s break this factor into its individual Likert items.
We saw from our analysis above that org_culture and grievances_resolution were the two Likert items that seemed to contribute most to organizational environment’s low overall sentiment.
It would seem org-culture has scored low and at times very low across all departments. From an age perspective, org_culture is the lowest for 46–50 yr olds but it’s generally low for individuals between 26–50 yrs old. Executives have scored extremely low on this Likert item (1.80) followed by machine ops and managerial. That said, all job types besides sales have scored below an average score of 3.00. Finally from a tenure perspective, all tenure groups scored below 3.00 with 5–9yrs group scoring particularly low.
Once again purchasing, HR, customer service and production scored the lowest on grievances_resolution. Age groups, once more we see 46–50-year-old respondents make up the lowest sentiment. Executives and machine ops had the lowest sentiment for grievances resolution. Finally, again 5–9yrs tenure group scored the lowest on this Likert item much like org_culture.
Voluntary terminations made up the largest group of survey respondents at almost 50%. This is wonderful news as it allows us enough data to make insights into the organizational sentiment of a, particularly important population. Understanding the potential reason why voluntary terminations are occurring can help the company reduce this turnover thereby minimizing knowledge drain and hiring cost.
Production (32%), customer service (19%), and sales (16%) made up the majority of survey responses from a departmental perspective. Despite the remaining departments having a significantly lower response rate their number of responses is not low enough which would warrant their insights meaningless.
Respondents 56 yrs of age and older made up the largest group at (23%) and the remaining groups were relatively even besides 20 yrs and younger which only made up (2.3%). By slicing this data by reason of termination we can see that 54% of 56 yrs and older responders were retiring.
Females answered the survey at almost 2:1 rate compared to males.
Job types were fairly evenly represented in the survey with Service workers (19%), professional (17%), and sales (14%) taking the top three. Executives answered the survey at the lowest rates (3%) or 24 responses. 24 is a relatively low number of responses which can produce skewed results. Furthermore, the executive job type had the largest percentage (38%) of involuntary terminations and we know that involuntary terminations have a tendency to produce more negative overall sentiment. Any insights regarding the executive population will have to be scrutinized and validated with much larger sample size.
Finally, organization tenure yield an even representation of responses at average 20% per tenure group.
As expected involuntary terminations had the lowest average sentiment but closely followed by voluntary terminations. It would seem HR, production, and sales departments had the overall lowest sentiment. Furthermore, responders between the ages of 46–50 along with executive, machine ops, and managerial job types had the lowest overall sentiment.
The three latent factors with the lowest overall sentiment were salary satisfaction (3.14), employee valued (3.31), and organizational environment (3.46). If we examine the individual Likert items/questions for these three latent factors we can see that promotional opportunities and performance recognition were had the lowest sentiment for employee valued. Fair salary had the lowest sentiment for salary satisfaction. Finally, organizational culture and grievances resolution had the lowest overall sentiment for organizational environment.
When specifically looking at the voluntarily terminated population we see similar results as above. Salary satisfaction, employee value, and organizational environment had the lowest overall sentiment. Again promotional opportunities and performance recognition were the driving factors for low employee value sentiment. Fair salary was the main driver of low salary satisfaction. Finally, organizational culture and grievances resolution had the lowest scores on the organizational environment latent factor.
Promotional Opportunities (employee value)
Most departments need to improve their access to promotional opportunities but purchasing, HR, customer service, and production departments are in greatest need to stem voluntary turnover. Furthermore, it seems promotional opportunities sentiment is low across most age groups especially 46–50 years olds. Executives, managerial, machine ops and service worker job types suffered most from lack of promotional opportunities. Finally, tenured employees between 5–9 yrs had the lowest sentiment towards promotional opportunities.
Performance Recognition (employee value)
Purchasing and HR had suffered from low-performance recognition. Low sentiment for performance recognition was also shared by 46–50 yrs olds, executives, managerial, and machine ops job types. Finally, we again see 5–9 yrs of tenure seems to have low sentiment on this item.
Fair Salary (salary satisfaction)
HR, purchasing, R&D and IT had the lowest sentiment towards their salary. Older age groups, particularly 46–50 yrs old, had low sentiment. Executives, managerial and administrative respondents scored the lowest on salary satisfaction.
Organizational Culture (org environment)
It seems organizational culture has the lowest overall sentiment across the entire survey. All departments, especially purchasing, customer service, and production seem to suffer from low sentiment. The same is true for age and job type where 46–50 yr olds and executives, machine ops, and managerial seem to score the lowest.
Grievance Resolution (org environment)
The sentiment for this topic is generally higher than organization culture but it is still a major contributing factor to low organizational environment sentiment. Again the same departments, purchasing, HR, customer service, and production score the lowest. The trend continues as 46–50-year-olds score the lowest again. Executives, machine ops, and service workers score the lowest as well.
We focused our attention on analyzing an employee exit survey from roughly 600 employees which was collected over a 4 year prior. The vast majority of survey responders (50%) were voluntary terminations. Departments of production, customer service, and sales made up the majority of respondents. The overall respondents’ age was slightly skewed as the largest group was 56 yrs of age and older. Finally, job types were proportionally represented.
Involuntary terminations had the lowest overall sentiment closely followed by voluntary terminations. Overall, salary satisfaction, employee value and organizational environment had the lowest sentiment. These results were confirmed for the voluntary terminated sample as well.
The analysis was then specifically focused on the voluntarily terminated sample. It seems in order to increase overall employee sentiment and potentially reduce voluntary turnover the organization needs to focus its initiatives on improving promotional opportunities, performance recognition, salary, organizational culture, and grievances resolution.
Any initiatives developed towards improving the aforementioned areas in order to potentially stem voluntary turnover would be best targeted towards the purchasing, HR, customer service, and production departments (in order to need). Furthermore, employees between the ages of 46–50, 26–30, and 36–40 would also benefit from any and all initiatives. From a job type perspective, executives, machine ops, managerial, and service workers would also benefit from these initiatives (in order of need). It is important to note the executive job type had a small sample size (24) and only a third of that were voluntary terminations. The survey, in general, had a relatively small sample size (600), therefore, it is recommended these results be validated by a larger survey sample. That said, these results do provide a small glimpse into the organizational issues which might reside inside.
|
[
{
"code": null,
"e": 290,
"s": 172,
"text": "When analyzing employee sentiment data, which in our case is an employee exit survey, we have to look at four topics."
},
{
"code": null,
"e": 505,
"s": 290,
"text": "Statistical rigor of the surveyDemographical composition of survey respondentsOverall sentiment for defined latent constructsSentiment scores by respondents’ characteristics (ie. gender, location, department, etc.)"
},
{
"code": null,
"e": 537,
"s": 505,
"text": "Statistical rigor of the survey"
},
{
"code": null,
"e": 585,
"s": 537,
"text": "Demographical composition of survey respondents"
},
{
"code": null,
"e": 633,
"s": 585,
"text": "Overall sentiment for defined latent constructs"
},
{
"code": null,
"e": 723,
"s": 633,
"text": "Sentiment scores by respondents’ characteristics (ie. gender, location, department, etc.)"
},
{
"code": null,
"e": 1297,
"s": 723,
"text": "First, keeping to this methodology will enable us to determine how well our survey is measuring what it is meant to measure. Secondly, by understanding who answered the survey from a respondent characteristics perspective (ie. gender, departments, etc) we can provide context to our analysis and results. Thirdly, this methodology will help us determine the general sentiment of the responders. Last but not least, it will help us determine not only what organization initiatives might be useful to increase sentiment but also where these initiatives should be implemented."
},
{
"code": null,
"e": 1679,
"s": 1297,
"text": "The dataset we’ll be using is a fictional employee exit survey which asks the employee a series of questions regarding their organizational demographics (ie. department) and 5-point Likert (ie. Strongly Disagree, Disagree, Neutral, Agree, Strongly Agree) sentiment questions (ie. the organization offered plenty of promotional opportunities). No open-ended questions were utilized."
},
{
"code": null,
"e": 1983,
"s": 1679,
"text": "import pandas as pdimport numpy as npimport scipy.stats as statsimport matplotlib.pyplot as pltimport seaborn as snsimport warningswarnings.filterwarnings('ignore')pd.set_option('display.max_columns', None)%matplotlib inlinewith open('exit_data_final.csv') as f: df = pd.read_csv(f)f.close()df.info()"
},
{
"code": null,
"e": 2124,
"s": 1983,
"text": "We have 33 items or questions which were asked of the employees. Before we can begin our analysis we have a bit of data cleaning to perform."
},
{
"code": null,
"e": 2168,
"s": 2124,
"text": "df.drop('Unnamed: 0', axis=1, inplace=True)"
},
{
"code": null,
"e": 2232,
"s": 2168,
"text": "Let’s drop this odd “Unnamed” column as it services no purpose."
},
{
"code": null,
"e": 2287,
"s": 2232,
"text": "for var in df.columns: print(var, df[var].unique())"
},
{
"code": null,
"e": 2357,
"s": 2287,
"text": "By examining the unique values for each item we can see a few issues."
},
{
"code": null,
"e": 2672,
"s": 2357,
"text": "Some items have missing values labeled correctly as np.nan but others are simply null.Based on df.info() we need to transform the item types for our Likert items as they are currently formatted as ‘objects’.Finally, we need to transform some of the values in order to improve the readability of our visualizations."
},
{
"code": null,
"e": 2759,
"s": 2672,
"text": "Some items have missing values labeled correctly as np.nan but others are simply null."
},
{
"code": null,
"e": 2881,
"s": 2759,
"text": "Based on df.info() we need to transform the item types for our Likert items as they are currently formatted as ‘objects’."
},
{
"code": null,
"e": 2989,
"s": 2881,
"text": "Finally, we need to transform some of the values in order to improve the readability of our visualizations."
},
{
"code": null,
"e": 4022,
"s": 2989,
"text": "# Replacing nulls with np.nanfor var in df.columns: df[var].replace(to_replace=' ', value=np.nan, inplace=True)# Converting feature typeslikert_items = df[['promotional_opportunities', 'performance_recognized', 'feedback_offered', 'coaching_offered', 'mgmt_clear_mission', 'mgmt_support_me', 'mgmt_support_team', 'mgmt_clear_comm', 'direct_mgmt_satisfaction', 'job_stimulating', 'initiative_encouraged', 'skill_variety', 'knowledge_variety', 'task_variety', 'fair_salary', 'teamwork', 'team_support', 'team_comm', 'team_culture', 'job_train_satisfaction', 'personal_train_satisfaction', 'org_culture', 'grievances_resolution', 'co-worker_interaction', 'workplace_conditions', 'job_stress', 'work/life_balance']]for col in likert_items: df[col] = pd.to_numeric(df[col], errors='coerce').astype('float64')# Discretization of tenurebins = [0,4,9,14,19,24]labels = ['0-4yrs', '5-9yrs', '10-14yrs', '15-19yrs', '20+yrs']df['tenure'] = pd.cut(df['tenure'], bins = bins, labels=labels)"
},
{
"code": null,
"e": 4274,
"s": 4022,
"text": "In my previous article, we reviewed the process of analyzing the statistical rigor (ie. validity, reliability, factor analysis) of our survey. Feel free to review the but let’s quickly review what latent survey constructs are and how they are derived."
},
{
"code": null,
"e": 5279,
"s": 4274,
"text": "In order to develop survey items or questions which maintain good statistical rigor, we have to begin with scholarly literature. We want to find a theoretical model that describes the phenomena we wish to measure. For example, personality surveys very often will use the Big-5 model (ie. openness, conscientiousness, extraversion, agreeableness, and neuroticism) to develop the survey items. The survey developer will carefully craft 2–10 (depending on the length of the survey) items for each component of the model. The items which are meant to assess the same component are said to be measuring a “latent construct”. In order words, we are not measuring “extraversion” explicitly as that would be an “observed construct” but indirectly through the individual survey items. The survey is pilot tested with multiple samples of respondents until a certain level of rigor is attained. Once again, if you’re interested in the statistical analyses used to determine rigor take a look at my previous article."
},
{
"code": null,
"e": 6923,
"s": 5279,
"text": "# Calculating latent variablesdf['employee_valued'] = np.nanmean(df[['promotional_opportunities', 'performance_recognized', 'feedback_offered', 'coaching_offered']], axis=1)df['mgmt_sati'] = np.nanmean(df[['mgmt_clear_mission', 'mgmt_support_me', 'mgmt_support_team', 'mgmt_clear_comm', 'direct_mgmt_satisfaction']], axis=1)df['job_satisfaction'] = np.nanmean(df[['job_stimulating','initiative_encouraged','skill_variety','knowledge_variety', 'task_variety']], axis=1)df['team_satisfaction'] = np.nanmean(df[['teamwork','team_support', 'team_comm','team_culture']], axis=1)df['training_satisfaction'] = np.nanmean(df[['job_train_satisfaction','personal_train_satisfaction']], axis=1)df['org_environment'] = np.nanmean(df[['org_culture','grievances_resolution','co-worker_interaction','workplace_conditions']], axis=1)df['work_life_balance'] = np.nanmean(df[['job_stress','work/life_balance']], axis=1)df['overall_sati'] = np.nanmean(df[['promotional_opportunities', 'performance_recognized','feedback_offered', 'coaching_offered', 'mgmt_clear_mission','mgmt_support_me', 'mgmt_support_team', 'mgmt_clear_comm','direct_mgmt_satisfaction', 'job_stimulating', 'initiative_encouraged','skill_variety', 'knowledge_variety', 'task_variety', 'fair_salary','teamwork', 'team_support', 'team_comm', 'team_culture', 'job_train_satisfaction', 'personal_train_satisfaction', 'org_culture', 'grievances_resolution', 'co-worker_interaction', 'workplace_conditions', 'job_stress', 'work/life_balance']], axis=1)"
},
{
"code": null,
"e": 7232,
"s": 6923,
"text": "Our exit survey has also been developed to assess certain latent constructs. Each survey item is averaged in accordance with the latent factor is it meant to measure. Finally, we have calculated an “overall_sati” feature which calculates the grand average across all items/latent factors for each respondent."
},
{
"code": null,
"e": 7534,
"s": 7232,
"text": "Below is a list of the survey items and the latent construct they are meant to measure. Keep in mind each label for each item has been shortened significantly in order to help facilitate visualizations. You can imagine the items asking questions such as “On a scale of 1–5, I find my job stimulating”."
},
{
"code": null,
"e": 8327,
"s": 7534,
"text": "mappings = {1:'1) Dissatisfied', 2:'1) Dissatisfied', 3:'2) Neutral', 4:'3) Satisfied', 5:'3) Satisfied'}likert = ['promotional_opportunities', 'performance_recognized', 'feedback_offered', 'coaching_offered', 'mgmt_clear_mission', 'mgmt_support_me', 'mgmt_support_team', 'mgmt_clear_comm', 'direct_mgmt_satisfaction', 'job_stimulating', 'initiative_encouraged', 'skill_variety', 'knowledge_variety', 'task_variety', 'fair_salary', 'teamwork', 'team_support', 'team_comm', 'team_culture', 'job_train_satisfaction', 'personal_train_satisfaction', 'org_culture', 'grievances_resolution', 'co-worker_interaction', 'workplace_conditions', 'job_stress', 'work/life_balance']for col in likert: df[col+'_short'] = df[col].map(mappings) df.head()"
},
{
"code": null,
"e": 8575,
"s": 8327,
"text": "In order to aid with visualizations, we are going to create new features which will aggregate ratings of 1 and 2 into Dissatisfied, 3 into neutral, and 4 and 5 into Satisfied. This will enable us to create stacked bar plots with 3 unique portions."
},
{
"code": null,
"e": 9347,
"s": 8575,
"text": "Understanding the demographics of survey respondents’ helps to provide contextual information for our analysis. We also have to keep in mind that most employee exit surveys are completed on a volunteer basis. Due to this confounding variable, we need to take any insights gleaned from the data as “evidence” of organizational affairs instead of definitive “proof”. Employees might have been extremely happy or angry with the organization and their attitude will surely be represented in their answers. Finally, the survey consists of roughly 600 respondents and we need to be careful not to consider these as the total number of all termination which occurred in the last 4 years. 600 terminations might only be a small percentage of all terminations which have occurred."
},
{
"code": null,
"e": 9595,
"s": 9347,
"text": "In other words, our analysis hopes to determine the level satisfaction on several organizational factors for those employees who RESPONDED to the survey. We should not generalize our results to the broader organization or all terminated employees."
},
{
"code": null,
"e": 11899,
"s": 9595,
"text": "def uni_plots(feature, text): tmp_count = df[feature].dropna().value_counts().values tmp_percent = ((df[feature].dropna().value_counts()/len(df))*100).values df1 = pd.DataFrame({feature: df[feature].value_counts().index, 'Number of Employees': tmp_count, 'Percent of Employees': tmp_percent}) f, ax = plt.subplots(figsize=(20,10)) plt.title(text, fontsize=25, pad=30) plt.tick_params(axis='both', labelsize=15, pad=10) plt.xlabel(feature, fontsize=20) plt.xticks(size=18) plt.yticks(size=18) sns.set_color_codes('pastel') count = sns.barplot(x=feature, y='Number of Employees', color='b', data=df1, label='Number of Employees') for p in count.patches: count.annotate(format(p.get_height(), '.1f'), (p.get_x() + p.get_width() / 2., p.get_height()), ha = 'center', va = 'center', xytext = (0, 9), textcoords = 'offset points', size = 20) sns.set_color_codes('muted') percent = sns.barplot(x=feature, y='Percent of Employees', color='b', data=df1, label='Percent of Employees') for i in percent.patches: percent.annotate(format(i.get_height(), '.1f'), (i.get_x() + i.get_width() / 2., i.get_height()), ha = 'center', va = 'center', xytext = (0, 9), size = 20, textcoords = 'offset points') ax.set_ylabel('') ax.legend(ncol=2, loc=\"upper right\", fontsize=15, frameon=True) sns.despine(left=False, bottom=False) ax.set_xticklabels(ax.get_xticklabels(), rotation=45) plt.show()def bi_cat_plot(feature1, feature2): ax = pd.crosstab(df[feature1], df[feature2], normalize='index')*100 ax1 = ax.plot(kind='barh', stacked=True, figsize=(25,15), fontsize=25) for i in ax1.patches: width, height = i.get_width(), i.get_height() x, y = i.get_xy() ax1.text(x+width/2, y+height/2, '{:.0f} %'.format(width), horizontalalignment='center', verticalalignment='center', size=25) plt.title('Percentage of Termination Reasons by {}'.format(feature1), fontsize=30, pad=25) plt.ylabel(' ') plt.legend(prop={'size':20})"
},
{
"code": null,
"e": 12175,
"s": 11899,
"text": "The production, customer service, and sales departments make up over 65% of the survey respondents across 4 years (2017–2020) of data collection. We have a large discrepancy in survey respondents across all four years. 2018 saw 342 terminations whereas 2020 has only seen 37."
},
{
"code": null,
"e": 12728,
"s": 12175,
"text": "A major insight stems from the fact that almost 50% of the respondents were voluntary terminations. Once again it is difficult to generalize our results to the broader organization without conclusive HRIS data but this size of discrepancy in termination reasons points us to the possibility that the company may have a problem with voluntary terminations. We don’t have any employee performance data to determine constructive or regrettable voluntary turnover as this would allow us to specifically focus our analysis on regrettable voluntary turnover."
},
{
"code": null,
"e": 13045,
"s": 12728,
"text": "The largest age group of respondents is 56 and older which makes up almost 20% of the respondents. Slicing age by reason for termination we can see that this age group makes up 87% of retirements which would make sense. If we look at voluntary turnover and age, we can see an even distribution across all age groups."
},
{
"code": null,
"e": 13382,
"s": 13045,
"text": "Variables with a low number of categories such as gender typically don’t provide us with many insights unless we see major skewness to the data. It seems females responded to the survey at almost 2:1 ratio compared to males. Looking at gender by reason for termination we see percentages that mirror the ratio we see for gender overall."
},
{
"code": null,
"e": 13893,
"s": 13382,
"text": "We have a fairly even distribution of respondents based on job type. We do see managerial and executive job types to make up a significantly smaller portion but these positions make up smaller portions of the organization in general. What is more interesting that we see a spike in involuntary terminations (38%) for executives. We typically see lower sentiment for involuntary terminations compared to other reasons of termination, therefore, we can expect executives to score fairly low on overall sentiment."
},
{
"code": null,
"e": 14111,
"s": 13893,
"text": "Overall, we see voluntary terminations make up the majority of respondents who mainly come from the production, customer service and sales departments and fall towards the latter years of their careers (41 and older)."
},
{
"code": null,
"e": 14340,
"s": 14111,
"text": "The overall respondent sentiment is calculated by first taking the average of all the individual sentiment items (ie. Likert items) for each respondent. Finally, a grand average is calculated depending on how the data is sliced."
},
{
"code": null,
"e": 14976,
"s": 14340,
"text": "def overall_plot(feature): ax = round(df.groupby(feature)['overall_sati'].mean(),2).sort_values().plot(kind='barh', stacked=True, figsize=(25,15), fontsize=25) for i in ax.patches: width, height = i.get_width(), i.get_height() x, y = i.get_xy() ax.text(x+width/2, y+height/2, '{:.2f}'.format(width), horizontalalignment='center', verticalalignment='center', size=25) plt.title('Overall Employee Sentiment by {}'.format(feature), fontsize=30, pad=25) plt.ylabel(' ')"
},
{
"code": null,
"e": 15512,
"s": 14976,
"text": "Overall, HR has the lowest overall sentiment but it also makes up the smallest percentage of respondents (5.8%). This is problematic because the average can be quickly swayed by just a few respondents who rated the Likert items very low. That said, we cannot ignore this low overall average sentiment. On the other hand, production and sales make up the two largest portion of the respondents and they score 2nd and 3rd lowest. We will have to take a look into these three departments to determine which factors score particularly low."
},
{
"code": null,
"e": 16018,
"s": 15512,
"text": "The fact involuntary terminations scored the lowest on overall sentiment is not surprising. Being terminated (fired/laid off) by the organization typically produces adverse emotions which can affect how you respond to the survey. What is more interesting is that voluntary terminations, which is the number one reason in response rate, scored second-lowest on overall sentiment. Understanding the potential causes of voluntary turnover can pay enormous dividends in keeping your high performing workforce."
},
{
"code": null,
"e": 16069,
"s": 16018,
"text": "We can see that 46–50 age group scored the lowest."
},
{
"code": null,
"e": 16480,
"s": 16069,
"text": "As expected, executives scores particularly low on overall sentiment as 38% of them were terminated involuntarily but we also have to remember that 33% were terminated voluntarily. We definitely have to look into which specific factors executives score particularly low on. Finally, machine_ops scored equally low (3.39) on overall sentiment, also this population has a 52% voluntary termination response rate."
},
{
"code": null,
"e": 16573,
"s": 16480,
"text": "Finally, we don’t see any particular differences in general sentiment between tenure groups."
},
{
"code": null,
"e": 17210,
"s": 16573,
"text": "In summary, HR, production, and sales had the lowest overall sentiment with HR scoring (3.39). Since production and sales maintain the highest number of survey respondents we need to examine which specific factors these departments score the lowest on. Involuntary terminations had the lowest sentiment (3.42) which is of no surprise but voluntary turnover had the second-lowest average sentiment while being having the highest number of survey respondents. Finally, we saw executives and machine ops job types to have the lowest sentiment (3.39). Yet again additional analyses are required to ascertain the nature of this relationship."
},
{
"code": null,
"e": 18688,
"s": 17210,
"text": "emp_value_avg = round(np.mean(df['employee_valued']),2)mgmt_sati_avg = round(np.mean(df['mgmt_sati']),2)job_sati_avg = round(np.mean(df['job_satisfaction']),2)team_sati_avg = round(np.mean(df['team_satisfaction']),2)training_sati_avg = round(np.mean(df['training_satisfaction']),2)org_env_avg = round(np.mean(df['org_environment']),2)work_life_avg = round(np.mean(df['work_life_balance']),2)overall_sati = round(np.mean([emp_value_avg, mgmt_sati_avg, job_sati_avg, team_sati_avg, training_sati_avg, org_env_avg, work_life_avg]), 2)temp_dict = {'emp_value_avg': emp_value_avg, 'mgmt_sati_avg': mgmt_sati_avg, 'job_sati_avg': job_sati_avg, 'team_sati_avg': team_sati_avg, 'training_sati_avg': training_sati_avg, 'org_env_avg': org_env_avg, 'work_life_avg': work_life_avg, 'overall_sati': overall_sati}tmp_df = pd.DataFrame.from_dict(temp_dict, orient='index', columns=['average']).sort_values(by='average')plt.figure(figsize=(25,15))plt.title('Overall Latent Factor Averages', fontsize=28)plt.ylabel('Average Employee Rating', fontsize=25)ax = tmp_df['average'].plot(kind='barh', fontsize=25)for i in ax.patches: width, height = i.get_width(), i.get_height() x, y = i.get_xy() ax.text(x+width/2, y+height/2, '{:.2f}'.format(width), horizontalalignment='center', verticalalignment='center', size=25)plt.grid(False)plt.show()"
},
{
"code": null,
"e": 19099,
"s": 18688,
"text": "If we disregard any respondent demographics and look at our latent sentiment factors we see that fair_salary, emp_value, and org_env have scored the lowest. It is important to focus our analysis on these factors in order to understand why these factors are low but also where in the organization they are the lowest (ie. department, job type, etc.). Our results are confirmed for voluntary termination as well."
},
{
"code": null,
"e": 20452,
"s": 19099,
"text": "likert = ['promotional_opportunities', 'performance_recognized', 'feedback_offered', 'coaching_offered', 'mgmt_clear_mission', 'mgmt_support_me', 'mgmt_support_team', 'mgmt_clear_comm', 'direct_mgmt_satisfaction', 'job_stimulating', 'initiative_encouraged', 'skill_variety', 'knowledge_variety', 'task_variety', 'fair_salary', 'teamwork', 'team_support', 'team_comm', 'team_culture', 'job_train_satisfaction', 'personal_train_satisfaction', 'org_culture', 'grievances_resolution', 'co-worker_interaction', 'workplace_conditions', 'job_stress', 'work/life_balance']likert_avgs = []for col in likert: likert_avgs.append(round(np.nanmean(df[col]),2))likert_avgs_df = pd.DataFrame(list(zip(likert, likert_avgs)), columns=['likert_item', 'avg_sentiment'])likert_avgs_df.set_index('likert_item', inplace=True)plt.figure()ax = likert_avgs_df.plot(kind='bar', figsize=(25,15), fontsize=20)for i in ax.patches: width, height = i.get_width(), i.get_height() x, y = i.get_xy() ax.text(x+width-0.25, y+height+.1, '{:.2f}'.format(height), horizontalalignment='center', verticalalignment='center', size=20)plt.title('Average Overall Likert Item Sentiment', fontsize=30, pad=25)plt.legend().remove()plt.xlabel(' ')"
},
{
"code": null,
"e": 20959,
"s": 20452,
"text": "By examining the individual Likert items which make up each latent factor we can see that promotional opportunities and performance_recognized contribute the most to the low sentiment of emp_value. Although we would have liked to see more than one Likert item to assess salary satisfaction we can examine fair_salary in greater detail to determine where this sentiment is particularly low. Finally, it seems org_culture and grievances_resolution contribute the most to the low sentiment of org_environment."
},
{
"code": null,
"e": 21770,
"s": 20959,
"text": "When analyzing survey data it is quite easy to end-up down a proverbial rabbit-hole of charts and plots only to lose sight of your goal. In other words, we need to narrow our focus. The ultimate goal of analyzing sentiment surveys is to identify areas of weakness where organizational initiatives can be implemented to improve those identified areas. The area we will mainly focus our efforts on are voluntary terminations. First, they make up almost 50% of the respondents. Secondly, this is the employee population where we can make the most significant impact on using organizational initiatives. Finally, we want to limit the amount of voluntary turnover in order to limit the knowledge drain from the organization and minimize the recruiting and training cost associated with hiring replacement employees."
},
{
"code": null,
"e": 22633,
"s": 21770,
"text": "# plotting average likert sentiment by respondent characteristics for voluntary terminationsdef bi_volterm_plot(feature1, feature2): tmp_df = df.loc[(df['reason_of_term']=='vol_term')] ax = round(tmp_df.groupby(feature1)[feature2].mean(),2).sort_values().plot(kind='barh', stacked=True, figsize=(25,15), fontsize=25) for i in ax.patches: width, height = i.get_width(), i.get_height() x, y = i.get_xy() ax.text(x+width/2, y+height/2, '{:.2f}'.format(width), horizontalalignment='center', verticalalignment='center', size=25) plt.title('Average {} Sentiment of Voluntary Terminations by {}'.format(feature2, feature1),fontsize=30, pad=25) plt.ylabel(' ') plt.legend(prop={'size':20})"
},
{
"code": null,
"e": 22956,
"s": 22633,
"text": "Not surprisingly voluntary termination from the HR department had the lowest score on emp_value as HR has the lowest overall sentiment. Additionally, purchasing, customer service, and production also scored relatively low. This is important as production and customer service have the largest number of survey respondents."
},
{
"code": null,
"e": 23149,
"s": 22956,
"text": "Since we know promotional opportunities and performance recognized are the main drivers behind low emp_value sentiment we are plotting these Likert items against department, age, and job type."
},
{
"code": null,
"e": 23855,
"s": 23149,
"text": "Filtering the data for only voluntary terminations, we can see that most departments score low on promotional opportunities but customer_service, HR, and purchasing score particularly low. Age scores especially low as voluntarily terminated employees between the ages of 21–50 score very low on promotional opportunities sentiment. Age group 46–50 yrs old scores very low (2.62) on this Likert item. Voluntarily terminated executives, managerial, machine ops, and service workers job types scored low on promotional opportunities sentiment with executives scoring very low (2.17). Finally, all tenure groups besides 1–14 yrs score low on promotional opportunities but 5–9 yrs scored especially low (2.80)."
},
{
"code": null,
"e": 24336,
"s": 23855,
"text": "Once again we see purchasing and HR score the lowest on performance recognized but IT and production have fairly low sentiment as well. From an employee age perspective, 26–50 have scored the lowest, plus these age groups also scored very low on promotional opportunities. Again we see executive, managerial, and machine ops job types score the lowest. Finally, much like we saw with promotional opportunities, tenure group 5–9 yrs has scored the lowest on performance recognized."
},
{
"code": null,
"e": 24980,
"s": 24336,
"text": "Fair_salary scored second-lowest on overall respondent sentiment. Now that we have filtered our data for voluntary terminations let’s take a look where salary sentiment is the lowest. Not surprisingly, HR and purchasing departments scored the lowest. However, production which has a tendency to score low as well on many Likert items actually scored relatively well. That said, we do see R&D and IT scoring low on this Likert item. 46–50 yr olds again score low as they record an average sentiment of (2.76). Executives, managerial, and administrative job types score the lowest on fair_salary. Finally, tenure group 5–9 yrs scored the lowest."
},
{
"code": null,
"e": 25244,
"s": 24980,
"text": "We know that the organizational environment factor scored third lowest in terms of overall sentiment. As we filter for voluntary terminations we see that HR and purchasing scored the lowest on this factor. Let’s break this factor into its individual Likert items."
},
{
"code": null,
"e": 25430,
"s": 25244,
"text": "We saw from our analysis above that org_culture and grievances_resolution were the two Likert items that seemed to contribute most to organizational environment’s low overall sentiment."
},
{
"code": null,
"e": 25950,
"s": 25430,
"text": "It would seem org-culture has scored low and at times very low across all departments. From an age perspective, org_culture is the lowest for 46–50 yr olds but it’s generally low for individuals between 26–50 yrs old. Executives have scored extremely low on this Likert item (1.80) followed by machine ops and managerial. That said, all job types besides sales have scored below an average score of 3.00. Finally from a tenure perspective, all tenure groups scored below 3.00 with 5–9yrs group scoring particularly low."
},
{
"code": null,
"e": 26314,
"s": 25950,
"text": "Once again purchasing, HR, customer service and production scored the lowest on grievances_resolution. Age groups, once more we see 46–50-year-old respondents make up the lowest sentiment. Executives and machine ops had the lowest sentiment for grievances resolution. Finally, again 5–9yrs tenure group scored the lowest on this Likert item much like org_culture."
},
{
"code": null,
"e": 26713,
"s": 26314,
"text": "Voluntary terminations made up the largest group of survey respondents at almost 50%. This is wonderful news as it allows us enough data to make insights into the organizational sentiment of a, particularly important population. Understanding the potential reason why voluntary terminations are occurring can help the company reduce this turnover thereby minimizing knowledge drain and hiring cost."
},
{
"code": null,
"e": 27014,
"s": 26713,
"text": "Production (32%), customer service (19%), and sales (16%) made up the majority of survey responses from a departmental perspective. Despite the remaining departments having a significantly lower response rate their number of responses is not low enough which would warrant their insights meaningless."
},
{
"code": null,
"e": 27297,
"s": 27014,
"text": "Respondents 56 yrs of age and older made up the largest group at (23%) and the remaining groups were relatively even besides 20 yrs and younger which only made up (2.3%). By slicing this data by reason of termination we can see that 54% of 56 yrs and older responders were retiring."
},
{
"code": null,
"e": 27363,
"s": 27297,
"text": "Females answered the survey at almost 2:1 rate compared to males."
},
{
"code": null,
"e": 27973,
"s": 27363,
"text": "Job types were fairly evenly represented in the survey with Service workers (19%), professional (17%), and sales (14%) taking the top three. Executives answered the survey at the lowest rates (3%) or 24 responses. 24 is a relatively low number of responses which can produce skewed results. Furthermore, the executive job type had the largest percentage (38%) of involuntary terminations and we know that involuntary terminations have a tendency to produce more negative overall sentiment. Any insights regarding the executive population will have to be scrutinized and validated with much larger sample size."
},
{
"code": null,
"e": 28077,
"s": 27973,
"text": "Finally, organization tenure yield an even representation of responses at average 20% per tenure group."
},
{
"code": null,
"e": 28425,
"s": 28077,
"text": "As expected involuntary terminations had the lowest average sentiment but closely followed by voluntary terminations. It would seem HR, production, and sales departments had the overall lowest sentiment. Furthermore, responders between the ages of 46–50 along with executive, machine ops, and managerial job types had the lowest overall sentiment."
},
{
"code": null,
"e": 28969,
"s": 28425,
"text": "The three latent factors with the lowest overall sentiment were salary satisfaction (3.14), employee valued (3.31), and organizational environment (3.46). If we examine the individual Likert items/questions for these three latent factors we can see that promotional opportunities and performance recognition were had the lowest sentiment for employee valued. Fair salary had the lowest sentiment for salary satisfaction. Finally, organizational culture and grievances resolution had the lowest overall sentiment for organizational environment."
},
{
"code": null,
"e": 29479,
"s": 28969,
"text": "When specifically looking at the voluntarily terminated population we see similar results as above. Salary satisfaction, employee value, and organizational environment had the lowest overall sentiment. Again promotional opportunities and performance recognition were the driving factors for low employee value sentiment. Fair salary was the main driver of low salary satisfaction. Finally, organizational culture and grievances resolution had the lowest scores on the organizational environment latent factor."
},
{
"code": null,
"e": 29522,
"s": 29479,
"text": "Promotional Opportunities (employee value)"
},
{
"code": null,
"e": 30050,
"s": 29522,
"text": "Most departments need to improve their access to promotional opportunities but purchasing, HR, customer service, and production departments are in greatest need to stem voluntary turnover. Furthermore, it seems promotional opportunities sentiment is low across most age groups especially 46–50 years olds. Executives, managerial, machine ops and service worker job types suffered most from lack of promotional opportunities. Finally, tenured employees between 5–9 yrs had the lowest sentiment towards promotional opportunities."
},
{
"code": null,
"e": 30091,
"s": 30050,
"text": "Performance Recognition (employee value)"
},
{
"code": null,
"e": 30366,
"s": 30091,
"text": "Purchasing and HR had suffered from low-performance recognition. Low sentiment for performance recognition was also shared by 46–50 yrs olds, executives, managerial, and machine ops job types. Finally, we again see 5–9 yrs of tenure seems to have low sentiment on this item."
},
{
"code": null,
"e": 30400,
"s": 30366,
"text": "Fair Salary (salary satisfaction)"
},
{
"code": null,
"e": 30635,
"s": 30400,
"text": "HR, purchasing, R&D and IT had the lowest sentiment towards their salary. Older age groups, particularly 46–50 yrs old, had low sentiment. Executives, managerial and administrative respondents scored the lowest on salary satisfaction."
},
{
"code": null,
"e": 30676,
"s": 30635,
"text": "Organizational Culture (org environment)"
},
{
"code": null,
"e": 31003,
"s": 30676,
"text": "It seems organizational culture has the lowest overall sentiment across the entire survey. All departments, especially purchasing, customer service, and production seem to suffer from low sentiment. The same is true for age and job type where 46–50 yr olds and executives, machine ops, and managerial seem to score the lowest."
},
{
"code": null,
"e": 31042,
"s": 31003,
"text": "Grievance Resolution (org environment)"
},
{
"code": null,
"e": 31435,
"s": 31042,
"text": "The sentiment for this topic is generally higher than organization culture but it is still a major contributing factor to low organizational environment sentiment. Again the same departments, purchasing, HR, customer service, and production score the lowest. The trend continues as 46–50-year-olds score the lowest again. Executives, machine ops, and service workers score the lowest as well."
},
{
"code": null,
"e": 31882,
"s": 31435,
"text": "We focused our attention on analyzing an employee exit survey from roughly 600 employees which was collected over a 4 year prior. The vast majority of survey responders (50%) were voluntary terminations. Departments of production, customer service, and sales made up the majority of respondents. The overall respondents’ age was slightly skewed as the largest group was 56 yrs of age and older. Finally, job types were proportionally represented."
},
{
"code": null,
"e": 32160,
"s": 31882,
"text": "Involuntary terminations had the lowest overall sentiment closely followed by voluntary terminations. Overall, salary satisfaction, employee value and organizational environment had the lowest sentiment. These results were confirmed for the voluntary terminated sample as well."
},
{
"code": null,
"e": 32512,
"s": 32160,
"text": "The analysis was then specifically focused on the voluntarily terminated sample. It seems in order to increase overall employee sentiment and potentially reduce voluntary turnover the organization needs to focus its initiatives on improving promotional opportunities, performance recognition, salary, organizational culture, and grievances resolution."
}
] |
How to get the id of a form containing a dropdown list with JavaScript?
|
To get the id of a form with a drop-down list, use the id property in JavaScript.
You can try to run the following code to find the id of a form containing drop-down list −
Live Demo
<!DOCTYPE html>
<html>
<body>
<form id="myForm1">
<button id="btn" type="button" value="my_button">Demo</button>
</form><br>
<form id="myForm2">
<select id="mySelect">
<option>One</option>
<option>Two</option>
<option>Three</option>
</select>
</form>
<script>
var val = document.getElementById("mySelect").form.id;
document.write("<br>Form id with dropdown: "+val);
</script>
</body>
</html>
|
[
{
"code": null,
"e": 1144,
"s": 1062,
"text": "To get the id of a form with a drop-down list, use the id property in JavaScript."
},
{
"code": null,
"e": 1235,
"s": 1144,
"text": "You can try to run the following code to find the id of a form containing drop-down list −"
},
{
"code": null,
"e": 1245,
"s": 1235,
"text": "Live Demo"
},
{
"code": null,
"e": 1760,
"s": 1245,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <form id=\"myForm1\">\n <button id=\"btn\" type=\"button\" value=\"my_button\">Demo</button>\n </form><br>\n <form id=\"myForm2\">\n <select id=\"mySelect\">\n <option>One</option>\n <option>Two</option>\n <option>Three</option>\n </select>\n </form>\n <script>\n var val = document.getElementById(\"mySelect\").form.id;\n document.write(\"<br>Form id with dropdown: \"+val);\n </script>\n </body>\n</html>"
}
] |
How to create a self-signed certificate using PowerShell?
|
To create a self-signed certificate there are various methods like OpenSSL, IIS, PowerShell, etc. Here, we will see how we can create a self-signed certificate with PowerShell.
To create a self-signed certificate with PowerShell, we need to use the New-SelfSignedCertificate command. When you create a self-signed certificate manually, you need to give few properties like DNSName, FriendlyName, Certificate start date, expiry date, Subject, a path of the certificate. Similarly, you can use those properties for this command to create it. Not all properties are mandatory.
New-SelfSignedCertificate `
-CertStoreLocation Cert:\LocalMachine\My `
-DnsName "testdomain.local" -Verbose
PSParentPath: Microsoft.PowerShell.Security\Certificate::LocalMachine\My
Thumbprint Subject ---------- ------- 17722DE732EB07465938FF4810D3CC4B3E87AA5A CN=testdomain.local
You will get output something like above. By default, the self-signed certificate creates a 1-year expiry date from creation. To create a certificate with different expiry and a start date and other properties like a friendly name, use the below command.
New-SelfSignedCertificate `
-CertStoreLocation Cert:\LocalMachine\My `
-DnsName "testdomain.local" `
-FriendlyName "testdomain" `
-NotAfter "03/12/2025" -Verbose
There are also other options like adding the Subject and other properties.
|
[
{
"code": null,
"e": 1239,
"s": 1062,
"text": "To create a self-signed certificate there are various methods like OpenSSL, IIS, PowerShell, etc. Here, we will see how we can create a self-signed certificate with PowerShell."
},
{
"code": null,
"e": 1636,
"s": 1239,
"text": "To create a self-signed certificate with PowerShell, we need to use the New-SelfSignedCertificate command. When you create a self-signed certificate manually, you need to give few properties like DNSName, FriendlyName, Certificate start date, expiry date, Subject, a path of the certificate. Similarly, you can use those properties for this command to create it. Not all properties are mandatory."
},
{
"code": null,
"e": 1750,
"s": 1636,
"text": "New-SelfSignedCertificate `\n -CertStoreLocation Cert:\\LocalMachine\\My `\n -DnsName \"testdomain.local\" -Verbose"
},
{
"code": null,
"e": 2125,
"s": 1750,
"text": "PSParentPath: Microsoft.PowerShell.Security\\Certificate::LocalMachine\\My\nThumbprint Subject ---------- ------- 17722DE732EB07465938FF4810D3CC4B3E87AA5A CN=testdomain.local "
},
{
"code": null,
"e": 2380,
"s": 2125,
"text": "You will get output something like above. By default, the self-signed certificate creates a 1-year expiry date from creation. To create a certificate with different expiry and a start date and other properties like a friendly name, use the below command."
},
{
"code": null,
"e": 2554,
"s": 2380,
"text": "New-SelfSignedCertificate `\n -CertStoreLocation Cert:\\LocalMachine\\My `\n -DnsName \"testdomain.local\" `\n -FriendlyName \"testdomain\" `\n -NotAfter \"03/12/2025\" -Verbose"
},
{
"code": null,
"e": 2629,
"s": 2554,
"text": "There are also other options like adding the Subject and other properties."
}
] |
Why non-static variable cannot be referenced from a static method in Java - GeeksforGeeks
|
14 Oct, 2020
Java is one of the most popular and widely used programming language and platform. Java is Object Oriented. However, it is not considered as a pure object-oriented as it provides support for primitive data types (like int, char, etc). In java, methods can be declared as either static or non-static. In this article, let’s discuss why non-static variable cannot be referenced from a static method. Before getting into the error, lets first understand what each of the methods means:
Static Method: A static method is a method that belongs to a class, but it does not belong to an instance of that class and this method can be called without the instance or object of that class. In the static method, the method can only access only static data members and static methods of another class or same class but cannot access non-static methods and variables.
Non-static method: Any method whose definition doesn’t contain the static keyword is a non-static method. In the non-static method, the method can access static data members and static methods as well as non-static members and method of another class or same class, also can change the values of any static data member.
What is the Issue with non-static variable referenced from static context?Let’s consider the following code where class A is created with a non-static variable and a static method. The object of this class is being created in another class and the static method is being accessed as follows:
JAVA
// Java program to demonstrate// why a non-static variable cannot// be accessed from a static context // Creating a class Aclass A { // A non-static variable int N; // Static method public static void increment() { // this throws a compile - time error. N++; }} public class Demo { // Main method public static void main(String args[]) { // Creating multiple objects // for class A A obj1 = new A(); A obj2 = new A(); A obj3 = new A(); // Assigning the different values // for the non static variable N obj1.N = 3; obj2.N = 4; obj3.N = 5; // Calling the method A.increment(); System.out.println(obj1.N); System.out.println(obj2.N); System.out.println(obj3.N); }}
IF this code could actually be run, you would expect the output to be:
4
5
6
But instead a compile-time error is thrown
Compile Errors:
prog.java:16: error: non-static variable N cannot be referenced from a static context
N++;
^
1 error
As we can see that the above program gives the error. Though in the above code, all the objects names have the same variable name N, if we try to increment N, its giving an error. This error is very common during object oriented programming. Why does this error occur?For the non-static variable, there is a need for an object instance to call the variables. We can also create multiple objects by assigning different values for that non-static variable. So, different objects may have different values for the same variable. In the above program we have created three objects obj1, obj2, obj3 for the class A and assigned the three different values 3, 4, 5 for the objects obj1, obj2, obj3 respectively. When we try to call the function increment, as every object of N have its own value there will be ambiguity for the compiler to understand for what value of N should the method increment the value.How to solve this error? In order to avoid ambiguity, the java compiler throws a compile time error. Therefore, this issue can be solved by addressing the variables with the object names. In short, we always need to create an object in order to refer to a non-static variable from a static context. Whenever a new instance is created, a new copy of all the non-static variables and methods are created. By using the reference of the new instance, these variables can be accessed. For example:
Java
// Java program to access a// non static variable from// a static blockpublic class GFG { int count = 0; // Driver code public static void main(String args[]) { // Accessing static variable // by creating an instance // of the class GFG test = new GFG(); test.count++; System.out.println(test.count); }}
1
anjuitsme
java-basics
Java-Interview
Static Keyword
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Initialize an ArrayList in Java
HashMap in Java with Examples
How to iterate any Map in Java
ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
Multidimensional Arrays in Java
Stack Class in Java
LinkedList in Java
Overriding in Java
Set in Java
|
[
{
"code": null,
"e": 24346,
"s": 24318,
"text": "\n14 Oct, 2020"
},
{
"code": null,
"e": 24831,
"s": 24346,
"text": "Java is one of the most popular and widely used programming language and platform. Java is Object Oriented. However, it is not considered as a pure object-oriented as it provides support for primitive data types (like int, char, etc). In java, methods can be declared as either static or non-static. In this article, let’s discuss why non-static variable cannot be referenced from a static method. Before getting into the error, lets first understand what each of the methods means: "
},
{
"code": null,
"e": 25203,
"s": 24831,
"text": "Static Method: A static method is a method that belongs to a class, but it does not belong to an instance of that class and this method can be called without the instance or object of that class. In the static method, the method can only access only static data members and static methods of another class or same class but cannot access non-static methods and variables."
},
{
"code": null,
"e": 25523,
"s": 25203,
"text": "Non-static method: Any method whose definition doesn’t contain the static keyword is a non-static method. In the non-static method, the method can access static data members and static methods as well as non-static members and method of another class or same class, also can change the values of any static data member."
},
{
"code": null,
"e": 25816,
"s": 25523,
"text": "What is the Issue with non-static variable referenced from static context?Let’s consider the following code where class A is created with a non-static variable and a static method. The object of this class is being created in another class and the static method is being accessed as follows: "
},
{
"code": null,
"e": 25821,
"s": 25816,
"text": "JAVA"
},
{
"code": "// Java program to demonstrate// why a non-static variable cannot// be accessed from a static context // Creating a class Aclass A { // A non-static variable int N; // Static method public static void increment() { // this throws a compile - time error. N++; }} public class Demo { // Main method public static void main(String args[]) { // Creating multiple objects // for class A A obj1 = new A(); A obj2 = new A(); A obj3 = new A(); // Assigning the different values // for the non static variable N obj1.N = 3; obj2.N = 4; obj3.N = 5; // Calling the method A.increment(); System.out.println(obj1.N); System.out.println(obj2.N); System.out.println(obj3.N); }}",
"e": 26646,
"s": 25821,
"text": null
},
{
"code": null,
"e": 26719,
"s": 26646,
"text": "IF this code could actually be run, you would expect the output to be: "
},
{
"code": null,
"e": 26726,
"s": 26719,
"text": "4\n5\n6\n"
},
{
"code": null,
"e": 26770,
"s": 26726,
"text": "But instead a compile-time error is thrown "
},
{
"code": null,
"e": 26905,
"s": 26770,
"text": "Compile Errors:\n\nprog.java:16: error: non-static variable N cannot be referenced from a static context\n N++;\n ^\n1 error\n"
},
{
"code": null,
"e": 28301,
"s": 26905,
"text": "As we can see that the above program gives the error. Though in the above code, all the objects names have the same variable name N, if we try to increment N, its giving an error. This error is very common during object oriented programming. Why does this error occur?For the non-static variable, there is a need for an object instance to call the variables. We can also create multiple objects by assigning different values for that non-static variable. So, different objects may have different values for the same variable. In the above program we have created three objects obj1, obj2, obj3 for the class A and assigned the three different values 3, 4, 5 for the objects obj1, obj2, obj3 respectively. When we try to call the function increment, as every object of N have its own value there will be ambiguity for the compiler to understand for what value of N should the method increment the value.How to solve this error? In order to avoid ambiguity, the java compiler throws a compile time error. Therefore, this issue can be solved by addressing the variables with the object names. In short, we always need to create an object in order to refer to a non-static variable from a static context. Whenever a new instance is created, a new copy of all the non-static variables and methods are created. By using the reference of the new instance, these variables can be accessed. For example: "
},
{
"code": null,
"e": 28306,
"s": 28301,
"text": "Java"
},
{
"code": "// Java program to access a// non static variable from// a static blockpublic class GFG { int count = 0; // Driver code public static void main(String args[]) { // Accessing static variable // by creating an instance // of the class GFG test = new GFG(); test.count++; System.out.println(test.count); }}",
"e": 28671,
"s": 28306,
"text": null
},
{
"code": null,
"e": 28674,
"s": 28671,
"text": "1\n"
},
{
"code": null,
"e": 28684,
"s": 28674,
"text": "anjuitsme"
},
{
"code": null,
"e": 28696,
"s": 28684,
"text": "java-basics"
},
{
"code": null,
"e": 28711,
"s": 28696,
"text": "Java-Interview"
},
{
"code": null,
"e": 28726,
"s": 28711,
"text": "Static Keyword"
},
{
"code": null,
"e": 28731,
"s": 28726,
"text": "Java"
},
{
"code": null,
"e": 28736,
"s": 28731,
"text": "Java"
},
{
"code": null,
"e": 28834,
"s": 28736,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28843,
"s": 28834,
"text": "Comments"
},
{
"code": null,
"e": 28856,
"s": 28843,
"text": "Old Comments"
},
{
"code": null,
"e": 28888,
"s": 28856,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 28918,
"s": 28888,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 28949,
"s": 28918,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 28967,
"s": 28949,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 29018,
"s": 28967,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 29050,
"s": 29018,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 29070,
"s": 29050,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 29089,
"s": 29070,
"text": "LinkedList in Java"
},
{
"code": null,
"e": 29108,
"s": 29089,
"text": "Overriding in Java"
}
] |
Python | Inverse Fast Walsh Hadamard Transformation - GeeksforGeeks
|
31 Jan, 2022
It is an Hadamard ordered efficient algorithm to compute the inverse Walsh Hadamard transform (WHT). Normal WHT computation has N = 2m complexity but using IFWHT reduces the computation to O(n2). The FWHT requires O(n logn) additions and subtraction operations. It is a divide and conquer algorithm which breaks down the WHT recursively.
It can perform Inverse Walsh Hadamard Transform (WHT). This method is based on Hadamard sequence ordering. Automatically the sequence is padded with zero to the right because the radix-2 FWHT requires the sample point number as a power of 2.
Syntax:
sympy.discrete.transforms.ifwht()
Parameters :
-> seq : [iterable] sequence on which IWHT is to be applied.
Returns :
Coefficient of Inverse Fast Walsh Hadamard Transform Transform
Example #1 :
Python3
# import sympyfrom sympy import ifwht # sequenceseq = [15, 21, 13, 44] # ifwhttransform = ifwht(seq)print ("Transform : ", transform)
Output :
Transform : [93/4, -37/4, -21/4, 25/4]
Example #2 :
Python3
# import sympyfrom sympy import ifwht # sequenceseq = [23, 56, 12, 555] # ifwhttransform = ifwht(seq)print ("Transform : ", transform)
Output :
Transform : [323/2, -144, -122, 255/2]
varshagumber28
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
|
[
{
"code": null,
"e": 24105,
"s": 24077,
"text": "\n31 Jan, 2022"
},
{
"code": null,
"e": 24444,
"s": 24105,
"text": "It is an Hadamard ordered efficient algorithm to compute the inverse Walsh Hadamard transform (WHT). Normal WHT computation has N = 2m complexity but using IFWHT reduces the computation to O(n2). The FWHT requires O(n logn) additions and subtraction operations. It is a divide and conquer algorithm which breaks down the WHT recursively. "
},
{
"code": null,
"e": 24688,
"s": 24444,
"text": "It can perform Inverse Walsh Hadamard Transform (WHT). This method is based on Hadamard sequence ordering. Automatically the sequence is padded with zero to the right because the radix-2 FWHT requires the sample point number as a power of 2. "
},
{
"code": null,
"e": 24882,
"s": 24688,
"text": "Syntax: \nsympy.discrete.transforms.ifwht()\n\nParameters : \n-> seq : [iterable] sequence on which IWHT is to be applied.\n\nReturns : \nCoefficient of Inverse Fast Walsh Hadamard Transform Transform"
},
{
"code": null,
"e": 24897,
"s": 24882,
"text": "Example #1 : "
},
{
"code": null,
"e": 24905,
"s": 24897,
"text": "Python3"
},
{
"code": "# import sympyfrom sympy import ifwht # sequenceseq = [15, 21, 13, 44] # ifwhttransform = ifwht(seq)print (\"Transform : \", transform)",
"e": 25040,
"s": 24905,
"text": null
},
{
"code": null,
"e": 25051,
"s": 25040,
"text": "Output : "
},
{
"code": null,
"e": 25092,
"s": 25051,
"text": "Transform : [93/4, -37/4, -21/4, 25/4]"
},
{
"code": null,
"e": 25107,
"s": 25092,
"text": "Example #2 : "
},
{
"code": null,
"e": 25115,
"s": 25107,
"text": "Python3"
},
{
"code": "# import sympyfrom sympy import ifwht # sequenceseq = [23, 56, 12, 555] # ifwhttransform = ifwht(seq)print (\"Transform : \", transform)",
"e": 25269,
"s": 25115,
"text": null
},
{
"code": null,
"e": 25280,
"s": 25269,
"text": "Output : "
},
{
"code": null,
"e": 25321,
"s": 25280,
"text": "Transform : [323/2, -144, -122, 255/2]"
},
{
"code": null,
"e": 25338,
"s": 25323,
"text": "varshagumber28"
},
{
"code": null,
"e": 25345,
"s": 25338,
"text": "Python"
},
{
"code": null,
"e": 25443,
"s": 25345,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25452,
"s": 25443,
"text": "Comments"
},
{
"code": null,
"e": 25465,
"s": 25452,
"text": "Old Comments"
},
{
"code": null,
"e": 25483,
"s": 25465,
"text": "Python Dictionary"
},
{
"code": null,
"e": 25518,
"s": 25483,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 25540,
"s": 25518,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 25572,
"s": 25540,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25614,
"s": 25572,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 25640,
"s": 25614,
"text": "Python String | replace()"
},
{
"code": null,
"e": 25684,
"s": 25640,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 25709,
"s": 25684,
"text": "sum() function in Python"
},
{
"code": null,
"e": 25746,
"s": 25709,
"text": "Create a Pandas DataFrame from Lists"
}
] |
Reset MySQL field to default value?
|
In MySQL, there are two approaches by which you can reset the MySQL field to default value. One is default keyword and another is default() function.
Case 1: Using default keyword. The syntax is as follows:
UPDATE yourTableName SET yourColumnName=default where yourCondition;
Case 2: Using default() function. The syntax is as follows:
UPDATE yourTableName SET yourColumnName=default(yourColumnName) where yourCondition;
To understand the above syntax, let us create a table. The query to create a table is as follows:
mysql> create table Default_Demo
-> (
-> Id int NOT NULL AUTO_INCREMENT,
-> Name varchar(20),
-> Age int,
-> Salary float,
-> PRIMARY KEY(Id)
-> );
Query OK, 0 rows affected (0.73 sec)
Insert some records in the table using insert command. The query is as follows:
mysql> insert into Default_Demo(Name,Age,Salary) values('John',23,405.56);
Query OK, 1 row affected (0.18 sec)
mysql> insert into Default_Demo(Name,Age,Salary) values('Carol',25,1000.98);
Query OK, 1 row affected (0.22 sec)
mysql> insert into Default_Demo(Name,Age,Salary) values('Larry',21,987.24);
Query OK, 1 row affected (0.09 sec)
mysql> insert into Default_Demo(Name,Age,Salary) values('Sam',24,986.10);
Query OK, 1 row affected (0.17 sec)
mysql> insert into Default_Demo(Name,Age,Salary) values('Mike',22,10000.50);
Query OK, 1 row affected (0.17 sec)
mysql> insert into Default_Demo(Name,Age,Salary) values('David',26,100.45);
Query OK, 1 row affected (0.20 sec)
Display all records from the table using select statement. The query is as follows:
mysql> select *from Default_Demo;
The following is the output:
+----+-------+------+---------+
| Id | Name | Age | Salary |
+----+-------+------+---------+
| 1 | John | 23 | 405.56 |
| 2 | Carol | 25 | 1000.98 |
| 3 | Larry | 21 | 987.24 |
| 4 | Sam | 24 | 986.1 |
| 5 | Mike | 22 | 10000.5 |
| 6 | David | 26 | 100.45 |
+----+-------+------+---------+
6 rows in set (0.00 sec)
Here is the query to reset the MySQL field to default values.
Case 1: Using default keyword. The query is as follows:
mysql> update Default_Demo set Age=Default where Id=6;
Query OK, 1 row affected (0.10 sec)
Rows matched: 1 Changed: 1 Warnings: 0
Now you can check the table record, the column Age is NULL where Id is 6. The query is as follows:
mysql> select *from Default_Demo;
The following is the output:
+----+-------+------+---------+
| Id | Name | Age | Salary |
+----+-------+------+---------+
| 1 | John | 23 | 405.56 |
| 2 | Carol | 25 | 1000.98 |
| 3 | Larry | 21 | 987.24 |
| 4 | Sam | 24 | 986.1 |
| 5 | Mike | 22 | 10000.5 |
| 6 | David | NULL | 100.45 |
+----+-------+------+---------+
6 rows in set (0.00 sec)
Look at the Id 6 in which Age column has been updated with default value NULL.
Case 2: Now you can also use default() function. Here, update the Salary column with default value where Id is 6. The query is as follows:
mysql> update Default_Demo set Salary=Default(Salary) where Id=6;
Query OK, 1 row affected (0.21 sec)
Rows matched: 1 Changed: 1 Warnings: 0
Now check the table record where Id is 6.
mysql> select *from Default_Demo where Id=6;
The following is the output:
+----+-------+------+--------+
| Id | Name | Age | Salary |
+----+-------+------+--------+
| 6 | David | NULL | NULL |
+----+-------+------+--------+
1 row in set (0.00 sec)
Look at the salary column the default value NULL is updated successfully.
|
[
{
"code": null,
"e": 1212,
"s": 1062,
"text": "In MySQL, there are two approaches by which you can reset the MySQL field to default value. One is default keyword and another is default() function."
},
{
"code": null,
"e": 1269,
"s": 1212,
"text": "Case 1: Using default keyword. The syntax is as follows:"
},
{
"code": null,
"e": 1338,
"s": 1269,
"text": "UPDATE yourTableName SET yourColumnName=default where yourCondition;"
},
{
"code": null,
"e": 1398,
"s": 1338,
"text": "Case 2: Using default() function. The syntax is as follows:"
},
{
"code": null,
"e": 1483,
"s": 1398,
"text": "UPDATE yourTableName SET yourColumnName=default(yourColumnName) where yourCondition;"
},
{
"code": null,
"e": 1581,
"s": 1483,
"text": "To understand the above syntax, let us create a table. The query to create a table is as follows:"
},
{
"code": null,
"e": 1787,
"s": 1581,
"text": "mysql> create table Default_Demo\n -> (\n -> Id int NOT NULL AUTO_INCREMENT,\n -> Name varchar(20),\n -> Age int,\n -> Salary float,\n -> PRIMARY KEY(Id)\n -> );\nQuery OK, 0 rows affected (0.73 sec)"
},
{
"code": null,
"e": 1867,
"s": 1787,
"text": "Insert some records in the table using insert command. The query is as follows:"
},
{
"code": null,
"e": 2538,
"s": 1867,
"text": "mysql> insert into Default_Demo(Name,Age,Salary) values('John',23,405.56);\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into Default_Demo(Name,Age,Salary) values('Carol',25,1000.98);\nQuery OK, 1 row affected (0.22 sec)\nmysql> insert into Default_Demo(Name,Age,Salary) values('Larry',21,987.24);\nQuery OK, 1 row affected (0.09 sec)\nmysql> insert into Default_Demo(Name,Age,Salary) values('Sam',24,986.10);\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into Default_Demo(Name,Age,Salary) values('Mike',22,10000.50);\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into Default_Demo(Name,Age,Salary) values('David',26,100.45);\nQuery OK, 1 row affected (0.20 sec)"
},
{
"code": null,
"e": 2622,
"s": 2538,
"text": "Display all records from the table using select statement. The query is as follows:"
},
{
"code": null,
"e": 2656,
"s": 2622,
"text": "mysql> select *from Default_Demo;"
},
{
"code": null,
"e": 2685,
"s": 2656,
"text": "The following is the output:"
},
{
"code": null,
"e": 3030,
"s": 2685,
"text": "+----+-------+------+---------+\n| Id | Name | Age | Salary |\n+----+-------+------+---------+\n| 1 | John | 23 | 405.56 |\n| 2 | Carol | 25 | 1000.98 |\n| 3 | Larry | 21 | 987.24 |\n| 4 | Sam | 24 | 986.1 |\n| 5 | Mike | 22 | 10000.5 |\n| 6 | David | 26 | 100.45 |\n+----+-------+------+---------+\n6 rows in set (0.00 sec)"
},
{
"code": null,
"e": 3092,
"s": 3030,
"text": "Here is the query to reset the MySQL field to default values."
},
{
"code": null,
"e": 3148,
"s": 3092,
"text": "Case 1: Using default keyword. The query is as follows:"
},
{
"code": null,
"e": 3278,
"s": 3148,
"text": "mysql> update Default_Demo set Age=Default where Id=6;\nQuery OK, 1 row affected (0.10 sec)\nRows matched: 1 Changed: 1 Warnings: 0"
},
{
"code": null,
"e": 3377,
"s": 3278,
"text": "Now you can check the table record, the column Age is NULL where Id is 6. The query is as follows:"
},
{
"code": null,
"e": 3411,
"s": 3377,
"text": "mysql> select *from Default_Demo;"
},
{
"code": null,
"e": 3440,
"s": 3411,
"text": "The following is the output:"
},
{
"code": null,
"e": 3785,
"s": 3440,
"text": "+----+-------+------+---------+\n| Id | Name | Age | Salary |\n+----+-------+------+---------+\n| 1 | John | 23 | 405.56 |\n| 2 | Carol | 25 | 1000.98 |\n| 3 | Larry | 21 | 987.24 |\n| 4 | Sam | 24 | 986.1 |\n| 5 | Mike | 22 | 10000.5 |\n| 6 | David | NULL | 100.45 |\n+----+-------+------+---------+\n6 rows in set (0.00 sec)"
},
{
"code": null,
"e": 3864,
"s": 3785,
"text": "Look at the Id 6 in which Age column has been updated with default value NULL."
},
{
"code": null,
"e": 4003,
"s": 3864,
"text": "Case 2: Now you can also use default() function. Here, update the Salary column with default value where Id is 6. The query is as follows:"
},
{
"code": null,
"e": 4144,
"s": 4003,
"text": "mysql> update Default_Demo set Salary=Default(Salary) where Id=6;\nQuery OK, 1 row affected (0.21 sec)\nRows matched: 1 Changed: 1 Warnings: 0"
},
{
"code": null,
"e": 4186,
"s": 4144,
"text": "Now check the table record where Id is 6."
},
{
"code": null,
"e": 4231,
"s": 4186,
"text": "mysql> select *from Default_Demo where Id=6;"
},
{
"code": null,
"e": 4260,
"s": 4231,
"text": "The following is the output:"
},
{
"code": null,
"e": 4439,
"s": 4260,
"text": "+----+-------+------+--------+\n| Id | Name | Age | Salary |\n+----+-------+------+--------+\n| 6 | David | NULL | NULL |\n+----+-------+------+--------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 4513,
"s": 4439,
"text": "Look at the salary column the default value NULL is updated successfully."
}
] |
Check for Amicable Pair - GeeksforGeeks
|
24 Mar, 2021
Amicable numbers are two different numbers so related that the sum of the proper divisors of each is equal to the other number. (A proper divisor of a number is a positive factor of that number other than the number itself. Examples:
Input : x = 220, y = 284
Output : Yes
Proper divisors of 220 are 1, 2, 4, 5,
10, 11, 20, 22, 44, 55 and 110. Sum of
these is 284. Proper divisors of 284
are 1, 2, 4, 71 and 142 with sum 220.
Input : 1 2
Output :No
The logic is very simple. We compare sum of the proper divisors of both numbers and compare sum for one number with other number.
C++
Java
Python3
C#
PHP
Javascript
// CPP program to check if two numbers are// Amicable or not.#include <bits/stdc++.h>using namespace std; // Function to calculate sum of all // proper divisors of a given numberint divSum(int n){ // Sum of divisors int result = 0; // find all divisors which divides 'num' for (int i = 2; i <= sqrt(n); i++) { // if 'i' is divisor of 'n' if (n % i == 0) { // if both divisors are same // then add it once else add // both if (i == (n / i)) result += i; else result += (i + n/i); } } // Add 1 and n to result as above loop // considers proper divisors greater // than 1. return (result + 1);} // Returns true if x and y are Amicable// else false.bool areAmicable(int x, int y){ if (divSum(x) != y) return false; return (divSum(y) == x);} int main() { int x = 220, y = 284; if (areAmicable(x, y)) cout << "Yes"; else cout << "No"; return 0;}
// JAVA program to check if two numbers are// Amicable or not.import java.io.*; class GFG { // Function to calculate sum of all // proper divisors of a given number static int divSum(int n) { // Sum of divisors int result = 0; // find all divisors which divides 'num' for (int i = 2; i <= Math.sqrt(n); i++) { // if 'i' is divisor of 'n' if (n % i == 0) { // if both divisors are same // then add it once else add // both if (i == (n / i)) result += i; else result += (i + n / i); } } // Add 1 and n to result as above loop // considers proper divisors greater // than 1. return (result + 1); } // Returns true if x and y are Amicable // else false. static boolean areAmicable(int x, int y) { if (divSum(x) != y) return false; return (divSum(y) == x); } public static void main (String[] args) { int x = 220, y = 284; if (areAmicable(x, y)) System.out.println( "Yes"); else System.out.println("No"); }} // This code is contributed by vt_m.
# Python program to check # if two numbers are# Amicable or not.import math # def to calculate sum # of all proper divisors# of a given numberdef divSum(n) : # Sum of divisors result = 0 # find all divisors # which divides 'num' for i in range(2, int(math.sqrt(n)) + 1) : # if 'i' is # divisor of 'n' if (n % i == 0) : # if both divisors are same # then add it once else add # both if (i == int(n / i)) : result = result + i else : result = result + (i + int(n / i)) # Add 1 and n to result # as above loop considers # proper divisors greater # than 1. return (result + 1) # Returns true if x and y # are Amicable else false.def areAmicable(x, y) : if (divSum(x) != y) : return False return (divSum(y) == x) # Driver Codex = 220y = 284if (areAmicable(x, y)) : print ("Yes")else : print ("No") # This code is contributed by # Manish Shaw(manishshaw1)
// C# program to check if two numbers are// Amicable or not.using System; class GFG { // Function to calculate sum of all // proper divisors of a given number static int divSum(int n) { // Sum of divisors int result = 0; // find all divisors which divides 'num' for (int i = 2; i <= Math.Sqrt(n); i++) { // if 'i' is divisor of 'n' if (n % i == 0) { // if both divisors are same // then add it once else add // both if (i == (n / i)) result += i; else result += (i + n / i); } } // Add 1 and n to result as above loop // considers proper divisors greater // than 1. return (result + 1); } // Returns true if x and y are Amicable // else false. static bool areAmicable(int x, int y) { if (divSum(x) != y) return false; return (divSum(y) == x); } public static void Main () { int x = 220, y = 284; if (areAmicable(x, y)) Console.WriteLine( "Yes"); else Console.WriteLine("No"); }} // This code is contributed by vt_m.
<?php// PHP program to check if two// numbers are Amicable or not. // Function to calculate sum of all // proper divisors of a given numberfunction divSum( $n){ // Sum of divisors $result = 0; // find all divisors // which divides 'num' for ($i = 2; $i <= sqrt($n); $i++) { // if 'i' is divisor of 'n' if ($n % $i == 0) { // if both divisors are same // then add it once else add // both if ($i == ($n / $i)) $result += $i; else $result += ($i + $n / $i); } } // Add 1 and n to result // as above loop considers // proper divisors greater // than 1. return ($result + 1);} // Returns true if x and y // are Amicable else false.function areAmicable($x, $y){ if (divSum($x) != $y) return false; return (divSum($y) == $x);} // Driver Code $x = 220; $y = 284; if (areAmicable($x, $y)) echo "Yes"; else echo "No"; // This code is contributed by anuj_67.?>
<script> // Javascript program to check if two // numbers are Amicable or not. // Function to calculate sum of all // proper divisors of a given number function divSum(n) { // Sum of divisors let result = 0; // find all divisors // which divides 'num' for (let i = 2; i <= Math.sqrt(n); i++) { // if 'i' is divisor of 'n' if (n % i == 0) { // if both divisors are same // then add it once else add // both if (i == (n / i)) result += i; else result += (i + n / i); } } // Add 1 and n to result // as above loop considers // proper divisors greater // than 1. return (result + 1); } // Returns true if x and y // are Amicable else false. function areAmicable(x, y) { if (divSum(x) != y) return false; return (divSum(y) == x); } // Driver Code let x = 220; let y = 284; if (areAmicable(x, y)) document.write("Yes"); else document.write("No"); // This code is contributed by _saurabh_jaiswal. </script>
Output:
Yes
YouTubeGeeksforGeeks507K subscribersAmicable Numbers | 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 / 3:52•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=gYX-A6U-XDw" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
vt_m
manishshaw1
_saurabh_jaiswal
divisors
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to print prime numbers from 1 to N.
Modular multiplicative inverse
Fizz Buzz Implementation
Generate all permutation of a set in Python
Check if a number is Palindrome
Program to multiply two matrices
Segment Tree | Set 1 (Sum of given range)
Merge two sorted arrays with O(1) extra space
How to check if a given point lies inside or outside a polygon?
Count ways to reach the n'th stair
|
[
{
"code": null,
"e": 25961,
"s": 25933,
"text": "\n24 Mar, 2021"
},
{
"code": null,
"e": 26197,
"s": 25961,
"text": "Amicable numbers are two different numbers so related that the sum of the proper divisors of each is equal to the other number. (A proper divisor of a number is a positive factor of that number other than the number itself. Examples: "
},
{
"code": null,
"e": 26415,
"s": 26197,
"text": "Input : x = 220, y = 284\nOutput : Yes \nProper divisors of 220 are 1, 2, 4, 5,\n10, 11, 20, 22, 44, 55 and 110. Sum of \nthese is 284. Proper divisors of 284 \nare 1, 2, 4, 71 and 142 with sum 220.\n\nInput : 1 2\nOutput :No"
},
{
"code": null,
"e": 26548,
"s": 26417,
"text": "The logic is very simple. We compare sum of the proper divisors of both numbers and compare sum for one number with other number. "
},
{
"code": null,
"e": 26552,
"s": 26548,
"text": "C++"
},
{
"code": null,
"e": 26557,
"s": 26552,
"text": "Java"
},
{
"code": null,
"e": 26565,
"s": 26557,
"text": "Python3"
},
{
"code": null,
"e": 26568,
"s": 26565,
"text": "C#"
},
{
"code": null,
"e": 26572,
"s": 26568,
"text": "PHP"
},
{
"code": null,
"e": 26583,
"s": 26572,
"text": "Javascript"
},
{
"code": "// CPP program to check if two numbers are// Amicable or not.#include <bits/stdc++.h>using namespace std; // Function to calculate sum of all // proper divisors of a given numberint divSum(int n){ // Sum of divisors int result = 0; // find all divisors which divides 'num' for (int i = 2; i <= sqrt(n); i++) { // if 'i' is divisor of 'n' if (n % i == 0) { // if both divisors are same // then add it once else add // both if (i == (n / i)) result += i; else result += (i + n/i); } } // Add 1 and n to result as above loop // considers proper divisors greater // than 1. return (result + 1);} // Returns true if x and y are Amicable// else false.bool areAmicable(int x, int y){ if (divSum(x) != y) return false; return (divSum(y) == x);} int main() { int x = 220, y = 284; if (areAmicable(x, y)) cout << \"Yes\"; else cout << \"No\"; return 0;}",
"e": 27618,
"s": 26583,
"text": null
},
{
"code": "// JAVA program to check if two numbers are// Amicable or not.import java.io.*; class GFG { // Function to calculate sum of all // proper divisors of a given number static int divSum(int n) { // Sum of divisors int result = 0; // find all divisors which divides 'num' for (int i = 2; i <= Math.sqrt(n); i++) { // if 'i' is divisor of 'n' if (n % i == 0) { // if both divisors are same // then add it once else add // both if (i == (n / i)) result += i; else result += (i + n / i); } } // Add 1 and n to result as above loop // considers proper divisors greater // than 1. return (result + 1); } // Returns true if x and y are Amicable // else false. static boolean areAmicable(int x, int y) { if (divSum(x) != y) return false; return (divSum(y) == x); } public static void main (String[] args) { int x = 220, y = 284; if (areAmicable(x, y)) System.out.println( \"Yes\"); else System.out.println(\"No\"); }} // This code is contributed by vt_m.",
"e": 28922,
"s": 27618,
"text": null
},
{
"code": "# Python program to check # if two numbers are# Amicable or not.import math # def to calculate sum # of all proper divisors# of a given numberdef divSum(n) : # Sum of divisors result = 0 # find all divisors # which divides 'num' for i in range(2, int(math.sqrt(n)) + 1) : # if 'i' is # divisor of 'n' if (n % i == 0) : # if both divisors are same # then add it once else add # both if (i == int(n / i)) : result = result + i else : result = result + (i + int(n / i)) # Add 1 and n to result # as above loop considers # proper divisors greater # than 1. return (result + 1) # Returns true if x and y # are Amicable else false.def areAmicable(x, y) : if (divSum(x) != y) : return False return (divSum(y) == x) # Driver Codex = 220y = 284if (areAmicable(x, y)) : print (\"Yes\")else : print (\"No\") # This code is contributed by # Manish Shaw(manishshaw1)",
"e": 30011,
"s": 28922,
"text": null
},
{
"code": "// C# program to check if two numbers are// Amicable or not.using System; class GFG { // Function to calculate sum of all // proper divisors of a given number static int divSum(int n) { // Sum of divisors int result = 0; // find all divisors which divides 'num' for (int i = 2; i <= Math.Sqrt(n); i++) { // if 'i' is divisor of 'n' if (n % i == 0) { // if both divisors are same // then add it once else add // both if (i == (n / i)) result += i; else result += (i + n / i); } } // Add 1 and n to result as above loop // considers proper divisors greater // than 1. return (result + 1); } // Returns true if x and y are Amicable // else false. static bool areAmicable(int x, int y) { if (divSum(x) != y) return false; return (divSum(y) == x); } public static void Main () { int x = 220, y = 284; if (areAmicable(x, y)) Console.WriteLine( \"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed by vt_m.",
"e": 31309,
"s": 30011,
"text": null
},
{
"code": "<?php// PHP program to check if two// numbers are Amicable or not. // Function to calculate sum of all // proper divisors of a given numberfunction divSum( $n){ // Sum of divisors $result = 0; // find all divisors // which divides 'num' for ($i = 2; $i <= sqrt($n); $i++) { // if 'i' is divisor of 'n' if ($n % $i == 0) { // if both divisors are same // then add it once else add // both if ($i == ($n / $i)) $result += $i; else $result += ($i + $n / $i); } } // Add 1 and n to result // as above loop considers // proper divisors greater // than 1. return ($result + 1);} // Returns true if x and y // are Amicable else false.function areAmicable($x, $y){ if (divSum($x) != $y) return false; return (divSum($y) == $x);} // Driver Code $x = 220; $y = 284; if (areAmicable($x, $y)) echo \"Yes\"; else echo \"No\"; // This code is contributed by anuj_67.?>",
"e": 32403,
"s": 31309,
"text": null
},
{
"code": "<script> // Javascript program to check if two // numbers are Amicable or not. // Function to calculate sum of all // proper divisors of a given number function divSum(n) { // Sum of divisors let result = 0; // find all divisors // which divides 'num' for (let i = 2; i <= Math.sqrt(n); i++) { // if 'i' is divisor of 'n' if (n % i == 0) { // if both divisors are same // then add it once else add // both if (i == (n / i)) result += i; else result += (i + n / i); } } // Add 1 and n to result // as above loop considers // proper divisors greater // than 1. return (result + 1); } // Returns true if x and y // are Amicable else false. function areAmicable(x, y) { if (divSum(x) != y) return false; return (divSum(y) == x); } // Driver Code let x = 220; let y = 284; if (areAmicable(x, y)) document.write(\"Yes\"); else document.write(\"No\"); // This code is contributed by _saurabh_jaiswal. </script>",
"e": 33582,
"s": 32403,
"text": null
},
{
"code": null,
"e": 33591,
"s": 33582,
"text": "Output: "
},
{
"code": null,
"e": 33595,
"s": 33591,
"text": "Yes"
},
{
"code": null,
"e": 34412,
"s": 33597,
"text": "YouTubeGeeksforGeeks507K subscribersAmicable Numbers | 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 / 3:52•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=gYX-A6U-XDw\" 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": 34417,
"s": 34412,
"text": "vt_m"
},
{
"code": null,
"e": 34429,
"s": 34417,
"text": "manishshaw1"
},
{
"code": null,
"e": 34446,
"s": 34429,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 34455,
"s": 34446,
"text": "divisors"
},
{
"code": null,
"e": 34468,
"s": 34455,
"text": "Mathematical"
},
{
"code": null,
"e": 34481,
"s": 34468,
"text": "Mathematical"
},
{
"code": null,
"e": 34579,
"s": 34481,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34623,
"s": 34579,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 34654,
"s": 34623,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 34679,
"s": 34654,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 34723,
"s": 34679,
"text": "Generate all permutation of a set in Python"
},
{
"code": null,
"e": 34755,
"s": 34723,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 34788,
"s": 34755,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 34830,
"s": 34788,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 34876,
"s": 34830,
"text": "Merge two sorted arrays with O(1) extra space"
},
{
"code": null,
"e": 34940,
"s": 34876,
"text": "How to check if a given point lies inside or outside a polygon?"
}
] |
Data Version control & machine learning process control using DVC & GitHub | by Nisarg Dave | Towards Data Science
|
Even with all the success we’ve seen today in machine learning (ML), specifically deep learning and its applications in business, the data science community still lacks good practices for organizing their projects and effectively collaborating across their varied ML projects.
Improving the productivity of machine learning workflow is necessary. As a Data Scientist at Group K Diagnostics, I deal with the hundreds of gigabytes of data. It is indeed very tough for data scientist to manage and track the data. The data tracking is necessary thing for any data science workflow. The need for data versioning is extreme, thus Data Version control (https://dvc.org) is very crucial tool for any data scientist. This is very handy and useful tool for your data science projects. The main reasons are,
DVC tracks ML models and data sets: DVC is built to make ML models shareable and reproducible.
ML project version control: Version control machine learning models, data sets and intermediate files.
ML experiment management: Harness the full power of Git branches to try different ideas instead of sloppy file suffixes and comments in code.
Deployment & Collaboration: Instead of ad-hoc scripts, use push/pull commands to move consistent bundles of ML models, data, and code into production, remote machines, or a colleague’s computer.
Major advantage here is that, we can use it with Amazon AWS S3, Microsoft Azure and other data/resource management systems. We can configure those systems to store, read, write and snap data. The setup and usage is very simple,
Install DVC using, (assuming you have python environment ready)
Install DVC using, (assuming you have python environment ready)
pip install dvc
2. Perform the DVC initialization, (assuming you are in Github repository, if not then perform)
git initdvc init
3. Now let’s assume that our project has ‘data’ folder which has various data directory (connected & downloaded through AWS S3)
├── data │ ├── exp1│ ├── x1.png│ ├── y1.png│ ├── exp2│ ├── x2.png│ ├── y2.png│ └── exp3│ ├── x3.png│ ├── y3.png│ └── exp4│ ├── x4.png│ ├── y4.png
Now after using this data first time, we will perform the following steps.
dvc add ./data/exp1 && git add ./data/exp1.dvcdvc add ./data/exp2 && git add ./data/exp2.dvcdvc add ./data/exp3 && git add ./data/exp3.dvcdvc add ./data/exp4 && git add ./data/exp4.dvc
This will create .dvc file for each folder and that file will be committed to GitHub so we know which version of model uses which version of data.
After this we need to push the dvc changes if we are using remote data storages,
dvc push filename
This command will push the recent changes and will update the cache, Let’s do,
dvc status
This will check for any potential change in data, if any then it will track it and we can commit it.
DVC makes collaboration very easy. Collaborators can set it up in the same way or they can pull up the data with, ‘ dvc pull filename’ command.
This procedure also works for data versions containing a lot more data than currently persistent in the data folder as dvc stores differences of arbitrary size between different versions in its cache and can therefore recreate older or newer states of the data directories by its checkout command. The checkout is of course also possible in the other direction.
For more information on commands visit their documentation here.
For using DVC with Amazon AWS S3, please visit https://dvc.org/doc/user-guide/external-dependencies
The best overall highlights and features are,
It is Git-compatible! DVC runs on top of any Git repository and is compatible with any standard Git server or provider (GitHub, GitLab, etc). Data file contents can be shared by network-accessible storage or any supported cloud solution. DVC offers all the advantages of a distributed version control system — lock-free, local branching, and versioning.It’s storage agnoistic. You can work with S3, Google cloud and Azure.It comes with Metric tracking and includes a command to list all branches, along with metric values, to track the progress or pick the best version.Language- & framework-agnosticProvides end to end support for ML pipeline framework.It can track failures!It is also compatible with HDFS, Hive & Apache Spark.
It is Git-compatible! DVC runs on top of any Git repository and is compatible with any standard Git server or provider (GitHub, GitLab, etc). Data file contents can be shared by network-accessible storage or any supported cloud solution. DVC offers all the advantages of a distributed version control system — lock-free, local branching, and versioning.
It’s storage agnoistic. You can work with S3, Google cloud and Azure.
It comes with Metric tracking and includes a command to list all branches, along with metric values, to track the progress or pick the best version.
Language- & framework-agnostic
Provides end to end support for ML pipeline framework.
It can track failures!
It is also compatible with HDFS, Hive & Apache Spark.
So give it a shot and make your life easy! Click here to get started! As a Data Scientist, I highly recommend it to each and every data scientist to use it within their ML pipeline.
|
[
{
"code": null,
"e": 448,
"s": 171,
"text": "Even with all the success we’ve seen today in machine learning (ML), specifically deep learning and its applications in business, the data science community still lacks good practices for organizing their projects and effectively collaborating across their varied ML projects."
},
{
"code": null,
"e": 969,
"s": 448,
"text": "Improving the productivity of machine learning workflow is necessary. As a Data Scientist at Group K Diagnostics, I deal with the hundreds of gigabytes of data. It is indeed very tough for data scientist to manage and track the data. The data tracking is necessary thing for any data science workflow. The need for data versioning is extreme, thus Data Version control (https://dvc.org) is very crucial tool for any data scientist. This is very handy and useful tool for your data science projects. The main reasons are,"
},
{
"code": null,
"e": 1064,
"s": 969,
"text": "DVC tracks ML models and data sets: DVC is built to make ML models shareable and reproducible."
},
{
"code": null,
"e": 1167,
"s": 1064,
"text": "ML project version control: Version control machine learning models, data sets and intermediate files."
},
{
"code": null,
"e": 1309,
"s": 1167,
"text": "ML experiment management: Harness the full power of Git branches to try different ideas instead of sloppy file suffixes and comments in code."
},
{
"code": null,
"e": 1504,
"s": 1309,
"text": "Deployment & Collaboration: Instead of ad-hoc scripts, use push/pull commands to move consistent bundles of ML models, data, and code into production, remote machines, or a colleague’s computer."
},
{
"code": null,
"e": 1732,
"s": 1504,
"text": "Major advantage here is that, we can use it with Amazon AWS S3, Microsoft Azure and other data/resource management systems. We can configure those systems to store, read, write and snap data. The setup and usage is very simple,"
},
{
"code": null,
"e": 1796,
"s": 1732,
"text": "Install DVC using, (assuming you have python environment ready)"
},
{
"code": null,
"e": 1860,
"s": 1796,
"text": "Install DVC using, (assuming you have python environment ready)"
},
{
"code": null,
"e": 1876,
"s": 1860,
"text": "pip install dvc"
},
{
"code": null,
"e": 1972,
"s": 1876,
"text": "2. Perform the DVC initialization, (assuming you are in Github repository, if not then perform)"
},
{
"code": null,
"e": 1989,
"s": 1972,
"text": "git initdvc init"
},
{
"code": null,
"e": 2117,
"s": 1989,
"text": "3. Now let’s assume that our project has ‘data’ folder which has various data directory (connected & downloaded through AWS S3)"
},
{
"code": null,
"e": 2325,
"s": 2117,
"text": "├── data │ ├── exp1│ ├── x1.png│ ├── y1.png│ ├── exp2│ ├── x2.png│ ├── y2.png│ └── exp3│ ├── x3.png│ ├── y3.png│ └── exp4│ ├── x4.png│ ├── y4.png"
},
{
"code": null,
"e": 2400,
"s": 2325,
"text": "Now after using this data first time, we will perform the following steps."
},
{
"code": null,
"e": 2585,
"s": 2400,
"text": "dvc add ./data/exp1 && git add ./data/exp1.dvcdvc add ./data/exp2 && git add ./data/exp2.dvcdvc add ./data/exp3 && git add ./data/exp3.dvcdvc add ./data/exp4 && git add ./data/exp4.dvc"
},
{
"code": null,
"e": 2732,
"s": 2585,
"text": "This will create .dvc file for each folder and that file will be committed to GitHub so we know which version of model uses which version of data."
},
{
"code": null,
"e": 2813,
"s": 2732,
"text": "After this we need to push the dvc changes if we are using remote data storages,"
},
{
"code": null,
"e": 2832,
"s": 2813,
"text": "dvc push filename "
},
{
"code": null,
"e": 2911,
"s": 2832,
"text": "This command will push the recent changes and will update the cache, Let’s do,"
},
{
"code": null,
"e": 2922,
"s": 2911,
"text": "dvc status"
},
{
"code": null,
"e": 3023,
"s": 2922,
"text": "This will check for any potential change in data, if any then it will track it and we can commit it."
},
{
"code": null,
"e": 3167,
"s": 3023,
"text": "DVC makes collaboration very easy. Collaborators can set it up in the same way or they can pull up the data with, ‘ dvc pull filename’ command."
},
{
"code": null,
"e": 3529,
"s": 3167,
"text": "This procedure also works for data versions containing a lot more data than currently persistent in the data folder as dvc stores differences of arbitrary size between different versions in its cache and can therefore recreate older or newer states of the data directories by its checkout command. The checkout is of course also possible in the other direction."
},
{
"code": null,
"e": 3594,
"s": 3529,
"text": "For more information on commands visit their documentation here."
},
{
"code": null,
"e": 3694,
"s": 3594,
"text": "For using DVC with Amazon AWS S3, please visit https://dvc.org/doc/user-guide/external-dependencies"
},
{
"code": null,
"e": 3740,
"s": 3694,
"text": "The best overall highlights and features are,"
},
{
"code": null,
"e": 4470,
"s": 3740,
"text": "It is Git-compatible! DVC runs on top of any Git repository and is compatible with any standard Git server or provider (GitHub, GitLab, etc). Data file contents can be shared by network-accessible storage or any supported cloud solution. DVC offers all the advantages of a distributed version control system — lock-free, local branching, and versioning.It’s storage agnoistic. You can work with S3, Google cloud and Azure.It comes with Metric tracking and includes a command to list all branches, along with metric values, to track the progress or pick the best version.Language- & framework-agnosticProvides end to end support for ML pipeline framework.It can track failures!It is also compatible with HDFS, Hive & Apache Spark."
},
{
"code": null,
"e": 4824,
"s": 4470,
"text": "It is Git-compatible! DVC runs on top of any Git repository and is compatible with any standard Git server or provider (GitHub, GitLab, etc). Data file contents can be shared by network-accessible storage or any supported cloud solution. DVC offers all the advantages of a distributed version control system — lock-free, local branching, and versioning."
},
{
"code": null,
"e": 4894,
"s": 4824,
"text": "It’s storage agnoistic. You can work with S3, Google cloud and Azure."
},
{
"code": null,
"e": 5043,
"s": 4894,
"text": "It comes with Metric tracking and includes a command to list all branches, along with metric values, to track the progress or pick the best version."
},
{
"code": null,
"e": 5074,
"s": 5043,
"text": "Language- & framework-agnostic"
},
{
"code": null,
"e": 5129,
"s": 5074,
"text": "Provides end to end support for ML pipeline framework."
},
{
"code": null,
"e": 5152,
"s": 5129,
"text": "It can track failures!"
},
{
"code": null,
"e": 5206,
"s": 5152,
"text": "It is also compatible with HDFS, Hive & Apache Spark."
}
] |
Are true and false keywords in java?
|
Keywords − Keywords in Java convey a special meaning to the compiler therefore, these cannot be used as identifiers. Java provides a set of 50 keywords.
Reserved words − Among the list of key words list mentioned above the key words goto and const are currently not in use. They are reserved words (for the future use).
The true false and null − True, false and null represents certain values in Java, they are used as literals. They are not considered as keywords.
Still, you cannot use them as identifiers in Java if you try to do so, a compile time error will be generated.
public class Example {
public static void main(String args[]) {
int true = 20;
int false = 30;
float null = 23.6f;
}
}
Example.java:3: error: not a statement
int true = 20;
^
Example.java:3: error: ';' expected
int true = 20;
^
Example.java:4: error: not a statement
int false = 30;
^
Example.java:4: error: ';' expected
int false = 30;
^
Example.java:5: error: not a statement
float null = 23.6f;
^
Example.java:5: error: ';' expected
float null = 23.6f;
^
6 errors
|
[
{
"code": null,
"e": 1215,
"s": 1062,
"text": "Keywords − Keywords in Java convey a special meaning to the compiler therefore, these cannot be used as identifiers. Java provides a set of 50 keywords."
},
{
"code": null,
"e": 1382,
"s": 1215,
"text": "Reserved words − Among the list of key words list mentioned above the key words goto and const are currently not in use. They are reserved words (for the future use)."
},
{
"code": null,
"e": 1528,
"s": 1382,
"text": "The true false and null − True, false and null represents certain values in Java, they are used as literals. They are not considered as keywords."
},
{
"code": null,
"e": 1639,
"s": 1528,
"text": "Still, you cannot use them as identifiers in Java if you try to do so, a compile time error will be generated."
},
{
"code": null,
"e": 1782,
"s": 1639,
"text": "public class Example {\n public static void main(String args[]) {\n int true = 20;\n int false = 30;\n float null = 23.6f;\n }\n}"
},
{
"code": null,
"e": 2180,
"s": 1782,
"text": "Example.java:3: error: not a statement\n int true = 20;\n ^\nExample.java:3: error: ';' expected\n int true = 20;\n ^\nExample.java:4: error: not a statement\n int false = 30;\n ^\nExample.java:4: error: ';' expected\n int false = 30;\n ^\nExample.java:5: error: not a statement\n float null = 23.6f;\n ^\nExample.java:5: error: ';' expected\n float null = 23.6f;\n ^\n6 errors"
}
] |
Differences between a Matrix and a Tensor - GeeksforGeeks
|
14 Jun, 2021
In this article, we will learn about Matrix and Tensor.
Matrix : It is a tabular format in which numbers can be represented, like below –
Here, a11 means 1st row and 1st column. Rows are horizontal lines and columns are vertical lines. Here, the matrix is 4 x 4. These are shown as n x m, where n is the number of rows and m is the number of columns. Also called the 2-D arrays i.e. 2 Dimensional Arrays.
Basic mathematical operations can be done on matrices like Addition, Subtraction, Multiplication, but with some conditions. For + and -, the size of two matrices must be the same and for multiplication, it follows the below rule –
(n X m) X (m X p) = n X p
We can also multiply the entire matrix with a constant.Example –
A =
B =
A * B =
A matrix is like a simple BOX. A matrix can be rectangular(nXm) or square(nXn).
Tensor : Tensor is like a function, i.e. is linear in nature. It describes an object that is in space. Tensors are of different types –
0 Rank tensors – Scalars1st Rank tensors – 1-D arrays 2nd Rank tensors – 2-D arrays (A matrix)nth Rank tensors – n-D arrays
0 Rank tensors – Scalars
1st Rank tensors – 1-D arrays
2nd Rank tensors – 2-D arrays (A matrix)
nth Rank tensors – n-D arrays
So tensor is an n-dimensional array satisfying a particular transformation law. Unlike a matrix, it shows an object placed in a specific coordinate system. When the coordinate systems change, the entries of a tensor also transform in that way, such that the tensor still describes the same map in the new coordinate system.
Most machine learning algorithms use tensor to perform any calculation. In a defined system, a matrix is just a container for entries and it doesn’t change if any change occurs in the system, whereas a tensor is an entity in the system that interacts with other entities in a system and changes its values when other values change.
To understand this point, let’s see an example –Assume there is a system having all matrices of 2×2 i.e. the coordinate system contains only 2 directions. Suddenly, a new direction came and we had to shift our matrices to 3×3. With matrices, this is not possible. Instead, if we use tensors, then by changing only 1 tensor, all other tensors will be changed to 3×3. This dynamism is not allowed in matrices.
The major difference is that a matrix has only 2 indices (can also be represented as M[n][m]) whereas tensors can have any indices( T[i1][i2][i3]....) even tensor can be a single number without any index.
To sum this in a single line we can say that, All matrices are not tensors, although all Rank 2 tensors are matrices.Still confused let’s see an easy example of Rank 1 tensor.Say this is our tensor in the standard Euclidean basis –
Now, let’s shift to the basis of 2 using the following transformation rule –
To do that, we will multiply it by the inverse of a scaling matrix –
Now, after scaling, our tensor becomes –
And yet it gives the same results. This operation is not possible with matrices. Moreover, in a matrix, each entity is a number. Example –
But in a tensor, each entity can be another tensor also. Example –
Similarly, we can have other degree tensors also. The RGB Image can be represented by tensors having 3 layers of a 2D matrix. A tensor can contain a matrix, but a matrix can’t contain a tensor.Another definition of the tensor could be that it is a multi-way extension of a matrix. Let’s see the product of a tensor –
T1 =
T2 =
T1 * T2 =
This is how tensors are multiplied.
Picked
Difference Between
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference between Internal and External fragmentation
Difference between Prim's and Kruskal's algorithm for MST
Differences and Applications of List, Tuple, Set and Dictionary in Python
Difference between Top down parsing and Bottom up parsing
Difference between Synchronous and Asynchronous Transmission
Difference Between Spark DataFrame and Pandas DataFrame
Difference Between Web server and Application server
Difference between Compile-time and Run-time Polymorphism in Java
|
[
{
"code": null,
"e": 24802,
"s": 24774,
"text": "\n14 Jun, 2021"
},
{
"code": null,
"e": 24859,
"s": 24802,
"text": "In this article, we will learn about Matrix and Tensor. "
},
{
"code": null,
"e": 24942,
"s": 24859,
"text": "Matrix : It is a tabular format in which numbers can be represented, like below – "
},
{
"code": null,
"e": 25210,
"s": 24942,
"text": "Here, a11 means 1st row and 1st column. Rows are horizontal lines and columns are vertical lines. Here, the matrix is 4 x 4. These are shown as n x m, where n is the number of rows and m is the number of columns. Also called the 2-D arrays i.e. 2 Dimensional Arrays. "
},
{
"code": null,
"e": 25442,
"s": 25210,
"text": "Basic mathematical operations can be done on matrices like Addition, Subtraction, Multiplication, but with some conditions. For + and -, the size of two matrices must be the same and for multiplication, it follows the below rule – "
},
{
"code": null,
"e": 25468,
"s": 25442,
"text": "(n X m) X (m X p) = n X p"
},
{
"code": null,
"e": 25534,
"s": 25468,
"text": "We can also multiply the entire matrix with a constant.Example – "
},
{
"code": null,
"e": 25539,
"s": 25534,
"text": "A = "
},
{
"code": null,
"e": 25544,
"s": 25539,
"text": "B = "
},
{
"code": null,
"e": 25556,
"s": 25544,
"text": "A * B = "
},
{
"code": null,
"e": 25637,
"s": 25556,
"text": "A matrix is like a simple BOX. A matrix can be rectangular(nXm) or square(nXn). "
},
{
"code": null,
"e": 25773,
"s": 25637,
"text": "Tensor : Tensor is like a function, i.e. is linear in nature. It describes an object that is in space. Tensors are of different types –"
},
{
"code": null,
"e": 25898,
"s": 25773,
"text": "0 Rank tensors – Scalars1st Rank tensors – 1-D arrays 2nd Rank tensors – 2-D arrays (A matrix)nth Rank tensors – n-D arrays "
},
{
"code": null,
"e": 25923,
"s": 25898,
"text": "0 Rank tensors – Scalars"
},
{
"code": null,
"e": 25954,
"s": 25923,
"text": "1st Rank tensors – 1-D arrays "
},
{
"code": null,
"e": 25995,
"s": 25954,
"text": "2nd Rank tensors – 2-D arrays (A matrix)"
},
{
"code": null,
"e": 26026,
"s": 25995,
"text": "nth Rank tensors – n-D arrays "
},
{
"code": null,
"e": 26351,
"s": 26026,
"text": "So tensor is an n-dimensional array satisfying a particular transformation law. Unlike a matrix, it shows an object placed in a specific coordinate system. When the coordinate systems change, the entries of a tensor also transform in that way, such that the tensor still describes the same map in the new coordinate system. "
},
{
"code": null,
"e": 26683,
"s": 26351,
"text": "Most machine learning algorithms use tensor to perform any calculation. In a defined system, a matrix is just a container for entries and it doesn’t change if any change occurs in the system, whereas a tensor is an entity in the system that interacts with other entities in a system and changes its values when other values change."
},
{
"code": null,
"e": 27092,
"s": 26683,
"text": "To understand this point, let’s see an example –Assume there is a system having all matrices of 2×2 i.e. the coordinate system contains only 2 directions. Suddenly, a new direction came and we had to shift our matrices to 3×3. With matrices, this is not possible. Instead, if we use tensors, then by changing only 1 tensor, all other tensors will be changed to 3×3. This dynamism is not allowed in matrices. "
},
{
"code": null,
"e": 27297,
"s": 27092,
"text": "The major difference is that a matrix has only 2 indices (can also be represented as M[n][m]) whereas tensors can have any indices( T[i1][i2][i3]....) even tensor can be a single number without any index."
},
{
"code": null,
"e": 27529,
"s": 27297,
"text": "To sum this in a single line we can say that, All matrices are not tensors, although all Rank 2 tensors are matrices.Still confused let’s see an easy example of Rank 1 tensor.Say this is our tensor in the standard Euclidean basis –"
},
{
"code": null,
"e": 27606,
"s": 27529,
"text": "Now, let’s shift to the basis of 2 using the following transformation rule –"
},
{
"code": null,
"e": 27675,
"s": 27606,
"text": "To do that, we will multiply it by the inverse of a scaling matrix –"
},
{
"code": null,
"e": 27716,
"s": 27675,
"text": "Now, after scaling, our tensor becomes –"
},
{
"code": null,
"e": 27855,
"s": 27716,
"text": "And yet it gives the same results. This operation is not possible with matrices. Moreover, in a matrix, each entity is a number. Example –"
},
{
"code": null,
"e": 27923,
"s": 27855,
"text": "But in a tensor, each entity can be another tensor also. Example – "
},
{
"code": null,
"e": 28241,
"s": 27923,
"text": "Similarly, we can have other degree tensors also. The RGB Image can be represented by tensors having 3 layers of a 2D matrix. A tensor can contain a matrix, but a matrix can’t contain a tensor.Another definition of the tensor could be that it is a multi-way extension of a matrix. Let’s see the product of a tensor – "
},
{
"code": null,
"e": 28246,
"s": 28241,
"text": "T1 ="
},
{
"code": null,
"e": 28252,
"s": 28246,
"text": "T2 = "
},
{
"code": null,
"e": 28262,
"s": 28252,
"text": "T1 * T2 ="
},
{
"code": null,
"e": 28299,
"s": 28262,
"text": "This is how tensors are multiplied. "
},
{
"code": null,
"e": 28306,
"s": 28299,
"text": "Picked"
},
{
"code": null,
"e": 28325,
"s": 28306,
"text": "Difference Between"
},
{
"code": null,
"e": 28423,
"s": 28325,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28432,
"s": 28423,
"text": "Comments"
},
{
"code": null,
"e": 28445,
"s": 28432,
"text": "Old Comments"
},
{
"code": null,
"e": 28506,
"s": 28445,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28574,
"s": 28506,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 28629,
"s": 28574,
"text": "Difference between Internal and External fragmentation"
},
{
"code": null,
"e": 28687,
"s": 28629,
"text": "Difference between Prim's and Kruskal's algorithm for MST"
},
{
"code": null,
"e": 28761,
"s": 28687,
"text": "Differences and Applications of List, Tuple, Set and Dictionary in Python"
},
{
"code": null,
"e": 28819,
"s": 28761,
"text": "Difference between Top down parsing and Bottom up parsing"
},
{
"code": null,
"e": 28880,
"s": 28819,
"text": "Difference between Synchronous and Asynchronous Transmission"
},
{
"code": null,
"e": 28936,
"s": 28880,
"text": "Difference Between Spark DataFrame and Pandas DataFrame"
},
{
"code": null,
"e": 28989,
"s": 28936,
"text": "Difference Between Web server and Application server"
}
] |
Spark in Docker in Kubernetes: A Practical Approach for Scalable NLP | by Jürgen Schmidl | Towards Data Science
|
This article is part of a larger project. If you are also interested in scalable web scraping or building highly scalable dashboards, you will find corresponding links at the end of the article.
Prerequisites to the readerIntroduction2.1 Purpose of this Project2.2 Introduction to scalable NLPArchitectureSetupHow to use Spark-NLP5.1 Overview5.2 Spark-NLP in Python5.3 Build DockerDeploy to Kubernetes6.1 Set up Kubernetes Cluster6.2 Set up Redis as a Kubernetesservice6.3 Fill Redis queue with tasks6.4 Deploy a Docker Container6.5 Check results
Prerequisites to the reader
Introduction2.1 Purpose of this Project2.2 Introduction to scalable NLP
Architecture
Setup
How to use Spark-NLP5.1 Overview5.2 Spark-NLP in Python5.3 Build Docker
Deploy to Kubernetes6.1 Set up Kubernetes Cluster6.2 Set up Redis as a Kubernetesservice6.3 Fill Redis queue with tasks6.4 Deploy a Docker Container6.5 Check results
The project was developed on the Google Cloud Platform and it is recommended to do the tutorial there as well. Nevertheless you can run it on a local machine, but you need to alter the code and replace some of the used resources.
This article is aimed to readers who already have some experience with the Google Cloud Platform and Linux shell. To help new readers getting started, links to additional resources can be found within this article. If you haven’t worked with Google Cloud Plattform, you can use Google’s free trial program.
The goal of this article is to show how entities (e.g. Docker, Hadoop, etc.) can be extracted from articles (based on the structure of TowardsDatascience) in a scalable way using NLP. We will also look at how we can use other NLP methods like POS tagging.
Natural Language Processing (NLP)Natural Language Processing enables machines to understand the structure and meaning of natural language, and allows them to recognize patterns and relationships in text.
Why should it be scalable?The processing of written language can be very complex and can take a long time without scalable architecture. Of course you can upgrade any system and use faster processors, but in doing so the costs increase disproportionately to the achieved efficiency gains. It is better to choose an architecture which can distribute the computing load over several machines.
Apache SparkSpark is a great way to make data processing and machine learning scalable. It can be run locally or on a cluster and uses distributed Datasets, as well as processing pipelines. Further information about Spark can be found here:
towardsdatascience.com
Spark-NLPSpark-NLP is a library for Python and Scala, that allows to process written language with Spark. It will be presented in the following chapters. More information can be found here:
towardsdatascience.com
RedisRedis is a key value store we will use to build a task queue.
Docker and KubernetesA Docker container can be imagined as a complete system in a box. If the code runs in a container, it is independent from the host’s operating system. This limits the scalability of Spark, but can be compensated by using a Kubernetes cluster. These clusters scale very quickly and easily via the number of containers. If you want to know more, please see:
blog.containership.io
To start with, this is how our architecture will look like:
As you can see, this approach is a batch architecture. The Python script processes text stored in the Google Datastore and creates a job queue. This queue will be processed by the Kubernetes pods and the results are written into BigQuery.
To keep the tutorial as short as possible, only the more computationally intensive language processing part scales. The task queue creator is a simple Python script (which could also run in Docker).
We will work with the Cloud Console from Google. To open it you need to create a project and activate billing.
Then you should see the Cloud Shell button in the upper right corner.
After clicking, the shell should open in the lower part of the window (if you run into trouble, use Chrome Browser). To work comfortably with the shell, I recommend to start the editor:
You can download the Repository using:
git clone https://github.com/Juergen-Schmidl/TWD-01-2020.git
and the necessary model template:
$cd TWD-01-2020/5_NLP$bash get_model.sh &Your Cloud Shell may freeze, try reconnecting after a few minutes
Since we need the Project ID on many occasions, it is easier to set it as an environment variable. Please note, that if you interrupt the shell during this tutorial, you have to set it again. You can find your projects with ID using:
$gcloud projects list
Please run:
$export Project="yourprojectID"
You will need the key for a service account quite often. To learn how to create one, you can read this. I prefer the method using the IAM web interface, but there are many ways. For simplicity’s sake, it should be given the role of “editor”, but a finer adjustment is recommended in the long run. After that, carry out the following steps:
Download the key as JSON file
Rename your key to sa.json
put one copy in each directory (4_Setup, 5_NLP, 6_Scheduler)
Your directory should now look like this:
Setup Input-data:(If you have completed the first part of the project, you can skip this.)
We use Google Cloud Datastore in Datastore-Mode to provide the source data. In order to prepare the Datastore, you have to put it into Datastore-Mode. To do this, simply search for Datastore in the Cloud Platform and click on “Select Datastore Mode”. (if needed, choose a location as well)
After that change directory to 4_Setup and run:
$cd .. ; cd 4_Setup(You may have to enter this command manually)$python3 Create_Samples.py
If you see “Samples generated”, you have got 20 sample entries in your Cloud Datastore.
Setup Output-TablesTo store the processed data we create several BigQuery tables. We do this using the following bash-script:
$bash Create_BQ_Tables.sh
If all tables were created, we have successfully created all required resources.
The NLP module is located in the repository folder “5_NLP”. Please move to this directory (using the shell). The following files should be in the folder:
Explainer.py The main script. Here Spark will be started, the pipeline will be created and filled with the pipeline model. The text processing also takes place here.
Model_Template.zipAn example model that extracts entities, i.e. proper names from the texts.
sa.jsonYour Google Cloud service account. If you run into 404 or 403 errors, please check the permission granted in the IAM for this service account.
DockerfileThis file contains the setup for the environment of the script. The exact setup is explained below.
requirements.txtThis file contains required Python libraries, which are installed during the creation of the Docker image.
Explainer.yamlThis file contains information on how Kubernetes should handle the Docker image.
As mentioned above, spark-nlp is a library that allows us to process texts in Spark. To do so, we use the library with the Python script “Explainer.py”. I commented on the code extensively, so I will only cover a few parts here:
First of all, you may need to specify the name of your service account file (if you haven’t stuck to sa.json):
The script’s entry point uses Peter Hoffmann’s Redis class to query the Redis instance regularly for new entries in the task queue. We haven’t set up the instance, so the script will not work yet.
As soon as a task arrives in the task queue, the “Explain” function is called, where the processing takes place.
As you can see, the actual logic is located in the model that is stored in (self.Model). This model contains all important steps for the NLP, like Tokenizer, Lemmatizer or Enitiy-Tagging and is unpacked from a ZIP file with the function Load_Model(). To build a model yourself, please refer to this notebook:
The Python file needs a working Spark environment. In order to provide this environment, a docker container is created using the docker file. Our docker file looks like this:
A docker file allows us to create a complete system using one file. The most important commands are:
FROM: Sets the Base-Image. A base image can be a native operating system, but other programs may already have been installed on it.
ENV: Spark needs some environment variables to work. With the ENV command those are set for the Docker container.
COPY and WORKDIR: COPY copies the entire parent directory of the docker file into the container and WORKDIR sets this directory as working directory.
RUN: Calls commands that are executed in the Docker Containers shell. Usually used to install applications.
CMD: A docker file can only have one CMD, here the actual Python script is called. The -u operator is important to get logs from the container.
To build the Docker File, please chance the directory to “5_NLP” and execute the following commands:
$docker build --tag explainer_img .(You may have to enter this command manually)
This command builds the Docker image from the Dockerfile in this directory. We cannot start it yet because the Redis instance is not running, but we have successfully created the image.
To run it later on a Kubernetes Cluster, we have to push the image into the Container Registry. To do so, activate the API by using Google Cloud Platform and search for “Container Registry”. Afterwards, run the following commands:
$docker tag explainer_img gcr.io/$Project/nlp_explainer:latest$docker push gcr.io/$Project/nlp_explainer:latest
You should now be able to see your file in the Container Registry:
If this worked so far, we can now move on to the Kubernetes cluster and get this project to work.
This part is quite simple, since Google allows us to create a Kubernetes cluster by command line. You can run this command to create a very small cluster.
$bash Create_Cluster.sh
The creation may take a few minutes. If you want to create a bigger cluster, check out Kubernetes Engine on Google Cloud Plattform. If you created the cluster using the web interface of Kubernetes Engine, you initially need to connect your console to the cluster. You can get the statement by clicking on “Connect”:
First we have to make Redis available on the Kubernetes cluster and register it as a service. This is necessary because the containers run isolated from each other. If a container is registered as service, all containers can connect to it.
To do this, the Redis container must be created from a .yaml file, located in the folder “6_Scheduler”. Run:
$kubectl create -f redis-master-service.yaml
and register it as as service (from another .yaml file):
$kubectl create -f redis-master.yaml
If you take a closer look on the .yaml files, you will see that you can specify all the settings needed. The line “replicas:” is of particular importance, because its value defines the number of parallel instances and therefore the capacity for processing data (of course limited by the underlying machine).
We work on a quite small machine, so we shouldn’t create more than one replica.
If the creation was successful, you should see the following output:
$kubectl get pods
$kubectl get services
Now that we have set up the Redis instance, we can start filling it with tasks. First we need to establish a local connection with the Redis service. The following command is needed for this:
$kubectl port-forward deployment/redis-master 6379 &
Then we have to install Redis on the local machine:
$sudo pip3 install redis
Afterwards, the Python script can be called. It retrieves the data from the Cloud Datastore, preprocesses it and puts it into the Redis task queue. You can start the script with:
$python3 Scheduler.py
This script is commented in detail so I will only mention a few points :
The “Process Batch” method contains the actual logic. Here, the articles are read from the Cloud Datastore in batches and passed to the “Send_Job” method.
Since Redis does not like special characters, these are removed to ensure smooth processing.
Then the created jobs are stored in the Redis database with the .put command.
Note: Checking if we need to call a regex method is 10 times faster than the replacement. If special characters are already taken into account when filling the Datastore, the scheduler can work much faster.
You should see the following output:
Don’t forget to terminate the port forwarding afterwards:
$pkill kubectl -9
You have already created the docker container for the explainer in 5.3 and pushed it into the Cloud Container Registry with the name “gcr/[your Project]nlp_explainer:latest”. We will now deploy it on the Kubernetes Cluster.
For this purpose a .yaml file containing all relevant information for Kubernetes is used again.
Please Note, that you have to insert your own container from the registry(image:)!
To push the .yaml file, you just need to execute the following command in the “5_NLP” folder:
$kubectl create -f Explainer.yaml
If you use the small cluster, I recommend to just deploy one replica!Otherwise you will run into problems caused by lack of performance.
After that you can see the pods using:
$kubectl get pods
After the creation of the container, you should get this result with the following command (can take up to 2 minutes):
$kubectl logs [pod-name]for example:$kubectl logs explainer-544d123125-7nzbg
You can also see errors in the log, if something went wrong.
If everything has been processed, the pod stays idle or will be evicted and recreated by Kubernetes (because it uses a loop and does not finish).
To delete all pods without recreation use:
$kubectl delete deployments [deployment]for example:$kubectl delete deployments explainer
If you don’t want to use the Kubernetes Cluster anymore you should delete it either via the web interface or by using the following command, otherwise Google will continue billing you.
$gcloud config set project $Project$gcloud container clusters delete [your-clustername] --zone [Zone]for example:$gcloud config set project $Project$gcloud container clusters delete "your-first-cluster-1" --zone "us-central1-a"
To check the result, please go to the Google Cloud Platform and search for “BigQuery”.
You should be able to see the following tables in the left bottom:
The tables “Article_masterdata” and “Article_tags” have been created by the Scheduler to serve the needs of the consecutive project. But we want to see the content of the “Entitiy_raw” table.
To access them click on it and move to “Preview”:
You should see the results of the entity recognition with the respective article ID.
And that’s it, you are done!
If you are interested in seeing how to create a highly scalable dashboard based on this data, we would be happy if you read the following tutorial: Build a highly scalable dashboard that runs on Kubernetes by Arnold Lutsch
You could also replace the sample data with real articles using this tutorial: Build a scalable webcrawler for towards data science with Selenium and python by Philipp Postels
Some rights reserved
|
[
{
"code": null,
"e": 367,
"s": 172,
"text": "This article is part of a larger project. If you are also interested in scalable web scraping or building highly scalable dashboards, you will find corresponding links at the end of the article."
},
{
"code": null,
"e": 719,
"s": 367,
"text": "Prerequisites to the readerIntroduction2.1 Purpose of this Project2.2 Introduction to scalable NLPArchitectureSetupHow to use Spark-NLP5.1 Overview5.2 Spark-NLP in Python5.3 Build DockerDeploy to Kubernetes6.1 Set up Kubernetes Cluster6.2 Set up Redis as a Kubernetesservice6.3 Fill Redis queue with tasks6.4 Deploy a Docker Container6.5 Check results"
},
{
"code": null,
"e": 747,
"s": 719,
"text": "Prerequisites to the reader"
},
{
"code": null,
"e": 819,
"s": 747,
"text": "Introduction2.1 Purpose of this Project2.2 Introduction to scalable NLP"
},
{
"code": null,
"e": 832,
"s": 819,
"text": "Architecture"
},
{
"code": null,
"e": 838,
"s": 832,
"text": "Setup"
},
{
"code": null,
"e": 910,
"s": 838,
"text": "How to use Spark-NLP5.1 Overview5.2 Spark-NLP in Python5.3 Build Docker"
},
{
"code": null,
"e": 1076,
"s": 910,
"text": "Deploy to Kubernetes6.1 Set up Kubernetes Cluster6.2 Set up Redis as a Kubernetesservice6.3 Fill Redis queue with tasks6.4 Deploy a Docker Container6.5 Check results"
},
{
"code": null,
"e": 1306,
"s": 1076,
"text": "The project was developed on the Google Cloud Platform and it is recommended to do the tutorial there as well. Nevertheless you can run it on a local machine, but you need to alter the code and replace some of the used resources."
},
{
"code": null,
"e": 1613,
"s": 1306,
"text": "This article is aimed to readers who already have some experience with the Google Cloud Platform and Linux shell. To help new readers getting started, links to additional resources can be found within this article. If you haven’t worked with Google Cloud Plattform, you can use Google’s free trial program."
},
{
"code": null,
"e": 1869,
"s": 1613,
"text": "The goal of this article is to show how entities (e.g. Docker, Hadoop, etc.) can be extracted from articles (based on the structure of TowardsDatascience) in a scalable way using NLP. We will also look at how we can use other NLP methods like POS tagging."
},
{
"code": null,
"e": 2073,
"s": 1869,
"text": "Natural Language Processing (NLP)Natural Language Processing enables machines to understand the structure and meaning of natural language, and allows them to recognize patterns and relationships in text."
},
{
"code": null,
"e": 2464,
"s": 2073,
"text": "Why should it be scalable?The processing of written language can be very complex and can take a long time without scalable architecture. Of course you can upgrade any system and use faster processors, but in doing so the costs increase disproportionately to the achieved efficiency gains. It is better to choose an architecture which can distribute the computing load over several machines."
},
{
"code": null,
"e": 2705,
"s": 2464,
"text": "Apache SparkSpark is a great way to make data processing and machine learning scalable. It can be run locally or on a cluster and uses distributed Datasets, as well as processing pipelines. Further information about Spark can be found here:"
},
{
"code": null,
"e": 2728,
"s": 2705,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 2918,
"s": 2728,
"text": "Spark-NLPSpark-NLP is a library for Python and Scala, that allows to process written language with Spark. It will be presented in the following chapters. More information can be found here:"
},
{
"code": null,
"e": 2941,
"s": 2918,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 3008,
"s": 2941,
"text": "RedisRedis is a key value store we will use to build a task queue."
},
{
"code": null,
"e": 3385,
"s": 3008,
"text": "Docker and KubernetesA Docker container can be imagined as a complete system in a box. If the code runs in a container, it is independent from the host’s operating system. This limits the scalability of Spark, but can be compensated by using a Kubernetes cluster. These clusters scale very quickly and easily via the number of containers. If you want to know more, please see:"
},
{
"code": null,
"e": 3407,
"s": 3385,
"text": "blog.containership.io"
},
{
"code": null,
"e": 3467,
"s": 3407,
"text": "To start with, this is how our architecture will look like:"
},
{
"code": null,
"e": 3706,
"s": 3467,
"text": "As you can see, this approach is a batch architecture. The Python script processes text stored in the Google Datastore and creates a job queue. This queue will be processed by the Kubernetes pods and the results are written into BigQuery."
},
{
"code": null,
"e": 3905,
"s": 3706,
"text": "To keep the tutorial as short as possible, only the more computationally intensive language processing part scales. The task queue creator is a simple Python script (which could also run in Docker)."
},
{
"code": null,
"e": 4016,
"s": 3905,
"text": "We will work with the Cloud Console from Google. To open it you need to create a project and activate billing."
},
{
"code": null,
"e": 4086,
"s": 4016,
"text": "Then you should see the Cloud Shell button in the upper right corner."
},
{
"code": null,
"e": 4272,
"s": 4086,
"text": "After clicking, the shell should open in the lower part of the window (if you run into trouble, use Chrome Browser). To work comfortably with the shell, I recommend to start the editor:"
},
{
"code": null,
"e": 4311,
"s": 4272,
"text": "You can download the Repository using:"
},
{
"code": null,
"e": 4372,
"s": 4311,
"text": "git clone https://github.com/Juergen-Schmidl/TWD-01-2020.git"
},
{
"code": null,
"e": 4406,
"s": 4372,
"text": "and the necessary model template:"
},
{
"code": null,
"e": 4513,
"s": 4406,
"text": "$cd TWD-01-2020/5_NLP$bash get_model.sh &Your Cloud Shell may freeze, try reconnecting after a few minutes"
},
{
"code": null,
"e": 4747,
"s": 4513,
"text": "Since we need the Project ID on many occasions, it is easier to set it as an environment variable. Please note, that if you interrupt the shell during this tutorial, you have to set it again. You can find your projects with ID using:"
},
{
"code": null,
"e": 4769,
"s": 4747,
"text": "$gcloud projects list"
},
{
"code": null,
"e": 4781,
"s": 4769,
"text": "Please run:"
},
{
"code": null,
"e": 4813,
"s": 4781,
"text": "$export Project=\"yourprojectID\""
},
{
"code": null,
"e": 5153,
"s": 4813,
"text": "You will need the key for a service account quite often. To learn how to create one, you can read this. I prefer the method using the IAM web interface, but there are many ways. For simplicity’s sake, it should be given the role of “editor”, but a finer adjustment is recommended in the long run. After that, carry out the following steps:"
},
{
"code": null,
"e": 5183,
"s": 5153,
"text": "Download the key as JSON file"
},
{
"code": null,
"e": 5210,
"s": 5183,
"text": "Rename your key to sa.json"
},
{
"code": null,
"e": 5271,
"s": 5210,
"text": "put one copy in each directory (4_Setup, 5_NLP, 6_Scheduler)"
},
{
"code": null,
"e": 5313,
"s": 5271,
"text": "Your directory should now look like this:"
},
{
"code": null,
"e": 5404,
"s": 5313,
"text": "Setup Input-data:(If you have completed the first part of the project, you can skip this.)"
},
{
"code": null,
"e": 5694,
"s": 5404,
"text": "We use Google Cloud Datastore in Datastore-Mode to provide the source data. In order to prepare the Datastore, you have to put it into Datastore-Mode. To do this, simply search for Datastore in the Cloud Platform and click on “Select Datastore Mode”. (if needed, choose a location as well)"
},
{
"code": null,
"e": 5742,
"s": 5694,
"text": "After that change directory to 4_Setup and run:"
},
{
"code": null,
"e": 5833,
"s": 5742,
"text": "$cd .. ; cd 4_Setup(You may have to enter this command manually)$python3 Create_Samples.py"
},
{
"code": null,
"e": 5921,
"s": 5833,
"text": "If you see “Samples generated”, you have got 20 sample entries in your Cloud Datastore."
},
{
"code": null,
"e": 6047,
"s": 5921,
"text": "Setup Output-TablesTo store the processed data we create several BigQuery tables. We do this using the following bash-script:"
},
{
"code": null,
"e": 6073,
"s": 6047,
"text": "$bash Create_BQ_Tables.sh"
},
{
"code": null,
"e": 6154,
"s": 6073,
"text": "If all tables were created, we have successfully created all required resources."
},
{
"code": null,
"e": 6308,
"s": 6154,
"text": "The NLP module is located in the repository folder “5_NLP”. Please move to this directory (using the shell). The following files should be in the folder:"
},
{
"code": null,
"e": 6474,
"s": 6308,
"text": "Explainer.py The main script. Here Spark will be started, the pipeline will be created and filled with the pipeline model. The text processing also takes place here."
},
{
"code": null,
"e": 6567,
"s": 6474,
"text": "Model_Template.zipAn example model that extracts entities, i.e. proper names from the texts."
},
{
"code": null,
"e": 6717,
"s": 6567,
"text": "sa.jsonYour Google Cloud service account. If you run into 404 or 403 errors, please check the permission granted in the IAM for this service account."
},
{
"code": null,
"e": 6827,
"s": 6717,
"text": "DockerfileThis file contains the setup for the environment of the script. The exact setup is explained below."
},
{
"code": null,
"e": 6950,
"s": 6827,
"text": "requirements.txtThis file contains required Python libraries, which are installed during the creation of the Docker image."
},
{
"code": null,
"e": 7045,
"s": 6950,
"text": "Explainer.yamlThis file contains information on how Kubernetes should handle the Docker image."
},
{
"code": null,
"e": 7274,
"s": 7045,
"text": "As mentioned above, spark-nlp is a library that allows us to process texts in Spark. To do so, we use the library with the Python script “Explainer.py”. I commented on the code extensively, so I will only cover a few parts here:"
},
{
"code": null,
"e": 7385,
"s": 7274,
"text": "First of all, you may need to specify the name of your service account file (if you haven’t stuck to sa.json):"
},
{
"code": null,
"e": 7582,
"s": 7385,
"text": "The script’s entry point uses Peter Hoffmann’s Redis class to query the Redis instance regularly for new entries in the task queue. We haven’t set up the instance, so the script will not work yet."
},
{
"code": null,
"e": 7695,
"s": 7582,
"text": "As soon as a task arrives in the task queue, the “Explain” function is called, where the processing takes place."
},
{
"code": null,
"e": 8004,
"s": 7695,
"text": "As you can see, the actual logic is located in the model that is stored in (self.Model). This model contains all important steps for the NLP, like Tokenizer, Lemmatizer or Enitiy-Tagging and is unpacked from a ZIP file with the function Load_Model(). To build a model yourself, please refer to this notebook:"
},
{
"code": null,
"e": 8179,
"s": 8004,
"text": "The Python file needs a working Spark environment. In order to provide this environment, a docker container is created using the docker file. Our docker file looks like this:"
},
{
"code": null,
"e": 8280,
"s": 8179,
"text": "A docker file allows us to create a complete system using one file. The most important commands are:"
},
{
"code": null,
"e": 8412,
"s": 8280,
"text": "FROM: Sets the Base-Image. A base image can be a native operating system, but other programs may already have been installed on it."
},
{
"code": null,
"e": 8526,
"s": 8412,
"text": "ENV: Spark needs some environment variables to work. With the ENV command those are set for the Docker container."
},
{
"code": null,
"e": 8676,
"s": 8526,
"text": "COPY and WORKDIR: COPY copies the entire parent directory of the docker file into the container and WORKDIR sets this directory as working directory."
},
{
"code": null,
"e": 8784,
"s": 8676,
"text": "RUN: Calls commands that are executed in the Docker Containers shell. Usually used to install applications."
},
{
"code": null,
"e": 8928,
"s": 8784,
"text": "CMD: A docker file can only have one CMD, here the actual Python script is called. The -u operator is important to get logs from the container."
},
{
"code": null,
"e": 9029,
"s": 8928,
"text": "To build the Docker File, please chance the directory to “5_NLP” and execute the following commands:"
},
{
"code": null,
"e": 9110,
"s": 9029,
"text": "$docker build --tag explainer_img .(You may have to enter this command manually)"
},
{
"code": null,
"e": 9296,
"s": 9110,
"text": "This command builds the Docker image from the Dockerfile in this directory. We cannot start it yet because the Redis instance is not running, but we have successfully created the image."
},
{
"code": null,
"e": 9527,
"s": 9296,
"text": "To run it later on a Kubernetes Cluster, we have to push the image into the Container Registry. To do so, activate the API by using Google Cloud Platform and search for “Container Registry”. Afterwards, run the following commands:"
},
{
"code": null,
"e": 9639,
"s": 9527,
"text": "$docker tag explainer_img gcr.io/$Project/nlp_explainer:latest$docker push gcr.io/$Project/nlp_explainer:latest"
},
{
"code": null,
"e": 9706,
"s": 9639,
"text": "You should now be able to see your file in the Container Registry:"
},
{
"code": null,
"e": 9804,
"s": 9706,
"text": "If this worked so far, we can now move on to the Kubernetes cluster and get this project to work."
},
{
"code": null,
"e": 9959,
"s": 9804,
"text": "This part is quite simple, since Google allows us to create a Kubernetes cluster by command line. You can run this command to create a very small cluster."
},
{
"code": null,
"e": 9983,
"s": 9959,
"text": "$bash Create_Cluster.sh"
},
{
"code": null,
"e": 10299,
"s": 9983,
"text": "The creation may take a few minutes. If you want to create a bigger cluster, check out Kubernetes Engine on Google Cloud Plattform. If you created the cluster using the web interface of Kubernetes Engine, you initially need to connect your console to the cluster. You can get the statement by clicking on “Connect”:"
},
{
"code": null,
"e": 10539,
"s": 10299,
"text": "First we have to make Redis available on the Kubernetes cluster and register it as a service. This is necessary because the containers run isolated from each other. If a container is registered as service, all containers can connect to it."
},
{
"code": null,
"e": 10648,
"s": 10539,
"text": "To do this, the Redis container must be created from a .yaml file, located in the folder “6_Scheduler”. Run:"
},
{
"code": null,
"e": 10693,
"s": 10648,
"text": "$kubectl create -f redis-master-service.yaml"
},
{
"code": null,
"e": 10750,
"s": 10693,
"text": "and register it as as service (from another .yaml file):"
},
{
"code": null,
"e": 10787,
"s": 10750,
"text": "$kubectl create -f redis-master.yaml"
},
{
"code": null,
"e": 11095,
"s": 10787,
"text": "If you take a closer look on the .yaml files, you will see that you can specify all the settings needed. The line “replicas:” is of particular importance, because its value defines the number of parallel instances and therefore the capacity for processing data (of course limited by the underlying machine)."
},
{
"code": null,
"e": 11175,
"s": 11095,
"text": "We work on a quite small machine, so we shouldn’t create more than one replica."
},
{
"code": null,
"e": 11244,
"s": 11175,
"text": "If the creation was successful, you should see the following output:"
},
{
"code": null,
"e": 11262,
"s": 11244,
"text": "$kubectl get pods"
},
{
"code": null,
"e": 11284,
"s": 11262,
"text": "$kubectl get services"
},
{
"code": null,
"e": 11476,
"s": 11284,
"text": "Now that we have set up the Redis instance, we can start filling it with tasks. First we need to establish a local connection with the Redis service. The following command is needed for this:"
},
{
"code": null,
"e": 11529,
"s": 11476,
"text": "$kubectl port-forward deployment/redis-master 6379 &"
},
{
"code": null,
"e": 11581,
"s": 11529,
"text": "Then we have to install Redis on the local machine:"
},
{
"code": null,
"e": 11606,
"s": 11581,
"text": "$sudo pip3 install redis"
},
{
"code": null,
"e": 11785,
"s": 11606,
"text": "Afterwards, the Python script can be called. It retrieves the data from the Cloud Datastore, preprocesses it and puts it into the Redis task queue. You can start the script with:"
},
{
"code": null,
"e": 11807,
"s": 11785,
"text": "$python3 Scheduler.py"
},
{
"code": null,
"e": 11880,
"s": 11807,
"text": "This script is commented in detail so I will only mention a few points :"
},
{
"code": null,
"e": 12035,
"s": 11880,
"text": "The “Process Batch” method contains the actual logic. Here, the articles are read from the Cloud Datastore in batches and passed to the “Send_Job” method."
},
{
"code": null,
"e": 12128,
"s": 12035,
"text": "Since Redis does not like special characters, these are removed to ensure smooth processing."
},
{
"code": null,
"e": 12206,
"s": 12128,
"text": "Then the created jobs are stored in the Redis database with the .put command."
},
{
"code": null,
"e": 12413,
"s": 12206,
"text": "Note: Checking if we need to call a regex method is 10 times faster than the replacement. If special characters are already taken into account when filling the Datastore, the scheduler can work much faster."
},
{
"code": null,
"e": 12450,
"s": 12413,
"text": "You should see the following output:"
},
{
"code": null,
"e": 12508,
"s": 12450,
"text": "Don’t forget to terminate the port forwarding afterwards:"
},
{
"code": null,
"e": 12526,
"s": 12508,
"text": "$pkill kubectl -9"
},
{
"code": null,
"e": 12750,
"s": 12526,
"text": "You have already created the docker container for the explainer in 5.3 and pushed it into the Cloud Container Registry with the name “gcr/[your Project]nlp_explainer:latest”. We will now deploy it on the Kubernetes Cluster."
},
{
"code": null,
"e": 12846,
"s": 12750,
"text": "For this purpose a .yaml file containing all relevant information for Kubernetes is used again."
},
{
"code": null,
"e": 12929,
"s": 12846,
"text": "Please Note, that you have to insert your own container from the registry(image:)!"
},
{
"code": null,
"e": 13023,
"s": 12929,
"text": "To push the .yaml file, you just need to execute the following command in the “5_NLP” folder:"
},
{
"code": null,
"e": 13057,
"s": 13023,
"text": "$kubectl create -f Explainer.yaml"
},
{
"code": null,
"e": 13194,
"s": 13057,
"text": "If you use the small cluster, I recommend to just deploy one replica!Otherwise you will run into problems caused by lack of performance."
},
{
"code": null,
"e": 13233,
"s": 13194,
"text": "After that you can see the pods using:"
},
{
"code": null,
"e": 13251,
"s": 13233,
"text": "$kubectl get pods"
},
{
"code": null,
"e": 13370,
"s": 13251,
"text": "After the creation of the container, you should get this result with the following command (can take up to 2 minutes):"
},
{
"code": null,
"e": 13447,
"s": 13370,
"text": "$kubectl logs [pod-name]for example:$kubectl logs explainer-544d123125-7nzbg"
},
{
"code": null,
"e": 13508,
"s": 13447,
"text": "You can also see errors in the log, if something went wrong."
},
{
"code": null,
"e": 13654,
"s": 13508,
"text": "If everything has been processed, the pod stays idle or will be evicted and recreated by Kubernetes (because it uses a loop and does not finish)."
},
{
"code": null,
"e": 13697,
"s": 13654,
"text": "To delete all pods without recreation use:"
},
{
"code": null,
"e": 13787,
"s": 13697,
"text": "$kubectl delete deployments [deployment]for example:$kubectl delete deployments explainer"
},
{
"code": null,
"e": 13972,
"s": 13787,
"text": "If you don’t want to use the Kubernetes Cluster anymore you should delete it either via the web interface or by using the following command, otherwise Google will continue billing you."
},
{
"code": null,
"e": 14200,
"s": 13972,
"text": "$gcloud config set project $Project$gcloud container clusters delete [your-clustername] --zone [Zone]for example:$gcloud config set project $Project$gcloud container clusters delete \"your-first-cluster-1\" --zone \"us-central1-a\""
},
{
"code": null,
"e": 14287,
"s": 14200,
"text": "To check the result, please go to the Google Cloud Platform and search for “BigQuery”."
},
{
"code": null,
"e": 14354,
"s": 14287,
"text": "You should be able to see the following tables in the left bottom:"
},
{
"code": null,
"e": 14546,
"s": 14354,
"text": "The tables “Article_masterdata” and “Article_tags” have been created by the Scheduler to serve the needs of the consecutive project. But we want to see the content of the “Entitiy_raw” table."
},
{
"code": null,
"e": 14596,
"s": 14546,
"text": "To access them click on it and move to “Preview”:"
},
{
"code": null,
"e": 14681,
"s": 14596,
"text": "You should see the results of the entity recognition with the respective article ID."
},
{
"code": null,
"e": 14710,
"s": 14681,
"text": "And that’s it, you are done!"
},
{
"code": null,
"e": 14933,
"s": 14710,
"text": "If you are interested in seeing how to create a highly scalable dashboard based on this data, we would be happy if you read the following tutorial: Build a highly scalable dashboard that runs on Kubernetes by Arnold Lutsch"
},
{
"code": null,
"e": 15109,
"s": 14933,
"text": "You could also replace the sample data with real articles using this tutorial: Build a scalable webcrawler for towards data science with Selenium and python by Philipp Postels"
}
] |
How to insert Date in MongoDB?
|
To insert date in MongoDB, use Date(). Let us create a collection with documents −
> db.demo421.insert({"DueDate":new Date(Date.now())});
WriteResult({ "nInserted" : 1 })
> db.demo421.insert({"DueDate":new Date("2020-01-15")});
WriteResult({ "nInserted" : 1 })
> db.demo421.insert({"DueDate":new Date("2018-12-31")});
WriteResult({ "nInserted" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo421.find();
This will produce the following output −
{ "_id" : ObjectId("5e73a2ec9822da45b30346de"), "DueDate" : ISODate("2020-03-19T16:50:52.746Z") }
{ "_id" : ObjectId("5e73a2fb9822da45b30346df"), "DueDate" : ISODate("2020-01-15T00:00:00Z") }
{ "_id" : ObjectId("5e73a3079822da45b30346e0"), "DueDate" : ISODate("2018-12-31T00:00:00Z") }
|
[
{
"code": null,
"e": 1145,
"s": 1062,
"text": "To insert date in MongoDB, use Date(). Let us create a collection with documents −"
},
{
"code": null,
"e": 1413,
"s": 1145,
"text": "> db.demo421.insert({\"DueDate\":new Date(Date.now())});\nWriteResult({ \"nInserted\" : 1 })\n> db.demo421.insert({\"DueDate\":new Date(\"2020-01-15\")});\nWriteResult({ \"nInserted\" : 1 })\n> db.demo421.insert({\"DueDate\":new Date(\"2018-12-31\")});\nWriteResult({ \"nInserted\" : 1 })"
},
{
"code": null,
"e": 1486,
"s": 1413,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1507,
"s": 1486,
"text": "> db.demo421.find();"
},
{
"code": null,
"e": 1548,
"s": 1507,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1834,
"s": 1548,
"text": "{ \"_id\" : ObjectId(\"5e73a2ec9822da45b30346de\"), \"DueDate\" : ISODate(\"2020-03-19T16:50:52.746Z\") }\n{ \"_id\" : ObjectId(\"5e73a2fb9822da45b30346df\"), \"DueDate\" : ISODate(\"2020-01-15T00:00:00Z\") }\n{ \"_id\" : ObjectId(\"5e73a3079822da45b30346e0\"), \"DueDate\" : ISODate(\"2018-12-31T00:00:00Z\") }"
}
] |
Axure RP - Quick Guide
|
Close
Edit
Cut
Copy
Paste
Find
Replace
View
Show Status Bar
Toolbars
Main Toolbar
Styling Toolbar
Main Toolbar
Styling Toolbar
Help
Getting Started
Using Help
What’s this
To get started, drag and drop Classic Menu – Horizontal in the design area. You will find it under Libraries → Menus and Tables. Name the control as MenuBarExample. Let us make this element of width 300 px and height 30 px. Position it at 100 on X-axis and at 30 on Y-axis. You can adjust these values under the Style tab under Inspector section on the right.
At the end of the above procedure, you will be able to see the end result as shown in the following screenshot.
Let us add the names to the menu titles in the Inspector section as well. Click each menu title and observe the inspector section. If the name is not given to the specific menu bar, the name will turn as (Menu Item Name).
Name the File menu as FileMenu.
Same goes for Edit as EditMenu and View as ViewMenu.
To confirm whether the names have been provided, click each individual menu and confirm under Inspector: Menu Item. You will be able to see the names and not (Menu Item Name).
Now, as per our requirement, let us complete the menu bar with the Help menu. Right-click the menu bar title – View, you will see a context menu. Click Add Menu Item After.
A blank menu item will appear. Double-click the blank menu item, and enter menu title as Help. Repeat the procedure, providing it a name under Inspector: Menu Item Name. Once complete, you will see the design area as follows.
Next, let us design the interaction for File Menu.
Click the File menu bar title and observe the Inspector: Menu Item.
As highlighted in the screenshot above, observe the Properties tab.
Under Properties tab, we will create the interaction for File Menu.
It is very simple to add a submenu to the menu. Right-click on File menu, in the context menu that appears, click Add Submenu.
Note − We can also remove the submenu by repeating the same step, and clicking Remove Submenu.
Once the submenu has been added, a blank sub-menu will appear. Double-click each of the menu items and provide names such as – New, Open, Save.
Right-click on the last submenu item and add one more submenu item. Name it as Close.
It is a good practice to name all the submenu items under the Inspector section as well. This helps referencing them in your overall design process.
While designing this part, notice that whenever we click any other part of the design area, the submenu will disappear. We need to click the File menu item to view the submenu.
Let us talk about the interaction – Hover. This interaction has a unique behavior of getting triggered, when the mouse pointer is hovered over a particular element. In Axure, this interaction is automatically implemented with the Classic Menu – Horizontal.
To see the interaction in action, click the Preview button in the toolbar. Axure will open the preview in the default browser.
Hover on the File menu. The submenu will be displayed as shown in the following screenshot.
If we look at it objectively, we have just utilized Axure to create a complex interaction, such as hovering on the menu item. In usual HTML coding, it would have taken close to 1 to 1.5 hours of time.
As an assignment, complete the rest of the menus for their submenus.
Now, let us quickly create an interaction on the Close submenu under the File menu. We will highlight it in red when hovered. To do this, right-click on Close submenu. Click Interaction Styles...
Under MouseOver tab, check select Fill Color and select red color. Axure will immediately show the preview in the design area. Assuming that the Apply to section Selected Menu and all submenus is selected, it will highlight the whole menu in red.
Click Selected Menu Item only. Now check select Font Color and choose white color for the font. The preview will be updated immediately.
Click OK to complete this setup.
Click Preview again to see the interaction in action.
This completes the example.
You may try the following interaction as a quick assignment.
OnClick property by using a button widget.
Many of the software development approaches, when it comes to user interfaces development, employ a common technique − Creating Masters.
A master is a reusable wireframe, which will be created once and used extensively thereafter on the subsequent pages. With Axure RP, when we create a master page, the changes made to this page will be applied to the pages where it is being used. Hence, it reduces time to a great extent for the components common to all pages.
To get started with Masters, you can focus on the Masters section (marked as 5) as highlighted in the following screenshot.
Use this masters section to −
Organize the prototype’s masters by adding, deleting, or editing master page/folder.
Organize the prototype’s masters by adding, deleting, or editing master page/folder.
Select a particular master for editing.
Select a particular master for editing.
In Axure RP, as we have seen in the previous chapter, there are different states associated with a given widget. For consolidating/organizing the states of a particular widget or set of widgets, we need a container/placeholder. Dynamic panels serve as the container/placeholder for the states of a widget.
Let us understand the dynamic panel better using an example. We will continue from our menu bar example.
The addition in this example will be an image area and a button underneath the menu bar. Use the widget Placeholder for the image area and button under common widgets. Name the placeholder as ImageAreaPlaceholder, button as showImageButton.
Also, let us have the menu bar added into masters. Right-click on the menu bar and click Convert to Master. A dialog box will appear prompting the name for the master. Add the name as menuBarMaster.
As shown in the above screenshot, the menu bar turns pink and the entry for the masters has been added.
Now, let us create a dynamic panel. The context for dynamic panel is, you want to control the visibility of image area based on Show Image button click. Having a dynamic panel will allow for the flexibility of image area.
Let us see how to create the dynamic panel. Right-click on the Image Area, the context menu will appear, select Convert to Dynamic Panel.
The dynamic panel will be under Outline: Page. Also under Inspector, it shows the dynamic panel. Name the dynamic panel as showImageDynamicPanel. The name for this dynamic panel will get updated under Outline: Page section.
In the design area, right-click on Show Image dynamic panel to see the context menu. Select Set Hidden, the dynamic panel will disappear from the screen.
The dynamic panel can be accessed by double-clicking under Outline: Page.
Now, let us provide a click event to the button. Click the Show Image button, under Inspector → Properties, double-click OnClick interaction.
As shown in the above screenshot, click the Show/Hide under Widgets. It will automatically show the available widgets to configure actions. Check select showImageDynamicPanel. Click OK.
Now, click Preview. On the preview screen, click Show Image. Another interaction for a button is finally created.
In this chapter, we will discuss the conditional logic used in Axure RP.
Just like any other programming tools, Axure also supports conditional logic to create enhanced interactions in prototypes. Once you are familiar with how you can provide interactions, providing conditional logic to the interactions is the next level.
Following is the simple and concise flow for conditional logic −
If, a particular widget/screen is clicked
Then, perform a particular action/interaction
Else, keep/change the state of the widget or the screen
To understand this better, let us resume our flow from the previous example. For this purpose, its required for us to get acquainted with the Condition Builder.
Double-click any of the interactions, for instance OnClick. You will be able to see the Case Editor as shown in the following screenshot.
Click the button – Add Condition near the Case Name. It will show below in the dialog box.
As shown under the Description, the condition builder will create the If-Then-Else flow as per the conditions chosen in the condition section.
Let us create a condition on this button.
We want to show the hide image button, once the dynamic panel is visible. We made the dynamic panel visible on the Show Image button click in the previous example. Now, let us make another button Hide Image visible.
Close the condition builder, and come back to the design area.
Insert the Hide Image button from the Libraries under common libraries. To reiterate, it is a best practice to name the UI element right after you’ve inserted it in the design area.
Right-click the Hide Image button and click Set Hidden. The button will be hidden from the design area as shown in the following screenshot.
Now, let us come back to the interactions for Show Image button.
First, under the Show Image button interactions, double-click Case 1, you will be able to see the case editor. Use the Show/Hide action, to select hideImageButton and set its visibility to show.
Similarly, using the Show/Hide action, select showImageButton and set its visibility to hide.
We have managed the visibility of Hide Image button such that, when we click the Show Image button, the button will be shown.
A complete condition will be as shown in the following screenshot.
Let us build the condition.
Under the design area, click the Hide Image button. From the Inspector section, click Add Case.
Under Add Case, click Add Condition button. As per the background provided earlier, create the condition set using the dropdown values in the Condition Builder.
In simple words, with the above condition, we are checking whether the dynamic panel showImageDynamicPanel is visible or not
Now, let us design the interaction for Hide Image button, configure it as follows −
Select Show/Hide action.
Select the widget showImageDynamicPanel.
Set the visibility to Hide.
Similarly, repeat the drill for showing showImageButton and hiding the hideImageButton.
Once done, click OK to close Case Editor.
Then, click Preview to see the changes done.
The successful results will be as shown in the following screenshots.
When the Show Image button is clicked −
When the Hide Image button is clicked −
Until now, we have got ourselves introduced to the basic features of Axure for interactions. However, there will be many real-world scenarios, where the prototype will have to be intelligent. By the word intelligent, the prototype will need to detect the state of a certain widget in order to perform an action/trigger a certain behavior.
A typical example of such an interaction is setting the color of a button. This requires UX engineer to wear the thinking hat and take the prototype designing to the next level.
Variable, by definition, stands for a factor that is liable to vary or change. In Axure, we can use variables to represent or identify the state of a widget/interaction.
A typical example will be storing a data value when transferring data from one page to the other. To keep the example simple and clear, let us consider a scenario where we need to show the state of a particular widget.
Continuing with our last example, let us consider that we want to show how many times the image was shown.
Here is how we will do it −
We will create a variable for initiating the count to 0.
We will create a variable for initiating the count to 0.
On the click of the button Show Image, we will increment the value of this variable.
On the click of the button Show Image, we will increment the value of this variable.
Display the value in the text label.
Display the value in the text label.
For this example, we will be creating a text below the Dynamic Panel. The text will read – Image is shown 0 times.
Critical − It is important that the labels are broken into three. Please follow the label names and text listed in the table.
This is required as we want to control the countLabel value for every Show Image button click.
Let us define a variable first.
We will need a variable, which will be controlled when the button is clicked. This variable in Axure’s terminology is − Global Variable. To define a global variable, click Project in the menu bar, and then click Global Variables. A dialog box will open as shown in the following screenshot.
Click the green plus (+) icon to add a global variable. Let us call our global variable − varDynamicPanel. Its default value will be 0.
With the Show Image button interactions, double-click on Case 1. Add another action. As shown in the following screenshot, the action is Set Text on countLabel to [[varDynamicPanel + 1]].
Selecting a text label to a value is pretty straightforward. Let us see how to get the value from a dynamic panel.
As indicated by step 4 in the above screenshot, click fx button and the following dialog box will open up.
Under the first text area, enter the following string.
[[varDynamicPanel + 1]]
Click OK.
Now, we need to ensure that the variable is updated after every button click.
In the case editor dialog box, under actions, select Variables → Set Variable Value.
Select the varDynamicPanel as the variable.
Set the variable to fetch value from the text on widget as countLabel from the available options.
Close the Case Editor by clicking OK. Then, click Preview button.
After showing/hiding image for four times, here is the result on the preview screen.
Now that you are well-versed with different interactions and events that are possible in Axure, you may want to extend your work in order to minimize efforts in future.
For instance, the very first example with Classic Menu – Horizontal, was once present in Axure versions as a combination of different available widgets. This means, Axure evolved with time to accommodate frequently used widgets in the form of single widget library.
The concept of widget library is applicable more prominently in large UX teams. Some organizations keep approved widgets for subsequent UX engineers on a central repository.
Thus, in a nutshell, Axure Widget Library is a collection of custom widgets stored in a single file. The file type for Axure Widget Library is RPLIB.
These libraries are accessible from Libraries pane. These libraries can’t be updated/removed. For most of the complex prototyping needs, Axure built-in libraries come to rescue.
The library consists of 17 unique flow widgets, which are used primarily for diagram creation. Also, there are 25 widgets in the wireframe library.
A brief functioning of libraries is present in Chapter 3 − User Interface.
Axure community, growing day-by-day in size, has a vast collection of user-created libraries. You can visit them at − https://www.axure.com/support/download-widget-libraries.
The UX professionals from all around the world, who are committed to make this community grow, submit their work on the above link.
You can download the libraries from the website and add them to Axure using Load Library option under libraries. Also, you can directly download libraries from the application interface itself.
As shown in the above screen, we have a context menu, where you can download different libraries as offered on https://www.axure.com/support/download-widget-libraries. You can also create your own library, which will be handy while creating repetitive controls for a given prototype.
The complete instructions to download/load libraries is available at: https://www.axure.com/support/reference/widget-libraries.
When it comes to using a custom widget from one of your loaded libraries, drag and drop it in the design area similar to the built-in widgets. If the widget includes variables or a custom style, the Import Wizard dialog would flag such dependencies.
Among such dependencies, you may notice there are certain incompatible styles that come along with the widget library being imported. You may choose to Cancel and import only the widgets or click the Finish button to import the entire package.
Once you drag and drop a widget into your wireframe, that particular instance is no longer associated with its original widget library. Thus, edits and changes made to widgets in the imported widget library are not applied to any of the instances of these widgets in your project file, even after you refresh the library. Rest assured, once imported, you can utilize the widgets in the imported library without worrying about the updates that take place in the same widget library as available online.
Using an Axure RP Library file is pretty straightforward. When you download a library, the icon for library file (.rplib) is clearly distinguished from the Axure RP prototype file (.rp). For instance, as seen in the following screenshot.
The mechanism for this to work - You can import the iOS Wireframe document in iOS Wireframe Demo.
This library can be used for multiple projects and updates in the library file will be available once you Refresh the library from the context menu. As highlighted earlier, this comes very handy when working on a team project and distributing the libraries in this fashion.
Axure RP 8 supports collaboration with the feature − Team Projects. This feature is not only beneficial for the distributed teams but also for the single user. The benefit to the single user is the ability to create versioning on the work in progress.
In the Team Projects scenario, each team member has a copy of the project on their computer. This project will be synced with a shared repository. This shared repository is connected to other members of the team.
After the course of a day's work, each team member will create new elements, check out files, and generally edit the project. Check Out is a commonly used term for indicating the work in progress for a particular file.
The changes will not be reflected in the shared repository until the team member checks in all their checked out elements. The Manage Team Project console provides all team members with a real-time view of the availability status of the elements that are managed by the system.
This view provides the details of an element that is checked out by another team member.
For working with or creating a team project, head over to the Team menu. Click Team and then select Create Team Project from Current File. Following screen pops up.
Available options for hosting a team project are − using AxShare and SVN. We will discuss AxShare in the next section. SVN is the commonly used Version Controlling System, which provides a server to host your documents.
Follow the on-screen guidelines for creating a team project and then you will be able to start collaborating with a single Axure file across the team/use it for your own historical storage.
When it comes to showcasing your prototype, there are multiple options available as per the environment you are in. Most commonly used method to export your prototype is to use Axure Share (aka AxShare).
With Axure Share, the following collaboration capabilities are possible.
Prototypes can be hosted on Axure Share and shared with the involved team members/clients.
Prototypes can be hosted on Axure Share and shared with the involved team members/clients.
With the discussion/comments feature, you can get the on-the-go inputs on the prototype in the making.
With the discussion/comments feature, you can get the on-the-go inputs on the prototype in the making.
Once you are ready with the prototype, you can upload the prototype to AxShare using Publish → Publish to Axure Share. Following dialog box will be displayed.
You must create an account at AxShare.com in order to progress ahead. If you already have an account, you can use the ‘Log In’ option to log in and upload your work to AxShare.
The uploaded data is in HTML, CSS, and JavaScript. Once uploaded, you are provided with a link, which you can provide to the intended stakeholders/team.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 21245,
"s": 21239,
"text": "Close"
},
{
"code": null,
"e": 21250,
"s": 21245,
"text": "Edit"
},
{
"code": null,
"e": 21254,
"s": 21250,
"text": "Cut"
},
{
"code": null,
"e": 21259,
"s": 21254,
"text": "Copy"
},
{
"code": null,
"e": 21265,
"s": 21259,
"text": "Paste"
},
{
"code": null,
"e": 21270,
"s": 21265,
"text": "Find"
},
{
"code": null,
"e": 21278,
"s": 21270,
"text": "Replace"
},
{
"code": null,
"e": 21283,
"s": 21278,
"text": "View"
},
{
"code": null,
"e": 21299,
"s": 21283,
"text": "Show Status Bar"
},
{
"code": null,
"e": 21340,
"s": 21299,
"text": "Toolbars\n\nMain Toolbar\nStyling Toolbar\n\n"
},
{
"code": null,
"e": 21353,
"s": 21340,
"text": "Main Toolbar"
},
{
"code": null,
"e": 21369,
"s": 21353,
"text": "Styling Toolbar"
},
{
"code": null,
"e": 21374,
"s": 21369,
"text": "Help"
},
{
"code": null,
"e": 21390,
"s": 21374,
"text": "Getting Started"
},
{
"code": null,
"e": 21401,
"s": 21390,
"text": "Using Help"
},
{
"code": null,
"e": 21413,
"s": 21401,
"text": "What’s this"
},
{
"code": null,
"e": 21773,
"s": 21413,
"text": "To get started, drag and drop Classic Menu – Horizontal in the design area. You will find it under Libraries → Menus and Tables. Name the control as MenuBarExample. Let us make this element of width 300 px and height 30 px. Position it at 100 on X-axis and at 30 on Y-axis. You can adjust these values under the Style tab under Inspector section on the right."
},
{
"code": null,
"e": 21885,
"s": 21773,
"text": "At the end of the above procedure, you will be able to see the end result as shown in the following screenshot."
},
{
"code": null,
"e": 22107,
"s": 21885,
"text": "Let us add the names to the menu titles in the Inspector section as well. Click each menu title and observe the inspector section. If the name is not given to the specific menu bar, the name will turn as (Menu Item Name)."
},
{
"code": null,
"e": 22139,
"s": 22107,
"text": "Name the File menu as FileMenu."
},
{
"code": null,
"e": 22192,
"s": 22139,
"text": "Same goes for Edit as EditMenu and View as ViewMenu."
},
{
"code": null,
"e": 22368,
"s": 22192,
"text": "To confirm whether the names have been provided, click each individual menu and confirm under Inspector: Menu Item. You will be able to see the names and not (Menu Item Name)."
},
{
"code": null,
"e": 22541,
"s": 22368,
"text": "Now, as per our requirement, let us complete the menu bar with the Help menu. Right-click the menu bar title – View, you will see a context menu. Click Add Menu Item After."
},
{
"code": null,
"e": 22767,
"s": 22541,
"text": "A blank menu item will appear. Double-click the blank menu item, and enter menu title as Help. Repeat the procedure, providing it a name under Inspector: Menu Item Name. Once complete, you will see the design area as follows."
},
{
"code": null,
"e": 22818,
"s": 22767,
"text": "Next, let us design the interaction for File Menu."
},
{
"code": null,
"e": 22886,
"s": 22818,
"text": "Click the File menu bar title and observe the Inspector: Menu Item."
},
{
"code": null,
"e": 22954,
"s": 22886,
"text": "As highlighted in the screenshot above, observe the Properties tab."
},
{
"code": null,
"e": 23022,
"s": 22954,
"text": "Under Properties tab, we will create the interaction for File Menu."
},
{
"code": null,
"e": 23149,
"s": 23022,
"text": "It is very simple to add a submenu to the menu. Right-click on File menu, in the context menu that appears, click Add Submenu."
},
{
"code": null,
"e": 23244,
"s": 23149,
"text": "Note − We can also remove the submenu by repeating the same step, and clicking Remove Submenu."
},
{
"code": null,
"e": 23388,
"s": 23244,
"text": "Once the submenu has been added, a blank sub-menu will appear. Double-click each of the menu items and provide names such as – New, Open, Save."
},
{
"code": null,
"e": 23474,
"s": 23388,
"text": "Right-click on the last submenu item and add one more submenu item. Name it as Close."
},
{
"code": null,
"e": 23623,
"s": 23474,
"text": "It is a good practice to name all the submenu items under the Inspector section as well. This helps referencing them in your overall design process."
},
{
"code": null,
"e": 23800,
"s": 23623,
"text": "While designing this part, notice that whenever we click any other part of the design area, the submenu will disappear. We need to click the File menu item to view the submenu."
},
{
"code": null,
"e": 24057,
"s": 23800,
"text": "Let us talk about the interaction – Hover. This interaction has a unique behavior of getting triggered, when the mouse pointer is hovered over a particular element. In Axure, this interaction is automatically implemented with the Classic Menu – Horizontal."
},
{
"code": null,
"e": 24184,
"s": 24057,
"text": "To see the interaction in action, click the Preview button in the toolbar. Axure will open the preview in the default browser."
},
{
"code": null,
"e": 24276,
"s": 24184,
"text": "Hover on the File menu. The submenu will be displayed as shown in the following screenshot."
},
{
"code": null,
"e": 24477,
"s": 24276,
"text": "If we look at it objectively, we have just utilized Axure to create a complex interaction, such as hovering on the menu item. In usual HTML coding, it would have taken close to 1 to 1.5 hours of time."
},
{
"code": null,
"e": 24546,
"s": 24477,
"text": "As an assignment, complete the rest of the menus for their submenus."
},
{
"code": null,
"e": 24742,
"s": 24546,
"text": "Now, let us quickly create an interaction on the Close submenu under the File menu. We will highlight it in red when hovered. To do this, right-click on Close submenu. Click Interaction Styles..."
},
{
"code": null,
"e": 24989,
"s": 24742,
"text": "Under MouseOver tab, check select Fill Color and select red color. Axure will immediately show the preview in the design area. Assuming that the Apply to section Selected Menu and all submenus is selected, it will highlight the whole menu in red."
},
{
"code": null,
"e": 25126,
"s": 24989,
"text": "Click Selected Menu Item only. Now check select Font Color and choose white color for the font. The preview will be updated immediately."
},
{
"code": null,
"e": 25159,
"s": 25126,
"text": "Click OK to complete this setup."
},
{
"code": null,
"e": 25213,
"s": 25159,
"text": "Click Preview again to see the interaction in action."
},
{
"code": null,
"e": 25241,
"s": 25213,
"text": "This completes the example."
},
{
"code": null,
"e": 25302,
"s": 25241,
"text": "You may try the following interaction as a quick assignment."
},
{
"code": null,
"e": 25345,
"s": 25302,
"text": "OnClick property by using a button widget."
},
{
"code": null,
"e": 25482,
"s": 25345,
"text": "Many of the software development approaches, when it comes to user interfaces development, employ a common technique − Creating Masters."
},
{
"code": null,
"e": 25809,
"s": 25482,
"text": "A master is a reusable wireframe, which will be created once and used extensively thereafter on the subsequent pages. With Axure RP, when we create a master page, the changes made to this page will be applied to the pages where it is being used. Hence, it reduces time to a great extent for the components common to all pages."
},
{
"code": null,
"e": 25933,
"s": 25809,
"text": "To get started with Masters, you can focus on the Masters section (marked as 5) as highlighted in the following screenshot."
},
{
"code": null,
"e": 25963,
"s": 25933,
"text": "Use this masters section to −"
},
{
"code": null,
"e": 26048,
"s": 25963,
"text": "Organize the prototype’s masters by adding, deleting, or editing master page/folder."
},
{
"code": null,
"e": 26133,
"s": 26048,
"text": "Organize the prototype’s masters by adding, deleting, or editing master page/folder."
},
{
"code": null,
"e": 26173,
"s": 26133,
"text": "Select a particular master for editing."
},
{
"code": null,
"e": 26213,
"s": 26173,
"text": "Select a particular master for editing."
},
{
"code": null,
"e": 26519,
"s": 26213,
"text": "In Axure RP, as we have seen in the previous chapter, there are different states associated with a given widget. For consolidating/organizing the states of a particular widget or set of widgets, we need a container/placeholder. Dynamic panels serve as the container/placeholder for the states of a widget."
},
{
"code": null,
"e": 26624,
"s": 26519,
"text": "Let us understand the dynamic panel better using an example. We will continue from our menu bar example."
},
{
"code": null,
"e": 26865,
"s": 26624,
"text": "The addition in this example will be an image area and a button underneath the menu bar. Use the widget Placeholder for the image area and button under common widgets. Name the placeholder as ImageAreaPlaceholder, button as showImageButton."
},
{
"code": null,
"e": 27064,
"s": 26865,
"text": "Also, let us have the menu bar added into masters. Right-click on the menu bar and click Convert to Master. A dialog box will appear prompting the name for the master. Add the name as menuBarMaster."
},
{
"code": null,
"e": 27168,
"s": 27064,
"text": "As shown in the above screenshot, the menu bar turns pink and the entry for the masters has been added."
},
{
"code": null,
"e": 27390,
"s": 27168,
"text": "Now, let us create a dynamic panel. The context for dynamic panel is, you want to control the visibility of image area based on Show Image button click. Having a dynamic panel will allow for the flexibility of image area."
},
{
"code": null,
"e": 27528,
"s": 27390,
"text": "Let us see how to create the dynamic panel. Right-click on the Image Area, the context menu will appear, select Convert to Dynamic Panel."
},
{
"code": null,
"e": 27752,
"s": 27528,
"text": "The dynamic panel will be under Outline: Page. Also under Inspector, it shows the dynamic panel. Name the dynamic panel as showImageDynamicPanel. The name for this dynamic panel will get updated under Outline: Page section."
},
{
"code": null,
"e": 27906,
"s": 27752,
"text": "In the design area, right-click on Show Image dynamic panel to see the context menu. Select Set Hidden, the dynamic panel will disappear from the screen."
},
{
"code": null,
"e": 27980,
"s": 27906,
"text": "The dynamic panel can be accessed by double-clicking under Outline: Page."
},
{
"code": null,
"e": 28122,
"s": 27980,
"text": "Now, let us provide a click event to the button. Click the Show Image button, under Inspector → Properties, double-click OnClick interaction."
},
{
"code": null,
"e": 28308,
"s": 28122,
"text": "As shown in the above screenshot, click the Show/Hide under Widgets. It will automatically show the available widgets to configure actions. Check select showImageDynamicPanel. Click OK."
},
{
"code": null,
"e": 28422,
"s": 28308,
"text": "Now, click Preview. On the preview screen, click Show Image. Another interaction for a button is finally created."
},
{
"code": null,
"e": 28495,
"s": 28422,
"text": "In this chapter, we will discuss the conditional logic used in Axure RP."
},
{
"code": null,
"e": 28747,
"s": 28495,
"text": "Just like any other programming tools, Axure also supports conditional logic to create enhanced interactions in prototypes. Once you are familiar with how you can provide interactions, providing conditional logic to the interactions is the next level."
},
{
"code": null,
"e": 28812,
"s": 28747,
"text": "Following is the simple and concise flow for conditional logic −"
},
{
"code": null,
"e": 28854,
"s": 28812,
"text": "If, a particular widget/screen is clicked"
},
{
"code": null,
"e": 28900,
"s": 28854,
"text": "Then, perform a particular action/interaction"
},
{
"code": null,
"e": 28956,
"s": 28900,
"text": "Else, keep/change the state of the widget or the screen"
},
{
"code": null,
"e": 29117,
"s": 28956,
"text": "To understand this better, let us resume our flow from the previous example. For this purpose, its required for us to get acquainted with the Condition Builder."
},
{
"code": null,
"e": 29255,
"s": 29117,
"text": "Double-click any of the interactions, for instance OnClick. You will be able to see the Case Editor as shown in the following screenshot."
},
{
"code": null,
"e": 29346,
"s": 29255,
"text": "Click the button – Add Condition near the Case Name. It will show below in the dialog box."
},
{
"code": null,
"e": 29489,
"s": 29346,
"text": "As shown under the Description, the condition builder will create the If-Then-Else flow as per the conditions chosen in the condition section."
},
{
"code": null,
"e": 29531,
"s": 29489,
"text": "Let us create a condition on this button."
},
{
"code": null,
"e": 29747,
"s": 29531,
"text": "We want to show the hide image button, once the dynamic panel is visible. We made the dynamic panel visible on the Show Image button click in the previous example. Now, let us make another button Hide Image visible."
},
{
"code": null,
"e": 29810,
"s": 29747,
"text": "Close the condition builder, and come back to the design area."
},
{
"code": null,
"e": 29992,
"s": 29810,
"text": "Insert the Hide Image button from the Libraries under common libraries. To reiterate, it is a best practice to name the UI element right after you’ve inserted it in the design area."
},
{
"code": null,
"e": 30133,
"s": 29992,
"text": "Right-click the Hide Image button and click Set Hidden. The button will be hidden from the design area as shown in the following screenshot."
},
{
"code": null,
"e": 30198,
"s": 30133,
"text": "Now, let us come back to the interactions for Show Image button."
},
{
"code": null,
"e": 30393,
"s": 30198,
"text": "First, under the Show Image button interactions, double-click Case 1, you will be able to see the case editor. Use the Show/Hide action, to select hideImageButton and set its visibility to show."
},
{
"code": null,
"e": 30487,
"s": 30393,
"text": "Similarly, using the Show/Hide action, select showImageButton and set its visibility to hide."
},
{
"code": null,
"e": 30613,
"s": 30487,
"text": "We have managed the visibility of Hide Image button such that, when we click the Show Image button, the button will be shown."
},
{
"code": null,
"e": 30680,
"s": 30613,
"text": "A complete condition will be as shown in the following screenshot."
},
{
"code": null,
"e": 30708,
"s": 30680,
"text": "Let us build the condition."
},
{
"code": null,
"e": 30804,
"s": 30708,
"text": "Under the design area, click the Hide Image button. From the Inspector section, click Add Case."
},
{
"code": null,
"e": 30965,
"s": 30804,
"text": "Under Add Case, click Add Condition button. As per the background provided earlier, create the condition set using the dropdown values in the Condition Builder."
},
{
"code": null,
"e": 31090,
"s": 30965,
"text": "In simple words, with the above condition, we are checking whether the dynamic panel showImageDynamicPanel is visible or not"
},
{
"code": null,
"e": 31174,
"s": 31090,
"text": "Now, let us design the interaction for Hide Image button, configure it as follows −"
},
{
"code": null,
"e": 31199,
"s": 31174,
"text": "Select Show/Hide action."
},
{
"code": null,
"e": 31240,
"s": 31199,
"text": "Select the widget showImageDynamicPanel."
},
{
"code": null,
"e": 31268,
"s": 31240,
"text": "Set the visibility to Hide."
},
{
"code": null,
"e": 31356,
"s": 31268,
"text": "Similarly, repeat the drill for showing showImageButton and hiding the hideImageButton."
},
{
"code": null,
"e": 31398,
"s": 31356,
"text": "Once done, click OK to close Case Editor."
},
{
"code": null,
"e": 31443,
"s": 31398,
"text": "Then, click Preview to see the changes done."
},
{
"code": null,
"e": 31513,
"s": 31443,
"text": "The successful results will be as shown in the following screenshots."
},
{
"code": null,
"e": 31553,
"s": 31513,
"text": "When the Show Image button is clicked −"
},
{
"code": null,
"e": 31593,
"s": 31553,
"text": "When the Hide Image button is clicked −"
},
{
"code": null,
"e": 31932,
"s": 31593,
"text": "Until now, we have got ourselves introduced to the basic features of Axure for interactions. However, there will be many real-world scenarios, where the prototype will have to be intelligent. By the word intelligent, the prototype will need to detect the state of a certain widget in order to perform an action/trigger a certain behavior."
},
{
"code": null,
"e": 32110,
"s": 31932,
"text": "A typical example of such an interaction is setting the color of a button. This requires UX engineer to wear the thinking hat and take the prototype designing to the next level."
},
{
"code": null,
"e": 32280,
"s": 32110,
"text": "Variable, by definition, stands for a factor that is liable to vary or change. In Axure, we can use variables to represent or identify the state of a widget/interaction."
},
{
"code": null,
"e": 32499,
"s": 32280,
"text": "A typical example will be storing a data value when transferring data from one page to the other. To keep the example simple and clear, let us consider a scenario where we need to show the state of a particular widget."
},
{
"code": null,
"e": 32606,
"s": 32499,
"text": "Continuing with our last example, let us consider that we want to show how many times the image was shown."
},
{
"code": null,
"e": 32634,
"s": 32606,
"text": "Here is how we will do it −"
},
{
"code": null,
"e": 32691,
"s": 32634,
"text": "We will create a variable for initiating the count to 0."
},
{
"code": null,
"e": 32748,
"s": 32691,
"text": "We will create a variable for initiating the count to 0."
},
{
"code": null,
"e": 32833,
"s": 32748,
"text": "On the click of the button Show Image, we will increment the value of this variable."
},
{
"code": null,
"e": 32918,
"s": 32833,
"text": "On the click of the button Show Image, we will increment the value of this variable."
},
{
"code": null,
"e": 32955,
"s": 32918,
"text": "Display the value in the text label."
},
{
"code": null,
"e": 32992,
"s": 32955,
"text": "Display the value in the text label."
},
{
"code": null,
"e": 33107,
"s": 32992,
"text": "For this example, we will be creating a text below the Dynamic Panel. The text will read – Image is shown 0 times."
},
{
"code": null,
"e": 33233,
"s": 33107,
"text": "Critical − It is important that the labels are broken into three. Please follow the label names and text listed in the table."
},
{
"code": null,
"e": 33328,
"s": 33233,
"text": "This is required as we want to control the countLabel value for every Show Image button click."
},
{
"code": null,
"e": 33360,
"s": 33328,
"text": "Let us define a variable first."
},
{
"code": null,
"e": 33651,
"s": 33360,
"text": "We will need a variable, which will be controlled when the button is clicked. This variable in Axure’s terminology is − Global Variable. To define a global variable, click Project in the menu bar, and then click Global Variables. A dialog box will open as shown in the following screenshot."
},
{
"code": null,
"e": 33787,
"s": 33651,
"text": "Click the green plus (+) icon to add a global variable. Let us call our global variable − varDynamicPanel. Its default value will be 0."
},
{
"code": null,
"e": 33975,
"s": 33787,
"text": "With the Show Image button interactions, double-click on Case 1. Add another action. As shown in the following screenshot, the action is Set Text on countLabel to [[varDynamicPanel + 1]]."
},
{
"code": null,
"e": 34090,
"s": 33975,
"text": "Selecting a text label to a value is pretty straightforward. Let us see how to get the value from a dynamic panel."
},
{
"code": null,
"e": 34197,
"s": 34090,
"text": "As indicated by step 4 in the above screenshot, click fx button and the following dialog box will open up."
},
{
"code": null,
"e": 34252,
"s": 34197,
"text": "Under the first text area, enter the following string."
},
{
"code": null,
"e": 34277,
"s": 34252,
"text": "[[varDynamicPanel + 1]]\n"
},
{
"code": null,
"e": 34287,
"s": 34277,
"text": "Click OK."
},
{
"code": null,
"e": 34365,
"s": 34287,
"text": "Now, we need to ensure that the variable is updated after every button click."
},
{
"code": null,
"e": 34450,
"s": 34365,
"text": "In the case editor dialog box, under actions, select Variables → Set Variable Value."
},
{
"code": null,
"e": 34494,
"s": 34450,
"text": "Select the varDynamicPanel as the variable."
},
{
"code": null,
"e": 34592,
"s": 34494,
"text": "Set the variable to fetch value from the text on widget as countLabel from the available options."
},
{
"code": null,
"e": 34658,
"s": 34592,
"text": "Close the Case Editor by clicking OK. Then, click Preview button."
},
{
"code": null,
"e": 34743,
"s": 34658,
"text": "After showing/hiding image for four times, here is the result on the preview screen."
},
{
"code": null,
"e": 34912,
"s": 34743,
"text": "Now that you are well-versed with different interactions and events that are possible in Axure, you may want to extend your work in order to minimize efforts in future."
},
{
"code": null,
"e": 35178,
"s": 34912,
"text": "For instance, the very first example with Classic Menu – Horizontal, was once present in Axure versions as a combination of different available widgets. This means, Axure evolved with time to accommodate frequently used widgets in the form of single widget library."
},
{
"code": null,
"e": 35352,
"s": 35178,
"text": "The concept of widget library is applicable more prominently in large UX teams. Some organizations keep approved widgets for subsequent UX engineers on a central repository."
},
{
"code": null,
"e": 35502,
"s": 35352,
"text": "Thus, in a nutshell, Axure Widget Library is a collection of custom widgets stored in a single file. The file type for Axure Widget Library is RPLIB."
},
{
"code": null,
"e": 35680,
"s": 35502,
"text": "These libraries are accessible from Libraries pane. These libraries can’t be updated/removed. For most of the complex prototyping needs, Axure built-in libraries come to rescue."
},
{
"code": null,
"e": 35828,
"s": 35680,
"text": "The library consists of 17 unique flow widgets, which are used primarily for diagram creation. Also, there are 25 widgets in the wireframe library."
},
{
"code": null,
"e": 35903,
"s": 35828,
"text": "A brief functioning of libraries is present in Chapter 3 − User Interface."
},
{
"code": null,
"e": 36078,
"s": 35903,
"text": "Axure community, growing day-by-day in size, has a vast collection of user-created libraries. You can visit them at − https://www.axure.com/support/download-widget-libraries."
},
{
"code": null,
"e": 36210,
"s": 36078,
"text": "The UX professionals from all around the world, who are committed to make this community grow, submit their work on the above link."
},
{
"code": null,
"e": 36404,
"s": 36210,
"text": "You can download the libraries from the website and add them to Axure using Load Library option under libraries. Also, you can directly download libraries from the application interface itself."
},
{
"code": null,
"e": 36688,
"s": 36404,
"text": "As shown in the above screen, we have a context menu, where you can download different libraries as offered on https://www.axure.com/support/download-widget-libraries. You can also create your own library, which will be handy while creating repetitive controls for a given prototype."
},
{
"code": null,
"e": 36816,
"s": 36688,
"text": "The complete instructions to download/load libraries is available at: https://www.axure.com/support/reference/widget-libraries."
},
{
"code": null,
"e": 37066,
"s": 36816,
"text": "When it comes to using a custom widget from one of your loaded libraries, drag and drop it in the design area similar to the built-in widgets. If the widget includes variables or a custom style, the Import Wizard dialog would flag such dependencies."
},
{
"code": null,
"e": 37310,
"s": 37066,
"text": "Among such dependencies, you may notice there are certain incompatible styles that come along with the widget library being imported. You may choose to Cancel and import only the widgets or click the Finish button to import the entire package."
},
{
"code": null,
"e": 37812,
"s": 37310,
"text": "Once you drag and drop a widget into your wireframe, that particular instance is no longer associated with its original widget library. Thus, edits and changes made to widgets in the imported widget library are not applied to any of the instances of these widgets in your project file, even after you refresh the library. Rest assured, once imported, you can utilize the widgets in the imported library without worrying about the updates that take place in the same widget library as available online."
},
{
"code": null,
"e": 38050,
"s": 37812,
"text": "Using an Axure RP Library file is pretty straightforward. When you download a library, the icon for library file (.rplib) is clearly distinguished from the Axure RP prototype file (.rp). For instance, as seen in the following screenshot."
},
{
"code": null,
"e": 38148,
"s": 38050,
"text": "The mechanism for this to work - You can import the iOS Wireframe document in iOS Wireframe Demo."
},
{
"code": null,
"e": 38422,
"s": 38148,
"text": "This library can be used for multiple projects and updates in the library file will be available once you Refresh the library from the context menu. As highlighted earlier, this comes very handy when working on a team project and distributing the libraries in this fashion."
},
{
"code": null,
"e": 38674,
"s": 38422,
"text": "Axure RP 8 supports collaboration with the feature − Team Projects. This feature is not only beneficial for the distributed teams but also for the single user. The benefit to the single user is the ability to create versioning on the work in progress."
},
{
"code": null,
"e": 38887,
"s": 38674,
"text": "In the Team Projects scenario, each team member has a copy of the project on their computer. This project will be synced with a shared repository. This shared repository is connected to other members of the team."
},
{
"code": null,
"e": 39106,
"s": 38887,
"text": "After the course of a day's work, each team member will create new elements, check out files, and generally edit the project. Check Out is a commonly used term for indicating the work in progress for a particular file."
},
{
"code": null,
"e": 39384,
"s": 39106,
"text": "The changes will not be reflected in the shared repository until the team member checks in all their checked out elements. The Manage Team Project console provides all team members with a real-time view of the availability status of the elements that are managed by the system."
},
{
"code": null,
"e": 39473,
"s": 39384,
"text": "This view provides the details of an element that is checked out by another team member."
},
{
"code": null,
"e": 39638,
"s": 39473,
"text": "For working with or creating a team project, head over to the Team menu. Click Team and then select Create Team Project from Current File. Following screen pops up."
},
{
"code": null,
"e": 39858,
"s": 39638,
"text": "Available options for hosting a team project are − using AxShare and SVN. We will discuss AxShare in the next section. SVN is the commonly used Version Controlling System, which provides a server to host your documents."
},
{
"code": null,
"e": 40048,
"s": 39858,
"text": "Follow the on-screen guidelines for creating a team project and then you will be able to start collaborating with a single Axure file across the team/use it for your own historical storage."
},
{
"code": null,
"e": 40252,
"s": 40048,
"text": "When it comes to showcasing your prototype, there are multiple options available as per the environment you are in. Most commonly used method to export your prototype is to use Axure Share (aka AxShare)."
},
{
"code": null,
"e": 40325,
"s": 40252,
"text": "With Axure Share, the following collaboration capabilities are possible."
},
{
"code": null,
"e": 40416,
"s": 40325,
"text": "Prototypes can be hosted on Axure Share and shared with the involved team members/clients."
},
{
"code": null,
"e": 40507,
"s": 40416,
"text": "Prototypes can be hosted on Axure Share and shared with the involved team members/clients."
},
{
"code": null,
"e": 40610,
"s": 40507,
"text": "With the discussion/comments feature, you can get the on-the-go inputs on the prototype in the making."
},
{
"code": null,
"e": 40713,
"s": 40610,
"text": "With the discussion/comments feature, you can get the on-the-go inputs on the prototype in the making."
},
{
"code": null,
"e": 40872,
"s": 40713,
"text": "Once you are ready with the prototype, you can upload the prototype to AxShare using Publish → Publish to Axure Share. Following dialog box will be displayed."
},
{
"code": null,
"e": 41049,
"s": 40872,
"text": "You must create an account at AxShare.com in order to progress ahead. If you already have an account, you can use the ‘Log In’ option to log in and upload your work to AxShare."
},
{
"code": null,
"e": 41202,
"s": 41049,
"text": "The uploaded data is in HTML, CSS, and JavaScript. Once uploaded, you are provided with a link, which you can provide to the intended stakeholders/team."
},
{
"code": null,
"e": 41209,
"s": 41202,
"text": " Print"
},
{
"code": null,
"e": 41220,
"s": 41209,
"text": " Add Notes"
}
] |
Change your way to put logic in your code - Python - GeeksforGeeks
|
28 May, 2020
Aren’t you bored coding in the same traditional logic over these years. It’s time to bring some differences. Well, be it any programming language. When we are asked to do some sort of basic programming exercises like sorting, searching, prime number checking, etc. we are all driven towards the same boat, which is the same coding logic. Now, we are in the past 2020, so let’s also take an initiative to change our thinking styles when it comes to coding. It is because, only if we think differently, we can code differently.
Lets dive deep into those wonderful coding tips.
Of course, what a simple question. We can easily check for even or odd using the modulus operator. You want to know how? Just see the below Python code snippet –
Python3
a = 4 if(a % 2 == 0): print("even")else: print("odd")
Output:
even
Here, the modulus operation is used to determine the remainder obtained. All even numbers are divisible by 2. That means, upon dividing an even number say 4 with 2, we will obtain the remainder as 0. So applying modulus operation between the two numbers will leave the answer as 0. This basic principle is always applied to programming whenever we are asked to check for odd and even numbers.
Can you think it differently? We all have taught our brains the logic that dividing a number by 2 determines whether it’s odd or even. And that line of code is followed traditionally by all those who code. So let’s start excavating an evergreen, but the unused method .
Python3
a = 4 if(a & 1): print("odd")else: print("even")
Output:
even
This was done using bitwise AND operation. Cool enough!
Bitwise operators are operating on integers bit by bit. This is done by converting the integers into binary and then performing logical AND operation on each of the corresponding bits.
Note: For more information, refer to Python Bitwise Operators
Those numbers which are divisible by 1 and that number only are called prime numbers. Examples for prime numbers are 2, 3, 5, 7, etc. which do not have any other factors(excluding themselves and 1). We all have been taught about the below logic for checking the prime numbers.
Python3
a = 10 if a>1: for i in range(2, (a//2)+1): if a % i == 0: print(a, "is not prime ") break else: print(a, "is prime ")else: print(a, "is not prime ")
Output:
10 is not prime
But we can optimize it even more. And it will look like:
Python3
a = 10i = 2 if a>1: while(i * i<a): if a % i == 0: print(a, "is not prime ") break else: print(a, "is prime ") i += 1else: print(a, "is not prime ")
Output:
10 is not prime
Both the codes are correct and output the same result. But the second code is more optimized because to check for factors, it is sufficient to loop till the square root of the given number instead of checking until its half.
In the above code, we are checking for the factors of a given number. And after each iteration, we have to increment the value of the loop variable ‘i’. It functions till i^2 less than the given number.
This can be coded easily in any language by basic mathematical steps. So the steps are:
Assign a value, say 5 to a variable ‘k’
Then, we have to store the value of 2^5 in another variable j.
Multiply the contents of both k and j.
Display the output .(Here 160 will be the resultant output)
This can be coded in a few lines and the code is as follows:
Python3
k = 5j = 2**kp = k * j print(p)
Output:
160
But there is another method which is much simpler and efficient. That is by using shift-operator. Left shift operation on the variable k, k times will result in the same function as displayed above. So the optimized code will become:
Python3
k = 5 print(k<<k)
Output:
160
Both these will result in the same output.
The dividing function also works similar to the multiply function. Only the operator changes. So the steps for dividing a number by 2^k are listed below:
Assign a value, say 5 to a variable ‘k’
Then, we have to store the value of 2^5 in another variable j.
Divide the contents of both k and j.
Display the output .(Here 160 will be the resultant output)
The Python 3 code for basic division is as follows:
Python3
k = 5j = 2**k p = k//j print(p)
Output:
0
We can use ‘//’ for integer division and ‘/’ for floor division as per our requirement.And the optimized code using right shift operation will look like :
Python3
k = 5 print(k>>k)
Output:
0
Both the codes will result in the output ‘0’(integer division).
Note: For more information, refer to Python Bitwise Operators.
All these operations already existed since history. But we forgot to practice using them. For our changing future, let’s adopt these small changes and become a part of it.
python-basics
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n28 May, 2020"
},
{
"code": null,
"e": 24819,
"s": 24292,
"text": "Aren’t you bored coding in the same traditional logic over these years. It’s time to bring some differences. Well, be it any programming language. When we are asked to do some sort of basic programming exercises like sorting, searching, prime number checking, etc. we are all driven towards the same boat, which is the same coding logic. Now, we are in the past 2020, so let’s also take an initiative to change our thinking styles when it comes to coding. It is because, only if we think differently, we can code differently. "
},
{
"code": null,
"e": 24869,
"s": 24819,
"text": " Lets dive deep into those wonderful coding tips."
},
{
"code": null,
"e": 25032,
"s": 24869,
"text": "Of course, what a simple question. We can easily check for even or odd using the modulus operator. You want to know how? Just see the below Python code snippet – "
},
{
"code": null,
"e": 25040,
"s": 25032,
"text": "Python3"
},
{
"code": "a = 4 if(a % 2 == 0): print(\"even\")else: print(\"odd\")",
"e": 25101,
"s": 25040,
"text": null
},
{
"code": null,
"e": 25109,
"s": 25101,
"text": "Output:"
},
{
"code": null,
"e": 25115,
"s": 25109,
"text": "even\n"
},
{
"code": null,
"e": 25508,
"s": 25115,
"text": "Here, the modulus operation is used to determine the remainder obtained. All even numbers are divisible by 2. That means, upon dividing an even number say 4 with 2, we will obtain the remainder as 0. So applying modulus operation between the two numbers will leave the answer as 0. This basic principle is always applied to programming whenever we are asked to check for odd and even numbers."
},
{
"code": null,
"e": 25778,
"s": 25508,
"text": "Can you think it differently? We all have taught our brains the logic that dividing a number by 2 determines whether it’s odd or even. And that line of code is followed traditionally by all those who code. So let’s start excavating an evergreen, but the unused method ."
},
{
"code": null,
"e": 25786,
"s": 25778,
"text": "Python3"
},
{
"code": "a = 4 if(a & 1): print(\"odd\")else: print(\"even\")",
"e": 25844,
"s": 25786,
"text": null
},
{
"code": null,
"e": 25852,
"s": 25844,
"text": "Output:"
},
{
"code": null,
"e": 25859,
"s": 25852,
"text": "even\n\n"
},
{
"code": null,
"e": 25915,
"s": 25859,
"text": "This was done using bitwise AND operation. Cool enough!"
},
{
"code": null,
"e": 26104,
"s": 25915,
"text": "Bitwise operators are operating on integers bit by bit. This is done by converting the integers into binary and then performing logical AND operation on each of the corresponding bits."
},
{
"code": null,
"e": 26166,
"s": 26104,
"text": "Note: For more information, refer to Python Bitwise Operators"
},
{
"code": null,
"e": 26443,
"s": 26166,
"text": "Those numbers which are divisible by 1 and that number only are called prime numbers. Examples for prime numbers are 2, 3, 5, 7, etc. which do not have any other factors(excluding themselves and 1). We all have been taught about the below logic for checking the prime numbers."
},
{
"code": null,
"e": 26451,
"s": 26443,
"text": "Python3"
},
{
"code": "a = 10 if a>1: for i in range(2, (a//2)+1): if a % i == 0: print(a, \"is not prime \") break else: print(a, \"is prime \")else: print(a, \"is not prime \")",
"e": 26681,
"s": 26451,
"text": null
},
{
"code": null,
"e": 26689,
"s": 26681,
"text": "Output:"
},
{
"code": null,
"e": 26707,
"s": 26689,
"text": "10 is not prime \n"
},
{
"code": null,
"e": 26764,
"s": 26707,
"text": "But we can optimize it even more. And it will look like:"
},
{
"code": null,
"e": 26772,
"s": 26764,
"text": "Python3"
},
{
"code": "a = 10i = 2 if a>1: while(i * i<a): if a % i == 0: print(a, \"is not prime \") break else: print(a, \"is prime \") i += 1else: print(a, \"is not prime \")",
"e": 27008,
"s": 26772,
"text": null
},
{
"code": null,
"e": 27016,
"s": 27008,
"text": "Output:"
},
{
"code": null,
"e": 27034,
"s": 27016,
"text": "10 is not prime \n"
},
{
"code": null,
"e": 27259,
"s": 27034,
"text": "Both the codes are correct and output the same result. But the second code is more optimized because to check for factors, it is sufficient to loop till the square root of the given number instead of checking until its half."
},
{
"code": null,
"e": 27462,
"s": 27259,
"text": "In the above code, we are checking for the factors of a given number. And after each iteration, we have to increment the value of the loop variable ‘i’. It functions till i^2 less than the given number."
},
{
"code": null,
"e": 27550,
"s": 27462,
"text": "This can be coded easily in any language by basic mathematical steps. So the steps are:"
},
{
"code": null,
"e": 27590,
"s": 27550,
"text": "Assign a value, say 5 to a variable ‘k’"
},
{
"code": null,
"e": 27653,
"s": 27590,
"text": "Then, we have to store the value of 2^5 in another variable j."
},
{
"code": null,
"e": 27692,
"s": 27653,
"text": "Multiply the contents of both k and j."
},
{
"code": null,
"e": 27752,
"s": 27692,
"text": "Display the output .(Here 160 will be the resultant output)"
},
{
"code": null,
"e": 27813,
"s": 27752,
"text": "This can be coded in a few lines and the code is as follows:"
},
{
"code": null,
"e": 27821,
"s": 27813,
"text": "Python3"
},
{
"code": "k = 5j = 2**kp = k * j print(p)",
"e": 27854,
"s": 27821,
"text": null
},
{
"code": null,
"e": 27862,
"s": 27854,
"text": "Output:"
},
{
"code": null,
"e": 27866,
"s": 27862,
"text": "160"
},
{
"code": null,
"e": 28100,
"s": 27866,
"text": "But there is another method which is much simpler and efficient. That is by using shift-operator. Left shift operation on the variable k, k times will result in the same function as displayed above. So the optimized code will become:"
},
{
"code": null,
"e": 28108,
"s": 28100,
"text": "Python3"
},
{
"code": "k = 5 print(k<<k)",
"e": 28127,
"s": 28108,
"text": null
},
{
"code": null,
"e": 28135,
"s": 28127,
"text": "Output:"
},
{
"code": null,
"e": 28139,
"s": 28135,
"text": "160"
},
{
"code": null,
"e": 28182,
"s": 28139,
"text": "Both these will result in the same output."
},
{
"code": null,
"e": 28336,
"s": 28182,
"text": "The dividing function also works similar to the multiply function. Only the operator changes. So the steps for dividing a number by 2^k are listed below:"
},
{
"code": null,
"e": 28376,
"s": 28336,
"text": "Assign a value, say 5 to a variable ‘k’"
},
{
"code": null,
"e": 28439,
"s": 28376,
"text": "Then, we have to store the value of 2^5 in another variable j."
},
{
"code": null,
"e": 28476,
"s": 28439,
"text": "Divide the contents of both k and j."
},
{
"code": null,
"e": 28536,
"s": 28476,
"text": "Display the output .(Here 160 will be the resultant output)"
},
{
"code": null,
"e": 28588,
"s": 28536,
"text": "The Python 3 code for basic division is as follows:"
},
{
"code": null,
"e": 28596,
"s": 28588,
"text": "Python3"
},
{
"code": "k = 5j = 2**k p = k//j print(p)",
"e": 28630,
"s": 28596,
"text": null
},
{
"code": null,
"e": 28638,
"s": 28630,
"text": "Output:"
},
{
"code": null,
"e": 28640,
"s": 28638,
"text": "0"
},
{
"code": null,
"e": 28795,
"s": 28640,
"text": "We can use ‘//’ for integer division and ‘/’ for floor division as per our requirement.And the optimized code using right shift operation will look like :"
},
{
"code": null,
"e": 28803,
"s": 28795,
"text": "Python3"
},
{
"code": "k = 5 print(k>>k)",
"e": 28822,
"s": 28803,
"text": null
},
{
"code": null,
"e": 28830,
"s": 28822,
"text": "Output:"
},
{
"code": null,
"e": 28832,
"s": 28830,
"text": "0"
},
{
"code": null,
"e": 28897,
"s": 28832,
"text": "Both the codes will result in the output ‘0’(integer division). "
},
{
"code": null,
"e": 28960,
"s": 28897,
"text": "Note: For more information, refer to Python Bitwise Operators."
},
{
"code": null,
"e": 29132,
"s": 28960,
"text": "All these operations already existed since history. But we forgot to practice using them. For our changing future, let’s adopt these small changes and become a part of it."
},
{
"code": null,
"e": 29146,
"s": 29132,
"text": "python-basics"
},
{
"code": null,
"e": 29161,
"s": 29146,
"text": "python-utility"
},
{
"code": null,
"e": 29168,
"s": 29161,
"text": "Python"
},
{
"code": null,
"e": 29266,
"s": 29168,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29298,
"s": 29266,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29354,
"s": 29298,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 29396,
"s": 29354,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 29438,
"s": 29396,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 29460,
"s": 29438,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 29499,
"s": 29460,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 29530,
"s": 29499,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 29585,
"s": 29530,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 29614,
"s": 29585,
"text": "Create a directory in Python"
}
] |
IntStream mapToDouble() method in Java
|
The mapToDouble() method returns a DoubleStream consisting of the results of applying the given function to the elements of this stream.
The syntax is as follows.
DoubleStream mapToDouble(IntToDoubleFunction mapper)
Here, the parameter mapper is the stateless function applied to each element.
Create an IntStream with some elements.
IntStream intStream = IntStream.of(5, 20, 25, 45, 60, 75, 85, 90);
Now, use the mapToDouble() method to return a DoubleStream.
DoubleStream doubleStream = intStream.mapToDouble(val -> (double) val);
The following is an example to implement IntStream mapToDouble() method in Java.
Live Demo
import java.util.*;
import java.util.stream.IntStream;
import java.util.stream.DoubleStream;
public class Demo {
public static void main(String[] args) {
IntStream intStream = IntStream.of(5, 20, 25, 45, 60, 75, 85, 90);
DoubleStream doubleStream = intStream.mapToDouble(val -> (double) val);
doubleStream.forEach(System.out::println);
}
}
5.0
20.0
25.0
45.0
60.0
75.0
85.0
90.0
|
[
{
"code": null,
"e": 1199,
"s": 1062,
"text": "The mapToDouble() method returns a DoubleStream consisting of the results of applying the given function to the elements of this stream."
},
{
"code": null,
"e": 1225,
"s": 1199,
"text": "The syntax is as follows."
},
{
"code": null,
"e": 1278,
"s": 1225,
"text": "DoubleStream mapToDouble(IntToDoubleFunction mapper)"
},
{
"code": null,
"e": 1356,
"s": 1278,
"text": "Here, the parameter mapper is the stateless function applied to each element."
},
{
"code": null,
"e": 1396,
"s": 1356,
"text": "Create an IntStream with some elements."
},
{
"code": null,
"e": 1463,
"s": 1396,
"text": "IntStream intStream = IntStream.of(5, 20, 25, 45, 60, 75, 85, 90);"
},
{
"code": null,
"e": 1523,
"s": 1463,
"text": "Now, use the mapToDouble() method to return a DoubleStream."
},
{
"code": null,
"e": 1595,
"s": 1523,
"text": "DoubleStream doubleStream = intStream.mapToDouble(val -> (double) val);"
},
{
"code": null,
"e": 1676,
"s": 1595,
"text": "The following is an example to implement IntStream mapToDouble() method in Java."
},
{
"code": null,
"e": 1687,
"s": 1676,
"text": " Live Demo"
},
{
"code": null,
"e": 2051,
"s": 1687,
"text": "import java.util.*;\nimport java.util.stream.IntStream;\nimport java.util.stream.DoubleStream;\npublic class Demo {\n public static void main(String[] args) {\n IntStream intStream = IntStream.of(5, 20, 25, 45, 60, 75, 85, 90);\n DoubleStream doubleStream = intStream.mapToDouble(val -> (double) val);\n doubleStream.forEach(System.out::println);\n }\n}"
},
{
"code": null,
"e": 2090,
"s": 2051,
"text": "5.0\n20.0\n25.0\n45.0\n60.0\n75.0\n85.0\n90.0"
}
] |
Create a password generator using shell scripting - GeeksforGeeks
|
19 Jul, 2019
Creating a strong password is often a time-consuming task and even after creating a good password by yourself it gets brute-forced by hackers. In this article, we will learn how to create a strong password which fulfills all requirements including symbols, capitals length etc using a simple shell script in Linux.
How to create a password generator using shell script ?This a simple short and quick method, just open the nano editor with .sh file using this command –
nano passwdgen.sh
You can use any name of the file.
#!/bin/bash # this can be anything of your choiceecho "Welcome to simple password generator" # ask the user how much long should beecho "please enter the length of the password" # read the input given by user and store in variableread PASS_LENGTH # loop will create 5 passwords according to# user as per length given by user for p in $(seq 1 5); do openssl rand -base64 48 | cut -c1-$PASS_LENGTH done
Save the file and give executable permission using sudo chmod +x command and run the script.
Output:
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
nohup Command in Linux with Examples
scp command in Linux with Examples
Thread functions in C/C++
mv command in Linux with examples
chown command in Linux with Examples
SED command in Linux | Set 2
Docker - COPY Instruction
Array Basics in Shell Scripting | Set 1
Basic Operators in Shell Scripting
nslookup command in Linux with Examples
|
[
{
"code": null,
"e": 24406,
"s": 24378,
"text": "\n19 Jul, 2019"
},
{
"code": null,
"e": 24721,
"s": 24406,
"text": "Creating a strong password is often a time-consuming task and even after creating a good password by yourself it gets brute-forced by hackers. In this article, we will learn how to create a strong password which fulfills all requirements including symbols, capitals length etc using a simple shell script in Linux."
},
{
"code": null,
"e": 24875,
"s": 24721,
"text": "How to create a password generator using shell script ?This a simple short and quick method, just open the nano editor with .sh file using this command –"
},
{
"code": null,
"e": 24893,
"s": 24875,
"text": "nano passwdgen.sh"
},
{
"code": null,
"e": 24927,
"s": 24893,
"text": "You can use any name of the file."
},
{
"code": "#!/bin/bash # this can be anything of your choiceecho \"Welcome to simple password generator\" # ask the user how much long should beecho \"please enter the length of the password\" # read the input given by user and store in variableread PASS_LENGTH # loop will create 5 passwords according to# user as per length given by user for p in $(seq 1 5); do openssl rand -base64 48 | cut -c1-$PASS_LENGTH done",
"e": 25398,
"s": 24927,
"text": null
},
{
"code": null,
"e": 25491,
"s": 25398,
"text": "Save the file and give executable permission using sudo chmod +x command and run the script."
},
{
"code": null,
"e": 25499,
"s": 25491,
"text": "Output:"
},
{
"code": null,
"e": 25510,
"s": 25499,
"text": "Linux-Unix"
},
{
"code": null,
"e": 25608,
"s": 25510,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25645,
"s": 25608,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 25680,
"s": 25645,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 25706,
"s": 25680,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 25740,
"s": 25706,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 25777,
"s": 25740,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 25806,
"s": 25777,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 25832,
"s": 25806,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 25872,
"s": 25832,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 25907,
"s": 25872,
"text": "Basic Operators in Shell Scripting"
}
] |
JavaScript - The Boolean Object
|
The Boolean object represents two values, either "true" or "false". If value parameter is omitted or is 0, -0, null, false, NaN, undefined, or the empty string (""), the object has an initial value of false.
Use the following syntax to create a boolean object.
var val = new Boolean(value);
Here is a list of the properties of Boolean object −
Returns a reference to the Boolean function that created the object.
The prototype property allows you to add properties and methods to an object.
In the following sections, we will have a few examples to illustrate the properties of Boolean object.
Here is a list of the methods of Boolean object and their description.
Returns a string containing the source of the Boolean object; you can use this string to create an equivalent object.
Returns a string of either "true" or "false" depending upon the value of the object.
Returns the primitive value of the Boolean object.
In the following sections, we will have a few examples to demonstrate the usage of the Boolean methods.
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": 2674,
"s": 2466,
"text": "The Boolean object represents two values, either \"true\" or \"false\". If value parameter is omitted or is 0, -0, null, false, NaN, undefined, or the empty string (\"\"), the object has an initial value of false."
},
{
"code": null,
"e": 2727,
"s": 2674,
"text": "Use the following syntax to create a boolean object."
},
{
"code": null,
"e": 2758,
"s": 2727,
"text": "var val = new Boolean(value);\n"
},
{
"code": null,
"e": 2811,
"s": 2758,
"text": "Here is a list of the properties of Boolean object −"
},
{
"code": null,
"e": 2880,
"s": 2811,
"text": "Returns a reference to the Boolean function that created the object."
},
{
"code": null,
"e": 2958,
"s": 2880,
"text": "The prototype property allows you to add properties and methods to an object."
},
{
"code": null,
"e": 3061,
"s": 2958,
"text": "In the following sections, we will have a few examples to illustrate the properties of Boolean object."
},
{
"code": null,
"e": 3132,
"s": 3061,
"text": "Here is a list of the methods of Boolean object and their description."
},
{
"code": null,
"e": 3250,
"s": 3132,
"text": "Returns a string containing the source of the Boolean object; you can use this string to create an equivalent object."
},
{
"code": null,
"e": 3335,
"s": 3250,
"text": "Returns a string of either \"true\" or \"false\" depending upon the value of the object."
},
{
"code": null,
"e": 3386,
"s": 3335,
"text": "Returns the primitive value of the Boolean object."
},
{
"code": null,
"e": 3490,
"s": 3386,
"text": "In the following sections, we will have a few examples to demonstrate the usage of the Boolean methods."
},
{
"code": null,
"e": 3525,
"s": 3490,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3539,
"s": 3525,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3573,
"s": 3539,
"text": "\n 74 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 3587,
"s": 3573,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3622,
"s": 3587,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3639,
"s": 3622,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3674,
"s": 3639,
"text": "\n 70 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3691,
"s": 3674,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3724,
"s": 3691,
"text": "\n 46 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3752,
"s": 3724,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3786,
"s": 3752,
"text": "\n 88 Lectures \n 14 hours \n"
},
{
"code": null,
"e": 3814,
"s": 3786,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3821,
"s": 3814,
"text": " Print"
},
{
"code": null,
"e": 3832,
"s": 3821,
"text": " Add Notes"
}
] |
C++ Program to calculate the value of sin(x) and cos(x)
|
Given with the input as angles and the task is to calculate the value of sin(x) and cos(x) corresponding to the given angle and display the result
Sin(x) is a trigonometric function which is used to calculate the value of x angle.
sin(x)=∑k=0∞(−1)k(2k+1)!x2k+1
Cos(x) is a trigonometric function which is used to calculate the value of x angle.
cos(x)=∑k=0∞(−1)k(2k)!x2k
Approach used in the below program is as follows −
Input the value of x angle for sin(x) and cos(x)
Apply the formulas given for sin(x) and cos(x)
Print the result
START
Step 1-> declare function to calculate value of sin
void cal_sin(float n)
declare and set float acc = 0.0001, denominator, sinx, sinval
Set n = n * (3.142 / 180.0)
Declare float temp = n
Set sinx = n
Set sinval = sin(n)
Declare and set int i = 1
DO
set denominator = 2 * i * (2 * i + 1)
set temp = -temp * n * n / denominator
Set sinx = sinx + temp
Set i = i + 1
While(acc <= fabs(sinval - sinx))
print sinx
Step 2-> Declare function to calculate value of cos
void cal_cos(float n)
Declare and set float acc = 0.0001, temp, denominator, cosx, cosval
Set n = n * (3.142 / 180.0)
Set temp = 1
set cosx = temp
set cosval = cos(n)
Set int i = 1
Do
set denominator = 2 * i * (2 * i - 1)
Set temp = -temp * n * n / denominator
Set cosx = cosx + temp
Set i = i + 1
While(acc <= fabs(cosval - cosx))
print cosx
Step 3-> In main()
Declare float n = 30
Call cal_sin(n0
set n=60
Call cal_cos(n)
STOP
#include <iostream>
#include <math.h>
using namespace std;
//calculate value of sin
void cal_sin(float n) {
float acc = 0.0001, denominator, sinx, sinval;
n = n * (3.142 / 180.0); //convert in radian
float temp = n;
sinx = n;
sinval = sin(n);
int i = 1;
do {
denominator = 2 * i * (2 * i + 1);
temp = -temp * n * n / denominator;
sinx = sinx + temp;
i = i + 1;
} while (acc <= fabs(sinval - sinx));
cout<<sinx;
}
//calculate value of cos
void cal_cos(float n) {
float acc = 0.0001, temp, denominator, cosx, cosval;
n = n * (3.142 / 180.0); //convert in radiam
temp = 1;
cosx = temp;
cosval = cos(n);
int i = 1;
do {
denominator = 2 * i * (2 * i - 1);
temp = -temp * n * n / denominator;
cosx = cosx + temp;
i = i + 1;
} while (acc <= fabs(cosval - cosx));
cout<< cosx;
}
int main() {
float n = 30;
cout<<"value of Sin is : "; cal_sin(n);
cout<<"\n";
n=60;
cout<<"value of Cos is : ";
cal_cos(n);
return 0;
}
value of Sin is : 0.500061
value of Cos is : 0.499847
|
[
{
"code": null,
"e": 1209,
"s": 1062,
"text": "Given with the input as angles and the task is to calculate the value of sin(x) and cos(x) corresponding to the given angle and display the result"
},
{
"code": null,
"e": 1293,
"s": 1209,
"text": "Sin(x) is a trigonometric function which is used to calculate the value of x angle."
},
{
"code": null,
"e": 1324,
"s": 1293,
"text": "sin(x)=∑k=0∞(−1)k(2k+1)!x2k+1"
},
{
"code": null,
"e": 1408,
"s": 1324,
"text": "Cos(x) is a trigonometric function which is used to calculate the value of x angle."
},
{
"code": null,
"e": 1435,
"s": 1408,
"text": "cos(x)=∑k=0∞(−1)k(2k)!x2k"
},
{
"code": null,
"e": 1486,
"s": 1435,
"text": "Approach used in the below program is as follows −"
},
{
"code": null,
"e": 1535,
"s": 1486,
"text": "Input the value of x angle for sin(x) and cos(x)"
},
{
"code": null,
"e": 1582,
"s": 1535,
"text": "Apply the formulas given for sin(x) and cos(x)"
},
{
"code": null,
"e": 1599,
"s": 1582,
"text": "Print the result"
},
{
"code": null,
"e": 2620,
"s": 1599,
"text": "START\nStep 1-> declare function to calculate value of sin\n void cal_sin(float n)\n declare and set float acc = 0.0001, denominator, sinx, sinval\n Set n = n * (3.142 / 180.0)\n Declare float temp = n\n Set sinx = n\n Set sinval = sin(n)\n Declare and set int i = 1\n DO\n set denominator = 2 * i * (2 * i + 1)\n set temp = -temp * n * n / denominator\n Set sinx = sinx + temp\n Set i = i + 1\n While(acc <= fabs(sinval - sinx))\n print sinx\nStep 2-> Declare function to calculate value of cos\n void cal_cos(float n)\n Declare and set float acc = 0.0001, temp, denominator, cosx, cosval\n Set n = n * (3.142 / 180.0)\n Set temp = 1\n set cosx = temp\n set cosval = cos(n)\n Set int i = 1\n Do\n set denominator = 2 * i * (2 * i - 1)\n Set temp = -temp * n * n / denominator\n Set cosx = cosx + temp\n Set i = i + 1\n While(acc <= fabs(cosval - cosx))\n print cosx\nStep 3-> In main()\n Declare float n = 30\n Call cal_sin(n0\n set n=60\n Call cal_cos(n)\nSTOP"
},
{
"code": null,
"e": 3711,
"s": 2620,
"text": "#include <iostream>\n#include <math.h>\nusing namespace std;\n//calculate value of sin\nvoid cal_sin(float n) { \n float acc = 0.0001, denominator, sinx, sinval;\n n = n * (3.142 / 180.0); //convert in radian\n float temp = n;\n sinx = n; \n sinval = sin(n); \n int i = 1;\n do {\n denominator = 2 * i * (2 * i + 1);\n temp = -temp * n * n / denominator;\n sinx = sinx + temp;\n i = i + 1;\n } while (acc <= fabs(sinval - sinx));\n cout<<sinx;\n}\n//calculate value of cos \nvoid cal_cos(float n) {\n float acc = 0.0001, temp, denominator, cosx, cosval;\n n = n * (3.142 / 180.0); //convert in radiam\n temp = 1;\n cosx = temp; \n cosval = cos(n);\n int i = 1;\n do {\n denominator = 2 * i * (2 * i - 1);\n temp = -temp * n * n / denominator;\n cosx = cosx + temp;\n i = i + 1;\n } while (acc <= fabs(cosval - cosx));\n cout<< cosx;\n}\nint main() {\n float n = 30;\n cout<<\"value of Sin is : \"; cal_sin(n);\ncout<<\"\\n\";\n n=60;\ncout<<\"value of Cos is : \";\ncal_cos(n);\n return 0;\n}"
},
{
"code": null,
"e": 3765,
"s": 3711,
"text": "value of Sin is : 0.500061\nvalue of Cos is : 0.499847"
}
] |
How to get the value of System Property and Environment Variable in Java? - GeeksforGeeks
|
08 Nov, 2019
The System class in Java provides a method named System.getenv() which can be used to get the value of an environment variable set in the current system.
Syntax:
public static String getenv(String key);
where key is the Environment variable
whose values we want
Below example illustrates how to use System.getenv() to get the System environment variable:
Example 1: To get the value of a specific environment variable
// Java program to get the value// of a specific environment variable// using System.getenv() method public class GFG { public static void main(String[] args) { // Get the value of // the TEMP environment variable System.out.println(System.getenv("TEMP")); // Get the value of // the OS environment variable System.out.println(System.getenv("OS")); // Get the value of // the JAVA_HOME environment variable System.out.println(System.getenv("JAVA_HOME")); }}
Output:
Example 2: To get the value of all environment variables at once
// Java program to get the value// of all environment variables at once// using System.getenv() method import java.util.Map; public class GFG { public static void main(String[] args) { // Get the value of // all environment variables at once // and store it in Map Map<String, String> env = System.getenv(); for (String envName : env.keySet()) { System.out.format("%s=%s%n", envName, env.get(envName)); } }}
Output:
Note: The output will depend on the system on which you run the above code. A sample output is given above
The System class in Java has two methods used to read system properties:
java.lang.System.getProperty(String key): fetches only those properties – values that you will specify using the key(associated to that particular value that you want).Example:// Java Program illustrating the working// of getProperty(String key) method import java.lang.*;import java.util.Properties; public class NewClass { public static void main(String[] args) { // Printing Name of the system property System.out.println("user.dir: " + System.getProperty( "user.dir")); // Fetches the property set with 'home' key System.out.println("home: " + System.getProperty( "home")); // Resulting in Null as no property is present // Printing 'name of Operating System' System.out.println("os.name: " + System.getProperty( "os.name")); // Printing 'JAVA Runtime version' System.out.println("version: " + System.getProperty( "java.runtime.version")); // Printing 'name' property System.out.println("name: " + System.getProperty( "name")); // Resulting in Null as no property is present }}Output:user.dir: /tmp/hsperfdata_bot
home: null
os.name: Linux
version: 1.8.0_101-b13
name: null
Example:
// Java Program illustrating the working// of getProperty(String key) method import java.lang.*;import java.util.Properties; public class NewClass { public static void main(String[] args) { // Printing Name of the system property System.out.println("user.dir: " + System.getProperty( "user.dir")); // Fetches the property set with 'home' key System.out.println("home: " + System.getProperty( "home")); // Resulting in Null as no property is present // Printing 'name of Operating System' System.out.println("os.name: " + System.getProperty( "os.name")); // Printing 'JAVA Runtime version' System.out.println("version: " + System.getProperty( "java.runtime.version")); // Printing 'name' property System.out.println("name: " + System.getProperty( "name")); // Resulting in Null as no property is present }}
Output:
user.dir: /tmp/hsperfdata_bot
home: null
os.name: Linux
version: 1.8.0_101-b13
name: null
java.lang.System.getProperty(String key, String definition): helps you to create your own key-value sets that you want.Example:// Java Program illustrating the working of// getProperty(String key, String definition) method import java.lang.*;import java.util.Properties; public class NewClass { public static void main(String[] args) { // Here key = "Hello" and // System Property = "Geeks" System.out.println("Hello property : " + System.getProperty( "Hello", "Geeks")); // Here key = "Geek" and // System Property = "For Geeks" System.out.println("System-property :" + System.getProperty( "System", "For Geeks")); // Here key = "Property" and // System Property = null System.out.println("Property-property :" + System.getProperty( "Property")); }}Output:Hello key property : Geeks
System key property :For Geeks
Property key property :null
Example:
// Java Program illustrating the working of// getProperty(String key, String definition) method import java.lang.*;import java.util.Properties; public class NewClass { public static void main(String[] args) { // Here key = "Hello" and // System Property = "Geeks" System.out.println("Hello property : " + System.getProperty( "Hello", "Geeks")); // Here key = "Geek" and // System Property = "For Geeks" System.out.println("System-property :" + System.getProperty( "System", "For Geeks")); // Here key = "Property" and // System Property = null System.out.println("Property-property :" + System.getProperty( "Property")); }}
Output:
Hello key property : Geeks
System key property :For Geeks
Property key property :null
java.lang.System.getProperties(): fetches all the properties – values that the JVM on your System gets from the Operating System.Example:// Java Program illustrating the working of// getProperties() method public class GFG { public static void main(String[] args) { System.out.println(System.getProperties()) }}Output:
Example:
// Java Program illustrating the working of// getProperties() method public class GFG { public static void main(String[] args) { System.out.println(System.getProperties()) }}
Output:
ManasChhabra2
java-basics
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize an ArrayList in Java
HashMap in Java with Examples
Object Oriented Programming (OOPs) Concept in Java
Interfaces in Java
ArrayList in Java
Convert a String to Character array in Java
Initializing a List in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
|
[
{
"code": null,
"e": 25032,
"s": 25004,
"text": "\n08 Nov, 2019"
},
{
"code": null,
"e": 25186,
"s": 25032,
"text": "The System class in Java provides a method named System.getenv() which can be used to get the value of an environment variable set in the current system."
},
{
"code": null,
"e": 25194,
"s": 25186,
"text": "Syntax:"
},
{
"code": null,
"e": 25296,
"s": 25194,
"text": "public static String getenv(String key);\n\nwhere key is the Environment variable\nwhose values we want\n"
},
{
"code": null,
"e": 25389,
"s": 25296,
"text": "Below example illustrates how to use System.getenv() to get the System environment variable:"
},
{
"code": null,
"e": 25452,
"s": 25389,
"text": "Example 1: To get the value of a specific environment variable"
},
{
"code": "// Java program to get the value// of a specific environment variable// using System.getenv() method public class GFG { public static void main(String[] args) { // Get the value of // the TEMP environment variable System.out.println(System.getenv(\"TEMP\")); // Get the value of // the OS environment variable System.out.println(System.getenv(\"OS\")); // Get the value of // the JAVA_HOME environment variable System.out.println(System.getenv(\"JAVA_HOME\")); }}",
"e": 25989,
"s": 25452,
"text": null
},
{
"code": null,
"e": 25997,
"s": 25989,
"text": "Output:"
},
{
"code": null,
"e": 26062,
"s": 25997,
"text": "Example 2: To get the value of all environment variables at once"
},
{
"code": "// Java program to get the value// of all environment variables at once// using System.getenv() method import java.util.Map; public class GFG { public static void main(String[] args) { // Get the value of // all environment variables at once // and store it in Map Map<String, String> env = System.getenv(); for (String envName : env.keySet()) { System.out.format(\"%s=%s%n\", envName, env.get(envName)); } }}",
"e": 26607,
"s": 26062,
"text": null
},
{
"code": null,
"e": 26615,
"s": 26607,
"text": "Output:"
},
{
"code": null,
"e": 26722,
"s": 26615,
"text": "Note: The output will depend on the system on which you run the above code. A sample output is given above"
},
{
"code": null,
"e": 26795,
"s": 26722,
"text": "The System class in Java has two methods used to read system properties:"
},
{
"code": null,
"e": 28267,
"s": 26795,
"text": "java.lang.System.getProperty(String key): fetches only those properties – values that you will specify using the key(associated to that particular value that you want).Example:// Java Program illustrating the working// of getProperty(String key) method import java.lang.*;import java.util.Properties; public class NewClass { public static void main(String[] args) { // Printing Name of the system property System.out.println(\"user.dir: \" + System.getProperty( \"user.dir\")); // Fetches the property set with 'home' key System.out.println(\"home: \" + System.getProperty( \"home\")); // Resulting in Null as no property is present // Printing 'name of Operating System' System.out.println(\"os.name: \" + System.getProperty( \"os.name\")); // Printing 'JAVA Runtime version' System.out.println(\"version: \" + System.getProperty( \"java.runtime.version\")); // Printing 'name' property System.out.println(\"name: \" + System.getProperty( \"name\")); // Resulting in Null as no property is present }}Output:user.dir: /tmp/hsperfdata_bot\nhome: null\nos.name: Linux\nversion: 1.8.0_101-b13\nname: null\n"
},
{
"code": null,
"e": 28276,
"s": 28267,
"text": "Example:"
},
{
"code": "// Java Program illustrating the working// of getProperty(String key) method import java.lang.*;import java.util.Properties; public class NewClass { public static void main(String[] args) { // Printing Name of the system property System.out.println(\"user.dir: \" + System.getProperty( \"user.dir\")); // Fetches the property set with 'home' key System.out.println(\"home: \" + System.getProperty( \"home\")); // Resulting in Null as no property is present // Printing 'name of Operating System' System.out.println(\"os.name: \" + System.getProperty( \"os.name\")); // Printing 'JAVA Runtime version' System.out.println(\"version: \" + System.getProperty( \"java.runtime.version\")); // Printing 'name' property System.out.println(\"name: \" + System.getProperty( \"name\")); // Resulting in Null as no property is present }}",
"e": 29475,
"s": 28276,
"text": null
},
{
"code": null,
"e": 29483,
"s": 29475,
"text": "Output:"
},
{
"code": null,
"e": 29574,
"s": 29483,
"text": "user.dir: /tmp/hsperfdata_bot\nhome: null\nos.name: Linux\nversion: 1.8.0_101-b13\nname: null\n"
},
{
"code": null,
"e": 30672,
"s": 29574,
"text": "java.lang.System.getProperty(String key, String definition): helps you to create your own key-value sets that you want.Example:// Java Program illustrating the working of// getProperty(String key, String definition) method import java.lang.*;import java.util.Properties; public class NewClass { public static void main(String[] args) { // Here key = \"Hello\" and // System Property = \"Geeks\" System.out.println(\"Hello property : \" + System.getProperty( \"Hello\", \"Geeks\")); // Here key = \"Geek\" and // System Property = \"For Geeks\" System.out.println(\"System-property :\" + System.getProperty( \"System\", \"For Geeks\")); // Here key = \"Property\" and // System Property = null System.out.println(\"Property-property :\" + System.getProperty( \"Property\")); }}Output:Hello key property : Geeks\nSystem key property :For Geeks\nProperty key property :null\n"
},
{
"code": null,
"e": 30681,
"s": 30672,
"text": "Example:"
},
{
"code": "// Java Program illustrating the working of// getProperty(String key, String definition) method import java.lang.*;import java.util.Properties; public class NewClass { public static void main(String[] args) { // Here key = \"Hello\" and // System Property = \"Geeks\" System.out.println(\"Hello property : \" + System.getProperty( \"Hello\", \"Geeks\")); // Here key = \"Geek\" and // System Property = \"For Geeks\" System.out.println(\"System-property :\" + System.getProperty( \"System\", \"For Geeks\")); // Here key = \"Property\" and // System Property = null System.out.println(\"Property-property :\" + System.getProperty( \"Property\")); }}",
"e": 31559,
"s": 30681,
"text": null
},
{
"code": null,
"e": 31567,
"s": 31559,
"text": "Output:"
},
{
"code": null,
"e": 31654,
"s": 31567,
"text": "Hello key property : Geeks\nSystem key property :For Geeks\nProperty key property :null\n"
},
{
"code": null,
"e": 31992,
"s": 31654,
"text": "java.lang.System.getProperties(): fetches all the properties – values that the JVM on your System gets from the Operating System.Example:// Java Program illustrating the working of// getProperties() method public class GFG { public static void main(String[] args) { System.out.println(System.getProperties()) }}Output:"
},
{
"code": null,
"e": 32001,
"s": 31992,
"text": "Example:"
},
{
"code": "// Java Program illustrating the working of// getProperties() method public class GFG { public static void main(String[] args) { System.out.println(System.getProperties()) }}",
"e": 32195,
"s": 32001,
"text": null
},
{
"code": null,
"e": 32203,
"s": 32195,
"text": "Output:"
},
{
"code": null,
"e": 32217,
"s": 32203,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 32229,
"s": 32217,
"text": "java-basics"
},
{
"code": null,
"e": 32236,
"s": 32229,
"text": "Picked"
},
{
"code": null,
"e": 32241,
"s": 32236,
"text": "Java"
},
{
"code": null,
"e": 32255,
"s": 32241,
"text": "Java Programs"
},
{
"code": null,
"e": 32260,
"s": 32255,
"text": "Java"
},
{
"code": null,
"e": 32358,
"s": 32260,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32390,
"s": 32358,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 32420,
"s": 32390,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 32471,
"s": 32420,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 32490,
"s": 32471,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 32508,
"s": 32490,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 32552,
"s": 32508,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 32580,
"s": 32552,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 32606,
"s": 32580,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 32640,
"s": 32606,
"text": "Convert Double to Integer in Java"
}
] |
Changing three.js background to transparent or another color in HTML
|
If you want a transparent background in three.js, you need a pass in the alpha parameter to the WebGLRenderer constructors in the below-given code −
var renderer = new THREE.WebGLRenderer( {alpha: true } );
// You can leave the clear color at the defaultvalue.
renderer.setClearColor( 0x000000, 0 ); //default
However, to set the background color,
renderer.setClearColor(0xb0f442 );
|
[
{
"code": null,
"e": 1211,
"s": 1062,
"text": "If you want a transparent background in three.js, you need a pass in the alpha parameter to the WebGLRenderer constructors in the below-given code −"
},
{
"code": null,
"e": 1372,
"s": 1211,
"text": "var renderer = new THREE.WebGLRenderer( {alpha: true } );\n// You can leave the clear color at the defaultvalue.\nrenderer.setClearColor( 0x000000, 0 ); //default"
},
{
"code": null,
"e": 1410,
"s": 1372,
"text": "However, to set the background color,"
},
{
"code": null,
"e": 1445,
"s": 1410,
"text": "renderer.setClearColor(0xb0f442 );"
}
] |
Subarray/Substring vs Subsequence and Programs to Generate them - GeeksforGeeks
|
09 May, 2022
Subarray/Substring
A subarray is a contiguous part of array. An array that is inside another array. For example, consider the array [1, 2, 3, 4], There are 10 non-empty sub-arrays. The subarrays are (1), (2), (3), (4), (1,2), (2,3), (3,4), (1,2,3), (2,3,4) and (1,2,3,4). In general, for an array/string of size n, there are n*(n+1)/2 non-empty subarrays/substrings.
How to generate all subarrays? We can run two nested loops, the outer loop picks starting element and inner loop considers all elements on right of the picked elements as ending element of subarray.
C++
Java
Python3
C#
PHP
Javascript
/* C++ code to generate all possible subarrays/subArrays Complexity- O(n^3) */#include<bits/stdc++.h>using namespace std; // Prints all subarrays in arr[0..n-1]void subArray(int arr[], int n){ // Pick starting point for (int i=0; i <n; i++) { // Pick ending point for (int j=i; j<n; j++) { // Print subarray between current starting // and ending points for (int k=i; k<=j; k++) cout << arr[k] << " "; cout << endl; } }} // Driver programint main(){ int arr[] = {1, 2, 3, 4}; int n = sizeof(arr)/sizeof(arr[0]); cout << "All Non-empty Subarrays\n"; subArray(arr, n); return 0;}
// Java program to generate all possible subarrays/subArrays// Complexity- O(n^3) */ class Test{ static int arr[] = new int[]{1, 2, 3, 4}; // Prints all subarrays in arr[0..n-1] static void subArray( int n) { // Pick starting point for (int i=0; i <n; i++) { // Pick ending point for (int j=i; j<n; j++) { // Print subarray between current starting // and ending points for (int k=i; k<=j; k++) System.out.print(arr[k]+" "); } } } // Driver method to test the above function public static void main(String[] args) { System.out.println("All Non-empty Subarrays"); subArray(arr.length); }}
# Python3 code to generate all possible# subarrays/subArrays# Complexity- O(n^3) # Prints all subarrays in arr[0..n-1]def subArray(arr, n): # Pick starting point for i in range(0,n): # Pick ending point for j in range(i,n): # Print subarray between # current starting # and ending points for k in range(i,j+1): print (arr[k],end=" ") print ("\n",end="") # Driver programarr = [1, 2, 3, 4]n = len(arr)print ("All Non-empty Subarrays") subArray(arr, n); # This code is contributed by Shreyanshi.
// C# program to generate all// possible subarrays/subArrays// Complexity- O(n^3)using System; class GFG{ static int []arr = new int[]{1, 2, 3, 4}; // Prints all subarrays in arr[0..n-1] static void subArray( int n) { // Pick starting point for (int i = 0; i < n; i++) { // Pick ending point for (int j = i; j < n; j++) { // Print subarray between current // starting and ending points for (int k = i; k <= j; k++) Console.Write(arr[k]+" "); Console.WriteLine(""); } } } // Driver Code public static void Main() { Console.WriteLine("All Non-empty Subarrays"); subArray(arr.Length); } } // This code is contributed by Sam007.
<?php// PHP code to generate all possible// subarrays/subArrays Complexity- O(n^3) // Prints all subarrays// in arr[0..n-1]function subArray($arr, $n){ // Pick starting point for ($i = 0; $i < $n; $i++) { // Pick ending point for ($j = $i; $j < $n; $j++) { // Print subarray between // current starting // and ending points for ($k = $i; $k <= $j; $k++) echo $arr[$k] , " "; echo "\n"; } }} // Driver Code $arr= array(1, 2, 3, 4); $n = sizeof($arr); echo "All Non-empty Subarrays\n"; subArray($arr, $n); // This code is contributed by m_kit?>
<script> // Javascript program to generate all// possible subarrays/subArrays// Complexity- O(n^3)let arr = [1, 2, 3, 4]; // Prints all subarrays in arr[0..n-1]function subArray(n){ // Pick starting point for(let i = 0; i < n; i++) { // Pick ending point for(let j = i; j < n; j++) { // Print subarray between current // starting and ending points for(let k = i; k <= j; k++) document.write(arr[k] + " "); document.write("</br>"); } }} // Driver codedocument.write("All Non-empty Subarrays" + "</br>"); subArray(arr.length); // This code is contributed by suresh07 </script>
Output:
All Non-empty Subarrays
1
1 2
1 2 3
1 2 3 4
2
2 3
2 3 4
3
3 4
4
Time Complexity: 0(n^3)
Space Complexity: 0(1)
Subsequence A subsequence is a sequence that can be derived from another sequence by removing zero or more elements, without changing the order of the remaining elements. For the same example, there are 15 sub-sequences. They are (1), (2), (3), (4), (1,2), (1,3),(1,4), (2,3), (2,4), (3,4), (1,2,3), (1,2,4), (1,3,4), (2,3,4), (1,2,3,4). More generally, we can say that for a sequence of size n, we can have (2n-1) non-empty sub-sequences in total. A string example to differentiate: Consider strings “geeksforgeeks” and “gks”. “gks” is a subsequence of “geeksforgeeks” but not a substring. “geeks” is both a subsequence and subarray. Every subarray is a subsequence. More specifically, Subsequence is a generalization of substring.
A subarray or substring will always be contiguous, but a subsequence need not be contiguous. That is, subsequences are not required to occupy consecutive positions within the original sequences. But we can say that both contiguous subsequence and subarray are the same.
How to generate all Subsequences? We can use algorithm to generate power set for generation of all subsequences.
C++
Java
Python3
C#
PHP
Javascript
/* C++ code to generate all possible subsequences. Time Complexity O(n * 2^n) */#include<bits/stdc++.h>using namespace std; void printSubsequences(int arr[], int n){ /* Number of subsequences is (2**n -1)*/ unsigned int opsize = pow(2, n); /* Run from counter 000..1 to 111..1*/ for (int counter = 1; counter < opsize; counter++) { for (int j = 0; j < n; j++) { /* Check if jth bit in the counter is set If set then print jth element from arr[] */ if (counter & (1<<j)) cout << arr[j] << " "; } cout << endl; }} // Driver programint main(){ int arr[] = {1, 2, 3, 4}; int n = sizeof(arr)/sizeof(arr[0]); cout << "All Non-empty Subsequences\n"; printSubsequences(arr, n); return 0;}
/* Java code to generate all possible subsequences. Time Complexity O(n * 2^n) */ import java.math.BigInteger; class Test{ static int arr[] = new int[]{1, 2, 3, 4}; static void printSubsequences(int n) { /* Number of subsequences is (2**n -1)*/ int opsize = (int)Math.pow(2, n); /* Run from counter 000..1 to 111..1*/ for (int counter = 1; counter < opsize; counter++) { for (int j = 0; j < n; j++) { /* Check if jth bit in the counter is set If set then print jth element from arr[] */ if (BigInteger.valueOf(counter).testBit(j)) System.out.print(arr[j]+" "); } System.out.println(); } } // Driver method to test the above function public static void main(String[] args) { System.out.println("All Non-empty Subsequences"); printSubsequences(arr.length); }}
# Python3 code to generate all# possible subsequences.# Time Complexity O(n * 2 ^ n)import math def printSubsequences(arr, n) : # Number of subsequences is (2**n -1) opsize = math.pow(2, n) # Run from counter 000..1 to 111..1 for counter in range( 1, (int)(opsize)) : for j in range(0, n) : # Check if jth bit in the counter # is set If set then print jth # element from arr[] if (counter & (1<<j)) : print( arr[j], end =" ") print() # Driver programarr = [1, 2, 3, 4]n = len(arr)print( "All Non-empty Subsequences") printSubsequences(arr, n) # This code is contributed by Nikita Tiwari.
// C# code to generate all possible subsequences.// Time Complexity O(n * 2^n)using System; class GFG{ static void printSubsequences(int[] arr, int n){ // Number of subsequences is (2**n -1) int opsize = (int)Math.Pow(2, n); // Run from counter 000..1 to 111..1 for(int counter = 1; counter < opsize; counter++) { for(int j = 0; j < n; j++) { // Check if jth bit in the counter is set // If set then print jth element from arr[] if ((counter & (1 << j)) != 0) Console.Write(arr[j] + " "); } Console.WriteLine(); }} // Driver Codestatic void Main(){ int[] arr = { 1, 2, 3, 4 }; int n = arr.Length; Console.WriteLine("All Non-empty Subsequences"); printSubsequences(arr, n);}} // This code is contributed by divyesh072019
<?php// PHP code to generate all// possible subsequences.// Time Complexity O(n * 2^n) function printSubsequences($arr, $n){ // Number of subsequences // is (2**n -1) $opsize = pow(2, $n); /* Run from counter 000..1 to 111..1*/ for ($counter = 1; $counter < $opsize; $counter++) { for ( $j = 0; $j < $n; $j++) { /* Check if jth bit in the counter is set If set then print jth element from arr[] */ if ($counter & (1 << $j)) echo $arr[$j], " "; } echo "\n"; }} // Driver Code$arr = array (1, 2, 3, 4);$n = sizeof($arr); echo "All Non-empty Subsequences\n"; printSubsequences($arr, $n); // This code is contributed by ajit?>
<script> // Javascript code to generate all possible subsequences. // Time Complexity O(n * 2^n) function printSubsequences(arr, n) { // Number of subsequences is (2**n -1) let opsize = parseInt(Math.pow(2, n), 10); // Run from counter 000..1 to 111..1 for(let counter = 1; counter < opsize; counter++) { for(let j = 0; j < n; j++) { // Check if jth bit in the counter is set // If set then print jth element from arr[] if ((counter & (1 << j)) != 0) document.write(arr[j] + " "); } document.write("</br>"); } } let arr = [ 1, 2, 3, 4 ]; let n = arr.length; document.write("All Non-empty Subsequences" + "</br>"); printSubsequences(arr, n); // This code is contributed by divyeshrabadiya07.</script>
Output:
All Non-empty Subsequences
1
2
1 2
3
1 3
2 3
1 2 3
4
1 4
2 4
1 2 4
3 4
1 3 4
2 3 4
1 2 3 4
Time Complexity: 0(n*(2^n))
Space Complexity: 0(1)This article is contributed by Harshit Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Sam007
jit_t
ancientone
divyesh072019
suresh07
divyeshrabadiya07
sweetyty
interview_rev
guptameetanshi25
surinderdawra388
kapilag
subsequence
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Arrays in C/C++
Write a program to reverse an array or string
Program for array rotation
Top 50 Array Coding Problems for Interviews
Largest Sum Contiguous Subarray
Stack Data Structure (Introduction and Program)
Introduction to Arrays
Multidimensional Arrays in Java
|
[
{
"code": null,
"e": 42631,
"s": 42603,
"text": "\n09 May, 2022"
},
{
"code": null,
"e": 42650,
"s": 42631,
"text": "Subarray/Substring"
},
{
"code": null,
"e": 42999,
"s": 42650,
"text": "A subarray is a contiguous part of array. An array that is inside another array. For example, consider the array [1, 2, 3, 4], There are 10 non-empty sub-arrays. The subarrays are (1), (2), (3), (4), (1,2), (2,3), (3,4), (1,2,3), (2,3,4) and (1,2,3,4). In general, for an array/string of size n, there are n*(n+1)/2 non-empty subarrays/substrings. "
},
{
"code": null,
"e": 43199,
"s": 42999,
"text": "How to generate all subarrays? We can run two nested loops, the outer loop picks starting element and inner loop considers all elements on right of the picked elements as ending element of subarray. "
},
{
"code": null,
"e": 43203,
"s": 43199,
"text": "C++"
},
{
"code": null,
"e": 43208,
"s": 43203,
"text": "Java"
},
{
"code": null,
"e": 43216,
"s": 43208,
"text": "Python3"
},
{
"code": null,
"e": 43219,
"s": 43216,
"text": "C#"
},
{
"code": null,
"e": 43223,
"s": 43219,
"text": "PHP"
},
{
"code": null,
"e": 43234,
"s": 43223,
"text": "Javascript"
},
{
"code": "/* C++ code to generate all possible subarrays/subArrays Complexity- O(n^3) */#include<bits/stdc++.h>using namespace std; // Prints all subarrays in arr[0..n-1]void subArray(int arr[], int n){ // Pick starting point for (int i=0; i <n; i++) { // Pick ending point for (int j=i; j<n; j++) { // Print subarray between current starting // and ending points for (int k=i; k<=j; k++) cout << arr[k] << \" \"; cout << endl; } }} // Driver programint main(){ int arr[] = {1, 2, 3, 4}; int n = sizeof(arr)/sizeof(arr[0]); cout << \"All Non-empty Subarrays\\n\"; subArray(arr, n); return 0;}",
"e": 43931,
"s": 43234,
"text": null
},
{
"code": "// Java program to generate all possible subarrays/subArrays// Complexity- O(n^3) */ class Test{ static int arr[] = new int[]{1, 2, 3, 4}; // Prints all subarrays in arr[0..n-1] static void subArray( int n) { // Pick starting point for (int i=0; i <n; i++) { // Pick ending point for (int j=i; j<n; j++) { // Print subarray between current starting // and ending points for (int k=i; k<=j; k++) System.out.print(arr[k]+\" \"); } } } // Driver method to test the above function public static void main(String[] args) { System.out.println(\"All Non-empty Subarrays\"); subArray(arr.length); }}",
"e": 44716,
"s": 43931,
"text": null
},
{
"code": "# Python3 code to generate all possible# subarrays/subArrays# Complexity- O(n^3) # Prints all subarrays in arr[0..n-1]def subArray(arr, n): # Pick starting point for i in range(0,n): # Pick ending point for j in range(i,n): # Print subarray between # current starting # and ending points for k in range(i,j+1): print (arr[k],end=\" \") print (\"\\n\",end=\"\") # Driver programarr = [1, 2, 3, 4]n = len(arr)print (\"All Non-empty Subarrays\") subArray(arr, n); # This code is contributed by Shreyanshi.",
"e": 45317,
"s": 44716,
"text": null
},
{
"code": "// C# program to generate all// possible subarrays/subArrays// Complexity- O(n^3)using System; class GFG{ static int []arr = new int[]{1, 2, 3, 4}; // Prints all subarrays in arr[0..n-1] static void subArray( int n) { // Pick starting point for (int i = 0; i < n; i++) { // Pick ending point for (int j = i; j < n; j++) { // Print subarray between current // starting and ending points for (int k = i; k <= j; k++) Console.Write(arr[k]+\" \"); Console.WriteLine(\"\"); } } } // Driver Code public static void Main() { Console.WriteLine(\"All Non-empty Subarrays\"); subArray(arr.Length); } } // This code is contributed by Sam007.",
"e": 46196,
"s": 45317,
"text": null
},
{
"code": "<?php// PHP code to generate all possible// subarrays/subArrays Complexity- O(n^3) // Prints all subarrays// in arr[0..n-1]function subArray($arr, $n){ // Pick starting point for ($i = 0; $i < $n; $i++) { // Pick ending point for ($j = $i; $j < $n; $j++) { // Print subarray between // current starting // and ending points for ($k = $i; $k <= $j; $k++) echo $arr[$k] , \" \"; echo \"\\n\"; } }} // Driver Code $arr= array(1, 2, 3, 4); $n = sizeof($arr); echo \"All Non-empty Subarrays\\n\"; subArray($arr, $n); // This code is contributed by m_kit?>",
"e": 46897,
"s": 46196,
"text": null
},
{
"code": "<script> // Javascript program to generate all// possible subarrays/subArrays// Complexity- O(n^3)let arr = [1, 2, 3, 4]; // Prints all subarrays in arr[0..n-1]function subArray(n){ // Pick starting point for(let i = 0; i < n; i++) { // Pick ending point for(let j = i; j < n; j++) { // Print subarray between current // starting and ending points for(let k = i; k <= j; k++) document.write(arr[k] + \" \"); document.write(\"</br>\"); } }} // Driver codedocument.write(\"All Non-empty Subarrays\" + \"</br>\"); subArray(arr.length); // This code is contributed by suresh07 </script>",
"e": 47622,
"s": 46897,
"text": null
},
{
"code": null,
"e": 47631,
"s": 47622,
"text": "Output: "
},
{
"code": null,
"e": 47704,
"s": 47631,
"text": "All Non-empty Subarrays\n1 \n1 2 \n1 2 3 \n1 2 3 4 \n2 \n2 3 \n2 3 4 \n3 \n3 4 \n4"
},
{
"code": null,
"e": 47728,
"s": 47704,
"text": "Time Complexity: 0(n^3)"
},
{
"code": null,
"e": 47751,
"s": 47728,
"text": "Space Complexity: 0(1)"
},
{
"code": null,
"e": 48484,
"s": 47751,
"text": "Subsequence A subsequence is a sequence that can be derived from another sequence by removing zero or more elements, without changing the order of the remaining elements. For the same example, there are 15 sub-sequences. They are (1), (2), (3), (4), (1,2), (1,3),(1,4), (2,3), (2,4), (3,4), (1,2,3), (1,2,4), (1,3,4), (2,3,4), (1,2,3,4). More generally, we can say that for a sequence of size n, we can have (2n-1) non-empty sub-sequences in total. A string example to differentiate: Consider strings “geeksforgeeks” and “gks”. “gks” is a subsequence of “geeksforgeeks” but not a substring. “geeks” is both a subsequence and subarray. Every subarray is a subsequence. More specifically, Subsequence is a generalization of substring."
},
{
"code": null,
"e": 48754,
"s": 48484,
"text": "A subarray or substring will always be contiguous, but a subsequence need not be contiguous. That is, subsequences are not required to occupy consecutive positions within the original sequences. But we can say that both contiguous subsequence and subarray are the same."
},
{
"code": null,
"e": 48868,
"s": 48754,
"text": "How to generate all Subsequences? We can use algorithm to generate power set for generation of all subsequences. "
},
{
"code": null,
"e": 48872,
"s": 48868,
"text": "C++"
},
{
"code": null,
"e": 48877,
"s": 48872,
"text": "Java"
},
{
"code": null,
"e": 48885,
"s": 48877,
"text": "Python3"
},
{
"code": null,
"e": 48888,
"s": 48885,
"text": "C#"
},
{
"code": null,
"e": 48892,
"s": 48888,
"text": "PHP"
},
{
"code": null,
"e": 48903,
"s": 48892,
"text": "Javascript"
},
{
"code": "/* C++ code to generate all possible subsequences. Time Complexity O(n * 2^n) */#include<bits/stdc++.h>using namespace std; void printSubsequences(int arr[], int n){ /* Number of subsequences is (2**n -1)*/ unsigned int opsize = pow(2, n); /* Run from counter 000..1 to 111..1*/ for (int counter = 1; counter < opsize; counter++) { for (int j = 0; j < n; j++) { /* Check if jth bit in the counter is set If set then print jth element from arr[] */ if (counter & (1<<j)) cout << arr[j] << \" \"; } cout << endl; }} // Driver programint main(){ int arr[] = {1, 2, 3, 4}; int n = sizeof(arr)/sizeof(arr[0]); cout << \"All Non-empty Subsequences\\n\"; printSubsequences(arr, n); return 0;}",
"e": 49702,
"s": 48903,
"text": null
},
{
"code": "/* Java code to generate all possible subsequences. Time Complexity O(n * 2^n) */ import java.math.BigInteger; class Test{ static int arr[] = new int[]{1, 2, 3, 4}; static void printSubsequences(int n) { /* Number of subsequences is (2**n -1)*/ int opsize = (int)Math.pow(2, n); /* Run from counter 000..1 to 111..1*/ for (int counter = 1; counter < opsize; counter++) { for (int j = 0; j < n; j++) { /* Check if jth bit in the counter is set If set then print jth element from arr[] */ if (BigInteger.valueOf(counter).testBit(j)) System.out.print(arr[j]+\" \"); } System.out.println(); } } // Driver method to test the above function public static void main(String[] args) { System.out.println(\"All Non-empty Subsequences\"); printSubsequences(arr.length); }}",
"e": 50679,
"s": 49702,
"text": null
},
{
"code": "# Python3 code to generate all# possible subsequences.# Time Complexity O(n * 2 ^ n)import math def printSubsequences(arr, n) : # Number of subsequences is (2**n -1) opsize = math.pow(2, n) # Run from counter 000..1 to 111..1 for counter in range( 1, (int)(opsize)) : for j in range(0, n) : # Check if jth bit in the counter # is set If set then print jth # element from arr[] if (counter & (1<<j)) : print( arr[j], end =\" \") print() # Driver programarr = [1, 2, 3, 4]n = len(arr)print( \"All Non-empty Subsequences\") printSubsequences(arr, n) # This code is contributed by Nikita Tiwari.",
"e": 51376,
"s": 50679,
"text": null
},
{
"code": "// C# code to generate all possible subsequences.// Time Complexity O(n * 2^n)using System; class GFG{ static void printSubsequences(int[] arr, int n){ // Number of subsequences is (2**n -1) int opsize = (int)Math.Pow(2, n); // Run from counter 000..1 to 111..1 for(int counter = 1; counter < opsize; counter++) { for(int j = 0; j < n; j++) { // Check if jth bit in the counter is set // If set then print jth element from arr[] if ((counter & (1 << j)) != 0) Console.Write(arr[j] + \" \"); } Console.WriteLine(); }} // Driver Codestatic void Main(){ int[] arr = { 1, 2, 3, 4 }; int n = arr.Length; Console.WriteLine(\"All Non-empty Subsequences\"); printSubsequences(arr, n);}} // This code is contributed by divyesh072019",
"e": 52235,
"s": 51376,
"text": null
},
{
"code": "<?php// PHP code to generate all// possible subsequences.// Time Complexity O(n * 2^n) function printSubsequences($arr, $n){ // Number of subsequences // is (2**n -1) $opsize = pow(2, $n); /* Run from counter 000..1 to 111..1*/ for ($counter = 1; $counter < $opsize; $counter++) { for ( $j = 0; $j < $n; $j++) { /* Check if jth bit in the counter is set If set then print jth element from arr[] */ if ($counter & (1 << $j)) echo $arr[$j], \" \"; } echo \"\\n\"; }} // Driver Code$arr = array (1, 2, 3, 4);$n = sizeof($arr); echo \"All Non-empty Subsequences\\n\"; printSubsequences($arr, $n); // This code is contributed by ajit?>",
"e": 53014,
"s": 52235,
"text": null
},
{
"code": "<script> // Javascript code to generate all possible subsequences. // Time Complexity O(n * 2^n) function printSubsequences(arr, n) { // Number of subsequences is (2**n -1) let opsize = parseInt(Math.pow(2, n), 10); // Run from counter 000..1 to 111..1 for(let counter = 1; counter < opsize; counter++) { for(let j = 0; j < n; j++) { // Check if jth bit in the counter is set // If set then print jth element from arr[] if ((counter & (1 << j)) != 0) document.write(arr[j] + \" \"); } document.write(\"</br>\"); } } let arr = [ 1, 2, 3, 4 ]; let n = arr.length; document.write(\"All Non-empty Subsequences\" + \"</br>\"); printSubsequences(arr, n); // This code is contributed by divyeshrabadiya07.</script>",
"e": 53916,
"s": 53014,
"text": null
},
{
"code": null,
"e": 53925,
"s": 53916,
"text": "Output: "
},
{
"code": null,
"e": 54030,
"s": 53925,
"text": "All Non-empty Subsequences\n1 \n2 \n1 2 \n3 \n1 3 \n2 3 \n1 2 3 \n4 \n1 4 \n2 4 \n1 2 4 \n3 4 \n1 3 4 \n2 3 4 \n1 2 3 4"
},
{
"code": null,
"e": 54058,
"s": 54030,
"text": "Time Complexity: 0(n*(2^n))"
},
{
"code": null,
"e": 54472,
"s": 54058,
"text": "Space Complexity: 0(1)This article is contributed by Harshit Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 54479,
"s": 54472,
"text": "Sam007"
},
{
"code": null,
"e": 54485,
"s": 54479,
"text": "jit_t"
},
{
"code": null,
"e": 54496,
"s": 54485,
"text": "ancientone"
},
{
"code": null,
"e": 54510,
"s": 54496,
"text": "divyesh072019"
},
{
"code": null,
"e": 54519,
"s": 54510,
"text": "suresh07"
},
{
"code": null,
"e": 54537,
"s": 54519,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 54546,
"s": 54537,
"text": "sweetyty"
},
{
"code": null,
"e": 54560,
"s": 54546,
"text": "interview_rev"
},
{
"code": null,
"e": 54577,
"s": 54560,
"text": "guptameetanshi25"
},
{
"code": null,
"e": 54594,
"s": 54577,
"text": "surinderdawra388"
},
{
"code": null,
"e": 54602,
"s": 54594,
"text": "kapilag"
},
{
"code": null,
"e": 54614,
"s": 54602,
"text": "subsequence"
},
{
"code": null,
"e": 54621,
"s": 54614,
"text": "Arrays"
},
{
"code": null,
"e": 54628,
"s": 54621,
"text": "Arrays"
},
{
"code": null,
"e": 54726,
"s": 54628,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 54741,
"s": 54726,
"text": "Arrays in Java"
},
{
"code": null,
"e": 54757,
"s": 54741,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 54803,
"s": 54757,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 54830,
"s": 54803,
"text": "Program for array rotation"
},
{
"code": null,
"e": 54874,
"s": 54830,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 54906,
"s": 54874,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 54954,
"s": 54906,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 54977,
"s": 54954,
"text": "Introduction to Arrays"
}
] |
XLOOKUP Function in Excel With Examples - GeeksforGeeks
|
01 Jun, 2021
XLOOKUP Function helps us to search value in a horizontal or vertical dataset and return the relative value in some other row or column. In this article, we will look XLOOKUP Function in Excel.
Syntax:
=XLOOKUP(lookup_value, lookup_array, return_array, [if_not_found], [match_mode],[search_mode])
Parameter:
lookup_value: The value which we want to search
lookup_array: The range in which we want to search
if_not_found (Optional): The text which we want to return if the value is not found
match_mode (Optional): Here we can specify the type of match we want.
search_mode (Optional): where we can specify how the function should look up the value.
Example 1: To get a Lookup Value
Follow the below steps to Lookup a value:
Step 1: Format your data.
Now, if we want to get the math marks of Carry then follow the next step
Step 2: We will enter =XLOOKUP(E2,A2:A5,B2:B5) in F2 cell.
Then we will get the math marks of Carry.
Example 2: To Lookup and get the value of the entire row
Follow the below steps to lookup values of the entire row:
Step 1: Format your data.
Now, if we want to get the Math and English marks of Carry then follow next step
Step 2: We will enter =XLOOKUP(E2,A2:A5,B2:C5) in F2 cell.
Then we will get the Math and English marks.
Example 3: To get value using nested XLOOKUP function
Follow the below steps to use nested XLOOKUP functions:
Step 1: Format your data.
Now, if we want to get the math marks of Carry by two-way lookup then follow the next step.
Step 2: We will enter =XLOOKUP(F1,B1:C1,XLOOKUP(E2,A2:A5,B2:C5)) in F2 cell.
Here, XLOOKUP(E2,A2:A5,B2:C5) is{100,80} which is a array mark of Carry. In the outer XLOOKUP formula, we are looking for the subject name which is in F1 cell and the lookup array is B1:C1.
Then we will get the math marks of carry.
Example 4: When Lookup value is Not Found.
Follow the below steps when the LOOKUP function returns the Not Found message:
Step 1: Format your data.
If we want the marks of Sunny who is not in the dataset
Step 2: We will enter =XLOOKUP(E2,A2:A5,B2:B5,”Not Found”) in F2 cell.
Then it will show Not Found.
Example 5: To find the sum of a range using the SUM function.
Follow the below steps to find the sum of a range:
Step 1: Format your data.
If we want the total math marks from Harry to Jonny then do the next step
Step 2: We will enter =SUM(XLOOKUP(E2,A2:A5,B1:B6):XLOOKUP(F2,A2:A5,B1:B6)) in G2 cell this simply means =SUM($B$2:$B$5).
Then we will get the sum.
Example 6: Horizontal Lookup
Step 1: Format your data.
Now, if we want to get the math marks of Carry then follow the next step
Step 2: We will enter =XLOOKUP(B6,B1:E1,B2:E2) in B7 cell.
Then we will get the math marks of Carry
Picked
Excel
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Use Solver in Excel?
How to Find the Last Used Row and Column in Excel VBA?
How to Get Length of Array in Excel VBA?
Macros in Excel
How to Extract the Last Word From a Cell in Excel?
Using CHOOSE Function along with VLOOKUP in Excel
How to Remove Duplicates From Array Using VBA in Excel?
How to Show Percentages in Stacked Column Chart in Excel?
How to Calculate Deciles in Excel?
Introduction to Excel Spreadsheet
|
[
{
"code": null,
"e": 26425,
"s": 26397,
"text": "\n01 Jun, 2021"
},
{
"code": null,
"e": 26619,
"s": 26425,
"text": "XLOOKUP Function helps us to search value in a horizontal or vertical dataset and return the relative value in some other row or column. In this article, we will look XLOOKUP Function in Excel."
},
{
"code": null,
"e": 26627,
"s": 26619,
"text": "Syntax:"
},
{
"code": null,
"e": 26722,
"s": 26627,
"text": "=XLOOKUP(lookup_value, lookup_array, return_array, [if_not_found], [match_mode],[search_mode])"
},
{
"code": null,
"e": 26733,
"s": 26722,
"text": "Parameter:"
},
{
"code": null,
"e": 26781,
"s": 26733,
"text": "lookup_value: The value which we want to search"
},
{
"code": null,
"e": 26832,
"s": 26781,
"text": "lookup_array: The range in which we want to search"
},
{
"code": null,
"e": 26916,
"s": 26832,
"text": "if_not_found (Optional): The text which we want to return if the value is not found"
},
{
"code": null,
"e": 26986,
"s": 26916,
"text": "match_mode (Optional): Here we can specify the type of match we want."
},
{
"code": null,
"e": 27074,
"s": 26986,
"text": "search_mode (Optional): where we can specify how the function should look up the value."
},
{
"code": null,
"e": 27107,
"s": 27074,
"text": "Example 1: To get a Lookup Value"
},
{
"code": null,
"e": 27149,
"s": 27107,
"text": "Follow the below steps to Lookup a value:"
},
{
"code": null,
"e": 27175,
"s": 27149,
"text": "Step 1: Format your data."
},
{
"code": null,
"e": 27248,
"s": 27175,
"text": "Now, if we want to get the math marks of Carry then follow the next step"
},
{
"code": null,
"e": 27307,
"s": 27248,
"text": "Step 2: We will enter =XLOOKUP(E2,A2:A5,B2:B5) in F2 cell."
},
{
"code": null,
"e": 27349,
"s": 27307,
"text": "Then we will get the math marks of Carry."
},
{
"code": null,
"e": 27406,
"s": 27349,
"text": "Example 2: To Lookup and get the value of the entire row"
},
{
"code": null,
"e": 27465,
"s": 27406,
"text": "Follow the below steps to lookup values of the entire row:"
},
{
"code": null,
"e": 27491,
"s": 27465,
"text": "Step 1: Format your data."
},
{
"code": null,
"e": 27572,
"s": 27491,
"text": "Now, if we want to get the Math and English marks of Carry then follow next step"
},
{
"code": null,
"e": 27631,
"s": 27572,
"text": "Step 2: We will enter =XLOOKUP(E2,A2:A5,B2:C5) in F2 cell."
},
{
"code": null,
"e": 27676,
"s": 27631,
"text": "Then we will get the Math and English marks."
},
{
"code": null,
"e": 27730,
"s": 27676,
"text": "Example 3: To get value using nested XLOOKUP function"
},
{
"code": null,
"e": 27786,
"s": 27730,
"text": "Follow the below steps to use nested XLOOKUP functions:"
},
{
"code": null,
"e": 27812,
"s": 27786,
"text": "Step 1: Format your data."
},
{
"code": null,
"e": 27904,
"s": 27812,
"text": "Now, if we want to get the math marks of Carry by two-way lookup then follow the next step."
},
{
"code": null,
"e": 27981,
"s": 27904,
"text": "Step 2: We will enter =XLOOKUP(F1,B1:C1,XLOOKUP(E2,A2:A5,B2:C5)) in F2 cell."
},
{
"code": null,
"e": 28171,
"s": 27981,
"text": "Here, XLOOKUP(E2,A2:A5,B2:C5) is{100,80} which is a array mark of Carry. In the outer XLOOKUP formula, we are looking for the subject name which is in F1 cell and the lookup array is B1:C1."
},
{
"code": null,
"e": 28213,
"s": 28171,
"text": "Then we will get the math marks of carry."
},
{
"code": null,
"e": 28256,
"s": 28213,
"text": "Example 4: When Lookup value is Not Found."
},
{
"code": null,
"e": 28335,
"s": 28256,
"text": "Follow the below steps when the LOOKUP function returns the Not Found message:"
},
{
"code": null,
"e": 28361,
"s": 28335,
"text": "Step 1: Format your data."
},
{
"code": null,
"e": 28417,
"s": 28361,
"text": "If we want the marks of Sunny who is not in the dataset"
},
{
"code": null,
"e": 28488,
"s": 28417,
"text": "Step 2: We will enter =XLOOKUP(E2,A2:A5,B2:B5,”Not Found”) in F2 cell."
},
{
"code": null,
"e": 28517,
"s": 28488,
"text": "Then it will show Not Found."
},
{
"code": null,
"e": 28579,
"s": 28517,
"text": "Example 5: To find the sum of a range using the SUM function."
},
{
"code": null,
"e": 28630,
"s": 28579,
"text": "Follow the below steps to find the sum of a range:"
},
{
"code": null,
"e": 28656,
"s": 28630,
"text": "Step 1: Format your data."
},
{
"code": null,
"e": 28730,
"s": 28656,
"text": "If we want the total math marks from Harry to Jonny then do the next step"
},
{
"code": null,
"e": 28852,
"s": 28730,
"text": "Step 2: We will enter =SUM(XLOOKUP(E2,A2:A5,B1:B6):XLOOKUP(F2,A2:A5,B1:B6)) in G2 cell this simply means =SUM($B$2:$B$5)."
},
{
"code": null,
"e": 28878,
"s": 28852,
"text": "Then we will get the sum."
},
{
"code": null,
"e": 28907,
"s": 28878,
"text": "Example 6: Horizontal Lookup"
},
{
"code": null,
"e": 28933,
"s": 28907,
"text": "Step 1: Format your data."
},
{
"code": null,
"e": 29006,
"s": 28933,
"text": "Now, if we want to get the math marks of Carry then follow the next step"
},
{
"code": null,
"e": 29065,
"s": 29006,
"text": "Step 2: We will enter =XLOOKUP(B6,B1:E1,B2:E2) in B7 cell."
},
{
"code": null,
"e": 29106,
"s": 29065,
"text": "Then we will get the math marks of Carry"
},
{
"code": null,
"e": 29113,
"s": 29106,
"text": "Picked"
},
{
"code": null,
"e": 29119,
"s": 29113,
"text": "Excel"
},
{
"code": null,
"e": 29217,
"s": 29119,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29245,
"s": 29217,
"text": "How to Use Solver in Excel?"
},
{
"code": null,
"e": 29300,
"s": 29245,
"text": "How to Find the Last Used Row and Column in Excel VBA?"
},
{
"code": null,
"e": 29341,
"s": 29300,
"text": "How to Get Length of Array in Excel VBA?"
},
{
"code": null,
"e": 29357,
"s": 29341,
"text": "Macros in Excel"
},
{
"code": null,
"e": 29408,
"s": 29357,
"text": "How to Extract the Last Word From a Cell in Excel?"
},
{
"code": null,
"e": 29458,
"s": 29408,
"text": "Using CHOOSE Function along with VLOOKUP in Excel"
},
{
"code": null,
"e": 29514,
"s": 29458,
"text": "How to Remove Duplicates From Array Using VBA in Excel?"
},
{
"code": null,
"e": 29572,
"s": 29514,
"text": "How to Show Percentages in Stacked Column Chart in Excel?"
},
{
"code": null,
"e": 29607,
"s": 29572,
"text": "How to Calculate Deciles in Excel?"
}
] |
Is `definer` required when creating a MySQL stored procedure?
|
No, definer part is not compulsory when you are creating a stored procedure. It is used when you want to create a definer.
Check all the user and host from the MySQL.user table −
mysql> select user,host from mysql.user;
The following is the output −
+------------------+-----------+
| user | host |
+------------------+-----------+
| Manish | % |
| User2 | % |
| mysql.infoschema | % |
| mysql.session | % |
| mysql.sys | % |
| root | % |
| Adam Smith | localhost |
| User1 | localhost |
| am | localhost |
+------------------+-----------+
9 rows in set (0.03 sec)
Here, let us create a definer as Adam Smith. The query to create a stored procedure is as follows −
mysql> delimiter //
mysql> CREATE DEFINER = 'Adam Smith'@'localhost' procedure Sp_Definer()
-> begin
-> select 'Hello MySQL';
-> end;
-> //
Query OK, 0 rows affected (0.14 sec)
mysql> delimiter ;
Call the stored procedure using CALL command. The syntax is as follows −
CALL yourStoredProcedureName();
Call the above stored procedure.
mysql> call Sp_Definer();
The following is the output.
+-------------+
| Hello MySQL |
+-------------+
| Hello MySQL |
+-------------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.01 sec)
|
[
{
"code": null,
"e": 1185,
"s": 1062,
"text": "No, definer part is not compulsory when you are creating a stored procedure. It is used when you want to create a definer."
},
{
"code": null,
"e": 1241,
"s": 1185,
"text": "Check all the user and host from the MySQL.user table −"
},
{
"code": null,
"e": 1282,
"s": 1241,
"text": "mysql> select user,host from mysql.user;"
},
{
"code": null,
"e": 1312,
"s": 1282,
"text": "The following is the output −"
},
{
"code": null,
"e": 1766,
"s": 1312,
"text": "+------------------+-----------+\n| user | host |\n+------------------+-----------+\n| Manish | % |\n| User2 | % |\n| mysql.infoschema | % |\n| mysql.session | % |\n| mysql.sys | % |\n| root | % |\n| Adam Smith | localhost |\n| User1 | localhost |\n| am | localhost |\n+------------------+-----------+\n9 rows in set (0.03 sec)"
},
{
"code": null,
"e": 1866,
"s": 1766,
"text": "Here, let us create a definer as Adam Smith. The query to create a stored procedure is as follows −"
},
{
"code": null,
"e": 2074,
"s": 1866,
"text": "mysql> delimiter //\nmysql> CREATE DEFINER = 'Adam Smith'@'localhost' procedure Sp_Definer()\n -> begin\n -> select 'Hello MySQL';\n -> end;\n -> //\nQuery OK, 0 rows affected (0.14 sec)\nmysql> delimiter ;"
},
{
"code": null,
"e": 2147,
"s": 2074,
"text": "Call the stored procedure using CALL command. The syntax is as follows −"
},
{
"code": null,
"e": 2179,
"s": 2147,
"text": "CALL yourStoredProcedureName();"
},
{
"code": null,
"e": 2212,
"s": 2179,
"text": "Call the above stored procedure."
},
{
"code": null,
"e": 2238,
"s": 2212,
"text": "mysql> call Sp_Definer();"
},
{
"code": null,
"e": 2267,
"s": 2238,
"text": "The following is the output."
},
{
"code": null,
"e": 2408,
"s": 2267,
"text": "+-------------+\n| Hello MySQL |\n+-------------+\n| Hello MySQL |\n+-------------+\n1 row in set (0.00 sec)\nQuery OK, 0 rows affected (0.01 sec)"
}
] |
jQuery - Filer.js
|
Filer.js is a jQuery plugin for quickly and easily implementing of uploading files.
A Simple of filer.js example as shown below −
<html xmlns = "https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv = "Content-Type" content = "text/html; charset = utf-8" />
<link href = "css/jquery.filer.css" type = "text/css" rel = "stylesheet" />
<link href = "css/themes/jquery.filer-dragdropbox-theme.css"
type = "text/css" rel = "stylesheet" />
<!--jQuery-->
<script type = "text/javascript"
src = "https://code.jquery.com/jquery-latest.min.js">
</script>
<script type = "text/javascript" src = "js/jquery.filer.min.js"></script>
<script type = "text/javascript">
$(document).ready(function() {
$('#input1').filer();
$('.file_input').filer({
showThumbs: true,
templates: {
box: '<ul class = "jFiler-item-list"></ul>',
item: '<li class = "jFiler-item">\
<div class = "jFiler-item-container">\
<div class = "jFiler-item-inner">\
<div class = "jFiler-item-thumb">\
<div class = "jFiler-item-status"></div>\
<div class = "jFiler-item-info">\
<span class = "jFiler-item-title"><
b title = "{{fi-name}}">{{fi-name |
limitTo: 25}}</b></span>\
</div>\
{{fi-image}}\
</div>\
<div class = "jFiler-item-assets jFiler-row">\
<ul class = "list-inline pull-left">\
<li><span class = "jFiler-item-others">
{{fi-icon}} {{fi-size2}}</span></li>\
</ul>\
<ul class = "list-inline pull-right">\
<li><a class = "icon-jfi-trash
jFiler-item-trash-action"></a></li>\
</ul>\
</div>\
</div>\
</div>\
</li>',
itemAppend: '<li class = "jFiler-item">\
<div class = "jFiler-item-container">\
<div class = "jFiler-item-inner">\
<div class = "jFiler-item-thumb">\
<div class = "jFiler-item-status"></div>\
<div class = "jFiler-item-info">\
<span class = "jFiler-item-title"><
b title = "{{fi-name}}">{{fi-name |
limitTo: 25}}</b></span>\
</div>\
{{fi-image}}\
</div>\
<div class = "jFiler-item-assets jFiler-row">\
<ul class = "list-inline pull-left">\
<span class = "jFiler-item-others">
{{fi-icon}} {{fi-size2}}</span>\
</ul>\
<ul class = "list-inline pull-right">\
<li><a class = "icon-jfi-trash
jFiler-item-trash-action"></a></li>\
</ul>\
</div>\
</div>\
</div>\
</li>',
progressBar: '<div class = "bar"></div>',
itemAppendToEnd: true,
removeConfirmation: true,
_selectors: {
list: '.jFiler-item-list',
item: '.jFiler-item',
progressBar: '.bar',
remove: '.jFiler-item-trash-action',
}
},
addMore: true,
files: [{
name: "appended_file.jpg",
size: 5453,
type: "image/jpg",
file: "https://dummyimage.com/158x113/f9f9f9/191a1a.jpg",
},{
name: "appended_file_2.png",
size: 9503,
type: "image/png",
file: "https://dummyimage.com/158x113/f9f9f9/191a1a.png",
}]
});
$('#input2').filer({
limit: null,
maxSize: null,
extensions: null,
changeInput: '
<div class = "jFiler-input-dragDrop">
<div class = "jFiler-input-inner">
<div class = "jFiler-input-icon">
<i class = "icon-jfi-cloud-up-o"></i>
</div>
<div class = "jFiler-input-text">
<h3>Drag&Drop files here</h3>
<span style = "display:inline-block;
margin: 15px 0">or</span>
</div>
<a class = "jFiler-input-choose-btn blue">Browse Files</a>
</div>
</div>',
showThumbs: true,
appendTo: null,
theme: "dragdropbox",
templates: {
box: '<ul class = "jFiler-item-list"></ul>',
item: '<li class = "jFiler-item">\
<div class = "jFiler-item-container">\
<div class = "jFiler-item-inner">\
<div class = "jFiler-item-thumb">\
<div class = "jFiler-item-status"></div>\
<div class = "jFiler-item-info">\
<span class = "jFiler-item-title">
<b title = "{{fi-name}}">{{fi-name |
limitTo: 25}}</b></span>\
</div>\
{{fi-image}}\
</div>\
<div class = "jFiler-item-assets jFiler-row">\
<ul class = "list-inline pull-left">\
<li>{{fi-progressBar}}</li>\
</ul>\
<ul class = "list-inline pull-right">\
<li><a class = "icon-jfi-trash
jFiler-item-trash-action"></a>
</li>\
</ul>\
</div>\
</div>\
</div>\
</li>',
itemAppend: '<li class = "jFiler-item">\
<div class = "jFiler-item-container">\
<div class = "jFiler-item-inner">\
<div class = "jFiler-item-thumb">\
<div class = "jFiler-item-status"></div>\
<div class = "jFiler-item-info">\
<span class = "jFiler-item-title">
<b title = "{{fi-name}}">{{fi-name |
limitTo: 25}}</b></span>\
</div>\
{{fi-image}}\
</div>\
<div class = "jFiler-item-assets jFiler-row">\
<ul class = "list-inline pull-left">\
<span class = "jFiler-item-others">
{{fi-icon}} {{fi-size2}}</span>\
</ul>\
<ul class = "list-inline pull-right">\
<li><a class = "icon-jfi-trash
jFiler-item-trash-action"></a>
</li>\
</ul>\
</div>\
</div>\
</div>\
</li>',
progressBar: '<div class = "bar"></div>',
itemAppendToEnd: false,
removeConfirmation: false,
_selectors: {
list: '.jFiler-item-list',
item: '.jFiler-item',
progressBar: '.bar',
remove: '.jFiler-item-trash-action',
}
},
uploadFile: {
url: "./php/upload.php",
data: {},
type: 'POST',
enctype: 'multipart/form-data',
beforeSend: function(){},
success: function(data, el){
var parent = el.find(".jFiler-jProgressBar").parent();
el.find(".jFiler-jProgressBar").fadeOut("slow", function(){
$("<div class = \"jFiler-item-others text-success\"
><i class = \"icon-jfi-check-circle\">
</i> Success
</div>").hide().appendTo(parent).fadeIn("slow");
});
},
error: function(el){
var parent = el.find(".jFiler-jProgressBar").parent();
el.find(".jFiler-jProgressBar").fadeOut("slow", function(){
$("<div class = \"jFiler-item-others text-error\"
><i class = \"icon-jfi-minus-circle\">
</i> Error
</div>").hide().appendTo(parent).fadeIn("slow");
});
},
statusCode: {},
onProgress: function(){},
},
dragDrop: {
dragEnter: function(){},
dragLeave: function(){},
drop: function(){},
},
addMore: true,
clipBoardPaste: true,
excludeName: null,
beforeShow: function(){return true},
onSelect: function(){},
afterShow: function(){},
onRemove: function(){},
onEmpty: function(){},
captions: {
button: "Choose Files",
feedback: "Choose files To Upload",
feedback2: "files were chosen",
drop: "Drop file here to Upload",
removeConfirmation: "Are you sure you want to remove this file?",
errors: {
filesLimit: "Only {{fi-limit}} files are allowed to be uploaded.",
filesType: "Only Images are allowed to be uploaded.",
filesSize: "{{fi-name}} is too large!
Please upload file up to {{fi-maxSize}} MB.",
filesSizeAll: "Files you've choosed are too large!
Please upload files up to {{fi-maxSize}} MB."
}
}
});
});
</script>
<style>
.file_input{
display: inline-block;
padding: 10px 16px;
outline: none;
cursor: pointer;
text-decoration: none;
text-align: center;
white-space: nowrap;
font-family: sans-serif;
font-size: 11px;
font-weight: bold;
border-radius: 3px;
color: #008BFF;
border: 1px solid #008BFF;
vertical-align: middle;
background-color: #fff;
margin-bottom: 10px;
box-shadow: 0px 1px 5px rgba(0,0,0,0.05);
-webkit-transition: all 0.2s;
-moz-transition: all 0.2s;
transition: all 0.2s;
}
.file_input:hover,
.file_input:active {
background: #008BFF;
color: #fff;
}
</style>
<!--[if IE]>
<script src = "https://html5shiv.googlecode.com/svn/trunk/html5.js"
>
</script>
<![endif]-->
</head>
<body>
<div>
<form action = "./php/upload.php" method = "post"
enctype = "multipart/form-data">
<!-- filer 1 -->
<input type = "file" multiple = "multiple"
name = "files[]" id = "input1">
<br>
<input type = "submit">
</form>
</div>
<br>
<hr>
<br>
<div>
<form action = "./php/upload.php" method = "post"
enctype = "multipart/form-data">
<!-- filer 2 -->
<a class = "file_input" data-jfiler-name = "files"
data-jfiler-extensions = "jpg, jpeg, png, gif">
<i class = "icon-jfi-paperclip"></i>
Attach a file</a>
<br>
<input type = "submit">
</form>
</div>
<br>
<hr>
<br>
<div style = "background: #f7f8fa;padding: 50px;">
<!-- filer 3 -->
<input type = "file" multiple = "multiple"
name = "files[]" id = "input2">
</div>
</body>
</html>
This should produce following result −
27 Lectures
1 hours
Mahesh Kumar
27 Lectures
1.5 hours
Pratik Singh
72 Lectures
4.5 hours
Frahaan Hussain
60 Lectures
9 hours
Eduonix Learning Solutions
17 Lectures
2 hours
Sandip Bhattacharya
12 Lectures
53 mins
Laurence Svekis
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2406,
"s": 2322,
"text": "Filer.js is a jQuery plugin for quickly and easily implementing of uploading files."
},
{
"code": null,
"e": 2453,
"s": 2406,
"text": "A Simple of filer.js example as shown below −"
},
{
"code": null,
"e": 16434,
"s": 2453,
"text": "<html xmlns = \"https://www.w3.org/1999/xhtml\">\n <head>\n <meta http-equiv = \"Content-Type\" content = \"text/html; charset = utf-8\" />\n <link href = \"css/jquery.filer.css\" type = \"text/css\" rel = \"stylesheet\" />\n <link href = \"css/themes/jquery.filer-dragdropbox-theme.css\" \n type = \"text/css\" rel = \"stylesheet\" />\n\n <!--jQuery-->\n\t\t\n <script type = \"text/javascript\" \n src = \"https://code.jquery.com/jquery-latest.min.js\">\n </script>\n <script type = \"text/javascript\" src = \"js/jquery.filer.min.js\"></script>\n\t\t\t\n <script type = \"text/javascript\">\n $(document).ready(function() {\n $('#input1').filer();\n \n $('.file_input').filer({\n showThumbs: true,\n templates: {\n box: '<ul class = \"jFiler-item-list\"></ul>',\n item: '<li class = \"jFiler-item\">\\\n\t\t\t\t\t\t\n <div class = \"jFiler-item-container\">\\\n <div class = \"jFiler-item-inner\">\\\n\t\t\t\t\t\t\t\n <div class = \"jFiler-item-thumb\">\\\n <div class = \"jFiler-item-status\"></div>\\\n <div class = \"jFiler-item-info\">\\\n <span class = \"jFiler-item-title\"><\n b title = \"{{fi-name}}\">{{fi-name | \n limitTo: 25}}</b></span>\\\n </div>\\\n {{fi-image}}\\\n </div>\\\n\t\t\t\t\t\t\t\t\n <div class = \"jFiler-item-assets jFiler-row\">\\\n <ul class = \"list-inline pull-left\">\\\n <li><span class = \"jFiler-item-others\">\n {{fi-icon}} {{fi-size2}}</span></li>\\\n </ul>\\\n\t\t\t\t\t\t\t\t\t\n <ul class = \"list-inline pull-right\">\\\n <li><a class = \"icon-jfi-trash\n jFiler-item-trash-action\"></a></li>\\\n </ul>\\\n\t\t\t\t\t\t\t\t\t\n </div>\\\n\t\t\t\t\t\t\t\t\n </div>\\\n </div>\\\n </li>',\n\t\t\t\t\t\t\n itemAppend: '<li class = \"jFiler-item\">\\\n\t\t\t\t\t\t\n <div class = \"jFiler-item-container\">\\\n <div class = \"jFiler-item-inner\">\\\n <div class = \"jFiler-item-thumb\">\\\n <div class = \"jFiler-item-status\"></div>\\\n <div class = \"jFiler-item-info\">\\\n <span class = \"jFiler-item-title\"><\n b title = \"{{fi-name}}\">{{fi-name |\n limitTo: 25}}</b></span>\\\n </div>\\\n {{fi-image}}\\\n </div>\\\n\t\t\t\t\t\t\t\t\t\n <div class = \"jFiler-item-assets jFiler-row\">\\\n <ul class = \"list-inline pull-left\">\\\n <span class = \"jFiler-item-others\">\n {{fi-icon}} {{fi-size2}}</span>\\\n </ul>\\\n\t\t\t\t\t\t\t\t\t\t\n <ul class = \"list-inline pull-right\">\\\n <li><a class = \"icon-jfi-trash \n jFiler-item-trash-action\"></a></li>\\\n </ul>\\\n\t\t\t\t\t\t\t\t\t\t\n </div>\\\n\t\t\t\t\t\t\t\t\t\n </div>\\\n </div>\\\n </li>',\n\t\t\t\t\t\t\n progressBar: '<div class = \"bar\"></div>',\n itemAppendToEnd: true,\n removeConfirmation: true,\n\t\t\t\t\t\t\n _selectors: {\n list: '.jFiler-item-list',\n item: '.jFiler-item',\n progressBar: '.bar',\n remove: '.jFiler-item-trash-action',\n }\n },\n\t\t\t\t\t\n addMore: true,\n\t\t\t\t\t\n files: [{\n name: \"appended_file.jpg\",\n size: 5453,\n type: \"image/jpg\",\n file: \"https://dummyimage.com/158x113/f9f9f9/191a1a.jpg\",\n },{\n name: \"appended_file_2.png\",\n size: 9503,\n type: \"image/png\",\n file: \"https://dummyimage.com/158x113/f9f9f9/191a1a.png\",\n }]\n });\n \n $('#input2').filer({\n limit: null,\n maxSize: null,\n extensions: null,\n changeInput: '\n\t\t\t\t\t\n <div class = \"jFiler-input-dragDrop\">\n <div class = \"jFiler-input-inner\">\n\t\t\t\t\t\t\n <div class = \"jFiler-input-icon\">\n <i class = \"icon-jfi-cloud-up-o\"></i>\n </div>\n\t\t\t\t\t\t\t\n <div class = \"jFiler-input-text\">\n <h3>Drag&Drop files here</h3> \n <span style = \"display:inline-block; \n margin: 15px 0\">or</span>\n </div>\n\t\t\t\t\t\t\t\n <a class = \"jFiler-input-choose-btn blue\">Browse Files</a>\n\t\t\t\t\t\t\t\t\n </div>\n </div>',\n\t\t\t\t\t\n showThumbs: true,\n appendTo: null,\n theme: \"dragdropbox\",\n\t\t\t\t\t\n templates: {\n box: '<ul class = \"jFiler-item-list\"></ul>',\n item: '<li class = \"jFiler-item\">\\\n <div class = \"jFiler-item-container\">\\\n <div class = \"jFiler-item-inner\">\\\n\t\t\t\t\t\t\t\t\n <div class = \"jFiler-item-thumb\">\\\n <div class = \"jFiler-item-status\"></div>\\\n\t\t\t\t\t\t\t\t\t\t\n <div class = \"jFiler-item-info\">\\\n <span class = \"jFiler-item-title\">\n <b title = \"{{fi-name}}\">{{fi-name | \n limitTo: 25}}</b></span>\\\n </div>\\\n\t\t\t\t\t\t\t\t\t\t\n {{fi-image}}\\\n </div>\\\n\t\t\t\t\t\t\t\t\t\n <div class = \"jFiler-item-assets jFiler-row\">\\\n <ul class = \"list-inline pull-left\">\\\n <li>{{fi-progressBar}}</li>\\\n </ul>\\\n\t\t\t\t\t\t\t\t\t\t\n <ul class = \"list-inline pull-right\">\\\n <li><a class = \"icon-jfi-trash\n jFiler-item-trash-action\"></a>\n </li>\\\n </ul>\\\n\t\t\t\t\t\t\t\t\t\t\n </div>\\\n\t\t\t\t\t\t\t\t\t\n </div>\\\n </div>\\\n </li>',\n\t\t\t\t\t\t\n itemAppend: '<li class = \"jFiler-item\">\\\n <div class = \"jFiler-item-container\">\\\n <div class = \"jFiler-item-inner\">\\\n\t\t\t\t\t\t\t\t\n <div class = \"jFiler-item-thumb\">\\\n <div class = \"jFiler-item-status\"></div>\\\n\t\t\t\t\t\t\t\t\t\t\n <div class = \"jFiler-item-info\">\\\n <span class = \"jFiler-item-title\">\n <b title = \"{{fi-name}}\">{{fi-name | \n limitTo: 25}}</b></span>\\\n </div>\\\n\t\t\t\t\t\t\t\t\t\t\n {{fi-image}}\\\n </div>\\\n\t\t\t\t\t\t\t\t\t\n <div class = \"jFiler-item-assets jFiler-row\">\\\n <ul class = \"list-inline pull-left\">\\\n <span class = \"jFiler-item-others\">\n {{fi-icon}} {{fi-size2}}</span>\\\n </ul>\\\n\t\t\t\t\t\t\t\t\t\t\n <ul class = \"list-inline pull-right\">\\\n <li><a class = \"icon-jfi-trash\n jFiler-item-trash-action\"></a>\n </li>\\\n </ul>\\\n\t\t\t\t\t\t\t\t\t\t\n </div>\\\n\t\t\t\t\t\t\t\t\t\n </div>\\\n </div>\\\n </li>',\n\t\t\t\t\t\t\n progressBar: '<div class = \"bar\"></div>',\n itemAppendToEnd: false,\n removeConfirmation: false,\n\t\t\t\t\t\t\n _selectors: {\n list: '.jFiler-item-list',\n item: '.jFiler-item',\n progressBar: '.bar',\n remove: '.jFiler-item-trash-action',\n }\n\t\t\t\t\t\t\n },\n\t\t\t\t\t\n uploadFile: {\n url: \"./php/upload.php\",\n data: {},\n type: 'POST',\n enctype: 'multipart/form-data',\n beforeSend: function(){},\n\t\t\t\t\t\t\n success: function(data, el){\n var parent = el.find(\".jFiler-jProgressBar\").parent();\n\t\t\t\t\t\t\t\n el.find(\".jFiler-jProgressBar\").fadeOut(\"slow\", function(){\n $(\"<div class = \\\"jFiler-item-others text-success\\\"\n ><i class = \\\"icon-jfi-check-circle\\\">\n </i> Success\n </div>\").hide().appendTo(parent).fadeIn(\"slow\"); \n });\n },\n\t\t\t\t\t\t\n error: function(el){\n var parent = el.find(\".jFiler-jProgressBar\").parent();\n\t\t\t\t\t\t\t\n el.find(\".jFiler-jProgressBar\").fadeOut(\"slow\", function(){\n $(\"<div class = \\\"jFiler-item-others text-error\\\"\n ><i class = \\\"icon-jfi-minus-circle\\\">\n </i> Error\n </div>\").hide().appendTo(parent).fadeIn(\"slow\"); \n });\n },\n\t\t\t\t\t\t\n statusCode: {},\n onProgress: function(){},\n },\n\t\t\t\t\t\n dragDrop: {\n dragEnter: function(){},\n dragLeave: function(){},\n drop: function(){},\n },\n\t\t\t\t\t\n addMore: true,\n clipBoardPaste: true,\n excludeName: null,\n beforeShow: function(){return true},\n onSelect: function(){},\n afterShow: function(){},\n onRemove: function(){},\n onEmpty: function(){},\n\t\t\t\t\t\n captions: {\n button: \"Choose Files\",\n feedback: \"Choose files To Upload\",\n feedback2: \"files were chosen\",\n drop: \"Drop file here to Upload\",\n removeConfirmation: \"Are you sure you want to remove this file?\",\n\t\t\t\t\t\t\n errors: {\n filesLimit: \"Only {{fi-limit}} files are allowed to be uploaded.\",\n filesType: \"Only Images are allowed to be uploaded.\",\n filesSize: \"{{fi-name}} is too large! \n Please upload file up to {{fi-maxSize}} MB.\",\n filesSizeAll: \"Files you've choosed are too large! \n Please upload files up to {{fi-maxSize}} MB.\"\n }\n }\n });\n });\n </script>\n \n <style>\n .file_input{\n display: inline-block;\n padding: 10px 16px;\n outline: none;\n cursor: pointer;\n\t\t\t\t\n text-decoration: none;\n text-align: center;\n white-space: nowrap;\n\t\t\t\t\n font-family: sans-serif;\n font-size: 11px;\n font-weight: bold;\n\t\t\t\t\n border-radius: 3px;\n color: #008BFF;\n border: 1px solid #008BFF;\n vertical-align: middle;\n background-color: #fff;\n margin-bottom: 10px;\n\t\t\t\t\n box-shadow: 0px 1px 5px rgba(0,0,0,0.05);\n -webkit-transition: all 0.2s;\n -moz-transition: all 0.2s;\n transition: all 0.2s;\n }\n\t\t\t\n .file_input:hover,\n\t\t \n .file_input:active {\n background: #008BFF;\n color: #fff;\n }\n\t\t\t\n </style>\n \n <!--[if IE]>\n <script src = \"https://html5shiv.googlecode.com/svn/trunk/html5.js\"\n >\n </script>\n <![endif]-->\n </head>\n\n <body>\n <div>\n <form action = \"./php/upload.php\" method = \"post\"\n enctype = \"multipart/form-data\">\n\t\t\t\n <!-- filer 1 -->\n <input type = \"file\" multiple = \"multiple\" \n name = \"files[]\" id = \"input1\">\n \n <br>\n <input type = \"submit\">\n </form>\n </div>\n \n <br>\n <hr>\n <br>\n \n <div>\n <form action = \"./php/upload.php\" method = \"post\"\n enctype = \"multipart/form-data\">\n\t\t\t\t\n <!-- filer 2 -->\n <a class = \"file_input\" data-jfiler-name = \"files\"\n data-jfiler-extensions = \"jpg, jpeg, png, gif\">\n <i class = \"icon-jfi-paperclip\"></i> \n Attach a file</a>\n \n <br>\n <input type = \"submit\">\n </form>\n </div>\n \n <br>\n <hr>\n <br>\n \n <div style = \"background: #f7f8fa;padding: 50px;\">\n <!-- filer 3 -->\n <input type = \"file\" multiple = \"multiple\" \n name = \"files[]\" id = \"input2\">\n \n </div>\n \n </body>\n</html>"
},
{
"code": null,
"e": 16473,
"s": 16434,
"text": "This should produce following result −"
},
{
"code": null,
"e": 16506,
"s": 16473,
"text": "\n 27 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 16520,
"s": 16506,
"text": " Mahesh Kumar"
},
{
"code": null,
"e": 16555,
"s": 16520,
"text": "\n 27 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 16569,
"s": 16555,
"text": " Pratik Singh"
},
{
"code": null,
"e": 16604,
"s": 16569,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 16621,
"s": 16604,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 16654,
"s": 16621,
"text": "\n 60 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 16682,
"s": 16654,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 16715,
"s": 16682,
"text": "\n 17 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 16736,
"s": 16715,
"text": " Sandip Bhattacharya"
},
{
"code": null,
"e": 16768,
"s": 16736,
"text": "\n 12 Lectures \n 53 mins\n"
},
{
"code": null,
"e": 16785,
"s": 16768,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 16792,
"s": 16785,
"text": " Print"
},
{
"code": null,
"e": 16803,
"s": 16792,
"text": " Add Notes"
}
] |
JDB - Quick Guide
|
Debugging is a technical procedure to find and remove bugs or defects in a program and get expected results. Debugging includes testing and monitoring. It is very complex when the subunits of a program are tightly coupled. We can debug a program using the debugger tools that follow the prescribed APIs. A debugger allows you to step through every aspect of a code, inspect all the elements, and remove errors, if any.
There are different kinds of techniques to debug a Java program. The old method of debugging is by using print statements at the end of every segment which will print the trace statements on the console. Take a look at the following code.
pubic class Add
{
public static void main(String ar[])
{
int a=ar[0];
system.out.println("A : " +a);
int b=ar[1];
system.out.println("B : " +b);
int c = a + b;
system.out.println("C = a + b : " +c);
}
}
Here, we have a program that adds two numbers and prints the output. Notice that at each step, we have introduced a print statement that prints the state of the program on the console. This is the traditional approach to debug a program.
In addition, we have advanced concepts that can be used to debug a program such as:
stepping
breakpoints, and
exceptions or watchpoints.
We can debug a program using various methods:
Using Java bytecode (compiled version of Java code)
Using comments inside the programs
Attaching class to a running program
Remote debugging
Debugging on demand
Optimized code debugging
Here are some examples of Java debuggers that are available in the market:
IDEs such as Eclipse, Netbeans, etc. contain their own debuggers (Visual cafe, Borland, JBuilder)
Standalone debugger GUIs (such as Jikes, Java platform debugger, and JProbe)
Command-line debugger (Sun’s JDB)
Notepad or VI driven (stack trace)
This tutorial covers how to use the command-line debugger, jdb.
The Java debugger (JDB) is a tool for Java classes to debug a program in command line. It implements the Java Platform Debugger Architecture. It helps in detecting and fixing bugs in a Java program using Java Debug Interface (JDI).
The following architecture defines the role of JDB in JDK. It contains mainly three units:
Java Virtual Machine Tool Interface (JVM TI)
Java Debug Wiring Pool (JDWP)
Java Debugger Interface (JDI)
It is a native programming interface implemented by VM. It provides ways to inspect and debug the state of the application running on the VM. It allows an implementer (VM Implementer) that can be enclosed easily into the debugging architecture. It also uses a third-party channel called JDWP for communication.
It defines the format of information and the requests that pass in between the debuggee process and the debugger front end. The primary purpose of having a JDWP is to allow the debuggee and the debugger to communicate when they run under separate VMs or in separate platforms.
It is a high-level Java interface implemented as front end. It defines the variable information at user code level. It is recommended to use a JDI layer for all debugger development. It uses JDWP for communication with the debuggee JVM.
This chapter explains how to install JDB on Windows and Linux based systems. JDB is a part of JDK. Therefore, JDK installation is enough for using JDB in command prompt.
Here are the system requirements for installing JDB:
Follow the simple steps given below to install JDB on your system.
First of all, you need to have Java Software Development Kit (SDK) installed on your system. To verify this, execute any of the two commands depending on the platform you are working on.
If the Java installation has been done properly, then it displays the current version and specifications of Java installation. A sample output is given in the following table.
Open command console and type:
\>java –version
Java version "1.7.0_60"
Java (TM) SE Run Time Environment (build 1.7.0_60-b19)
Java Hotspot (TM) 64-bit Server VM (build 24.60-b09,mixed mode)
Open command terminal and type:
$java –version
java version "1.7.0_25"
Open JDK Runtime Environment (rhel-2.3.10.4.el6_4-x86_64)
Open JDK 64-Bit Server VM (build 23.7-b01, mixed mode)
We assume the readers of this tutorial have Java SDK version 1.7.0_60 installed on their system. In case you do not have Java SDK, download its current version from the link http://www.oracle.com/technetwork/java/javase/downloads/index.html and install it.
Set the environment variable JAVA_HOME to point to the base directory location where Java is installed on your machine. For example,
Append the full path of Java compiler location to the System Path.
Execute the command java -version from the command prompt as explained above.
Verify the JDB version as follows:
Open command console and type:
\>jdb –version
Open command terminal and type:
$jdb –version
This chapter explains the syntax of JDB command. The syntax contains four sections listed as follows:
JDB
option
class
arguments
The syntax of JDB is as follows.
jdb [ options ] [ class ] [ arguments ]
It calls jdb.exe from the Java Development Kit.
These include the command line options used to debug a Java program in an efficient way. The JDB launcher accepts all the options (such as -D, -classpath, and -X) and some additional advanced options such as (-attach, -listen, -launch, etc.).
It is the class name on which you want to perform debugging operations.
These are the input values given to a program at runtime. For example, arg[0], arg[1] to the main() method.
In the above four segments, options is the most important one.
This chapter describes the important options available in JDB that are submitted as arguments with the jdb command.
The following table contains a list of options accepted by JDB:
The following commands show how to use some of the above options:
The following command gets -help on using JDB.
\>jdb -help
The following command attaches the debugger to a specified VM (port number:1099).
\> jdb -attach 1099
The following command makes the JDB process running on the current VM wait using standard connector (VM in 8008).
\>jdb -listen 8088
The following command makes the JDB process running on the current VM wait using any connector (VM in currently running port).
\>jdb –listenany
The following command executes the application in Java Hotspot(TM) VM(client).
\>jdb –tclient
The following command executes the application in Java Hotspot(TM) VM(server).
\>jdb -tserver
This chapter describes how to start a JDB session in different ways. JDB launch is the frequently used technique to start a JDB session.
There are two different ways to start a JDB session:
Starting JDB session by adding class (main class name) to it.
Adding JDB to running JVM to start session.
The following command starts a JDB session:
\>jdb <classname>
Let us assume we have a class named TestClass. The following command starts a JDB session from the TestClass.
\>jdb TestClass
If you follow this command, it starts a new Java VM with any specified parameters. Thereafter it loads the class and stops it before executing the first statement of the class.
Given below is the syntax and example to start a JDB session by adding the JDB to a running JVM.
The following syntax is for JDB session:
-agentlib:jdwp=transport=dt_shmem,address=,server=y,suspend=n
Let us assume the main class name is TestClass and JVM allows the JDB to connect it later. The following is the command to add JDB to JVM:
\>java
-agentlib:jdwp=transport=dt_shmem,address=jdbconn,server=y,suspend=n TestClass
Now you can attach the JDB to the JVM with the following command:
\> jdb -attach jdbconn
Note: Here, the TestClass is not added to the JDB command, because JDB is connected to the running VM instead of launching a new one.
This chapter takes you through the basic commands of JDB. After launching a session, these commands are used for debugging a program.
The following is the list of commands used for debugging.
Let us assume we have a sample class called Add for the following examples:
public class Add
{
public int addition( int x, int y)
{
int z = x+y;
return z;
}
public static void main( String ar[ ] )
{
int a = 5, b = 6;
Add ob = new Add();
int c = ob.addition(a,b);
System.out.println("Add: "+c);
}
}
Compile this class Add.java using the following command:
\>javac Add.java
This command executes the main class file, which is added to JDB for debugging. Execute the following commands to run the Add class.
\>jdb Add
initializing jdb ...
>run
On executing these commands, you get to see the following output:
This chapter explains the concept of breakpoints and how to set breakpoints in a program. A breakpoint introduces an explicit stop or pause in the execution of a program at a particular line of code while debugging. It is useful to acquire knowledge about variables in the program in its execution.
The following command sets up a breakpoint at a particular line number:
> stop at <class name>:<Line no>
The following command sets up a breakpoint on a particular method or on a particular variable:
> stop in <class name>:< Method name | Variable name>
The following example shows how to set up a breakpoint in a class.
public class Add
{
public int addition( int x, int y)
{
int z = x+y;
return z;
}
public static void main( String ar[ ] )
{
int a = 5, b = 6;
Add ob = new Add();
int c = ob.addition(a,b);
System.out.println("Add: "+c);
}
}
Save the above file as Add.java. Compile this file using the following command:
\>javac Add.java
Let us take an example for debugging. Here, we start the debugging process by setting up a breakpoint on main(). Given below are the steps to be followed in the debugging process:
The following command starts a JDB session on the Add class for debugging:
\> jdb Add
The following command sets up a breakpoint on the main() method of Add class.
> stop in Add.main
If the breakpoint is set successfully, you get to see the following output:
Deferring breakpoint Add.main.
It will set after the class is loaded.
>
The following command starts execution of the class Add:
> run Add
If you run this command, you get to see the following output. In this output, you find that the execution stops at the breakpoint position, that is at the main() function.
The execution stops at the first line of the main method, that is at "int a=5, b=6;" or Line no: 11 in the code. You can observe this information in the output.
The following command continues the program execution:
cont
It gives you the remaining execution part and output as follows:
> Add:11
The application exited
\>
This chapter explains how to use the concept of Stepping in debugging a program. Stepping is the debugger feature that lets you execute the code by stepping through line by line. Using this, you can examine each line of the code to ensure they are behaving as intended.
The following commands are used in the stepping process:
step: steps to the next line of execution
list: examines where you are in the code
cont: continues the remaining execution
The following example uses the Add class that we have used in the previous chapter:
public class Add
{
public int addition( int x, int y)
{
int z = x+y;
return z;
}
public static void main( String ar[ ] )
{
int a = 5, b = 6;
Add ob = new Add();
int c = ob.addition(a,b);
System.out.println("Add: "+c);
}
}
Save the above file as Add.java. Compile this file using the following command:
\>javac Add.java
Let us assume that the breakpoint is set on the main() method of the Add class. The following steps show how to apply stepping in the Add class.
The following command starts executing the class named Add.
> run Add
If you execute this command, you get to see the following output. In this output, you can find that the execution stops at the breakpoint position, i.e., at the main() method.
The execution stops at the first line of the main method, that is at "int a=5, b=6;" or Line no: 11 in the code. You can observe this information in the output.
The following command steps the execution to the next line.
main[1] step
Now the execution steps to Line no: 12. You get to see the following output.
The following command lists the code:
main[1] list
You get the following output. List command is used to let you know the line in the code up to which the program control has reached. Notice the arrow mark => in the following screenshot that shows the current position of the program control.
The following command continues to execute the code:
main[1] cont
This command continues executing the remaining lines of the code. The output is as shown below:
> Add:11
The application exited
\>
Generally, there are three types of stepping:
Step Into
Step Over
Step Out
Using this command, you can step to the next line of the code. If the next line of the code is a function call, then it enters the function by driving the control at the top line of the function.
In the following code, the arrow mark defines the controller in the code.
public class Add
{
public int addition( int x, int y)
{
int z = x+y;
return z;
}
public static void main( String ar[ ] )
{
int a = 5, b = 6;
-> Add ob = new Add();
int c = ob.addition(a,b);
System.out.println("Add: "+c);
}
}
If you use the step into command, the controller moves to the next line, i.e., "int c = ob.addition(a,b);". At this line, there is a function call addition(int, int) hence the controller moves to the topmost line of the addition function with the arrow mark as shown below:
public class Add
{
public int addition( int x, int y)
-> {
int z = x+y;
return z;
}
public static void main( String ar[ ] )
{
int a = 5, b = 6;
Add ob = new Add();
int c = ob.addition(a,b);
System.out.println("Add: "+c);
}
}
Step Over also executes the next line. But if the next line is a function call, it executes that function in the background and returns the result.
Let us take an example. In the following code, the arrow mark defines the control in the code.
public class Add
{
public int addition( int x, int y)
{
int z = x+y;
return z;
}
public static void main( String ar[ ] )
{
int a = 5, b = 6;
-> Add ob = new Add();
int c = ob.addition(a,b);
System.out.println("Add: "+c);
}
}
If you use the step over command, the control moves to the next line, i.e., "int c = ob.addition(a,b);". In this line, there is a function call addition(int, int) hence the function execution is done in the background and the result is returned to the current line with the arrow mark as shown below:
public class Add
{
public int addition( int x, int y)
{
int z = x+y;
return z;
}
public static void main( String ar[ ] )
{
int a = 5, b = 6;
Add ob = new Add();
-> int c = ob.addition(a,b);
System.out.println("Add: "+c);
}
}
Step Out executes the next line. If the next line is a function call, it skips that and the function execution continues with the remaining lines of the code.
Let us take an example. In the following code, the arrow mark defines the controller in the code.
public class Add
{
public int addition( int x, int y)
{
int z = x+y;
return z;
}
public static void main( String ar[ ] )
{
int a = 5, b = 6;
-> Add ob = new Add();
int c = ob.addition(a,b);
System.out.println("Add: "+c);
}
}
If you use the step out command, the controller moves to the next line, i.e., "int c = ob.addition(a,b);". In this line, there is a function call addition(int, int) hence the function execution is skipped and the remaining execution continues with the arrow mark as shown below:
public class Add
{
public int addition( int x, int y)
{
int z = x+y;
return z;
}
public static void main( String ar[ ] )
{
int a = 5, b = 6;
Add ob = new Add();
-> int c = ob.addition(a,b);
System.out.println("Add: "+c);
}
}
This chapter explains how to handle the exception class using JDB. Generally, whenever a program raises an exception without a catch statement, then the VM prints the exception line, the cause of the exception, and exits. If the exception has been raised with a catch statement, then the exception is handled by the catch statement. Here, the VM prints the output with the cause of exception.
When the class that raises the exception is running under JDB, it also throws the uncaught exception. That exception can be handled using the catch command.
Let us take an example of the class JdbException:
public class JdbException
{
public static void main(String ar[]) throws Exception
{
int a=8, b=0;
System.out.println("Welcome");
System.out.println("Ex: "+(a/b));
}
}
Save the above file with the name JdbException.java. Compile this file using the following command:
\>javac JdbException.java
Follow the steps given below to handle the exception.
The following command executes the class named JdbException as follows:
\>jdb JdbException
>run
This JdbException class contains an exception, hence you get to see the following output:
The following command catches the exception:
mian[1] catch java.lang.ArithmeticException
It will give you the following output:
Set all java.lang.ArithmeticException
The following command continues the execution. Now the catch handles the arithmetic exception as follows:
This chapter explains how to use JDB in Eclipse. Before proceeding further, you need to install Eclipse Indigo. Follow the steps given below to install Eclipse Indigo on your system.
You can download Eclipse from the following link: http://www.eclipse.org/downloads/packages/eclipse-ide-java-ee-developers/indigosr2
Create a new Java project by following the options File-> New -> Java project.
Name it as “sampledebug”.
Create a new class by right clicking on the samplebebug project.
Select options ->new -> class
Name it as “Add.java”
public class Add
{
public int addition( int x, int y)
{
int z = x+y;
return z;
}
public static void main( String ar[ ] )
{
int a = 5, b = 6;
Add ob = new Add();
int c = ob.addition(a,b);
System.out.println("Add: "+c);
}
}
Follow the instructions given below to open the debug perspective.
On the Eclipse IDE, go to Window -> Open perspective -> Debug. Now you get the debug perspective for the program Add.java. You get to see the following window.
The sections in the Debug perspective are as follows:
Java code is displayed in this section. It is the code you want to debug, that is, Add.java. Here we can add a breakpoint on a line by double clicking in front of the line. You find the blue bubble with an arrow symbol to point out the breakpoint of that line. See the following screenshot; you can find the selected area with a red circle pointed as “1”.
Double click here. You can set the breakpoint for this line.
Double click here. You can set the breakpoint for this line.
This section defines the list of breakpoints that are set to the program code. Here we can add, delete, find, and manage the breakpoints. The following screenshot shows the breakpoint section.
Observe the following options in the given screenshot:
Using the check box in the left, we can select or deselect a breakpoint. Here, we use one breakpoint, i.e., Add class-main() method.
The single cross icon “X” is used to delete the selected breakpoint.
The double cross icon “XX” is used to delete all the breakpoints in your code.
The arrow pointer is used to point to the code where the selected breakpoint is applied.
Using the check box in the left, we can select or deselect a breakpoint. Here, we use one breakpoint, i.e., Add class-main() method.
Using the check box in the left, we can select or deselect a breakpoint. Here, we use one breakpoint, i.e., Add class-main() method.
The single cross icon “X” is used to delete the selected breakpoint.
The single cross icon “X” is used to delete the selected breakpoint.
The double cross icon “XX” is used to delete all the breakpoints in your code.
The double cross icon “XX” is used to delete all the breakpoints in your code.
The arrow pointer is used to point to the code where the selected breakpoint is applied.
The arrow pointer is used to point to the code where the selected breakpoint is applied.
The remaining functionalities in the breakpoint section are as follows:
Hitcount : It shows how many times the control hits this breakpoint. It is used for recursive logic.
Hitcount : It shows how many times the control hits this breakpoint. It is used for recursive logic.
Suspend thread : We can suspend the current thread by selecting it.
Suspend thread : We can suspend the current thread by selecting it.
Suspend VM : We can suspend the VM by selecting it.
Suspend VM : We can suspend the VM by selecting it.
This section is used for the process of debugging. It contains options that are used in debugging.
Start debugging : Follow the instructions given below to start debugging.
Right click on the code -> click Debug as -> click 1 Java application.
The process of debugging starts as shown in the following screenshot. It contains some selected options, highlighted using numeric digits.
We apply a breakpoint on the Add class main() method. When we start debugging, the controller gets stuck at the first line of the main() method.
It is used to Resume the debugging process and skip the current breakpoint. It works similar to the cont command in the JDB command line.
It is used to stop the debugging process.
It works similar to the step in process in the JDB command line. It is used for moving the control to the next line, i.e., point “1” moves to the next line.
It works similar to the step over process in the JDB command line.
It is used to see on which line the breakpoint is applied.
We apply a breakpoint on the Add class main() method. When we start debugging, the controller gets stuck at the first line of the main() method.
We apply a breakpoint on the Add class main() method. When we start debugging, the controller gets stuck at the first line of the main() method.
It is used to Resume the debugging process and skip the current breakpoint. It works similar to the cont command in the JDB command line.
It is used to Resume the debugging process and skip the current breakpoint. It works similar to the cont command in the JDB command line.
It is used to stop the debugging process.
It is used to stop the debugging process.
It works similar to the step in process in the JDB command line. It is used for moving the control to the next line, i.e., point “1” moves to the next line.
It works similar to the step in process in the JDB command line. It is used for moving the control to the next line, i.e., point “1” moves to the next line.
It works similar to the step over process in the JDB command line.
It works similar to the step over process in the JDB command line.
It is used to see on which line the breakpoint is applied.
It is used to see on which line the breakpoint is applied.
Follow the given steps and sections to debug your code in eclipse IDE. By default, every IDE contains this debugging process.
19 Lectures
3.5 hours
Emenwa Global, Ejike IfeanyiChukwu
27 Lectures
3.5 hours
Nicolaas C Kock
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2142,
"s": 1723,
"text": "Debugging is a technical procedure to find and remove bugs or defects in a program and get expected results. Debugging includes testing and monitoring. It is very complex when the subunits of a program are tightly coupled. We can debug a program using the debugger tools that follow the prescribed APIs. A debugger allows you to step through every aspect of a code, inspect all the elements, and remove errors, if any."
},
{
"code": null,
"e": 2381,
"s": 2142,
"text": "There are different kinds of techniques to debug a Java program. The old method of debugging is by using print statements at the end of every segment which will print the trace statements on the console. Take a look at the following code."
},
{
"code": null,
"e": 2629,
"s": 2381,
"text": "pubic class Add\n{\n public static void main(String ar[])\n {\n int a=ar[0];\n system.out.println(\"A : \" +a);\n int b=ar[1];\n system.out.println(\"B : \" +b);\n int c = a + b;\n system.out.println(\"C = a + b : \" +c);\n }\n}"
},
{
"code": null,
"e": 2867,
"s": 2629,
"text": "Here, we have a program that adds two numbers and prints the output. Notice that at each step, we have introduced a print statement that prints the state of the program on the console. This is the traditional approach to debug a program."
},
{
"code": null,
"e": 2951,
"s": 2867,
"text": "In addition, we have advanced concepts that can be used to debug a program such as:"
},
{
"code": null,
"e": 2960,
"s": 2951,
"text": "stepping"
},
{
"code": null,
"e": 2977,
"s": 2960,
"text": "breakpoints, and"
},
{
"code": null,
"e": 3004,
"s": 2977,
"text": "exceptions or watchpoints."
},
{
"code": null,
"e": 3050,
"s": 3004,
"text": "We can debug a program using various methods:"
},
{
"code": null,
"e": 3102,
"s": 3050,
"text": "Using Java bytecode (compiled version of Java code)"
},
{
"code": null,
"e": 3137,
"s": 3102,
"text": "Using comments inside the programs"
},
{
"code": null,
"e": 3174,
"s": 3137,
"text": "Attaching class to a running program"
},
{
"code": null,
"e": 3191,
"s": 3174,
"text": "Remote debugging"
},
{
"code": null,
"e": 3211,
"s": 3191,
"text": "Debugging on demand"
},
{
"code": null,
"e": 3236,
"s": 3211,
"text": "Optimized code debugging"
},
{
"code": null,
"e": 3311,
"s": 3236,
"text": "Here are some examples of Java debuggers that are available in the market:"
},
{
"code": null,
"e": 3409,
"s": 3311,
"text": "IDEs such as Eclipse, Netbeans, etc. contain their own debuggers (Visual cafe, Borland, JBuilder)"
},
{
"code": null,
"e": 3486,
"s": 3409,
"text": "Standalone debugger GUIs (such as Jikes, Java platform debugger, and JProbe)"
},
{
"code": null,
"e": 3520,
"s": 3486,
"text": "Command-line debugger (Sun’s JDB)"
},
{
"code": null,
"e": 3555,
"s": 3520,
"text": "Notepad or VI driven (stack trace)"
},
{
"code": null,
"e": 3619,
"s": 3555,
"text": "This tutorial covers how to use the command-line debugger, jdb."
},
{
"code": null,
"e": 3851,
"s": 3619,
"text": "The Java debugger (JDB) is a tool for Java classes to debug a program in command line. It implements the Java Platform Debugger Architecture. It helps in detecting and fixing bugs in a Java program using Java Debug Interface (JDI)."
},
{
"code": null,
"e": 3942,
"s": 3851,
"text": "The following architecture defines the role of JDB in JDK. It contains mainly three units:"
},
{
"code": null,
"e": 3987,
"s": 3942,
"text": "Java Virtual Machine Tool Interface (JVM TI)"
},
{
"code": null,
"e": 4017,
"s": 3987,
"text": "Java Debug Wiring Pool (JDWP)"
},
{
"code": null,
"e": 4047,
"s": 4017,
"text": "Java Debugger Interface (JDI)"
},
{
"code": null,
"e": 4358,
"s": 4047,
"text": "It is a native programming interface implemented by VM. It provides ways to inspect and debug the state of the application running on the VM. It allows an implementer (VM Implementer) that can be enclosed easily into the debugging architecture. It also uses a third-party channel called JDWP for communication."
},
{
"code": null,
"e": 4635,
"s": 4358,
"text": "It defines the format of information and the requests that pass in between the debuggee process and the debugger front end. The primary purpose of having a JDWP is to allow the debuggee and the debugger to communicate when they run under separate VMs or in separate platforms."
},
{
"code": null,
"e": 4872,
"s": 4635,
"text": "It is a high-level Java interface implemented as front end. It defines the variable information at user code level. It is recommended to use a JDI layer for all debugger development. It uses JDWP for communication with the debuggee JVM."
},
{
"code": null,
"e": 5042,
"s": 4872,
"text": "This chapter explains how to install JDB on Windows and Linux based systems. JDB is a part of JDK. Therefore, JDK installation is enough for using JDB in command prompt."
},
{
"code": null,
"e": 5095,
"s": 5042,
"text": "Here are the system requirements for installing JDB:"
},
{
"code": null,
"e": 5162,
"s": 5095,
"text": "Follow the simple steps given below to install JDB on your system."
},
{
"code": null,
"e": 5349,
"s": 5162,
"text": "First of all, you need to have Java Software Development Kit (SDK) installed on your system. To verify this, execute any of the two commands depending on the platform you are working on."
},
{
"code": null,
"e": 5525,
"s": 5349,
"text": "If the Java installation has been done properly, then it displays the current version and specifications of Java installation. A sample output is given in the following table."
},
{
"code": null,
"e": 5556,
"s": 5525,
"text": "Open command console and type:"
},
{
"code": null,
"e": 5572,
"s": 5556,
"text": "\\>java –version"
},
{
"code": null,
"e": 5596,
"s": 5572,
"text": "Java version \"1.7.0_60\""
},
{
"code": null,
"e": 5651,
"s": 5596,
"text": "Java (TM) SE Run Time Environment (build 1.7.0_60-b19)"
},
{
"code": null,
"e": 5715,
"s": 5651,
"text": "Java Hotspot (TM) 64-bit Server VM (build 24.60-b09,mixed mode)"
},
{
"code": null,
"e": 5747,
"s": 5715,
"text": "Open command terminal and type:"
},
{
"code": null,
"e": 5762,
"s": 5747,
"text": "$java –version"
},
{
"code": null,
"e": 5786,
"s": 5762,
"text": "java version \"1.7.0_25\""
},
{
"code": null,
"e": 5844,
"s": 5786,
"text": "Open JDK Runtime Environment (rhel-2.3.10.4.el6_4-x86_64)"
},
{
"code": null,
"e": 5899,
"s": 5844,
"text": "Open JDK 64-Bit Server VM (build 23.7-b01, mixed mode)"
},
{
"code": null,
"e": 6156,
"s": 5899,
"text": "We assume the readers of this tutorial have Java SDK version 1.7.0_60 installed on their system. In case you do not have Java SDK, download its current version from the link http://www.oracle.com/technetwork/java/javase/downloads/index.html and install it."
},
{
"code": null,
"e": 6289,
"s": 6156,
"text": "Set the environment variable JAVA_HOME to point to the base directory location where Java is installed on your machine. For example,"
},
{
"code": null,
"e": 6356,
"s": 6289,
"text": "Append the full path of Java compiler location to the System Path."
},
{
"code": null,
"e": 6434,
"s": 6356,
"text": "Execute the command java -version from the command prompt as explained above."
},
{
"code": null,
"e": 6469,
"s": 6434,
"text": "Verify the JDB version as follows:"
},
{
"code": null,
"e": 6500,
"s": 6469,
"text": "Open command console and type:"
},
{
"code": null,
"e": 6515,
"s": 6500,
"text": "\\>jdb –version"
},
{
"code": null,
"e": 6547,
"s": 6515,
"text": "Open command terminal and type:"
},
{
"code": null,
"e": 6561,
"s": 6547,
"text": "$jdb –version"
},
{
"code": null,
"e": 6663,
"s": 6561,
"text": "This chapter explains the syntax of JDB command. The syntax contains four sections listed as follows:"
},
{
"code": null,
"e": 6667,
"s": 6663,
"text": "JDB"
},
{
"code": null,
"e": 6674,
"s": 6667,
"text": "option"
},
{
"code": null,
"e": 6680,
"s": 6674,
"text": "class"
},
{
"code": null,
"e": 6690,
"s": 6680,
"text": "arguments"
},
{
"code": null,
"e": 6723,
"s": 6690,
"text": "The syntax of JDB is as follows."
},
{
"code": null,
"e": 6763,
"s": 6723,
"text": "jdb [ options ] [ class ] [ arguments ]"
},
{
"code": null,
"e": 6811,
"s": 6763,
"text": "It calls jdb.exe from the Java Development Kit."
},
{
"code": null,
"e": 7054,
"s": 6811,
"text": "These include the command line options used to debug a Java program in an efficient way. The JDB launcher accepts all the options (such as -D, -classpath, and -X) and some additional advanced options such as (-attach, -listen, -launch, etc.)."
},
{
"code": null,
"e": 7126,
"s": 7054,
"text": "It is the class name on which you want to perform debugging operations."
},
{
"code": null,
"e": 7234,
"s": 7126,
"text": "These are the input values given to a program at runtime. For example, arg[0], arg[1] to the main() method."
},
{
"code": null,
"e": 7297,
"s": 7234,
"text": "In the above four segments, options is the most important one."
},
{
"code": null,
"e": 7413,
"s": 7297,
"text": "This chapter describes the important options available in JDB that are submitted as arguments with the jdb command."
},
{
"code": null,
"e": 7477,
"s": 7413,
"text": "The following table contains a list of options accepted by JDB:"
},
{
"code": null,
"e": 7543,
"s": 7477,
"text": "The following commands show how to use some of the above options:"
},
{
"code": null,
"e": 7590,
"s": 7543,
"text": "The following command gets -help on using JDB."
},
{
"code": null,
"e": 7602,
"s": 7590,
"text": "\\>jdb -help"
},
{
"code": null,
"e": 7684,
"s": 7602,
"text": "The following command attaches the debugger to a specified VM (port number:1099)."
},
{
"code": null,
"e": 7704,
"s": 7684,
"text": "\\> jdb -attach 1099"
},
{
"code": null,
"e": 7818,
"s": 7704,
"text": "The following command makes the JDB process running on the current VM wait using standard connector (VM in 8008)."
},
{
"code": null,
"e": 7837,
"s": 7818,
"text": "\\>jdb -listen 8088"
},
{
"code": null,
"e": 7964,
"s": 7837,
"text": "The following command makes the JDB process running on the current VM wait using any connector (VM in currently running port)."
},
{
"code": null,
"e": 7981,
"s": 7964,
"text": "\\>jdb –listenany"
},
{
"code": null,
"e": 8060,
"s": 7981,
"text": "The following command executes the application in Java Hotspot(TM) VM(client)."
},
{
"code": null,
"e": 8075,
"s": 8060,
"text": "\\>jdb –tclient"
},
{
"code": null,
"e": 8154,
"s": 8075,
"text": "The following command executes the application in Java Hotspot(TM) VM(server)."
},
{
"code": null,
"e": 8169,
"s": 8154,
"text": "\\>jdb -tserver"
},
{
"code": null,
"e": 8306,
"s": 8169,
"text": "This chapter describes how to start a JDB session in different ways. JDB launch is the frequently used technique to start a JDB session."
},
{
"code": null,
"e": 8359,
"s": 8306,
"text": "There are two different ways to start a JDB session:"
},
{
"code": null,
"e": 8421,
"s": 8359,
"text": "Starting JDB session by adding class (main class name) to it."
},
{
"code": null,
"e": 8465,
"s": 8421,
"text": "Adding JDB to running JVM to start session."
},
{
"code": null,
"e": 8509,
"s": 8465,
"text": "The following command starts a JDB session:"
},
{
"code": null,
"e": 8527,
"s": 8509,
"text": "\\>jdb <classname>"
},
{
"code": null,
"e": 8637,
"s": 8527,
"text": "Let us assume we have a class named TestClass. The following command starts a JDB session from the TestClass."
},
{
"code": null,
"e": 8653,
"s": 8637,
"text": "\\>jdb TestClass"
},
{
"code": null,
"e": 8830,
"s": 8653,
"text": "If you follow this command, it starts a new Java VM with any specified parameters. Thereafter it loads the class and stops it before executing the first statement of the class."
},
{
"code": null,
"e": 8927,
"s": 8830,
"text": "Given below is the syntax and example to start a JDB session by adding the JDB to a running JVM."
},
{
"code": null,
"e": 8968,
"s": 8927,
"text": "The following syntax is for JDB session:"
},
{
"code": null,
"e": 9030,
"s": 8968,
"text": "-agentlib:jdwp=transport=dt_shmem,address=,server=y,suspend=n"
},
{
"code": null,
"e": 9169,
"s": 9030,
"text": "Let us assume the main class name is TestClass and JVM allows the JDB to connect it later. The following is the command to add JDB to JVM:"
},
{
"code": null,
"e": 9255,
"s": 9169,
"text": "\\>java\n-agentlib:jdwp=transport=dt_shmem,address=jdbconn,server=y,suspend=n TestClass"
},
{
"code": null,
"e": 9321,
"s": 9255,
"text": "Now you can attach the JDB to the JVM with the following command:"
},
{
"code": null,
"e": 9344,
"s": 9321,
"text": "\\> jdb -attach jdbconn"
},
{
"code": null,
"e": 9478,
"s": 9344,
"text": "Note: Here, the TestClass is not added to the JDB command, because JDB is connected to the running VM instead of launching a new one."
},
{
"code": null,
"e": 9612,
"s": 9478,
"text": "This chapter takes you through the basic commands of JDB. After launching a session, these commands are used for debugging a program."
},
{
"code": null,
"e": 9670,
"s": 9612,
"text": "The following is the list of commands used for debugging."
},
{
"code": null,
"e": 9746,
"s": 9670,
"text": "Let us assume we have a sample class called Add for the following examples:"
},
{
"code": null,
"e": 10022,
"s": 9746,
"text": "public class Add\n{\n public int addition( int x, int y)\n {\n int z = x+y;\n return z;\n }\n public static void main( String ar[ ] )\n {\n int a = 5, b = 6;\n Add ob = new Add();\n int c = ob.addition(a,b);\n System.out.println(\"Add: \"+c);\n }\n}"
},
{
"code": null,
"e": 10079,
"s": 10022,
"text": "Compile this class Add.java using the following command:"
},
{
"code": null,
"e": 10096,
"s": 10079,
"text": "\\>javac Add.java"
},
{
"code": null,
"e": 10229,
"s": 10096,
"text": "This command executes the main class file, which is added to JDB for debugging. Execute the following commands to run the Add class."
},
{
"code": null,
"e": 10265,
"s": 10229,
"text": "\\>jdb Add\ninitializing jdb ...\n>run"
},
{
"code": null,
"e": 10331,
"s": 10265,
"text": "On executing these commands, you get to see the following output:"
},
{
"code": null,
"e": 10630,
"s": 10331,
"text": "This chapter explains the concept of breakpoints and how to set breakpoints in a program. A breakpoint introduces an explicit stop or pause in the execution of a program at a particular line of code while debugging. It is useful to acquire knowledge about variables in the program in its execution."
},
{
"code": null,
"e": 10702,
"s": 10630,
"text": "The following command sets up a breakpoint at a particular line number:"
},
{
"code": null,
"e": 10735,
"s": 10702,
"text": "> stop at <class name>:<Line no>"
},
{
"code": null,
"e": 10830,
"s": 10735,
"text": "The following command sets up a breakpoint on a particular method or on a particular variable:"
},
{
"code": null,
"e": 10884,
"s": 10830,
"text": "> stop in <class name>:< Method name | Variable name>"
},
{
"code": null,
"e": 10951,
"s": 10884,
"text": "The following example shows how to set up a breakpoint in a class."
},
{
"code": null,
"e": 11227,
"s": 10951,
"text": "public class Add\n{\n public int addition( int x, int y)\n {\n int z = x+y;\n return z;\n }\n public static void main( String ar[ ] )\n {\n int a = 5, b = 6;\n Add ob = new Add();\n int c = ob.addition(a,b);\n System.out.println(\"Add: \"+c);\n }\n}"
},
{
"code": null,
"e": 11307,
"s": 11227,
"text": "Save the above file as Add.java. Compile this file using the following command:"
},
{
"code": null,
"e": 11324,
"s": 11307,
"text": "\\>javac Add.java"
},
{
"code": null,
"e": 11504,
"s": 11324,
"text": "Let us take an example for debugging. Here, we start the debugging process by setting up a breakpoint on main(). Given below are the steps to be followed in the debugging process:"
},
{
"code": null,
"e": 11579,
"s": 11504,
"text": "The following command starts a JDB session on the Add class for debugging:"
},
{
"code": null,
"e": 11590,
"s": 11579,
"text": "\\> jdb Add"
},
{
"code": null,
"e": 11668,
"s": 11590,
"text": "The following command sets up a breakpoint on the main() method of Add class."
},
{
"code": null,
"e": 11687,
"s": 11668,
"text": "> stop in Add.main"
},
{
"code": null,
"e": 11763,
"s": 11687,
"text": "If the breakpoint is set successfully, you get to see the following output:"
},
{
"code": null,
"e": 11836,
"s": 11763,
"text": "Deferring breakpoint Add.main.\nIt will set after the class is loaded.\n>\n"
},
{
"code": null,
"e": 11893,
"s": 11836,
"text": "The following command starts execution of the class Add:"
},
{
"code": null,
"e": 11903,
"s": 11893,
"text": "> run Add"
},
{
"code": null,
"e": 12075,
"s": 11903,
"text": "If you run this command, you get to see the following output. In this output, you find that the execution stops at the breakpoint position, that is at the main() function."
},
{
"code": null,
"e": 12236,
"s": 12075,
"text": "The execution stops at the first line of the main method, that is at \"int a=5, b=6;\" or Line no: 11 in the code. You can observe this information in the output."
},
{
"code": null,
"e": 12291,
"s": 12236,
"text": "The following command continues the program execution:"
},
{
"code": null,
"e": 12296,
"s": 12291,
"text": "cont"
},
{
"code": null,
"e": 12361,
"s": 12296,
"text": "It gives you the remaining execution part and output as follows:"
},
{
"code": null,
"e": 12397,
"s": 12361,
"text": "> Add:11\nThe application exited\n\\>\n"
},
{
"code": null,
"e": 12667,
"s": 12397,
"text": "This chapter explains how to use the concept of Stepping in debugging a program. Stepping is the debugger feature that lets you execute the code by stepping through line by line. Using this, you can examine each line of the code to ensure they are behaving as intended."
},
{
"code": null,
"e": 12724,
"s": 12667,
"text": "The following commands are used in the stepping process:"
},
{
"code": null,
"e": 12766,
"s": 12724,
"text": "step: steps to the next line of execution"
},
{
"code": null,
"e": 12807,
"s": 12766,
"text": "list: examines where you are in the code"
},
{
"code": null,
"e": 12847,
"s": 12807,
"text": "cont: continues the remaining execution"
},
{
"code": null,
"e": 12931,
"s": 12847,
"text": "The following example uses the Add class that we have used in the previous chapter:"
},
{
"code": null,
"e": 13207,
"s": 12931,
"text": "public class Add\n{\n public int addition( int x, int y)\n {\n int z = x+y;\n return z;\n }\n public static void main( String ar[ ] )\n {\n int a = 5, b = 6;\n Add ob = new Add();\n int c = ob.addition(a,b);\n System.out.println(\"Add: \"+c);\n }\n}"
},
{
"code": null,
"e": 13287,
"s": 13207,
"text": "Save the above file as Add.java. Compile this file using the following command:"
},
{
"code": null,
"e": 13304,
"s": 13287,
"text": "\\>javac Add.java"
},
{
"code": null,
"e": 13449,
"s": 13304,
"text": "Let us assume that the breakpoint is set on the main() method of the Add class. The following steps show how to apply stepping in the Add class."
},
{
"code": null,
"e": 13509,
"s": 13449,
"text": "The following command starts executing the class named Add."
},
{
"code": null,
"e": 13519,
"s": 13509,
"text": "> run Add"
},
{
"code": null,
"e": 13695,
"s": 13519,
"text": "If you execute this command, you get to see the following output. In this output, you can find that the execution stops at the breakpoint position, i.e., at the main() method."
},
{
"code": null,
"e": 13856,
"s": 13695,
"text": "The execution stops at the first line of the main method, that is at \"int a=5, b=6;\" or Line no: 11 in the code. You can observe this information in the output."
},
{
"code": null,
"e": 13916,
"s": 13856,
"text": "The following command steps the execution to the next line."
},
{
"code": null,
"e": 13929,
"s": 13916,
"text": "main[1] step"
},
{
"code": null,
"e": 14006,
"s": 13929,
"text": "Now the execution steps to Line no: 12. You get to see the following output."
},
{
"code": null,
"e": 14044,
"s": 14006,
"text": "The following command lists the code:"
},
{
"code": null,
"e": 14057,
"s": 14044,
"text": "main[1] list"
},
{
"code": null,
"e": 14299,
"s": 14057,
"text": "You get the following output. List command is used to let you know the line in the code up to which the program control has reached. Notice the arrow mark => in the following screenshot that shows the current position of the program control."
},
{
"code": null,
"e": 14352,
"s": 14299,
"text": "The following command continues to execute the code:"
},
{
"code": null,
"e": 14365,
"s": 14352,
"text": "main[1] cont"
},
{
"code": null,
"e": 14461,
"s": 14365,
"text": "This command continues executing the remaining lines of the code. The output is as shown below:"
},
{
"code": null,
"e": 14497,
"s": 14461,
"text": "> Add:11\nThe application exited\n\\>\n"
},
{
"code": null,
"e": 14543,
"s": 14497,
"text": "Generally, there are three types of stepping:"
},
{
"code": null,
"e": 14553,
"s": 14543,
"text": "Step Into"
},
{
"code": null,
"e": 14563,
"s": 14553,
"text": "Step Over"
},
{
"code": null,
"e": 14572,
"s": 14563,
"text": "Step Out"
},
{
"code": null,
"e": 14768,
"s": 14572,
"text": "Using this command, you can step to the next line of the code. If the next line of the code is a function call, then it enters the function by driving the control at the top line of the function."
},
{
"code": null,
"e": 14842,
"s": 14768,
"text": "In the following code, the arrow mark defines the controller in the code."
},
{
"code": null,
"e": 15121,
"s": 14842,
"text": "public class Add\n{\n public int addition( int x, int y)\n {\n int z = x+y;\n return z;\n }\n public static void main( String ar[ ] )\n {\n int a = 5, b = 6;\n -> Add ob = new Add();\n int c = ob.addition(a,b);\n System.out.println(\"Add: \"+c);\n }\n}"
},
{
"code": null,
"e": 15395,
"s": 15121,
"text": "If you use the step into command, the controller moves to the next line, i.e., \"int c = ob.addition(a,b);\". At this line, there is a function call addition(int, int) hence the controller moves to the topmost line of the addition function with the arrow mark as shown below:"
},
{
"code": null,
"e": 15671,
"s": 15395,
"text": "public class Add\n{\n public int addition( int x, int y)\n -> {\n int z = x+y;\n return z;\n }\n public static void main( String ar[ ] )\n {\n int a = 5, b = 6;\n Add ob = new Add();\n int c = ob.addition(a,b);\n System.out.println(\"Add: \"+c);\n }\n}"
},
{
"code": null,
"e": 15819,
"s": 15671,
"text": "Step Over also executes the next line. But if the next line is a function call, it executes that function in the background and returns the result."
},
{
"code": null,
"e": 15914,
"s": 15819,
"text": "Let us take an example. In the following code, the arrow mark defines the control in the code."
},
{
"code": null,
"e": 16193,
"s": 15914,
"text": "public class Add\n{\n public int addition( int x, int y)\n {\n int z = x+y;\n return z;\n }\n public static void main( String ar[ ] )\n {\n int a = 5, b = 6;\n -> Add ob = new Add();\n int c = ob.addition(a,b);\n System.out.println(\"Add: \"+c);\n }\n}"
},
{
"code": null,
"e": 16494,
"s": 16193,
"text": "If you use the step over command, the control moves to the next line, i.e., \"int c = ob.addition(a,b);\". In this line, there is a function call addition(int, int) hence the function execution is done in the background and the result is returned to the current line with the arrow mark as shown below:"
},
{
"code": null,
"e": 16773,
"s": 16494,
"text": "public class Add\n{\n public int addition( int x, int y)\n {\n int z = x+y;\n return z;\n }\n public static void main( String ar[ ] )\n {\n int a = 5, b = 6;\n Add ob = new Add();\n -> int c = ob.addition(a,b);\n System.out.println(\"Add: \"+c);\n }\n}"
},
{
"code": null,
"e": 16932,
"s": 16773,
"text": "Step Out executes the next line. If the next line is a function call, it skips that and the function execution continues with the remaining lines of the code."
},
{
"code": null,
"e": 17030,
"s": 16932,
"text": "Let us take an example. In the following code, the arrow mark defines the controller in the code."
},
{
"code": null,
"e": 17309,
"s": 17030,
"text": "public class Add\n{\n public int addition( int x, int y)\n {\n int z = x+y;\n return z;\n }\n public static void main( String ar[ ] )\n {\n int a = 5, b = 6;\n -> Add ob = new Add();\n int c = ob.addition(a,b);\n System.out.println(\"Add: \"+c);\n }\n}"
},
{
"code": null,
"e": 17588,
"s": 17309,
"text": "If you use the step out command, the controller moves to the next line, i.e., \"int c = ob.addition(a,b);\". In this line, there is a function call addition(int, int) hence the function execution is skipped and the remaining execution continues with the arrow mark as shown below:"
},
{
"code": null,
"e": 17867,
"s": 17588,
"text": "public class Add\n{\n public int addition( int x, int y)\n {\n int z = x+y;\n return z;\n }\n public static void main( String ar[ ] )\n {\n int a = 5, b = 6;\n Add ob = new Add();\n -> int c = ob.addition(a,b);\n System.out.println(\"Add: \"+c);\n }\n}"
},
{
"code": null,
"e": 18260,
"s": 17867,
"text": "This chapter explains how to handle the exception class using JDB. Generally, whenever a program raises an exception without a catch statement, then the VM prints the exception line, the cause of the exception, and exits. If the exception has been raised with a catch statement, then the exception is handled by the catch statement. Here, the VM prints the output with the cause of exception."
},
{
"code": null,
"e": 18417,
"s": 18260,
"text": "When the class that raises the exception is running under JDB, it also throws the uncaught exception. That exception can be handled using the catch command."
},
{
"code": null,
"e": 18467,
"s": 18417,
"text": "Let us take an example of the class JdbException:"
},
{
"code": null,
"e": 18661,
"s": 18467,
"text": "public class JdbException\n{\n public static void main(String ar[]) throws Exception\n {\n int a=8, b=0;\n System.out.println(\"Welcome\");\n System.out.println(\"Ex: \"+(a/b));\n }\n}"
},
{
"code": null,
"e": 18761,
"s": 18661,
"text": "Save the above file with the name JdbException.java. Compile this file using the following command:"
},
{
"code": null,
"e": 18787,
"s": 18761,
"text": "\\>javac JdbException.java"
},
{
"code": null,
"e": 18841,
"s": 18787,
"text": "Follow the steps given below to handle the exception."
},
{
"code": null,
"e": 18913,
"s": 18841,
"text": "The following command executes the class named JdbException as follows:"
},
{
"code": null,
"e": 18937,
"s": 18913,
"text": "\\>jdb JdbException\n>run"
},
{
"code": null,
"e": 19027,
"s": 18937,
"text": "This JdbException class contains an exception, hence you get to see the following output:"
},
{
"code": null,
"e": 19072,
"s": 19027,
"text": "The following command catches the exception:"
},
{
"code": null,
"e": 19116,
"s": 19072,
"text": "mian[1] catch java.lang.ArithmeticException"
},
{
"code": null,
"e": 19155,
"s": 19116,
"text": "It will give you the following output:"
},
{
"code": null,
"e": 19194,
"s": 19155,
"text": "Set all java.lang.ArithmeticException\n"
},
{
"code": null,
"e": 19300,
"s": 19194,
"text": "The following command continues the execution. Now the catch handles the arithmetic exception as follows:"
},
{
"code": null,
"e": 19483,
"s": 19300,
"text": "This chapter explains how to use JDB in Eclipse. Before proceeding further, you need to install Eclipse Indigo. Follow the steps given below to install Eclipse Indigo on your system."
},
{
"code": null,
"e": 19616,
"s": 19483,
"text": "You can download Eclipse from the following link: http://www.eclipse.org/downloads/packages/eclipse-ide-java-ee-developers/indigosr2"
},
{
"code": null,
"e": 19695,
"s": 19616,
"text": "Create a new Java project by following the options File-> New -> Java project."
},
{
"code": null,
"e": 19721,
"s": 19695,
"text": "Name it as “sampledebug”."
},
{
"code": null,
"e": 19786,
"s": 19721,
"text": "Create a new class by right clicking on the samplebebug project."
},
{
"code": null,
"e": 19816,
"s": 19786,
"text": "Select options ->new -> class"
},
{
"code": null,
"e": 19838,
"s": 19816,
"text": "Name it as “Add.java”"
},
{
"code": null,
"e": 20114,
"s": 19838,
"text": "public class Add\n{\n public int addition( int x, int y)\n {\n int z = x+y;\n return z;\n }\n public static void main( String ar[ ] )\n {\n int a = 5, b = 6;\n Add ob = new Add();\n int c = ob.addition(a,b);\n System.out.println(\"Add: \"+c);\n }\n}"
},
{
"code": null,
"e": 20181,
"s": 20114,
"text": "Follow the instructions given below to open the debug perspective."
},
{
"code": null,
"e": 20341,
"s": 20181,
"text": "On the Eclipse IDE, go to Window -> Open perspective -> Debug. Now you get the debug perspective for the program Add.java. You get to see the following window."
},
{
"code": null,
"e": 20395,
"s": 20341,
"text": "The sections in the Debug perspective are as follows:"
},
{
"code": null,
"e": 20751,
"s": 20395,
"text": "Java code is displayed in this section. It is the code you want to debug, that is, Add.java. Here we can add a breakpoint on a line by double clicking in front of the line. You find the blue bubble with an arrow symbol to point out the breakpoint of that line. See the following screenshot; you can find the selected area with a red circle pointed as “1”."
},
{
"code": null,
"e": 20814,
"s": 20751,
"text": "\nDouble click here. You can set the breakpoint for this line.\n"
},
{
"code": null,
"e": 20875,
"s": 20814,
"text": "Double click here. You can set the breakpoint for this line."
},
{
"code": null,
"e": 21068,
"s": 20875,
"text": "This section defines the list of breakpoints that are set to the program code. Here we can add, delete, find, and manage the breakpoints. The following screenshot shows the breakpoint section."
},
{
"code": null,
"e": 21123,
"s": 21068,
"text": "Observe the following options in the given screenshot:"
},
{
"code": null,
"e": 21495,
"s": 21123,
"text": "\nUsing the check box in the left, we can select or deselect a breakpoint. Here, we use one breakpoint, i.e., Add class-main() method.\nThe single cross icon “X” is used to delete the selected breakpoint.\nThe double cross icon “XX” is used to delete all the breakpoints in your code.\nThe arrow pointer is used to point to the code where the selected breakpoint is applied.\n"
},
{
"code": null,
"e": 21628,
"s": 21495,
"text": "Using the check box in the left, we can select or deselect a breakpoint. Here, we use one breakpoint, i.e., Add class-main() method."
},
{
"code": null,
"e": 21761,
"s": 21628,
"text": "Using the check box in the left, we can select or deselect a breakpoint. Here, we use one breakpoint, i.e., Add class-main() method."
},
{
"code": null,
"e": 21830,
"s": 21761,
"text": "The single cross icon “X” is used to delete the selected breakpoint."
},
{
"code": null,
"e": 21899,
"s": 21830,
"text": "The single cross icon “X” is used to delete the selected breakpoint."
},
{
"code": null,
"e": 21978,
"s": 21899,
"text": "The double cross icon “XX” is used to delete all the breakpoints in your code."
},
{
"code": null,
"e": 22057,
"s": 21978,
"text": "The double cross icon “XX” is used to delete all the breakpoints in your code."
},
{
"code": null,
"e": 22146,
"s": 22057,
"text": "The arrow pointer is used to point to the code where the selected breakpoint is applied."
},
{
"code": null,
"e": 22235,
"s": 22146,
"text": "The arrow pointer is used to point to the code where the selected breakpoint is applied."
},
{
"code": null,
"e": 22307,
"s": 22235,
"text": "The remaining functionalities in the breakpoint section are as follows:"
},
{
"code": null,
"e": 22408,
"s": 22307,
"text": "Hitcount : It shows how many times the control hits this breakpoint. It is used for recursive logic."
},
{
"code": null,
"e": 22509,
"s": 22408,
"text": "Hitcount : It shows how many times the control hits this breakpoint. It is used for recursive logic."
},
{
"code": null,
"e": 22577,
"s": 22509,
"text": "Suspend thread : We can suspend the current thread by selecting it."
},
{
"code": null,
"e": 22645,
"s": 22577,
"text": "Suspend thread : We can suspend the current thread by selecting it."
},
{
"code": null,
"e": 22697,
"s": 22645,
"text": "Suspend VM : We can suspend the VM by selecting it."
},
{
"code": null,
"e": 22749,
"s": 22697,
"text": "Suspend VM : We can suspend the VM by selecting it."
},
{
"code": null,
"e": 22848,
"s": 22749,
"text": "This section is used for the process of debugging. It contains options that are used in debugging."
},
{
"code": null,
"e": 22922,
"s": 22848,
"text": "Start debugging : Follow the instructions given below to start debugging."
},
{
"code": null,
"e": 22993,
"s": 22922,
"text": "Right click on the code -> click Debug as -> click 1 Java application."
},
{
"code": null,
"e": 23132,
"s": 22993,
"text": "The process of debugging starts as shown in the following screenshot. It contains some selected options, highlighted using numeric digits."
},
{
"code": null,
"e": 23742,
"s": 23132,
"text": "\nWe apply a breakpoint on the Add class main() method. When we start debugging, the controller gets stuck at the first line of the main() method.\nIt is used to Resume the debugging process and skip the current breakpoint. It works similar to the cont command in the JDB command line.\nIt is used to stop the debugging process.\nIt works similar to the step in process in the JDB command line. It is used for moving the control to the next line, i.e., point “1” moves to the next line.\nIt works similar to the step over process in the JDB command line.\nIt is used to see on which line the breakpoint is applied.\n"
},
{
"code": null,
"e": 23887,
"s": 23742,
"text": "We apply a breakpoint on the Add class main() method. When we start debugging, the controller gets stuck at the first line of the main() method."
},
{
"code": null,
"e": 24032,
"s": 23887,
"text": "We apply a breakpoint on the Add class main() method. When we start debugging, the controller gets stuck at the first line of the main() method."
},
{
"code": null,
"e": 24170,
"s": 24032,
"text": "It is used to Resume the debugging process and skip the current breakpoint. It works similar to the cont command in the JDB command line."
},
{
"code": null,
"e": 24308,
"s": 24170,
"text": "It is used to Resume the debugging process and skip the current breakpoint. It works similar to the cont command in the JDB command line."
},
{
"code": null,
"e": 24350,
"s": 24308,
"text": "It is used to stop the debugging process."
},
{
"code": null,
"e": 24392,
"s": 24350,
"text": "It is used to stop the debugging process."
},
{
"code": null,
"e": 24549,
"s": 24392,
"text": "It works similar to the step in process in the JDB command line. It is used for moving the control to the next line, i.e., point “1” moves to the next line."
},
{
"code": null,
"e": 24706,
"s": 24549,
"text": "It works similar to the step in process in the JDB command line. It is used for moving the control to the next line, i.e., point “1” moves to the next line."
},
{
"code": null,
"e": 24773,
"s": 24706,
"text": "It works similar to the step over process in the JDB command line."
},
{
"code": null,
"e": 24840,
"s": 24773,
"text": "It works similar to the step over process in the JDB command line."
},
{
"code": null,
"e": 24899,
"s": 24840,
"text": "It is used to see on which line the breakpoint is applied."
},
{
"code": null,
"e": 24958,
"s": 24899,
"text": "It is used to see on which line the breakpoint is applied."
},
{
"code": null,
"e": 25084,
"s": 24958,
"text": "Follow the given steps and sections to debug your code in eclipse IDE. By default, every IDE contains this debugging process."
},
{
"code": null,
"e": 25119,
"s": 25084,
"text": "\n 19 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 25155,
"s": 25119,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 25190,
"s": 25155,
"text": "\n 27 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 25207,
"s": 25190,
"text": " Nicolaas C Kock"
},
{
"code": null,
"e": 25214,
"s": 25207,
"text": " Print"
},
{
"code": null,
"e": 25225,
"s": 25214,
"text": " Add Notes"
}
] |
5 Steps: Setup VS Code for Remote Development via SSH from Windows to Linux system | by Gong Na | Towards Data Science
|
Remote development is a very popular function in VS Code. Their official documentations provide standard instructions to configure it in a general way. But when I connect to the remote Linux server from Windows system, I always got the below Corrupted MAC on input error and hard to find a complete solution in one place.
So, this article will provide a VS Code guidance specific for the remote connection between Windows and Linux systems via key-based SSH which also handles the Corrupted MAC on input error.
For software developers, they usually develop new features locally then test on remote servers.
For data scientists, they need the extra computing resources such as the remote GPU node to support the large data processing.
For DevOps engineers, one of their main tasks is to deploy different products on different servers and this requires frequent remote configurations.
Installed VS Code.
You can download from their website and do the essential setups by following my previous guidance. This guidance also works for the general development workspace.
Installed OpenSSH on both local Windows and remote Linux systems.
To be short, this will allow you work with ssh . You can check it on both systems via ssh -V . It will return you the version of the installed OpenSSH on your system. Otherwise, the OpenSSH is not installed. And you can install it from here for Windows and here for Linux.
Now, let’s start ~ 🚀
Overview of ContentsStep 1: Install the Remote-SSH Extension in VS CodeStep 2: Verify the SSH Connection in PowerShellStep 3: Enable the Remote Connection in VS CodeStep 4: Generate SSH Key PairsStep 5: Copy the Public Key to the Remote Server
[following setup is based on Win10 PowerShell]
Launch VS Code -> click Extension icon in the left bar -> search Remote-SSH in search box -> install it:
Then you will see a little remote connection icon shown in the bottom-left of the Status Bar:
Click the top left Terminal or the shortcut ctrl+shift+` to open a PowerShell terminal in VS Code -> if it’s not PowerShell, change it from here:
Verify SSH connection by executing ssh username@hostname in PowerShell. (It doesn’t matter if you run this in a conda env or not)
If you can successfully login to the remote server, you are ready for the next step.
💢 If you get the Corrupted MAC on input error as below:
✅You can try the following solution:
Run ssh -Q mac first. It will return a list of all available MAC cryptographic algorithms on your local system:
Then, choose one of them as you like and connect to the remote server again by adding the selected algorithm with -m option:
ssh -m hmac-md5-96 username@hostname
You many need to try several times until you find the algorithm which is supported by your remote Linux server.
Now, you should be able login to the remote server and ready for the next step.
Click the left-bottom remote connection icon -> select Remote-SSH: Open Configuration File...
or you can directly open the ssh configuration file from your local home directory ~/.ssh/config .
Add your remote server information in configuration file in below format:
Host [hostname] HostName [hostname] User [username] MACs [optional; if you have the MAC error in Step 2, add the available algorithm which you found to here]
In case you have multiple servers to connect, just keep the format and append them one by one.
At the end, you will get a config file like below: (We will come back to the IdentityFile in the next step)
Now, you should be able to connect to the remote server without MAC error.
Click the remote connection icon in the bottom-left -> select Remote-SSH: Connect to Host... -> you will see a list of remote servers maintained in your config file -> click your target server (you may need to enter your login password)
After the successful connection, you will be navigated to a new VS Code window and the remote host name is shown in the bottom-left:
Until here, you have successfully setup a workable remote development workspace via VS Code. But, not finish yet.
If you stop here, you will be asked to enter the login password every time when you issue a remote connection. And you also need to enter the password for the each single operation on that remote server via VS Code even just open a folder. This would be really annoying. On the other hand, password logins is not secure enough. It’s easy to use and understand for everyone, but this convenience somehow sacrifices the security level. Password can be easily broken by the brute-force attack.
Therefore, instead of entering password in VS Code, it’s better to use SSH public and private key pairs to do the authentication.
In VS Code Powershell terminal, execute the command:
ssh-keygen
During the key generation, it will prompt:
This allows you define a location to store the keys. Press ENTER to leave it as default.
This allows you enter and double confirm a password to protect your private key (when you type, it won’t display your password). After this, you need to enter this password when you use the private key in future. This is an extra protection. You can press ENTER to skip it.
After the creation, you will see a key’s random art image. And your key pairs are stored in the default hidden ~/.sshdirectories:
To double check, you can review he key pairs in above location via:
cd ~/.sshls
You will see two new files id_rsa which stores the private key and id_rsa.pub which stores the public key. Run cat [filename]to check the key content.
If everything is fine. Now, you can add the path of the private key ~/.ssh/id_rsain the ssh configuration file as Step 2 with name of IdentityFile:
Just keep in mind, one public key can be used multiple times and ❗ do NOT share your private key to anyone.
Login to the remote server via VS Code or any other terminal with password. Check if you have the authorized_keys file under~/.ssh directory. If not, create one by following commands:
cd ~/.ssh touch authorized_keys
authorized_keys is the default file name defined by OpenSSH used to store the public keys. You can maintain multiple public keys in this file. Make sure that each key is on a single line and no line-breaks in the middle of the key.
Then maintain your public key (the content in your local ~/.ssh/id_rsa.pub file) in this remote file:
vim authorized_keys -> press i to shift to INSERT mode -> paste your public key content here -> press ESC + : + wq to write into and quit the file -> recheck it by cat authorized_keys .
Now, your secure and convenient remote development workspace in VS Code is ready!
Just go back to your VS Code. Issue a new remote connection. Now, you should be able to connect to the remote server without the password and work on it just as you are locally. Have fun!
|
[
{
"code": null,
"e": 494,
"s": 172,
"text": "Remote development is a very popular function in VS Code. Their official documentations provide standard instructions to configure it in a general way. But when I connect to the remote Linux server from Windows system, I always got the below Corrupted MAC on input error and hard to find a complete solution in one place."
},
{
"code": null,
"e": 683,
"s": 494,
"text": "So, this article will provide a VS Code guidance specific for the remote connection between Windows and Linux systems via key-based SSH which also handles the Corrupted MAC on input error."
},
{
"code": null,
"e": 779,
"s": 683,
"text": "For software developers, they usually develop new features locally then test on remote servers."
},
{
"code": null,
"e": 906,
"s": 779,
"text": "For data scientists, they need the extra computing resources such as the remote GPU node to support the large data processing."
},
{
"code": null,
"e": 1055,
"s": 906,
"text": "For DevOps engineers, one of their main tasks is to deploy different products on different servers and this requires frequent remote configurations."
},
{
"code": null,
"e": 1074,
"s": 1055,
"text": "Installed VS Code."
},
{
"code": null,
"e": 1237,
"s": 1074,
"text": "You can download from their website and do the essential setups by following my previous guidance. This guidance also works for the general development workspace."
},
{
"code": null,
"e": 1303,
"s": 1237,
"text": "Installed OpenSSH on both local Windows and remote Linux systems."
},
{
"code": null,
"e": 1576,
"s": 1303,
"text": "To be short, this will allow you work with ssh . You can check it on both systems via ssh -V . It will return you the version of the installed OpenSSH on your system. Otherwise, the OpenSSH is not installed. And you can install it from here for Windows and here for Linux."
},
{
"code": null,
"e": 1597,
"s": 1576,
"text": "Now, let’s start ~ 🚀"
},
{
"code": null,
"e": 1841,
"s": 1597,
"text": "Overview of ContentsStep 1: Install the Remote-SSH Extension in VS CodeStep 2: Verify the SSH Connection in PowerShellStep 3: Enable the Remote Connection in VS CodeStep 4: Generate SSH Key PairsStep 5: Copy the Public Key to the Remote Server"
},
{
"code": null,
"e": 1888,
"s": 1841,
"text": "[following setup is based on Win10 PowerShell]"
},
{
"code": null,
"e": 1993,
"s": 1888,
"text": "Launch VS Code -> click Extension icon in the left bar -> search Remote-SSH in search box -> install it:"
},
{
"code": null,
"e": 2087,
"s": 1993,
"text": "Then you will see a little remote connection icon shown in the bottom-left of the Status Bar:"
},
{
"code": null,
"e": 2233,
"s": 2087,
"text": "Click the top left Terminal or the shortcut ctrl+shift+` to open a PowerShell terminal in VS Code -> if it’s not PowerShell, change it from here:"
},
{
"code": null,
"e": 2363,
"s": 2233,
"text": "Verify SSH connection by executing ssh username@hostname in PowerShell. (It doesn’t matter if you run this in a conda env or not)"
},
{
"code": null,
"e": 2448,
"s": 2363,
"text": "If you can successfully login to the remote server, you are ready for the next step."
},
{
"code": null,
"e": 2504,
"s": 2448,
"text": "💢 If you get the Corrupted MAC on input error as below:"
},
{
"code": null,
"e": 2541,
"s": 2504,
"text": "✅You can try the following solution:"
},
{
"code": null,
"e": 2653,
"s": 2541,
"text": "Run ssh -Q mac first. It will return a list of all available MAC cryptographic algorithms on your local system:"
},
{
"code": null,
"e": 2778,
"s": 2653,
"text": "Then, choose one of them as you like and connect to the remote server again by adding the selected algorithm with -m option:"
},
{
"code": null,
"e": 2815,
"s": 2778,
"text": "ssh -m hmac-md5-96 username@hostname"
},
{
"code": null,
"e": 2927,
"s": 2815,
"text": "You many need to try several times until you find the algorithm which is supported by your remote Linux server."
},
{
"code": null,
"e": 3007,
"s": 2927,
"text": "Now, you should be able login to the remote server and ready for the next step."
},
{
"code": null,
"e": 3101,
"s": 3007,
"text": "Click the left-bottom remote connection icon -> select Remote-SSH: Open Configuration File..."
},
{
"code": null,
"e": 3200,
"s": 3101,
"text": "or you can directly open the ssh configuration file from your local home directory ~/.ssh/config ."
},
{
"code": null,
"e": 3274,
"s": 3200,
"text": "Add your remote server information in configuration file in below format:"
},
{
"code": null,
"e": 3435,
"s": 3274,
"text": "Host [hostname] HostName [hostname] User [username] MACs [optional; if you have the MAC error in Step 2, add the available algorithm which you found to here]"
},
{
"code": null,
"e": 3530,
"s": 3435,
"text": "In case you have multiple servers to connect, just keep the format and append them one by one."
},
{
"code": null,
"e": 3638,
"s": 3530,
"text": "At the end, you will get a config file like below: (We will come back to the IdentityFile in the next step)"
},
{
"code": null,
"e": 3713,
"s": 3638,
"text": "Now, you should be able to connect to the remote server without MAC error."
},
{
"code": null,
"e": 3950,
"s": 3713,
"text": "Click the remote connection icon in the bottom-left -> select Remote-SSH: Connect to Host... -> you will see a list of remote servers maintained in your config file -> click your target server (you may need to enter your login password)"
},
{
"code": null,
"e": 4083,
"s": 3950,
"text": "After the successful connection, you will be navigated to a new VS Code window and the remote host name is shown in the bottom-left:"
},
{
"code": null,
"e": 4197,
"s": 4083,
"text": "Until here, you have successfully setup a workable remote development workspace via VS Code. But, not finish yet."
},
{
"code": null,
"e": 4688,
"s": 4197,
"text": "If you stop here, you will be asked to enter the login password every time when you issue a remote connection. And you also need to enter the password for the each single operation on that remote server via VS Code even just open a folder. This would be really annoying. On the other hand, password logins is not secure enough. It’s easy to use and understand for everyone, but this convenience somehow sacrifices the security level. Password can be easily broken by the brute-force attack."
},
{
"code": null,
"e": 4818,
"s": 4688,
"text": "Therefore, instead of entering password in VS Code, it’s better to use SSH public and private key pairs to do the authentication."
},
{
"code": null,
"e": 4871,
"s": 4818,
"text": "In VS Code Powershell terminal, execute the command:"
},
{
"code": null,
"e": 4882,
"s": 4871,
"text": "ssh-keygen"
},
{
"code": null,
"e": 4925,
"s": 4882,
"text": "During the key generation, it will prompt:"
},
{
"code": null,
"e": 5014,
"s": 4925,
"text": "This allows you define a location to store the keys. Press ENTER to leave it as default."
},
{
"code": null,
"e": 5288,
"s": 5014,
"text": "This allows you enter and double confirm a password to protect your private key (when you type, it won’t display your password). After this, you need to enter this password when you use the private key in future. This is an extra protection. You can press ENTER to skip it."
},
{
"code": null,
"e": 5418,
"s": 5288,
"text": "After the creation, you will see a key’s random art image. And your key pairs are stored in the default hidden ~/.sshdirectories:"
},
{
"code": null,
"e": 5486,
"s": 5418,
"text": "To double check, you can review he key pairs in above location via:"
},
{
"code": null,
"e": 5498,
"s": 5486,
"text": "cd ~/.sshls"
},
{
"code": null,
"e": 5649,
"s": 5498,
"text": "You will see two new files id_rsa which stores the private key and id_rsa.pub which stores the public key. Run cat [filename]to check the key content."
},
{
"code": null,
"e": 5797,
"s": 5649,
"text": "If everything is fine. Now, you can add the path of the private key ~/.ssh/id_rsain the ssh configuration file as Step 2 with name of IdentityFile:"
},
{
"code": null,
"e": 5905,
"s": 5797,
"text": "Just keep in mind, one public key can be used multiple times and ❗ do NOT share your private key to anyone."
},
{
"code": null,
"e": 6089,
"s": 5905,
"text": "Login to the remote server via VS Code or any other terminal with password. Check if you have the authorized_keys file under~/.ssh directory. If not, create one by following commands:"
},
{
"code": null,
"e": 6123,
"s": 6089,
"text": "cd ~/.ssh touch authorized_keys "
},
{
"code": null,
"e": 6355,
"s": 6123,
"text": "authorized_keys is the default file name defined by OpenSSH used to store the public keys. You can maintain multiple public keys in this file. Make sure that each key is on a single line and no line-breaks in the middle of the key."
},
{
"code": null,
"e": 6457,
"s": 6355,
"text": "Then maintain your public key (the content in your local ~/.ssh/id_rsa.pub file) in this remote file:"
},
{
"code": null,
"e": 6643,
"s": 6457,
"text": "vim authorized_keys -> press i to shift to INSERT mode -> paste your public key content here -> press ESC + : + wq to write into and quit the file -> recheck it by cat authorized_keys ."
},
{
"code": null,
"e": 6725,
"s": 6643,
"text": "Now, your secure and convenient remote development workspace in VS Code is ready!"
}
] |
Visualising economic data using Plotly | by Daniel Foley | Towards Data Science
|
Since I am an Economist by training and love programming and data science I wanted to combine these passions and do some fun data analysis. This post makes use of a variety of python libraries to scrape and visualise economic data. I hope this is useful to some of you and that you enjoy readingthis as much as I did doing it.
The first thing I need to do is get some data. Since Wikipedia is the source of all internet knowledge (not!!) let’s start there. I decided to scrape a table from the following Wikipedia page: [Wiki]. I thought it would be interesting to look at some of the richest and poorest countries in the world. The table in question ranks countries by their GDP per capita.
Before I go any further it is probably a good idea to give a brief explanation of what GDP per capita is (you tend to take for granted that a lot of people don’t really speak “economics”). Simply put, it is a measure of how wealthy a country is. It is essentially the value of all the goods and services produced within a countries borders in a year divided by the population. This gives us a way of describing the average level of wealth per person in that country. It is quite an important economic variable and is often used to compare wealth levels across countries and across time.
In general, GDP per capita can increase for the following reasons.1. GDP increases2. Population decreases3. A combination of both.
This measure is generally thought to be a better indication of a countries wealth than GDP. So now we have the brief econ primer out of the way lets dig into the analysis. As I mentioned before, I will be scrapping data from Wikipedia so using Beautiful soup seems like a no-brainer. This library greatly simplifies extracting data from web pages and is pretty much the go-to library for web scraping in python.
Beautiful soup is a python library for pulling data out of html and xml files. This makes the library extremely useful for extracting info from web pages. If you want more info on how exactly the library works and the various tasks you can perform with beautiful soup, feel free to read the [Documentation]
In order to use beautiful soup, it is worth knowing some simple html tags. Having a little bit of knowledge of html will make it a great deal easier to search for the data we want. For example, Wikipedia uses a table tag for the tables it displays on its web pages. Knowing this, we can simply parse the html and look only for information contained within these tags.
First off I need to import all the necessary libraries for the analysis.
import requestsfrom bs4 import BeautifulSoupimport matplotlib.pyplot as pltimport seaborn as sns%matplotlib inlinefrom bubbly.bubbly import bubbleplotfrom plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplotimport plotly as pyimport plotly.graph_objs as goinit_notebook_mode(connected=True) #do not miss this linefrom plotly import tools
Now that I have loaded the libraries in we are ready to start the analysis.The code below allows us to load the webpage into our Jupyter notebook and pass it to the BeautifulSoup class to create a soup object.
web_page=“https://en.wikipedia.org/wiki/List_of_countries_by_GDP_(PPP)_per_capita"req=requests.get(web_page)page = req.textsoup = BeautifulSoup(page, ‘html.parser’)soup.title
Ok so it looks like it worked and we can use some functions on the soup object and extract the data we want. I mentioned before that we were interested in the table tag. Below is the code to extract all of the tables from the wiki page.
table = soup.find_all(“table”, “wikitable”)len(table)from IPython.display import IFrame, HTMLHTML(str(table))
The code above returns a list where each entry contains one of the tables on the page. This page only has five tables so it is pretty easy to just get the table we need which happens to be the first entry in the list. We can also confirm whether it is by using the HTML command from IPython.display which prints the table as it appears on Wikipedia.
Now that we have the table it is just a matter of getting the country names and the GDP per capita. To do this, we need to know a bit more about the structure of HTML tables. In particular, we should know about the <th>, <tr> and <td> tags. These stand for table header, table row, and cell respectively. Ok so let’s try extracting some of the data.
GDP_PC = table[0]table_rows = GDP_PC.find_all(‘tr’)header = table_rows[1]table_rows[1].a.get_text()
This code finds all the tr tags which indicate the rows of the table. We then get the header of the table and print it out to give the results below. This corresponds to the country names and we extract the name we need using a.get_text(). Each index in table_rows corresponds to a country and the country name is located in the <a> tag and is the same for each value of the index.
Now, all we need to do to get all the country names is to loop through table_rows, extract the data and append to a list.
countries = [table_rows[i].a.get_text() for i in range(len(table_rows))[1:]]cols = [col.get_text() for col in header.find_all(‘th’)]
Python has a really nice succinct way of coding these kinds of loops using list comprehensions. Note I skip the first entry of table_rows as it does not correspond to a country. We also use a list comprehension to extract the column headers which will be useful later on. The above code is equivalent to the for loop below.
country = []for i in range(len(table_rows))[1:]: country.append(table_rows[i].a.get_text())
Next up is the <td> tag. This is where our GDP per capita data is stored in the table. The data is pretty messy, however, and there are a number of workarounds we can use to get the correct data out and into the right format. Let’s take a quick look at one of the data points.
temp = GDP_PC.find_all(‘td’)temp[5].get_text()
This gives us ‘114,430\n’. We can see that all the data is defined as stringsand there are commas and line breaks in each cell so we will need to fix this later. First, let’s concentrate on getting the data into a list.
temp = GDP_PC.find_all(‘td’)GDP_per_capita = [temp[i].get_text() for i in range(len(temp)) if “,” in temp[i].get_text()]GDP_per_capita = [i for i in GDP_per_capita if ‘\xa0’ not in i]temp_list = []for i in range(len(temp)): temp_list.append(temp[i].get_text())new_list = temp_list[-11:]numbers = [i for i in new_list if “\n” in i]for i in numbers: GDP_per_capita.append(i)rank = list(range(len(countries)))
There is a lot going on in the code above so let’s go through it step by step.The first thing I do is find all the cells in GDP_PC and store in a temp variable.The next line loops through this variable and grabs the text if it contains a comma. I did this since most of the entries are in the thousands and therefore contain a comma. This approach does, however, miss the last four entries as they are hundreds of dollars so I have to create a workaround for that which is what the new_list and numbers variables are doing. Finally, I append these entries onto the GDP_per_capita list and also generate a rank column which is just numbers from 1 to 192. This may not be the most efficient way of doing this and there is probably a better way but hey it worked so I am happy with it.
After extracting the three columns, rank, country and GDP per capita as lists we need to merge these together and create a pandas data frame. This will make plotting and analysing the data much simpler. There is a handy function called zip that allows us to do this allowing us to create two separate data frames. One for the top 20 richest countries and one for the bottom twenty poorest countries. The code below implements this.
data = zip(rank[0:21],countries[0:21], GDP_pc[0:21])import pandas as pdcols = [‘Rank’, ‘Country’, ‘GDP Per Capita’]data1 = pd.DataFrame(list(data), columns = cols)data2 = zip(rank[-21:],countries[-21:], GDP_pc[-21:])data2 = pd.DataFrame(list(data2), columns = cols)
We now have our top and bottom 20 countries in pandas data frames. Before we can plot the data we need to do a little bit more cleaning. The data are currently defined as strings so we need to fix this in order to use certain Pandas functions. The code below removes HTML line breaks “\n”, commas and defines the data type as int.
data1['GDP Per Capita'] = data1['GDP Per Capita'].apply(lambda x: x.replace('\n', '')).astype(int)data2['GDP Per Capita'] = data1['GDP Per Capita'].apply(lambda x: x.replace(',', '')).astype(int)
We finally have our data ready to create some nice looking visualisations.
Now we can move onto Plotly to create what I think are really nice visualisations. I really like this library and it is simple enough to make pretty interactive plots. If you want to know about what kind of graphs you can create I encourage you to read the documentation [Website]
Below is the code to create a simple bar chart of the top 10 richest countries in the world. First, we pass the data to go.Bar to create a bar chart with the country names on the x-axis and the GDP per capita on the y-axis. We then store this in a list and it gets passed to the go.Figure method. The same steps here apply to create all the different types of plots in Plotly. Some of the results may or may not surprise you. For example, the top 10 is littered with countries heavily focused on producing oil such as Qatar and Kuwait who get approximately 70 and 94 per cent of government revenue from oil. A lot of these countries tend to have relatively small populations and large economies so it is not really surprising that they are very rich based on this measure (a lot of wealth to share out among a relatively small population).
trace1 = go.Bar( x = data1.Country, y = data1[‘GDP Per Capita’])data = [trace1]layout = go.Layout( title=’Top 20 countries ranked by GDP per Capita’)fig = go.Figure(data = data, layout = layout)py.offline.iplot(fig)
Pretty easy right? Now for the poorest countries. Not surprisingly, these countries tend to be concentrated in Africa where populations tend to grow rapidly and the economies lag behind the more developed nations.
After getting a quick overview of the top 10 and bottom 10 countries lets try and get a more broad overview looking at the world as a whole. A good way of doing this is by using a map. In Plotly you can create choropleth maps which shade the different regions based on some variable. In our case that is GDP per capita. Countries with a higher GDP per capita will have a darker shade of red. The most important things to note about this code is the country names passed into the locations argument and the location mode argument. These must match for the plot to work. You can also use country codes and even longitude and latitude to achieve the same plot but I think this is probably the easiest way. Notice that Plotly allows you to zoom in to particular regions for a closer look which is a really nice feature.
We can see that the richest countries tend to be centered in North America Europe, and the oil producing nations while the poorest countries are in Africa denoted by the lighter colour.
data = [ dict( type=’choropleth’, locations = data_all[‘Country’], autocolorscale = True, z = data_all[‘GDP Per Capita’], locationmode = ‘country names’, marker = dict( line = dict ( color = ‘rgb(255,255,255)’, width = 2 ) ), colorbar = dict( title = “Millions USD” ) ) ]layout = dict( title = ‘Top Countries by GDP per capital’)fig = go.Figure(data = data, layout = layout)py.offline.iplot(fig)
Ok, now that I have shown you some simple plots using Plotly I want to go a step further and create something really cool. There is a really nice library called bubbly which creates bubble charts and has some interesting features to enhance the level of interactivity you can have with your charts. You can do this with Plotly but there is quite a bit of coding involved to achieve the desired effect and bubbly makes it super easy. Credit to [Aashitak] for this library. There is also a nice [kaggle kernel] showing how the library works under the hood and is definitely worth checking out.
What I want to do here is create a bubble chart looking at GDP per capita vs life expectancy. The chart also takes into account the population of each country and what continent the country is in. I obtained all of the data from the world bank website. Below is the code to read the data in using pandas and I create a list of unique values of the countries, continents and years which will be useful for manipulating the data. As it turns out this is a pretty famous visualisation created by the gapminder foundation. They have a really nice tool for plotting this and other charts available [Here] if anyone wants to check it out.
The world bank data that I use here is in a completely different format then the gapminder_indicator dataset on Kaggle (which this plot is originally based on). To use the bubble library we need the data to be in the format of the latter so there is a bit of data manipulation required. The reason I used the world bank data is that it has a slightly longer time series and I wanted to get a view of more recent developments. The code below loads the datasets in and extracts the same countries that are used in the gapminder dataset.
gdp = pd.read_csv(“gdp_per_capota.csv”, engine = “python”)life = pd.read_csv(“LifeExp.csv”, engine = “python”)pop = pd.read_csv(“population.csv”, engine = “python”)gapminder_indicators = pd.read_csv(“gapminder_indicators.csv”, engine = “python”)countries = gapminder_indicators.country.unique()continents = gapminder_indicators.continent.unique()years = gapminder_indicators.year.unique()[‘Country Name’, ‘1982’, ‘1987’, ‘1992’, ‘1997’, ‘2002’, ‘2007’, ‘2010’, ‘2013’, ‘2016’]# Filter countries firstgdp_new = gdp[gdp[‘Country Name’].isin(countries)]life_new = life[life[‘Country Name’].isin(countries)]pop_new = pop[pop[‘Country Name’].isin(countries)]# # Now filter yearsyears = [str(year) for year in years]years = years[6:]for i in [‘2010’, ‘2013’, ‘2016’]: years.append(i)years.insert(0,”Country Name”)gdp_new = gdp_new[years]life_new = life_new[years]pop_new = pop_new[years]
The gapminder_indicator dataset has the data in the correct format (long format, see below) for plotting so essentially we need to manipulate the three datasets into the same format and merge them together before I can plot them using bubbly.
country continent year lifeExp pop gdpPercap Afghanistan Asia 1952 28.801 8425333 779.445314 Afghanistan Asia 1957 30.332 9240934 820.853030 Afghanistan Asia 1962 31.997 10267083 853.100710 Afghanistan Asia 1967 34.020 11537966 836.197138 Afghanistan Asia 1972 36.088 13079460 739.981106
The world banks data set is formatted differently with the population for each year being allocated a different column (wide format). Below is the code I use to manipulate the world bank data into the correct format.
Country name 1960 1961 1962 Aruba 54211.0 55438.0 56225.0 Afghanistan 8996351.0 9166764.0 9345868.0 Angola 5643182.0 5753024.0 5866061.0 Albania 1608800.0 1659800.0 1711319.0 Andorra 13411.0 14375.0 15370.0melted_gdp = pd.melt(gdp_new, id_vars = ["Country Name"], var_name = "Year", value_name = "Data")grouped_gdp = melted_gdp.groupby(["Country Name"]).apply(lambda x: x.sort_values(["Year"], ascending = True)).reset_index(drop=True)melted_life = pd.melt(life_new, id_vars = ["Country Name"], var_name = "Year", value_name = "Data")grouped_life = melted_life.groupby(["Country Name"]).apply(lambda x: x.sort_values(["Year"], ascending = True)).reset_index(drop=True)melted_pop = pd.melt(pop_new, id_vars = ["Country Name"], var_name = "Year", value_name = "Data")grouped_pop = melted_pop.groupby(["Country Name"]).apply(lambda x: x.sort_values(["Year"], ascending = True)).reset_index(drop=True)temp = pd.merge(grouped_gdp, grouped_life, on = ['Country Name', 'Year'], how = 'inner')temp = pd.merge(temp, grouped_pop, on = ['Country Name', 'Year'], how = 'inner')cols= ['Country Name', 'Year', 'Data_x', 'Data_y', 'Data']temp = temp[cols]data = temp.copy()
Let me explain what I am doing here. The melt function collapses all the year columns into one row alongside the values for each year in the values row. I then groupby the country names and sort each row by year so I am left with a dataset that has the country sorted alphabetically and year sorted chronologically. This is the same as the gapminder_indicators. The datasets are then merged datasets on the country name and year. I think you may be able to this in one Pandas function but I decided to do it in a bit more of a manual way as it is a good way of practicing how to manipulate data step by step.
The other thing we need to do now is to create a continent column which maps the country to the correct continent as this information will be used when plotting. To do this we create a dictionary using the gapminder dataset and then map this dictionary to a new column in my merged dataset.
dictionary = dict(zip(gapminder_indicators[‘country’], gapminder_indicators[‘continent’]))data[“continent”] = data[“Country Name”].map(dictionary)data.rename(columns = {‘Data_x’: ‘GDP_pc’, ‘Data_y’: ‘Life Expectancy’, ‘Data’: ‘Population’}, inplace=True)
Finally, we have a finished dataset and we can create our plot. We use the bubbleplot function in the bubbly library to do this. The function creates a beautiful interactive plot of life expectancy vs GDP per capita and plots the size of the bubble according to the population of the country. The bubbles are also coloured by the continent and we are able to plot all of this information across time which is really nice. The most notable changes are China and India indicated by the largest purple bubbles. At the start of the sample, they were among the poorest countries and had a relatively low life expectancy.Over time, however, the made a substantial move towards the upper right of the chart indicating large increases in both GDP per capita and life expectancy. This pretty much mirrors what we have seen with China becoming an economic powerhouse over the last 20 years or so.
What is also clear from the chart is that there is a positive correlation between GDP per capita and Life Expectancy. As one increases the other also tends to increase. Of course, this tells us nothing about any causal relationship and it is unclear whether countries have a higher life expectancy because they are rich or countries are rich because they have a higher life expectancy. That is perhaps a question for an economics research paper and not this particular blog post.
So that is how you can extract data from the internet using beautiful soup and also how to use data visualisations to interpret and uncover trends in data which might not be immediately obvious looking at the raw data.
from bubbly.bubbly import bubbleplotfigure = bubbleplot(dataset=data, x_column=’GDP_pc’, y_column=’Life Expectancy’, bubble_column=’Country Name’, time_column=’Year’, size_column=’Population’, color_column=’continent’, x_title=”GDP per Capita”, y_title=”Life Expectancy”, title=’Gapminder Global Indicators’, x_logscale=True, scale_bubble=3, height=650)iplot(figure, config={‘scrollzoom’: True})
Link to my original blog post: https://dfoly.github.io/blog/2018/08/10/Economic-data-plotly.html
|
[
{
"code": null,
"e": 499,
"s": 172,
"text": "Since I am an Economist by training and love programming and data science I wanted to combine these passions and do some fun data analysis. This post makes use of a variety of python libraries to scrape and visualise economic data. I hope this is useful to some of you and that you enjoy readingthis as much as I did doing it."
},
{
"code": null,
"e": 864,
"s": 499,
"text": "The first thing I need to do is get some data. Since Wikipedia is the source of all internet knowledge (not!!) let’s start there. I decided to scrape a table from the following Wikipedia page: [Wiki]. I thought it would be interesting to look at some of the richest and poorest countries in the world. The table in question ranks countries by their GDP per capita."
},
{
"code": null,
"e": 1451,
"s": 864,
"text": "Before I go any further it is probably a good idea to give a brief explanation of what GDP per capita is (you tend to take for granted that a lot of people don’t really speak “economics”). Simply put, it is a measure of how wealthy a country is. It is essentially the value of all the goods and services produced within a countries borders in a year divided by the population. This gives us a way of describing the average level of wealth per person in that country. It is quite an important economic variable and is often used to compare wealth levels across countries and across time."
},
{
"code": null,
"e": 1582,
"s": 1451,
"text": "In general, GDP per capita can increase for the following reasons.1. GDP increases2. Population decreases3. A combination of both."
},
{
"code": null,
"e": 1994,
"s": 1582,
"text": "This measure is generally thought to be a better indication of a countries wealth than GDP. So now we have the brief econ primer out of the way lets dig into the analysis. As I mentioned before, I will be scrapping data from Wikipedia so using Beautiful soup seems like a no-brainer. This library greatly simplifies extracting data from web pages and is pretty much the go-to library for web scraping in python."
},
{
"code": null,
"e": 2301,
"s": 1994,
"text": "Beautiful soup is a python library for pulling data out of html and xml files. This makes the library extremely useful for extracting info from web pages. If you want more info on how exactly the library works and the various tasks you can perform with beautiful soup, feel free to read the [Documentation]"
},
{
"code": null,
"e": 2669,
"s": 2301,
"text": "In order to use beautiful soup, it is worth knowing some simple html tags. Having a little bit of knowledge of html will make it a great deal easier to search for the data we want. For example, Wikipedia uses a table tag for the tables it displays on its web pages. Knowing this, we can simply parse the html and look only for information contained within these tags."
},
{
"code": null,
"e": 2742,
"s": 2669,
"text": "First off I need to import all the necessary libraries for the analysis."
},
{
"code": null,
"e": 3102,
"s": 2742,
"text": "import requestsfrom bs4 import BeautifulSoupimport matplotlib.pyplot as pltimport seaborn as sns%matplotlib inlinefrom bubbly.bubbly import bubbleplotfrom plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplotimport plotly as pyimport plotly.graph_objs as goinit_notebook_mode(connected=True) #do not miss this linefrom plotly import tools"
},
{
"code": null,
"e": 3312,
"s": 3102,
"text": "Now that I have loaded the libraries in we are ready to start the analysis.The code below allows us to load the webpage into our Jupyter notebook and pass it to the BeautifulSoup class to create a soup object."
},
{
"code": null,
"e": 3487,
"s": 3312,
"text": "web_page=“https://en.wikipedia.org/wiki/List_of_countries_by_GDP_(PPP)_per_capita\"req=requests.get(web_page)page = req.textsoup = BeautifulSoup(page, ‘html.parser’)soup.title"
},
{
"code": null,
"e": 3724,
"s": 3487,
"text": "Ok so it looks like it worked and we can use some functions on the soup object and extract the data we want. I mentioned before that we were interested in the table tag. Below is the code to extract all of the tables from the wiki page."
},
{
"code": null,
"e": 3834,
"s": 3724,
"text": "table = soup.find_all(“table”, “wikitable”)len(table)from IPython.display import IFrame, HTMLHTML(str(table))"
},
{
"code": null,
"e": 4184,
"s": 3834,
"text": "The code above returns a list where each entry contains one of the tables on the page. This page only has five tables so it is pretty easy to just get the table we need which happens to be the first entry in the list. We can also confirm whether it is by using the HTML command from IPython.display which prints the table as it appears on Wikipedia."
},
{
"code": null,
"e": 4534,
"s": 4184,
"text": "Now that we have the table it is just a matter of getting the country names and the GDP per capita. To do this, we need to know a bit more about the structure of HTML tables. In particular, we should know about the <th>, <tr> and <td> tags. These stand for table header, table row, and cell respectively. Ok so let’s try extracting some of the data."
},
{
"code": null,
"e": 4634,
"s": 4534,
"text": "GDP_PC = table[0]table_rows = GDP_PC.find_all(‘tr’)header = table_rows[1]table_rows[1].a.get_text()"
},
{
"code": null,
"e": 5016,
"s": 4634,
"text": "This code finds all the tr tags which indicate the rows of the table. We then get the header of the table and print it out to give the results below. This corresponds to the country names and we extract the name we need using a.get_text(). Each index in table_rows corresponds to a country and the country name is located in the <a> tag and is the same for each value of the index."
},
{
"code": null,
"e": 5138,
"s": 5016,
"text": "Now, all we need to do to get all the country names is to loop through table_rows, extract the data and append to a list."
},
{
"code": null,
"e": 5271,
"s": 5138,
"text": "countries = [table_rows[i].a.get_text() for i in range(len(table_rows))[1:]]cols = [col.get_text() for col in header.find_all(‘th’)]"
},
{
"code": null,
"e": 5595,
"s": 5271,
"text": "Python has a really nice succinct way of coding these kinds of loops using list comprehensions. Note I skip the first entry of table_rows as it does not correspond to a country. We also use a list comprehension to extract the column headers which will be useful later on. The above code is equivalent to the for loop below."
},
{
"code": null,
"e": 5687,
"s": 5595,
"text": "country = []for i in range(len(table_rows))[1:]: country.append(table_rows[i].a.get_text())"
},
{
"code": null,
"e": 5964,
"s": 5687,
"text": "Next up is the <td> tag. This is where our GDP per capita data is stored in the table. The data is pretty messy, however, and there are a number of workarounds we can use to get the correct data out and into the right format. Let’s take a quick look at one of the data points."
},
{
"code": null,
"e": 6011,
"s": 5964,
"text": "temp = GDP_PC.find_all(‘td’)temp[5].get_text()"
},
{
"code": null,
"e": 6231,
"s": 6011,
"text": "This gives us ‘114,430\\n’. We can see that all the data is defined as stringsand there are commas and line breaks in each cell so we will need to fix this later. First, let’s concentrate on getting the data into a list."
},
{
"code": null,
"e": 6638,
"s": 6231,
"text": "temp = GDP_PC.find_all(‘td’)GDP_per_capita = [temp[i].get_text() for i in range(len(temp)) if “,” in temp[i].get_text()]GDP_per_capita = [i for i in GDP_per_capita if ‘\\xa0’ not in i]temp_list = []for i in range(len(temp)): temp_list.append(temp[i].get_text())new_list = temp_list[-11:]numbers = [i for i in new_list if “\\n” in i]for i in numbers: GDP_per_capita.append(i)rank = list(range(len(countries)))"
},
{
"code": null,
"e": 7421,
"s": 6638,
"text": "There is a lot going on in the code above so let’s go through it step by step.The first thing I do is find all the cells in GDP_PC and store in a temp variable.The next line loops through this variable and grabs the text if it contains a comma. I did this since most of the entries are in the thousands and therefore contain a comma. This approach does, however, miss the last four entries as they are hundreds of dollars so I have to create a workaround for that which is what the new_list and numbers variables are doing. Finally, I append these entries onto the GDP_per_capita list and also generate a rank column which is just numbers from 1 to 192. This may not be the most efficient way of doing this and there is probably a better way but hey it worked so I am happy with it."
},
{
"code": null,
"e": 7853,
"s": 7421,
"text": "After extracting the three columns, rank, country and GDP per capita as lists we need to merge these together and create a pandas data frame. This will make plotting and analysing the data much simpler. There is a handy function called zip that allows us to do this allowing us to create two separate data frames. One for the top 20 richest countries and one for the bottom twenty poorest countries. The code below implements this."
},
{
"code": null,
"e": 8119,
"s": 7853,
"text": "data = zip(rank[0:21],countries[0:21], GDP_pc[0:21])import pandas as pdcols = [‘Rank’, ‘Country’, ‘GDP Per Capita’]data1 = pd.DataFrame(list(data), columns = cols)data2 = zip(rank[-21:],countries[-21:], GDP_pc[-21:])data2 = pd.DataFrame(list(data2), columns = cols)"
},
{
"code": null,
"e": 8450,
"s": 8119,
"text": "We now have our top and bottom 20 countries in pandas data frames. Before we can plot the data we need to do a little bit more cleaning. The data are currently defined as strings so we need to fix this in order to use certain Pandas functions. The code below removes HTML line breaks “\\n”, commas and defines the data type as int."
},
{
"code": null,
"e": 8646,
"s": 8450,
"text": "data1['GDP Per Capita'] = data1['GDP Per Capita'].apply(lambda x: x.replace('\\n', '')).astype(int)data2['GDP Per Capita'] = data1['GDP Per Capita'].apply(lambda x: x.replace(',', '')).astype(int)"
},
{
"code": null,
"e": 8721,
"s": 8646,
"text": "We finally have our data ready to create some nice looking visualisations."
},
{
"code": null,
"e": 9002,
"s": 8721,
"text": "Now we can move onto Plotly to create what I think are really nice visualisations. I really like this library and it is simple enough to make pretty interactive plots. If you want to know about what kind of graphs you can create I encourage you to read the documentation [Website]"
},
{
"code": null,
"e": 9842,
"s": 9002,
"text": "Below is the code to create a simple bar chart of the top 10 richest countries in the world. First, we pass the data to go.Bar to create a bar chart with the country names on the x-axis and the GDP per capita on the y-axis. We then store this in a list and it gets passed to the go.Figure method. The same steps here apply to create all the different types of plots in Plotly. Some of the results may or may not surprise you. For example, the top 10 is littered with countries heavily focused on producing oil such as Qatar and Kuwait who get approximately 70 and 94 per cent of government revenue from oil. A lot of these countries tend to have relatively small populations and large economies so it is not really surprising that they are very rich based on this measure (a lot of wealth to share out among a relatively small population)."
},
{
"code": null,
"e": 10058,
"s": 9842,
"text": "trace1 = go.Bar( x = data1.Country, y = data1[‘GDP Per Capita’])data = [trace1]layout = go.Layout( title=’Top 20 countries ranked by GDP per Capita’)fig = go.Figure(data = data, layout = layout)py.offline.iplot(fig)"
},
{
"code": null,
"e": 10272,
"s": 10058,
"text": "Pretty easy right? Now for the poorest countries. Not surprisingly, these countries tend to be concentrated in Africa where populations tend to grow rapidly and the economies lag behind the more developed nations."
},
{
"code": null,
"e": 11088,
"s": 10272,
"text": "After getting a quick overview of the top 10 and bottom 10 countries lets try and get a more broad overview looking at the world as a whole. A good way of doing this is by using a map. In Plotly you can create choropleth maps which shade the different regions based on some variable. In our case that is GDP per capita. Countries with a higher GDP per capita will have a darker shade of red. The most important things to note about this code is the country names passed into the locations argument and the location mode argument. These must match for the plot to work. You can also use country codes and even longitude and latitude to achieve the same plot but I think this is probably the easiest way. Notice that Plotly allows you to zoom in to particular regions for a closer look which is a really nice feature."
},
{
"code": null,
"e": 11274,
"s": 11088,
"text": "We can see that the richest countries tend to be centered in North America Europe, and the oil producing nations while the poorest countries are in Africa denoted by the lighter colour."
},
{
"code": null,
"e": 11670,
"s": 11274,
"text": "data = [ dict( type=’choropleth’, locations = data_all[‘Country’], autocolorscale = True, z = data_all[‘GDP Per Capita’], locationmode = ‘country names’, marker = dict( line = dict ( color = ‘rgb(255,255,255)’, width = 2 ) ), colorbar = dict( title = “Millions USD” ) ) ]layout = dict( title = ‘Top Countries by GDP per capital’)fig = go.Figure(data = data, layout = layout)py.offline.iplot(fig)"
},
{
"code": null,
"e": 12262,
"s": 11670,
"text": "Ok, now that I have shown you some simple plots using Plotly I want to go a step further and create something really cool. There is a really nice library called bubbly which creates bubble charts and has some interesting features to enhance the level of interactivity you can have with your charts. You can do this with Plotly but there is quite a bit of coding involved to achieve the desired effect and bubbly makes it super easy. Credit to [Aashitak] for this library. There is also a nice [kaggle kernel] showing how the library works under the hood and is definitely worth checking out."
},
{
"code": null,
"e": 12895,
"s": 12262,
"text": "What I want to do here is create a bubble chart looking at GDP per capita vs life expectancy. The chart also takes into account the population of each country and what continent the country is in. I obtained all of the data from the world bank website. Below is the code to read the data in using pandas and I create a list of unique values of the countries, continents and years which will be useful for manipulating the data. As it turns out this is a pretty famous visualisation created by the gapminder foundation. They have a really nice tool for plotting this and other charts available [Here] if anyone wants to check it out."
},
{
"code": null,
"e": 13430,
"s": 12895,
"text": "The world bank data that I use here is in a completely different format then the gapminder_indicator dataset on Kaggle (which this plot is originally based on). To use the bubble library we need the data to be in the format of the latter so there is a bit of data manipulation required. The reason I used the world bank data is that it has a slightly longer time series and I wanted to get a view of more recent developments. The code below loads the datasets in and extracts the same countries that are used in the gapminder dataset."
},
{
"code": null,
"e": 14312,
"s": 13430,
"text": "gdp = pd.read_csv(“gdp_per_capota.csv”, engine = “python”)life = pd.read_csv(“LifeExp.csv”, engine = “python”)pop = pd.read_csv(“population.csv”, engine = “python”)gapminder_indicators = pd.read_csv(“gapminder_indicators.csv”, engine = “python”)countries = gapminder_indicators.country.unique()continents = gapminder_indicators.continent.unique()years = gapminder_indicators.year.unique()[‘Country Name’, ‘1982’, ‘1987’, ‘1992’, ‘1997’, ‘2002’, ‘2007’, ‘2010’, ‘2013’, ‘2016’]# Filter countries firstgdp_new = gdp[gdp[‘Country Name’].isin(countries)]life_new = life[life[‘Country Name’].isin(countries)]pop_new = pop[pop[‘Country Name’].isin(countries)]# # Now filter yearsyears = [str(year) for year in years]years = years[6:]for i in [‘2010’, ‘2013’, ‘2016’]: years.append(i)years.insert(0,”Country Name”)gdp_new = gdp_new[years]life_new = life_new[years]pop_new = pop_new[years]"
},
{
"code": null,
"e": 14555,
"s": 14312,
"text": "The gapminder_indicator dataset has the data in the correct format (long format, see below) for plotting so essentially we need to manipulate the three datasets into the same format and merge them together before I can plot them using bubbly."
},
{
"code": null,
"e": 14899,
"s": 14555,
"text": " country continent year lifeExp pop gdpPercap Afghanistan Asia 1952 28.801 8425333 779.445314 Afghanistan Asia 1957 30.332 9240934 820.853030 Afghanistan Asia 1962 31.997 10267083 853.100710 Afghanistan Asia 1967 34.020 11537966 836.197138 Afghanistan Asia 1972 36.088 13079460 739.981106"
},
{
"code": null,
"e": 15116,
"s": 14899,
"text": "The world banks data set is formatted differently with the population for each year being allocated a different column (wide format). Below is the code I use to manipulate the world bank data into the correct format."
},
{
"code": null,
"e": 16323,
"s": 15116,
"text": "Country name 1960 1961 1962 Aruba 54211.0 55438.0 56225.0 Afghanistan 8996351.0 9166764.0 9345868.0 Angola 5643182.0 5753024.0 5866061.0 Albania 1608800.0 1659800.0 1711319.0 Andorra 13411.0 14375.0 15370.0melted_gdp = pd.melt(gdp_new, id_vars = [\"Country Name\"], var_name = \"Year\", value_name = \"Data\")grouped_gdp = melted_gdp.groupby([\"Country Name\"]).apply(lambda x: x.sort_values([\"Year\"], ascending = True)).reset_index(drop=True)melted_life = pd.melt(life_new, id_vars = [\"Country Name\"], var_name = \"Year\", value_name = \"Data\")grouped_life = melted_life.groupby([\"Country Name\"]).apply(lambda x: x.sort_values([\"Year\"], ascending = True)).reset_index(drop=True)melted_pop = pd.melt(pop_new, id_vars = [\"Country Name\"], var_name = \"Year\", value_name = \"Data\")grouped_pop = melted_pop.groupby([\"Country Name\"]).apply(lambda x: x.sort_values([\"Year\"], ascending = True)).reset_index(drop=True)temp = pd.merge(grouped_gdp, grouped_life, on = ['Country Name', 'Year'], how = 'inner')temp = pd.merge(temp, grouped_pop, on = ['Country Name', 'Year'], how = 'inner')cols= ['Country Name', 'Year', 'Data_x', 'Data_y', 'Data']temp = temp[cols]data = temp.copy()"
},
{
"code": null,
"e": 16932,
"s": 16323,
"text": "Let me explain what I am doing here. The melt function collapses all the year columns into one row alongside the values for each year in the values row. I then groupby the country names and sort each row by year so I am left with a dataset that has the country sorted alphabetically and year sorted chronologically. This is the same as the gapminder_indicators. The datasets are then merged datasets on the country name and year. I think you may be able to this in one Pandas function but I decided to do it in a bit more of a manual way as it is a good way of practicing how to manipulate data step by step."
},
{
"code": null,
"e": 17223,
"s": 16932,
"text": "The other thing we need to do now is to create a continent column which maps the country to the correct continent as this information will be used when plotting. To do this we create a dictionary using the gapminder dataset and then map this dictionary to a new column in my merged dataset."
},
{
"code": null,
"e": 17478,
"s": 17223,
"text": "dictionary = dict(zip(gapminder_indicators[‘country’], gapminder_indicators[‘continent’]))data[“continent”] = data[“Country Name”].map(dictionary)data.rename(columns = {‘Data_x’: ‘GDP_pc’, ‘Data_y’: ‘Life Expectancy’, ‘Data’: ‘Population’}, inplace=True)"
},
{
"code": null,
"e": 18365,
"s": 17478,
"text": "Finally, we have a finished dataset and we can create our plot. We use the bubbleplot function in the bubbly library to do this. The function creates a beautiful interactive plot of life expectancy vs GDP per capita and plots the size of the bubble according to the population of the country. The bubbles are also coloured by the continent and we are able to plot all of this information across time which is really nice. The most notable changes are China and India indicated by the largest purple bubbles. At the start of the sample, they were among the poorest countries and had a relatively low life expectancy.Over time, however, the made a substantial move towards the upper right of the chart indicating large increases in both GDP per capita and life expectancy. This pretty much mirrors what we have seen with China becoming an economic powerhouse over the last 20 years or so."
},
{
"code": null,
"e": 18845,
"s": 18365,
"text": "What is also clear from the chart is that there is a positive correlation between GDP per capita and Life Expectancy. As one increases the other also tends to increase. Of course, this tells us nothing about any causal relationship and it is unclear whether countries have a higher life expectancy because they are rich or countries are rich because they have a higher life expectancy. That is perhaps a question for an economics research paper and not this particular blog post."
},
{
"code": null,
"e": 19064,
"s": 18845,
"text": "So that is how you can extract data from the internet using beautiful soup and also how to use data visualisations to interpret and uncover trends in data which might not be immediately obvious looking at the raw data."
},
{
"code": null,
"e": 19462,
"s": 19064,
"text": "from bubbly.bubbly import bubbleplotfigure = bubbleplot(dataset=data, x_column=’GDP_pc’, y_column=’Life Expectancy’, bubble_column=’Country Name’, time_column=’Year’, size_column=’Population’, color_column=’continent’, x_title=”GDP per Capita”, y_title=”Life Expectancy”, title=’Gapminder Global Indicators’, x_logscale=True, scale_bubble=3, height=650)iplot(figure, config={‘scrollzoom’: True})"
}
] |
C program for Time Complexity plot of Bubble, Insertion and Selection Sort using Gnuplot - GeeksforGeeks
|
24 Nov, 2021
Prerequisite:Comparison among bubble sort, insertion sort and selection sort.
Write a C program to plot and analyze the time complexity of Bubble sort, Insertion sort and Selection sort (using Gnuplot).As per the problem we have to plot a time complexity graph by just using C. So we will be making sorting algorithms as functions and all the algorithms are given to sort exactly the same array to keep the comparison fair.
Examples:
Input: randomly generated arrays (using rand() function)
of different sizes as input for sorting.
Output:
A_size, Bubble, Insertion, Selection
10000, 366263, 80736, 152975
20000, 1594932, 332101, 609388
30000, 3773121, 785790, 1441547
40000, 7174455, 1574855, 2620006
50000, 10917061, 2029586, 4025993
60000, 15484338, 2998403, 5556494
70000, 21201561, 4146680, 7678139
80000, 29506758, 6027335, 10131950
90000, 36457272, 6699452, 12436376
100000, 43472313, 8335881, 15208712
Approach: We will be using arrays of different sizes to plot the graph between the time taken by the sorting algorithm versus array size. Execution of the program will take some time for sorting arrays of size up to 100000 elements.
Below is the implementation of the above approach:
// C program to store time taken by bubble sort,// insertion sort and selection sort// for sorting exactly same arrays. #include <stdio.h>#include <stdlib.h>#include <time.h> // Swap utilityvoid swap(long int* a, long int* b){ int tmp = *a; *a = *b; *b = tmp;} // Bubble sortvoid bubbleSort(long int a[], long int n){ for (long int i = 0; i < n - 1; i++) { for (long int j = 0; j < n - 1 - i; j++) { if (a[j] > a[j + 1]) { swap(&a[j], &a[j + 1]); } } }} // Insertion sortvoid insertionSort(long int arr[], long int n){ long int i, key, j; for (i = 1; i < n; i++) { key = arr[i]; j = i - 1; // Move elements of arr[0..i-1], that are // greater than key, to one position ahead // of their current position while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; }} // Selection sortvoid selectionSort(long int arr[], long int n){ long int i, j, midx; for (i = 0; i < n - 1; i++) { // Find the minimum element in unsorted array midx = i; for (j = i + 1; j < n; j++) if (arr[j] < arr[min_idx]) midx = j; // Swap the found minimum element // with the first element swap(&arr[midx], &arr[i]); }} // Driver codeint main(){ long int n = 10000; int it = 0; // Arrays to store time duration // of sorting algorithms double tim1[10], tim2[10], tim3[10]; printf("A_size, Bubble, Insertion, Selection\n"); // Performs 10 iterations while (it++ < 10) { long int a[n], b[n], c[n]; // generating n random numbers // storing them in arrays a, b, c for (int i = 0; i < n; i++) { long int no = rand() % n + 1; a[i] = no; b[i] = no; c[i] = no; } // using clock_t to store time clock_t start, end; // Bubble sort start = clock(); bubbleSort(a, n); end = clock(); tim1[it] = ((double)(end - start)); // Insertion sort start = clock(); insertionSort(b, n); end = clock(); tim2[it] = ((double)(end - start)); // Selection sort start = clock(); selectionSort(c, n); end = clock(); tim3[it] = ((double)(end - start)); // type conversion to long int // for plotting graph with integer values printf("%li, %li, %li, %li\n", n, (long int)tim1[it], (long int)tim2[it], (long int)tim3[it]); // increases the size of array by 10000 n += 10000; } return 0;}
Output:
A_size, Bubble, Insertion, Selection
10000, 366263, 80736, 152975
20000, 1594932, 332101, 609388
30000, 3773121, 785790, 1441547
40000, 7174455, 1574855, 2620006
50000, 10917061, 2029586, 4025993
60000, 15484338, 2998403, 5556494
70000, 21201561, 4146680, 7678139
80000, 29506758, 6027335, 10131950
90000, 36457272, 6699452, 12436376
100000, 43472313, 8335881, 15208712
Now comes the question that how are we going to plot a graph on x-y coordinates?For that, we will be using a very simple utility called Gnuplot.Gnuplot is a portable command-line driven graphing utility for Linux, MS Windows, OSX and many other platforms.
Note:In this article, Ubuntu(Linux) is used.
First things first how to install Gnuplot.Use this command to install Gnuplot.sudo apt-get install gnuplotAfter this compile your code and copy the output in a text file using this command../a.out>plot.txtOpen Gnuplot simply using.gnuplotNow the last thing is to plot the graph so use this command to plot the complexity graph.plot './plot.txt' using 1:2 with linespoints,
'./plot.txt' using 1:3 with linespoints,
'./plot.txt' using 1:4 with linespoints
First things first how to install Gnuplot.Use this command to install Gnuplot.sudo apt-get install gnuplot
sudo apt-get install gnuplot
After this compile your code and copy the output in a text file using this command../a.out>plot.txt
./a.out>plot.txt
Open Gnuplot simply using.gnuplot
gnuplot
Now the last thing is to plot the graph so use this command to plot the complexity graph.plot './plot.txt' using 1:2 with linespoints,
'./plot.txt' using 1:3 with linespoints,
'./plot.txt' using 1:4 with linespoints
plot './plot.txt' using 1:2 with linespoints,
'./plot.txt' using 1:3 with linespoints,
'./plot.txt' using 1:4 with linespoints
Here is a terminal-snap of commands.
Here is the graph of complexity comparing bubble sort(purple curve), insertion sort(green curve) and selection sort(blue curve).
Observation:The average time complexity of all three algorithms is O(n^2) but as the size of input data increases, insertion sort performs far better than bubble sort and slightly better than selection sort.
c-graphics
computer-graphics
Analysis
C Programs
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
3-coloring is NP Complete
Proof that Independent Set in Graph theory is NP Complete
Complexity analysis of various operations of Binary Min Heap
Proof that Hamiltonian Cycle is NP-Complete
Strings in C
Arrow operator -> in C/C++ with Examples
C Program to read contents of Whole File
UDP Server-Client implementation in C
Header files in C/C++ and its uses
|
[
{
"code": null,
"e": 25044,
"s": 25016,
"text": "\n24 Nov, 2021"
},
{
"code": null,
"e": 25122,
"s": 25044,
"text": "Prerequisite:Comparison among bubble sort, insertion sort and selection sort."
},
{
"code": null,
"e": 25468,
"s": 25122,
"text": "Write a C program to plot and analyze the time complexity of Bubble sort, Insertion sort and Selection sort (using Gnuplot).As per the problem we have to plot a time complexity graph by just using C. So we will be making sorting algorithms as functions and all the algorithms are given to sort exactly the same array to keep the comparison fair."
},
{
"code": null,
"e": 25478,
"s": 25468,
"text": "Examples:"
},
{
"code": null,
"e": 25959,
"s": 25478,
"text": "Input: randomly generated arrays (using rand() function)\n of different sizes as input for sorting.\nOutput:\nA_size, Bubble, Insertion, Selection\n10000, 366263, 80736, 152975\n20000, 1594932, 332101, 609388\n30000, 3773121, 785790, 1441547\n40000, 7174455, 1574855, 2620006\n50000, 10917061, 2029586, 4025993\n60000, 15484338, 2998403, 5556494\n70000, 21201561, 4146680, 7678139\n80000, 29506758, 6027335, 10131950\n90000, 36457272, 6699452, 12436376\n100000, 43472313, 8335881, 15208712\n"
},
{
"code": null,
"e": 26192,
"s": 25959,
"text": "Approach: We will be using arrays of different sizes to plot the graph between the time taken by the sorting algorithm versus array size. Execution of the program will take some time for sorting arrays of size up to 100000 elements."
},
{
"code": null,
"e": 26243,
"s": 26192,
"text": "Below is the implementation of the above approach:"
},
{
"code": "// C program to store time taken by bubble sort,// insertion sort and selection sort// for sorting exactly same arrays. #include <stdio.h>#include <stdlib.h>#include <time.h> // Swap utilityvoid swap(long int* a, long int* b){ int tmp = *a; *a = *b; *b = tmp;} // Bubble sortvoid bubbleSort(long int a[], long int n){ for (long int i = 0; i < n - 1; i++) { for (long int j = 0; j < n - 1 - i; j++) { if (a[j] > a[j + 1]) { swap(&a[j], &a[j + 1]); } } }} // Insertion sortvoid insertionSort(long int arr[], long int n){ long int i, key, j; for (i = 1; i < n; i++) { key = arr[i]; j = i - 1; // Move elements of arr[0..i-1], that are // greater than key, to one position ahead // of their current position while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; }} // Selection sortvoid selectionSort(long int arr[], long int n){ long int i, j, midx; for (i = 0; i < n - 1; i++) { // Find the minimum element in unsorted array midx = i; for (j = i + 1; j < n; j++) if (arr[j] < arr[min_idx]) midx = j; // Swap the found minimum element // with the first element swap(&arr[midx], &arr[i]); }} // Driver codeint main(){ long int n = 10000; int it = 0; // Arrays to store time duration // of sorting algorithms double tim1[10], tim2[10], tim3[10]; printf(\"A_size, Bubble, Insertion, Selection\\n\"); // Performs 10 iterations while (it++ < 10) { long int a[n], b[n], c[n]; // generating n random numbers // storing them in arrays a, b, c for (int i = 0; i < n; i++) { long int no = rand() % n + 1; a[i] = no; b[i] = no; c[i] = no; } // using clock_t to store time clock_t start, end; // Bubble sort start = clock(); bubbleSort(a, n); end = clock(); tim1[it] = ((double)(end - start)); // Insertion sort start = clock(); insertionSort(b, n); end = clock(); tim2[it] = ((double)(end - start)); // Selection sort start = clock(); selectionSort(c, n); end = clock(); tim3[it] = ((double)(end - start)); // type conversion to long int // for plotting graph with integer values printf(\"%li, %li, %li, %li\\n\", n, (long int)tim1[it], (long int)tim2[it], (long int)tim3[it]); // increases the size of array by 10000 n += 10000; } return 0;}",
"e": 28990,
"s": 26243,
"text": null
},
{
"code": null,
"e": 28998,
"s": 28990,
"text": "Output:"
},
{
"code": null,
"e": 29369,
"s": 28998,
"text": "A_size, Bubble, Insertion, Selection\n10000, 366263, 80736, 152975\n20000, 1594932, 332101, 609388\n30000, 3773121, 785790, 1441547\n40000, 7174455, 1574855, 2620006\n50000, 10917061, 2029586, 4025993\n60000, 15484338, 2998403, 5556494\n70000, 21201561, 4146680, 7678139\n80000, 29506758, 6027335, 10131950\n90000, 36457272, 6699452, 12436376\n100000, 43472313, 8335881, 15208712\n"
},
{
"code": null,
"e": 29625,
"s": 29369,
"text": "Now comes the question that how are we going to plot a graph on x-y coordinates?For that, we will be using a very simple utility called Gnuplot.Gnuplot is a portable command-line driven graphing utility for Linux, MS Windows, OSX and many other platforms."
},
{
"code": null,
"e": 29670,
"s": 29625,
"text": "Note:In this article, Ubuntu(Linux) is used."
},
{
"code": null,
"e": 30125,
"s": 29670,
"text": "First things first how to install Gnuplot.Use this command to install Gnuplot.sudo apt-get install gnuplotAfter this compile your code and copy the output in a text file using this command../a.out>plot.txtOpen Gnuplot simply using.gnuplotNow the last thing is to plot the graph so use this command to plot the complexity graph.plot './plot.txt' using 1:2 with linespoints, \n'./plot.txt' using 1:3 with linespoints,\n'./plot.txt' using 1:4 with linespoints"
},
{
"code": null,
"e": 30232,
"s": 30125,
"text": "First things first how to install Gnuplot.Use this command to install Gnuplot.sudo apt-get install gnuplot"
},
{
"code": null,
"e": 30261,
"s": 30232,
"text": "sudo apt-get install gnuplot"
},
{
"code": null,
"e": 30361,
"s": 30261,
"text": "After this compile your code and copy the output in a text file using this command../a.out>plot.txt"
},
{
"code": null,
"e": 30378,
"s": 30361,
"text": "./a.out>plot.txt"
},
{
"code": null,
"e": 30412,
"s": 30378,
"text": "Open Gnuplot simply using.gnuplot"
},
{
"code": null,
"e": 30420,
"s": 30412,
"text": "gnuplot"
},
{
"code": null,
"e": 30637,
"s": 30420,
"text": "Now the last thing is to plot the graph so use this command to plot the complexity graph.plot './plot.txt' using 1:2 with linespoints, \n'./plot.txt' using 1:3 with linespoints,\n'./plot.txt' using 1:4 with linespoints"
},
{
"code": null,
"e": 30765,
"s": 30637,
"text": "plot './plot.txt' using 1:2 with linespoints, \n'./plot.txt' using 1:3 with linespoints,\n'./plot.txt' using 1:4 with linespoints"
},
{
"code": null,
"e": 30802,
"s": 30765,
"text": "Here is a terminal-snap of commands."
},
{
"code": null,
"e": 30931,
"s": 30802,
"text": "Here is the graph of complexity comparing bubble sort(purple curve), insertion sort(green curve) and selection sort(blue curve)."
},
{
"code": null,
"e": 31139,
"s": 30931,
"text": "Observation:The average time complexity of all three algorithms is O(n^2) but as the size of input data increases, insertion sort performs far better than bubble sort and slightly better than selection sort."
},
{
"code": null,
"e": 31150,
"s": 31139,
"text": "c-graphics"
},
{
"code": null,
"e": 31168,
"s": 31150,
"text": "computer-graphics"
},
{
"code": null,
"e": 31177,
"s": 31168,
"text": "Analysis"
},
{
"code": null,
"e": 31188,
"s": 31177,
"text": "C Programs"
},
{
"code": null,
"e": 31196,
"s": 31188,
"text": "Sorting"
},
{
"code": null,
"e": 31204,
"s": 31196,
"text": "Sorting"
},
{
"code": null,
"e": 31302,
"s": 31204,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31369,
"s": 31302,
"text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete"
},
{
"code": null,
"e": 31395,
"s": 31369,
"text": "3-coloring is NP Complete"
},
{
"code": null,
"e": 31453,
"s": 31395,
"text": "Proof that Independent Set in Graph theory is NP Complete"
},
{
"code": null,
"e": 31514,
"s": 31453,
"text": "Complexity analysis of various operations of Binary Min Heap"
},
{
"code": null,
"e": 31558,
"s": 31514,
"text": "Proof that Hamiltonian Cycle is NP-Complete"
},
{
"code": null,
"e": 31571,
"s": 31558,
"text": "Strings in C"
},
{
"code": null,
"e": 31612,
"s": 31571,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 31653,
"s": 31612,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 31691,
"s": 31653,
"text": "UDP Server-Client implementation in C"
}
] |
How to delete the windows certificate using PowerShell?
|
To delete the Windows certificate using PowerShell, we can use the Remove-Item command.
Suppose you know the thumbprint of the certificate then to retrieve all the certificates that use that particular thumbprint, we will use the below command.
PS C:\> gci cert:\ -Recurse | where{$_.Thumbprint -eq
To remove the certificates, we will pipeline the Remove-Item command.
PS C:\> gci cert:\ -Recurse | where{$_.Thumbprint -eq
'920B033462B2FE268E6F9679F8621AEDC78D506C'} | Remove-Item -Force -Verbose
Or if you have the Subject name, then instead of the Thumbprint property, you can use the subject name.
PS C:\> gci cert:\ -Recurse | where{$_.Subject -eq "DemoCert"} | Remove-Item -Force - Verbose
To remove the certificate on the remote servers, you can use the Invoke-Command.
Invoke-Command -ComputerName $Server -ScriptBlock{
gci cert:\ -Recurse | where{$_.Subject -eq "DemoCert"} |
Remove-Item -Force -Verbose
}
|
[
{
"code": null,
"e": 1150,
"s": 1062,
"text": "To delete the Windows certificate using PowerShell, we can use the Remove-Item command."
},
{
"code": null,
"e": 1307,
"s": 1150,
"text": "Suppose you know the thumbprint of the certificate then to retrieve all the certificates that use that particular thumbprint, we will use the below command."
},
{
"code": null,
"e": 1361,
"s": 1307,
"text": "PS C:\\> gci cert:\\ -Recurse | where{$_.Thumbprint -eq"
},
{
"code": null,
"e": 1431,
"s": 1361,
"text": "To remove the certificates, we will pipeline the Remove-Item command."
},
{
"code": null,
"e": 1559,
"s": 1431,
"text": "PS C:\\> gci cert:\\ -Recurse | where{$_.Thumbprint -eq\n'920B033462B2FE268E6F9679F8621AEDC78D506C'} | Remove-Item -Force -Verbose"
},
{
"code": null,
"e": 1663,
"s": 1559,
"text": "Or if you have the Subject name, then instead of the Thumbprint property, you can use the subject name."
},
{
"code": null,
"e": 1757,
"s": 1663,
"text": "PS C:\\> gci cert:\\ -Recurse | where{$_.Subject -eq \"DemoCert\"} | Remove-Item -Force - Verbose"
},
{
"code": null,
"e": 1838,
"s": 1757,
"text": "To remove the certificate on the remote servers, you can use the Invoke-Command."
},
{
"code": null,
"e": 1979,
"s": 1838,
"text": "Invoke-Command -ComputerName $Server -ScriptBlock{\n gci cert:\\ -Recurse | where{$_.Subject -eq \"DemoCert\"} |\nRemove-Item -Force -Verbose\n}"
}
] |
Zend Framework - Module System
|
The Zend Framework provides a powerful module system. The module system has three components. They are as follows −
Module Autoloader − A Module Autoloader is responsible for locating and loading of modules from variety of sources. It can load modules packaged as Phar archives as well. The implementation of the Module Autoloader is located at myapp/vendor/zendframework/zend-loader/src/ModuleAutoloader.php.
Module Autoloader − A Module Autoloader is responsible for locating and loading of modules from variety of sources. It can load modules packaged as Phar archives as well. The implementation of the Module Autoloader is located at myapp/vendor/zendframework/zend-loader/src/ModuleAutoloader.php.
Module Manager − Once the Module Autoloader locates the modules, the module manager fires a sequence of events for each module. The implementation of the Module Manager is located at myapp/vendor/zendframework/zendmodulemanager/src/ModuleManager.php.
Module Manager − Once the Module Autoloader locates the modules, the module manager fires a sequence of events for each module. The implementation of the Module Manager is located at myapp/vendor/zendframework/zendmodulemanager/src/ModuleManager.php.
Module Manager Listeners − They can be attached to the events fired by the Module Manager. By attaching to the events of module manager, they can do everything from resolving and loading modules to performing complex work for each modules.
Module Manager Listeners − They can be attached to the events fired by the Module Manager. By attaching to the events of module manager, they can do everything from resolving and loading modules to performing complex work for each modules.
The MVC Web Application in the Zend Framework is usually written as Modules. A single website can contain one or more modules grouped by functionality. The recommended structure for MVC-Oriented module is as follows −
module_root/
Module.php
autoload_classmap.php
autoload_function.php
autoload_register.php
config/
module.config.php
public/
images/
css/
js/
src/
<module_namespace>/
<code files>
test/
phpunit.xml
bootstrap.php
<module_namespace>/
<test code files>
view/
<dir-named-after-module-namespace>/
<dir-named-after-a-controller>/
<.phtml files>
The structure is same as discussed in the previous chapter, but here it is generic. The autoload_ files can be used as a default mechanism for autoloading the classes available in the module without using the advanced Module Manager available in the zend-modulemanager.
autoload_classmap.php − Returns an array of class name and its corresponding filename.
autoload_classmap.php − Returns an array of class name and its corresponding filename.
autoload_function.php − Returns a PHP callback. This can utilize classes returned by autoload_classmap.php.
autoload_function.php − Returns a PHP callback. This can utilize classes returned by autoload_classmap.php.
autoload_register.php − Registers the PHP callback that is returned by the autoload_function.php.
autoload_register.php − Registers the PHP callback that is returned by the autoload_function.php.
These autoload files are not required but recommended. In the skeleton application, we have not used the autoload_ files.
The Module class should be named Module and the namespace of the module class should be Module name. This will help the Zend Framework to resolve and load the module easily. The Application module code in the skeleton(myapp) application,myapp/module/Application/src/Module.php is as follows −
namespace Application;
class Module {
const VERSION = '3.0.2dev';
public function getConfig() {
return include __DIR__ . '/../config/module.config.php';
}
}
The Zend Framework module manager will call the getConfig() function automatically and will do the necessary steps.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2428,
"s": 2312,
"text": "The Zend Framework provides a powerful module system. The module system has three components. They are as follows −"
},
{
"code": null,
"e": 2722,
"s": 2428,
"text": "Module Autoloader − A Module Autoloader is responsible for locating and loading of modules from variety of sources. It can load modules packaged as Phar archives as well. The implementation of the Module Autoloader is located at myapp/vendor/zendframework/zend-loader/src/ModuleAutoloader.php."
},
{
"code": null,
"e": 3016,
"s": 2722,
"text": "Module Autoloader − A Module Autoloader is responsible for locating and loading of modules from variety of sources. It can load modules packaged as Phar archives as well. The implementation of the Module Autoloader is located at myapp/vendor/zendframework/zend-loader/src/ModuleAutoloader.php."
},
{
"code": null,
"e": 3267,
"s": 3016,
"text": "Module Manager − Once the Module Autoloader locates the modules, the module manager fires a sequence of events for each module. The implementation of the Module Manager is located at myapp/vendor/zendframework/zendmodulemanager/src/ModuleManager.php."
},
{
"code": null,
"e": 3518,
"s": 3267,
"text": "Module Manager − Once the Module Autoloader locates the modules, the module manager fires a sequence of events for each module. The implementation of the Module Manager is located at myapp/vendor/zendframework/zendmodulemanager/src/ModuleManager.php."
},
{
"code": null,
"e": 3758,
"s": 3518,
"text": "Module Manager Listeners − They can be attached to the events fired by the Module Manager. By attaching to the events of module manager, they can do everything from resolving and loading modules to performing complex work for each modules."
},
{
"code": null,
"e": 3998,
"s": 3758,
"text": "Module Manager Listeners − They can be attached to the events fired by the Module Manager. By attaching to the events of module manager, they can do everything from resolving and loading modules to performing complex work for each modules."
},
{
"code": null,
"e": 4216,
"s": 3998,
"text": "The MVC Web Application in the Zend Framework is usually written as Modules. A single website can contain one or more modules grouped by functionality. The recommended structure for MVC-Oriented module is as follows −"
},
{
"code": null,
"e": 4693,
"s": 4216,
"text": "module_root/ \n Module.php \n autoload_classmap.php \n autoload_function.php \n autoload_register.php \n config/ \n module.config.php \n public/ \n images/ \n css/ \n js/ \n src/ \n <module_namespace>/ \n <code files> \n test/ \n phpunit.xml\n bootstrap.php \n <module_namespace>/ \n <test code files> \n view/ \n <dir-named-after-module-namespace>/ \n <dir-named-after-a-controller>/ \n <.phtml files>\n"
},
{
"code": null,
"e": 4963,
"s": 4693,
"text": "The structure is same as discussed in the previous chapter, but here it is generic. The autoload_ files can be used as a default mechanism for autoloading the classes available in the module without using the advanced Module Manager available in the zend-modulemanager."
},
{
"code": null,
"e": 5050,
"s": 4963,
"text": "autoload_classmap.php − Returns an array of class name and its corresponding filename."
},
{
"code": null,
"e": 5137,
"s": 5050,
"text": "autoload_classmap.php − Returns an array of class name and its corresponding filename."
},
{
"code": null,
"e": 5245,
"s": 5137,
"text": "autoload_function.php − Returns a PHP callback. This can utilize classes returned by autoload_classmap.php."
},
{
"code": null,
"e": 5353,
"s": 5245,
"text": "autoload_function.php − Returns a PHP callback. This can utilize classes returned by autoload_classmap.php."
},
{
"code": null,
"e": 5451,
"s": 5353,
"text": "autoload_register.php − Registers the PHP callback that is returned by the autoload_function.php."
},
{
"code": null,
"e": 5549,
"s": 5451,
"text": "autoload_register.php − Registers the PHP callback that is returned by the autoload_function.php."
},
{
"code": null,
"e": 5671,
"s": 5549,
"text": "These autoload files are not required but recommended. In the skeleton application, we have not used the autoload_ files."
},
{
"code": null,
"e": 5964,
"s": 5671,
"text": "The Module class should be named Module and the namespace of the module class should be Module name. This will help the Zend Framework to resolve and load the module easily. The Application module code in the skeleton(myapp) application,myapp/module/Application/src/Module.php is as follows −"
},
{
"code": null,
"e": 6142,
"s": 5964,
"text": "namespace Application; \nclass Module { \n const VERSION = '3.0.2dev'; \n public function getConfig() { \n return include __DIR__ . '/../config/module.config.php'; \n } \n}"
},
{
"code": null,
"e": 6258,
"s": 6142,
"text": "The Zend Framework module manager will call the getConfig() function automatically and will do the necessary steps."
},
{
"code": null,
"e": 6265,
"s": 6258,
"text": " Print"
},
{
"code": null,
"e": 6276,
"s": 6265,
"text": " Add Notes"
}
] |
How to use open source satellite data for your investigative reporting | by Techjournalist | Towards Data Science
|
Undoubtedly a vast goldmine of information — perhaps too vast — many journalists still shy away from working with satellite data extensively. Since the emergence of high-resolution data provided from firms like DigitalGlobe and Planet Labs, the supply of satellite stories has mushroomed. But open source data — a valid and timely source for stories, nonetheless, despite lower resolution— remains under-leveraged. With an untouched mountain of data at hand, many either fear to miss the forest — or story in this case — for the trees or to misinterpret. Both valid concerns. Today, we will try to tackle some of the reservations that you might share with your colleagues and teach some basics in accessing, understanding and handling open source satellite data.
Recent technical commentary on the execution of remote sensing exercises within and outside newsrooms attempted to demystify how to take advantage of open source satellite data platforms. Some attempted to explain how to streamline the process of gathering data. Few drawn viable connections between feasible stories and technical capabilities. This tutorial attempts to challenge this notion. We will walk you through some basic examples — from a beginner to a more advanced technical level.
Different satellites send different images to earth. Distinction includes resolution (how crisp the images are), the number and types of bands they produce and how frequently they are updated.
Sentinel 2 satellite image data, for instance, comes in the form of thirteen difference spectral bands, ranging from visible and near infrared to the shortwave infrared, featuring four spectral bands at 10 meters, six bands at 20 meters and three bands at 60 meters spatial resolution.
Consider these bands as a form of binoculars that allow you to spot things that otherwise would remain hidden in the data. The right mix of these bands is key. Various scripts — different band combos if you will — can be run on the data (either on your local machine or on Sentinel hub).
If you are reporting on a broad basis, you want to make yourself familiar with those different combinations and what they achieve for you, as it might come in handy at times when other outlets miss the beat.
Python 3.6
An adequate Tif reader (if you want to download raster files)
Jupyter notebook and various python packages
A free account for Sentinel hub (find a description in the python tutorial)
If you are an affectionate technologist, you might be slightly turned off by the idea of using a browser application. But do hear me out. For exploring and investigating, the EO Browser is a decent option (if you want to step back even further, ‘Sentinel Playground’ features fewer satellites but offers a slightly easier way to explore).
Predecessor and other open source satellite platforms may offer limited options in using python in the workflow. Sentinel Hub runs some useful options in this regard. Also, there is no need to download the whole raster tiles in order to do something interesting (arguably, it’s rare that investigations require all the tile data at the same time). Instead, it allows to zoom in on specific areas.
Let’s get going and indulge in a satellite frenzy.
Detection and reporting of the sudden proliferation and destruction of wildfires that spiraled last year when record flames raged across the U.S. state of California. It might not be the last time. Such fires are feasible to re-emerge in the near future, experts claim. Freely available go-to sources constitute Landsat 8 data — kindly provided with the help of U.S. Geological Survey — as well as Sentinel-2 data.
Sentinel-2 — offering higher resolution imagery than its open source colleagues in the visible and infrared part of the spectrum — is well up to the task to monitor vegetation, soil and water cover, inland waterways and coastal areas.
Go to EO Browser — sign up and login (it's free)
Select Sentinel-2
Narrow down the data collection by limiting cloud coverage to 30%.
Spot Wildfires in the U.S. state of California, that climaxed between July and August of 2018 (they are so comprehensively pronounced state-wide, you should not have problems to spot plumes of clouds)
Possible examples of 2018 fires:
Natchez Fire (July 20, 2018): 41.956°N 123.551°WCarr Fire (July 28, 2018): 40.6543°N 122.6236°WMendocino Complex Fire (July 29, 2018): 39.243283°N 123.103367°WFerguson Fire (July 14, 2018): 37.652°N 119.881°W
Next, we want to render a specific band combination to see more clearly where the action on the ground is happening.
copy ‘Wildfire script’:
The Wildfire script was kindly provided by Pierre Markuse. Insert it into the ‘Custom’ section (under the Visualisation tab) where the ‘</>’ is exhibited (next to the hand button).
Interesting angle: How successful are firefighters to contain/isolate fires
If you successfully found a wildfire in the specified time range, you should spot yellow-red ish blotches. Importantly: do not interpret these as flames. Despite showing it, you should tell your audience that what can be seen are not actual fires but a mere IR overlay — that, to some degree, lines up with the active fires and hot spots.
New wildfires recently sprawled around Mount Kenya (long, lat: -0.152739, 37.309095) burning nearly a week at the time of writing.
If you have time, discover those fires, apply the script as before and investigate.
Other band combination can be used to illustrate potential areas at risk of wildfires. Dryness of vegetation is one of such indicators. Moisture stress index — or MSI - can reveal such dry areas — and aid in something called ‘a fire hazard condition analysis’.
The index is inverted relative to other water vegetation indices. The higher the value, the greater the water stress level (and the less water content there is). Give it a try and follow the same procedure with a different band script and see what you can retrieve.
In order to use Sentinel Hub services, you need a Sentinel Hub account (sign up for free here https://www.sentinel-hub.com/, if you haven’t done already).
Login to Sentinel Hub Configurator. A configuration with an instance ID (alpha-numeric code of length 36) will already exist. For this tutorial, it is recommended that you create a new configuration (via “Add new configuration”) and set the configuration to be based on ‘Python scripts template’.
Write down your configuration’s instance ID and paste it into the INSTANCE_ID variable declaration:
All requests require a bounding box to be given as an instance of sentinelhub.geometry.BBox with corresponding Coordinate Reference System (sentinelhub.geometry.CRS). We will use WGS84 and we can use the predefined WGS84 coordinate reference system from sentinelhub.geometry.CRS.
Now we simply provide a URL address of a JS evalscript (a number of other clever scripts are available on this dedicated page).
Let’s select the fire script again and provide its URL as a value of parameter CustomUrlParam.EVALSCRIPTURL.
Another custom script, to specifically detect blight from fires is NBR — short for normalized burn ratio — (link to the script here). If you report on the post-mortem status of a large fire, this could aid your analysis and coverage.
Locate burned vegetation with the NBR script.
The general with the frightening nickname ‘The Tiger’ is the helmsman of Qawat Al-Nimr a.k.a Tiger Forces, a Russian backed campaign and an elite formation of the Syrian Arab Army which functions primarily as an offensive unit in the Syrian Civil War.
In Syria to retake eastern Ghouta, a recent operation executed by the Tiger Forces killed, according to the Violations Documentation Center (VDC), at least 600 civilians — of whom at least 100 were children.
To find out where Suheil al-Hassan was hiding back in 2016, we perform a typical act of intelligence work and start by taking a look at the following video:
We can spot whiffs of smoke wafted towards the left. On another sequence, we see the hideout the General operated out of.
From the video, we learn that it was shot for ‘Palmyra Battle Against ISIS’. This could be the Aleppo Thermal Plant.
A simple web search provides us with a level of clarification:
Search on Google for ‘Aleppo thermal plant’. The Wikipedia link supplies us with long/lat of the Thermal Power Plant.
Next, go to Google Earth or Google Maps and enter the coordinates you found: ‘36°10′30′′N 37°26′22′′E’. What you will see is a set of burned out towers to the right of the plant.
On EO Brower, turn on roads and enter the longitude and latitude (36.175000, 37.439444) from the Google maps result (into the search window of the EO Browser). In our case, we are interested in February 16 of 2016 (2016–02–16), for which we witness wondrous smoke plumes.
Next, we proceed as before and apply the fire-script to visualize fires in Sentinel-2 imagery (Challenge: if you feel confident, do it in your Python environment, alternatively analog, within your EO Browser window).
Now that we have a better understanding, we can infer the location of the Tiger’s hideout at the time of the fire.
To confirm our suspicion, we can check Google maps satellite images and learn that the hideout has since been bombed.
Benjamin Strick, an open source expert for conflict, security, arms, and digital forensics (who also suggested this example) explains that it does help to show which of the towers were on fire at the time. Later imagery of Al-Hassan in the plant would have confirmed: those four towers were on fire that day.
Spotting specific details in places from space has its merits. One, in fact, within the field of human rights. A recent investigation showed that satellite images can help reveal slavery from space. Doreen Boyd, director of the data program at the Rights Lab at the University of Nottingham in the United Kingdom estimates, that one-third of all slavery would be visible from space — whether in the form of scars of kilns or illegal mines or the outlines of transient fish processing camps (arguably, high-resolution commercial images may be better suited for this kind of investigation).
Let us assume you are reporting on distressed water levels, maybe covering a conflict that resulted from such (tension and fighting resulting from scarce water situations are becoming increasingly likely, according to recent research and covered by an Economist special report).
A Jupyter notebook* was composed to detect levels of water bodies, using Sentinel-2 multi-spectral and multi-temporal imagery.
We will run a water detection algorithm in python and extract surface water level for a single reservoir in a given time interval.
Defining geometries of a few waterbodiesPreparing and executing the full workflow for water detection: Downloading Sentinel-2 data (true color and NDWI index) using SentinelHub services and cloud detection using the s2cloudless cloud detector, and finally detect waterVisualizing water bodies and the water level over a period of timeFiltering out cloudy scenes to improve the results
Defining geometries of a few waterbodies
Preparing and executing the full workflow for water detection: Downloading Sentinel-2 data (true color and NDWI index) using SentinelHub services and cloud detection using the s2cloudless cloud detector, and finally detect water
Visualizing water bodies and the water level over a period of time
Filtering out cloudy scenes to improve the results
`eo-learn` — https://github.com/sentinel-hub/eo-learn
`Water Observatory Backend` — https://github.com/sentinel-hub/water-observatory-backend
Basic terminal/file setup:
As in the previous example: earlier, in order to run it, you will also need a Sentinel Hub account. You can create a free trial account at Sentinel Hub webpage. Once you have the account set up, login to Sentinel Hub Configurator. By default, you will already have the default configuration with an instance ID (alpha-numeric code of length 36). For this tutorial, we recommend that you create a new configuration ("Add new configuration") and set the configuration to be based on Python scripts template. Such configuration will already contain all layers used in these examples. Otherwise, you will have to define the layers for your configuration yourself. After you have prepared a configuration please put configuration’s instance ID into sentinelhub package's configuration file following the configuration instructions.
Set your Python working environment by loading the following Python Libraries. Make sure you run the Python virtual environment as instructed above.
Let’s use the Theewaterskloof Dam, in South Africa as an example — a substantial water reserve supplying the precious resource to a large chunk of the 4 million dwellers in Cape Town. It is the largest dam in the Western Cape Water Supply System and can run low during droughts. There are signs of increased consciousness for water shortages. How to cover such a topic shows this example.
In the case of Theewaterskloof Dam — or any other large waterbody across the planet — you can easily obtain geometries via the BlueDot Water Observatory API.
By searching for a specific waterbody, you can copy the ID number in the URL in order to access the nominal geometry of the corresponding waterbody (i.e. number 38538 in url https://water.blue-dot-observatory.com/38538/2019-02-05)
Python code to download geometries:
Now we need a bounding box for this geometry, in order to download Sentinel-2 data. We define a bounding box and inflate it a little bit in order to construct a BBox object which is used with Sentinel Hub services. The BBox class also accepts the coordinate system (CRS), where we use the same one as in the case of the geometry (which is WGS84).
Sentinel Hub services are installed with eo-learn. It is an open-source earth observation processing framework for machine learning in Python, which provides seamless access and abilities to process spatiotemporal image sequences acquired by any satellite fleet.
eo-learn works as a workflow — where a workflow consists of one or multiple tasks. Each tasks achieves a specific job (downloading data, calculating band combinations, etc.) on a small patch of an area, called EOPatch. EOPatch is a container for EO and non-EO data.
Let’s define a workflow to download and obtain the necessary data for water detection. We will download the RGB bands in order to actually visualize the true-color image of the waterbody. Additionally, we will download the NDWI band combination (Normalized Difference Water Index), which we will use for water detection. It is defined as
where B3 and B8 are the green and near-infrared Sentinel-2 bands, respectively.
Next: Definitions of some custom tasks that will be used in the workflow
Initializations of EOTasks:
Output: Finished loading model, total used 170 iterations
Output: CPU times: user 3min 9s, sys: 14.7 s, total: 3min 24sWall time: 3min 23s
Structure of the `EOPatch`
Check structure by typing
Input: eopatch
Let’s now visualize the first few true-color images of the selected waterbody in the given time series. We see below that some images contain clouds, which causes problems in proper water level detection.
Plot the NDWI to see how the water detector traces the waterbody outline:
Plot true-color images with the detected water outlines:
Plotting the detected water levels
You should see a lot of fluctuations in the data due to cloud interference (in grey, cloud coverage is plotted. It shares the same dates as the water level outliers).
Let us now set a threshold for the maximum cloud coverage of 2 % and filter out the dates which correspond to cloudy scenes. This is done by filtering out the dates which have a value of eopatch.scalar['COVERAGE'] larger than 0.02.
Voilà, there you have it. Water-levels hit a historic three-year low in mid-2018 but convalesced since.
Still hungry for more satellite image analysis? I covered some basic techniques related to economic nightlight analysis here(which served as a proxy for economic growth). 99 other ideas for application were pooled by Gisgeography.com and listed below. Knock yourself out.
The tutorial was composed by an investigative journalist with kind support from Matic Lubej, Data Scientist at @sinergise, Pierre Markuse, a remote sensing evangelist and Benjamin Strick, an open-source investigator for the BBC and instructor with the EUArms workshops.
|
[
{
"code": null,
"e": 934,
"s": 171,
"text": "Undoubtedly a vast goldmine of information — perhaps too vast — many journalists still shy away from working with satellite data extensively. Since the emergence of high-resolution data provided from firms like DigitalGlobe and Planet Labs, the supply of satellite stories has mushroomed. But open source data — a valid and timely source for stories, nonetheless, despite lower resolution— remains under-leveraged. With an untouched mountain of data at hand, many either fear to miss the forest — or story in this case — for the trees or to misinterpret. Both valid concerns. Today, we will try to tackle some of the reservations that you might share with your colleagues and teach some basics in accessing, understanding and handling open source satellite data."
},
{
"code": null,
"e": 1427,
"s": 934,
"text": "Recent technical commentary on the execution of remote sensing exercises within and outside newsrooms attempted to demystify how to take advantage of open source satellite data platforms. Some attempted to explain how to streamline the process of gathering data. Few drawn viable connections between feasible stories and technical capabilities. This tutorial attempts to challenge this notion. We will walk you through some basic examples — from a beginner to a more advanced technical level."
},
{
"code": null,
"e": 1620,
"s": 1427,
"text": "Different satellites send different images to earth. Distinction includes resolution (how crisp the images are), the number and types of bands they produce and how frequently they are updated."
},
{
"code": null,
"e": 1906,
"s": 1620,
"text": "Sentinel 2 satellite image data, for instance, comes in the form of thirteen difference spectral bands, ranging from visible and near infrared to the shortwave infrared, featuring four spectral bands at 10 meters, six bands at 20 meters and three bands at 60 meters spatial resolution."
},
{
"code": null,
"e": 2194,
"s": 1906,
"text": "Consider these bands as a form of binoculars that allow you to spot things that otherwise would remain hidden in the data. The right mix of these bands is key. Various scripts — different band combos if you will — can be run on the data (either on your local machine or on Sentinel hub)."
},
{
"code": null,
"e": 2402,
"s": 2194,
"text": "If you are reporting on a broad basis, you want to make yourself familiar with those different combinations and what they achieve for you, as it might come in handy at times when other outlets miss the beat."
},
{
"code": null,
"e": 2413,
"s": 2402,
"text": "Python 3.6"
},
{
"code": null,
"e": 2475,
"s": 2413,
"text": "An adequate Tif reader (if you want to download raster files)"
},
{
"code": null,
"e": 2520,
"s": 2475,
"text": "Jupyter notebook and various python packages"
},
{
"code": null,
"e": 2596,
"s": 2520,
"text": "A free account for Sentinel hub (find a description in the python tutorial)"
},
{
"code": null,
"e": 2935,
"s": 2596,
"text": "If you are an affectionate technologist, you might be slightly turned off by the idea of using a browser application. But do hear me out. For exploring and investigating, the EO Browser is a decent option (if you want to step back even further, ‘Sentinel Playground’ features fewer satellites but offers a slightly easier way to explore)."
},
{
"code": null,
"e": 3332,
"s": 2935,
"text": "Predecessor and other open source satellite platforms may offer limited options in using python in the workflow. Sentinel Hub runs some useful options in this regard. Also, there is no need to download the whole raster tiles in order to do something interesting (arguably, it’s rare that investigations require all the tile data at the same time). Instead, it allows to zoom in on specific areas."
},
{
"code": null,
"e": 3383,
"s": 3332,
"text": "Let’s get going and indulge in a satellite frenzy."
},
{
"code": null,
"e": 3798,
"s": 3383,
"text": "Detection and reporting of the sudden proliferation and destruction of wildfires that spiraled last year when record flames raged across the U.S. state of California. It might not be the last time. Such fires are feasible to re-emerge in the near future, experts claim. Freely available go-to sources constitute Landsat 8 data — kindly provided with the help of U.S. Geological Survey — as well as Sentinel-2 data."
},
{
"code": null,
"e": 4033,
"s": 3798,
"text": "Sentinel-2 — offering higher resolution imagery than its open source colleagues in the visible and infrared part of the spectrum — is well up to the task to monitor vegetation, soil and water cover, inland waterways and coastal areas."
},
{
"code": null,
"e": 4082,
"s": 4033,
"text": "Go to EO Browser — sign up and login (it's free)"
},
{
"code": null,
"e": 4100,
"s": 4082,
"text": "Select Sentinel-2"
},
{
"code": null,
"e": 4167,
"s": 4100,
"text": "Narrow down the data collection by limiting cloud coverage to 30%."
},
{
"code": null,
"e": 4368,
"s": 4167,
"text": "Spot Wildfires in the U.S. state of California, that climaxed between July and August of 2018 (they are so comprehensively pronounced state-wide, you should not have problems to spot plumes of clouds)"
},
{
"code": null,
"e": 4401,
"s": 4368,
"text": "Possible examples of 2018 fires:"
},
{
"code": null,
"e": 4610,
"s": 4401,
"text": "Natchez Fire (July 20, 2018): 41.956°N 123.551°WCarr Fire (July 28, 2018): 40.6543°N 122.6236°WMendocino Complex Fire (July 29, 2018): 39.243283°N 123.103367°WFerguson Fire (July 14, 2018): 37.652°N 119.881°W"
},
{
"code": null,
"e": 4727,
"s": 4610,
"text": "Next, we want to render a specific band combination to see more clearly where the action on the ground is happening."
},
{
"code": null,
"e": 4751,
"s": 4727,
"text": "copy ‘Wildfire script’:"
},
{
"code": null,
"e": 4932,
"s": 4751,
"text": "The Wildfire script was kindly provided by Pierre Markuse. Insert it into the ‘Custom’ section (under the Visualisation tab) where the ‘</>’ is exhibited (next to the hand button)."
},
{
"code": null,
"e": 5008,
"s": 4932,
"text": "Interesting angle: How successful are firefighters to contain/isolate fires"
},
{
"code": null,
"e": 5347,
"s": 5008,
"text": "If you successfully found a wildfire in the specified time range, you should spot yellow-red ish blotches. Importantly: do not interpret these as flames. Despite showing it, you should tell your audience that what can be seen are not actual fires but a mere IR overlay — that, to some degree, lines up with the active fires and hot spots."
},
{
"code": null,
"e": 5478,
"s": 5347,
"text": "New wildfires recently sprawled around Mount Kenya (long, lat: -0.152739, 37.309095) burning nearly a week at the time of writing."
},
{
"code": null,
"e": 5562,
"s": 5478,
"text": "If you have time, discover those fires, apply the script as before and investigate."
},
{
"code": null,
"e": 5823,
"s": 5562,
"text": "Other band combination can be used to illustrate potential areas at risk of wildfires. Dryness of vegetation is one of such indicators. Moisture stress index — or MSI - can reveal such dry areas — and aid in something called ‘a fire hazard condition analysis’."
},
{
"code": null,
"e": 6089,
"s": 5823,
"text": "The index is inverted relative to other water vegetation indices. The higher the value, the greater the water stress level (and the less water content there is). Give it a try and follow the same procedure with a different band script and see what you can retrieve."
},
{
"code": null,
"e": 6244,
"s": 6089,
"text": "In order to use Sentinel Hub services, you need a Sentinel Hub account (sign up for free here https://www.sentinel-hub.com/, if you haven’t done already)."
},
{
"code": null,
"e": 6541,
"s": 6244,
"text": "Login to Sentinel Hub Configurator. A configuration with an instance ID (alpha-numeric code of length 36) will already exist. For this tutorial, it is recommended that you create a new configuration (via “Add new configuration”) and set the configuration to be based on ‘Python scripts template’."
},
{
"code": null,
"e": 6641,
"s": 6541,
"text": "Write down your configuration’s instance ID and paste it into the INSTANCE_ID variable declaration:"
},
{
"code": null,
"e": 6921,
"s": 6641,
"text": "All requests require a bounding box to be given as an instance of sentinelhub.geometry.BBox with corresponding Coordinate Reference System (sentinelhub.geometry.CRS). We will use WGS84 and we can use the predefined WGS84 coordinate reference system from sentinelhub.geometry.CRS."
},
{
"code": null,
"e": 7049,
"s": 6921,
"text": "Now we simply provide a URL address of a JS evalscript (a number of other clever scripts are available on this dedicated page)."
},
{
"code": null,
"e": 7158,
"s": 7049,
"text": "Let’s select the fire script again and provide its URL as a value of parameter CustomUrlParam.EVALSCRIPTURL."
},
{
"code": null,
"e": 7392,
"s": 7158,
"text": "Another custom script, to specifically detect blight from fires is NBR — short for normalized burn ratio — (link to the script here). If you report on the post-mortem status of a large fire, this could aid your analysis and coverage."
},
{
"code": null,
"e": 7438,
"s": 7392,
"text": "Locate burned vegetation with the NBR script."
},
{
"code": null,
"e": 7690,
"s": 7438,
"text": "The general with the frightening nickname ‘The Tiger’ is the helmsman of Qawat Al-Nimr a.k.a Tiger Forces, a Russian backed campaign and an elite formation of the Syrian Arab Army which functions primarily as an offensive unit in the Syrian Civil War."
},
{
"code": null,
"e": 7898,
"s": 7690,
"text": "In Syria to retake eastern Ghouta, a recent operation executed by the Tiger Forces killed, according to the Violations Documentation Center (VDC), at least 600 civilians — of whom at least 100 were children."
},
{
"code": null,
"e": 8055,
"s": 7898,
"text": "To find out where Suheil al-Hassan was hiding back in 2016, we perform a typical act of intelligence work and start by taking a look at the following video:"
},
{
"code": null,
"e": 8177,
"s": 8055,
"text": "We can spot whiffs of smoke wafted towards the left. On another sequence, we see the hideout the General operated out of."
},
{
"code": null,
"e": 8294,
"s": 8177,
"text": "From the video, we learn that it was shot for ‘Palmyra Battle Against ISIS’. This could be the Aleppo Thermal Plant."
},
{
"code": null,
"e": 8357,
"s": 8294,
"text": "A simple web search provides us with a level of clarification:"
},
{
"code": null,
"e": 8475,
"s": 8357,
"text": "Search on Google for ‘Aleppo thermal plant’. The Wikipedia link supplies us with long/lat of the Thermal Power Plant."
},
{
"code": null,
"e": 8654,
"s": 8475,
"text": "Next, go to Google Earth or Google Maps and enter the coordinates you found: ‘36°10′30′′N 37°26′22′′E’. What you will see is a set of burned out towers to the right of the plant."
},
{
"code": null,
"e": 8926,
"s": 8654,
"text": "On EO Brower, turn on roads and enter the longitude and latitude (36.175000, 37.439444) from the Google maps result (into the search window of the EO Browser). In our case, we are interested in February 16 of 2016 (2016–02–16), for which we witness wondrous smoke plumes."
},
{
"code": null,
"e": 9143,
"s": 8926,
"text": "Next, we proceed as before and apply the fire-script to visualize fires in Sentinel-2 imagery (Challenge: if you feel confident, do it in your Python environment, alternatively analog, within your EO Browser window)."
},
{
"code": null,
"e": 9258,
"s": 9143,
"text": "Now that we have a better understanding, we can infer the location of the Tiger’s hideout at the time of the fire."
},
{
"code": null,
"e": 9376,
"s": 9258,
"text": "To confirm our suspicion, we can check Google maps satellite images and learn that the hideout has since been bombed."
},
{
"code": null,
"e": 9685,
"s": 9376,
"text": "Benjamin Strick, an open source expert for conflict, security, arms, and digital forensics (who also suggested this example) explains that it does help to show which of the towers were on fire at the time. Later imagery of Al-Hassan in the plant would have confirmed: those four towers were on fire that day."
},
{
"code": null,
"e": 10274,
"s": 9685,
"text": "Spotting specific details in places from space has its merits. One, in fact, within the field of human rights. A recent investigation showed that satellite images can help reveal slavery from space. Doreen Boyd, director of the data program at the Rights Lab at the University of Nottingham in the United Kingdom estimates, that one-third of all slavery would be visible from space — whether in the form of scars of kilns or illegal mines or the outlines of transient fish processing camps (arguably, high-resolution commercial images may be better suited for this kind of investigation)."
},
{
"code": null,
"e": 10553,
"s": 10274,
"text": "Let us assume you are reporting on distressed water levels, maybe covering a conflict that resulted from such (tension and fighting resulting from scarce water situations are becoming increasingly likely, according to recent research and covered by an Economist special report)."
},
{
"code": null,
"e": 10680,
"s": 10553,
"text": "A Jupyter notebook* was composed to detect levels of water bodies, using Sentinel-2 multi-spectral and multi-temporal imagery."
},
{
"code": null,
"e": 10811,
"s": 10680,
"text": "We will run a water detection algorithm in python and extract surface water level for a single reservoir in a given time interval."
},
{
"code": null,
"e": 11196,
"s": 10811,
"text": "Defining geometries of a few waterbodiesPreparing and executing the full workflow for water detection: Downloading Sentinel-2 data (true color and NDWI index) using SentinelHub services and cloud detection using the s2cloudless cloud detector, and finally detect waterVisualizing water bodies and the water level over a period of timeFiltering out cloudy scenes to improve the results"
},
{
"code": null,
"e": 11237,
"s": 11196,
"text": "Defining geometries of a few waterbodies"
},
{
"code": null,
"e": 11466,
"s": 11237,
"text": "Preparing and executing the full workflow for water detection: Downloading Sentinel-2 data (true color and NDWI index) using SentinelHub services and cloud detection using the s2cloudless cloud detector, and finally detect water"
},
{
"code": null,
"e": 11533,
"s": 11466,
"text": "Visualizing water bodies and the water level over a period of time"
},
{
"code": null,
"e": 11584,
"s": 11533,
"text": "Filtering out cloudy scenes to improve the results"
},
{
"code": null,
"e": 11638,
"s": 11584,
"text": "`eo-learn` — https://github.com/sentinel-hub/eo-learn"
},
{
"code": null,
"e": 11726,
"s": 11638,
"text": "`Water Observatory Backend` — https://github.com/sentinel-hub/water-observatory-backend"
},
{
"code": null,
"e": 11753,
"s": 11726,
"text": "Basic terminal/file setup:"
},
{
"code": null,
"e": 12580,
"s": 11753,
"text": "As in the previous example: earlier, in order to run it, you will also need a Sentinel Hub account. You can create a free trial account at Sentinel Hub webpage. Once you have the account set up, login to Sentinel Hub Configurator. By default, you will already have the default configuration with an instance ID (alpha-numeric code of length 36). For this tutorial, we recommend that you create a new configuration (\"Add new configuration\") and set the configuration to be based on Python scripts template. Such configuration will already contain all layers used in these examples. Otherwise, you will have to define the layers for your configuration yourself. After you have prepared a configuration please put configuration’s instance ID into sentinelhub package's configuration file following the configuration instructions."
},
{
"code": null,
"e": 12729,
"s": 12580,
"text": "Set your Python working environment by loading the following Python Libraries. Make sure you run the Python virtual environment as instructed above."
},
{
"code": null,
"e": 13118,
"s": 12729,
"text": "Let’s use the Theewaterskloof Dam, in South Africa as an example — a substantial water reserve supplying the precious resource to a large chunk of the 4 million dwellers in Cape Town. It is the largest dam in the Western Cape Water Supply System and can run low during droughts. There are signs of increased consciousness for water shortages. How to cover such a topic shows this example."
},
{
"code": null,
"e": 13276,
"s": 13118,
"text": "In the case of Theewaterskloof Dam — or any other large waterbody across the planet — you can easily obtain geometries via the BlueDot Water Observatory API."
},
{
"code": null,
"e": 13507,
"s": 13276,
"text": "By searching for a specific waterbody, you can copy the ID number in the URL in order to access the nominal geometry of the corresponding waterbody (i.e. number 38538 in url https://water.blue-dot-observatory.com/38538/2019-02-05)"
},
{
"code": null,
"e": 13543,
"s": 13507,
"text": "Python code to download geometries:"
},
{
"code": null,
"e": 13890,
"s": 13543,
"text": "Now we need a bounding box for this geometry, in order to download Sentinel-2 data. We define a bounding box and inflate it a little bit in order to construct a BBox object which is used with Sentinel Hub services. The BBox class also accepts the coordinate system (CRS), where we use the same one as in the case of the geometry (which is WGS84)."
},
{
"code": null,
"e": 14153,
"s": 13890,
"text": "Sentinel Hub services are installed with eo-learn. It is an open-source earth observation processing framework for machine learning in Python, which provides seamless access and abilities to process spatiotemporal image sequences acquired by any satellite fleet."
},
{
"code": null,
"e": 14419,
"s": 14153,
"text": "eo-learn works as a workflow — where a workflow consists of one or multiple tasks. Each tasks achieves a specific job (downloading data, calculating band combinations, etc.) on a small patch of an area, called EOPatch. EOPatch is a container for EO and non-EO data."
},
{
"code": null,
"e": 14757,
"s": 14419,
"text": "Let’s define a workflow to download and obtain the necessary data for water detection. We will download the RGB bands in order to actually visualize the true-color image of the waterbody. Additionally, we will download the NDWI band combination (Normalized Difference Water Index), which we will use for water detection. It is defined as"
},
{
"code": null,
"e": 14837,
"s": 14757,
"text": "where B3 and B8 are the green and near-infrared Sentinel-2 bands, respectively."
},
{
"code": null,
"e": 14910,
"s": 14837,
"text": "Next: Definitions of some custom tasks that will be used in the workflow"
},
{
"code": null,
"e": 14938,
"s": 14910,
"text": "Initializations of EOTasks:"
},
{
"code": null,
"e": 14996,
"s": 14938,
"text": "Output: Finished loading model, total used 170 iterations"
},
{
"code": null,
"e": 15077,
"s": 14996,
"text": "Output: CPU times: user 3min 9s, sys: 14.7 s, total: 3min 24sWall time: 3min 23s"
},
{
"code": null,
"e": 15104,
"s": 15077,
"text": "Structure of the `EOPatch`"
},
{
"code": null,
"e": 15130,
"s": 15104,
"text": "Check structure by typing"
},
{
"code": null,
"e": 15145,
"s": 15130,
"text": "Input: eopatch"
},
{
"code": null,
"e": 15350,
"s": 15145,
"text": "Let’s now visualize the first few true-color images of the selected waterbody in the given time series. We see below that some images contain clouds, which causes problems in proper water level detection."
},
{
"code": null,
"e": 15424,
"s": 15350,
"text": "Plot the NDWI to see how the water detector traces the waterbody outline:"
},
{
"code": null,
"e": 15481,
"s": 15424,
"text": "Plot true-color images with the detected water outlines:"
},
{
"code": null,
"e": 15516,
"s": 15481,
"text": "Plotting the detected water levels"
},
{
"code": null,
"e": 15683,
"s": 15516,
"text": "You should see a lot of fluctuations in the data due to cloud interference (in grey, cloud coverage is plotted. It shares the same dates as the water level outliers)."
},
{
"code": null,
"e": 15915,
"s": 15683,
"text": "Let us now set a threshold for the maximum cloud coverage of 2 % and filter out the dates which correspond to cloudy scenes. This is done by filtering out the dates which have a value of eopatch.scalar['COVERAGE'] larger than 0.02."
},
{
"code": null,
"e": 16020,
"s": 15915,
"text": "Voilà, there you have it. Water-levels hit a historic three-year low in mid-2018 but convalesced since."
},
{
"code": null,
"e": 16292,
"s": 16020,
"text": "Still hungry for more satellite image analysis? I covered some basic techniques related to economic nightlight analysis here(which served as a proxy for economic growth). 99 other ideas for application were pooled by Gisgeography.com and listed below. Knock yourself out."
}
] |
Difference between continue and pass statements in Python - GeeksforGeeks
|
25 Jun, 2020
Using loops in Python automates and repeats the tasks in an efficient manner. But sometimes, there may arise a condition where you want to exit the loop completely, skip an iteration or ignore that condition. These can be done by loop control statements. Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. Python supports the following control statements.
Continue statement
Break statement
Pass statement
In this article, the main focus will be on the difference between continue and pass statement.
This statement is used to skip over the execution part of the loop on a certain condition. After that, it transfers the control to the beginning of the loop. Basically, it skips its following statements and continues with the next iteration of the loop.
Syntax:
continue
As the name suggests pass statement simply does nothing. We use pass statement to write empty loops. Pass is also used for empty control statements, functions and classes.
Syntax:
pass
Consider the below example for better understanding the difference between continue and pass statement.
Example:
# Python program to demonstrate# difference between pass and # continue statements s = "geeks" # Pass statementfor i in s: if i == 'k': print('Pass executed') pass print(i) print() # Continue statementfor i in s: if i == 'k': print('Continue executed') continue print(i)
Output:
g
e
e
Pass executed
k
s
g
e
e
Continue executed
s
In the above example, when the value of i becomes equal to ‘k‘, the pass statement did nothing and hence the letter ‘k‘ is also printed. Whereas in the case of continue statement, the continue statement transfers the control to the beginning of the loop, hence the letter k is not printed.
Akanksha_Rai
python-basics
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
|
[
{
"code": null,
"e": 24294,
"s": 24266,
"text": "\n25 Jun, 2020"
},
{
"code": null,
"e": 24766,
"s": 24294,
"text": "Using loops in Python automates and repeats the tasks in an efficient manner. But sometimes, there may arise a condition where you want to exit the loop completely, skip an iteration or ignore that condition. These can be done by loop control statements. Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. Python supports the following control statements."
},
{
"code": null,
"e": 24785,
"s": 24766,
"text": "Continue statement"
},
{
"code": null,
"e": 24801,
"s": 24785,
"text": "Break statement"
},
{
"code": null,
"e": 24816,
"s": 24801,
"text": "Pass statement"
},
{
"code": null,
"e": 24911,
"s": 24816,
"text": "In this article, the main focus will be on the difference between continue and pass statement."
},
{
"code": null,
"e": 25165,
"s": 24911,
"text": "This statement is used to skip over the execution part of the loop on a certain condition. After that, it transfers the control to the beginning of the loop. Basically, it skips its following statements and continues with the next iteration of the loop."
},
{
"code": null,
"e": 25173,
"s": 25165,
"text": "Syntax:"
},
{
"code": null,
"e": 25183,
"s": 25173,
"text": "continue\n"
},
{
"code": null,
"e": 25355,
"s": 25183,
"text": "As the name suggests pass statement simply does nothing. We use pass statement to write empty loops. Pass is also used for empty control statements, functions and classes."
},
{
"code": null,
"e": 25363,
"s": 25355,
"text": "Syntax:"
},
{
"code": null,
"e": 25369,
"s": 25363,
"text": "pass\n"
},
{
"code": null,
"e": 25473,
"s": 25369,
"text": "Consider the below example for better understanding the difference between continue and pass statement."
},
{
"code": null,
"e": 25482,
"s": 25473,
"text": "Example:"
},
{
"code": "# Python program to demonstrate# difference between pass and # continue statements s = \"geeks\" # Pass statementfor i in s: if i == 'k': print('Pass executed') pass print(i) print() # Continue statementfor i in s: if i == 'k': print('Continue executed') continue print(i)",
"e": 25801,
"s": 25482,
"text": null
},
{
"code": null,
"e": 25809,
"s": 25801,
"text": "Output:"
},
{
"code": null,
"e": 25861,
"s": 25809,
"text": "g\ne\ne\nPass executed\nk\ns\n\ng\ne\ne\nContinue executed\ns\n"
},
{
"code": null,
"e": 26151,
"s": 25861,
"text": "In the above example, when the value of i becomes equal to ‘k‘, the pass statement did nothing and hence the letter ‘k‘ is also printed. Whereas in the case of continue statement, the continue statement transfers the control to the beginning of the loop, hence the letter k is not printed."
},
{
"code": null,
"e": 26164,
"s": 26151,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 26178,
"s": 26164,
"text": "python-basics"
},
{
"code": null,
"e": 26185,
"s": 26178,
"text": "Python"
},
{
"code": null,
"e": 26283,
"s": 26185,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26301,
"s": 26283,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26336,
"s": 26301,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26358,
"s": 26336,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26390,
"s": 26358,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26420,
"s": 26390,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26462,
"s": 26420,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26488,
"s": 26462,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26525,
"s": 26488,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 26568,
"s": 26525,
"text": "Python program to convert a list to string"
}
] |
Count the number of element present in the sequence in LINQ? - GeeksforGeeks
|
21 May, 2019
In LINQ, you can count the total number of elements present in the given sequence by using the Count Method. This method returns the total number of elements present in the given sequence.
This method can be overloaded in two different ways:
Count<TSource>(): This method returns the total number of elements present in the given specified sequence. The return type of this method is System.Int32. This method gives ArgumentNullException if the source is null and OverflowException if the value of the source is large. It does not support query syntax in C#, but you can wrap the query into brackets() and use aggregation functions as shown in Example 1. It supports query syntax in VB.NET.Syntax:int Count<TSource>();Count<TSource>(Func<TSource, bool> predicate): This method is used to return the number of items which satisfy the given condition. The return type of this method is System.Int32. This method gives ArgumentNullException if the source or predicate is null and OverflowException if the value of the source is large.Syntax:int Count<TSource>(Func<TSource, bool> predicate);Note: This method with predicate parameter is not supported in VB.NET.
Count<TSource>(): This method returns the total number of elements present in the given specified sequence. The return type of this method is System.Int32. This method gives ArgumentNullException if the source is null and OverflowException if the value of the source is large. It does not support query syntax in C#, but you can wrap the query into brackets() and use aggregation functions as shown in Example 1. It supports query syntax in VB.NET.Syntax:int Count<TSource>();
Syntax:
int Count<TSource>();
Count<TSource>(Func<TSource, bool> predicate): This method is used to return the number of items which satisfy the given condition. The return type of this method is System.Int32. This method gives ArgumentNullException if the source or predicate is null and OverflowException if the value of the source is large.Syntax:int Count<TSource>(Func<TSource, bool> predicate);Note: This method with predicate parameter is not supported in VB.NET.
Syntax:
int Count<TSource>(Func<TSource, bool> predicate);
Note: This method with predicate parameter is not supported in VB.NET.
Example 1:
// C# program to find total number of// elements present in the given arrayusing System;using System.Linq; class GFG { // Main Method static public void Main() { // Data source int[] sequence = {6, 455, 50, 56, 102, 89, 9, 100, 67, 29}; // Display the sequence Console.WriteLine("The sequence is: "); foreach(int s in sequence) { Console.WriteLine(s); } // Finding the total number of elements // present in the given sequence // Using Count function int result = sequence.Count(); Console.WriteLine("Total number of Elements: {0}", result); }}
The sequence is:
6
455
50
56
102
89
9
100
67
29
Total number of Elements: 10
Example 2:
// C# program to count the total// number of the employeesusing System;using System.Linq;using System.Collections.Generic; // Employee detailspublic class Employee { public int emp_id { get; set; } public string emp_name { get; set; } public string emp_gender { get; set; } public string emp_hire_date { get; set; } public int emp_salary { get; set; }} class GFG { // Main method static public void Main() { List<Employee> emp = new List<Employee>() { new Employee() { emp_id = 209, emp_name = "Anjita", emp_gender = "Female", emp_hire_date = "12/3/2017", emp_salary = 20000 }, new Employee() { emp_id = 210, emp_name = "Soniya", emp_gender = "Female", emp_hire_date = "22/4/2018", emp_salary = 30000 }, new Employee() { emp_id = 211, emp_name = "Rohit", emp_gender = "Male", emp_hire_date = "3/5/2016", emp_salary = 40000 }, new Employee() { emp_id = 212, emp_name = "Supriya", emp_gender = "Female", emp_hire_date = "4/8/2017", emp_salary = 40000 }, new Employee() { emp_id = 213, emp_name = "Anil", emp_gender = "Male", emp_hire_date = "12/1/2016", emp_salary = 40000 }, new Employee() { emp_id = 214, emp_name = "Anju", emp_gender = "Female", emp_hire_date = "17/6/2015", emp_salary = 50000 }, }; // Count the total number of employees // Using Count () method var res = (from e in emp select e.emp_id) .Count(); Console.WriteLine("Total number of Employees: {0}", res); }}
Total number of Employees: 6
CSharp LINQ
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 50 C# Interview Questions & Answers
Extension Method in C#
HashSet in C# with Examples
Partial Classes in C#
C# | Inheritance
Convert String to Character Array in C#
Linked List Implementation in C#
C# | How to insert an element in an Array?
C# | List Class
Difference between Hashtable and Dictionary in C#
|
[
{
"code": null,
"e": 23911,
"s": 23883,
"text": "\n21 May, 2019"
},
{
"code": null,
"e": 24100,
"s": 23911,
"text": "In LINQ, you can count the total number of elements present in the given sequence by using the Count Method. This method returns the total number of elements present in the given sequence."
},
{
"code": null,
"e": 24153,
"s": 24100,
"text": "This method can be overloaded in two different ways:"
},
{
"code": null,
"e": 25070,
"s": 24153,
"text": "Count<TSource>(): This method returns the total number of elements present in the given specified sequence. The return type of this method is System.Int32. This method gives ArgumentNullException if the source is null and OverflowException if the value of the source is large. It does not support query syntax in C#, but you can wrap the query into brackets() and use aggregation functions as shown in Example 1. It supports query syntax in VB.NET.Syntax:int Count<TSource>();Count<TSource>(Func<TSource, bool> predicate): This method is used to return the number of items which satisfy the given condition. The return type of this method is System.Int32. This method gives ArgumentNullException if the source or predicate is null and OverflowException if the value of the source is large.Syntax:int Count<TSource>(Func<TSource, bool> predicate);Note: This method with predicate parameter is not supported in VB.NET."
},
{
"code": null,
"e": 25547,
"s": 25070,
"text": "Count<TSource>(): This method returns the total number of elements present in the given specified sequence. The return type of this method is System.Int32. This method gives ArgumentNullException if the source is null and OverflowException if the value of the source is large. It does not support query syntax in C#, but you can wrap the query into brackets() and use aggregation functions as shown in Example 1. It supports query syntax in VB.NET.Syntax:int Count<TSource>();"
},
{
"code": null,
"e": 25555,
"s": 25547,
"text": "Syntax:"
},
{
"code": null,
"e": 25577,
"s": 25555,
"text": "int Count<TSource>();"
},
{
"code": null,
"e": 26018,
"s": 25577,
"text": "Count<TSource>(Func<TSource, bool> predicate): This method is used to return the number of items which satisfy the given condition. The return type of this method is System.Int32. This method gives ArgumentNullException if the source or predicate is null and OverflowException if the value of the source is large.Syntax:int Count<TSource>(Func<TSource, bool> predicate);Note: This method with predicate parameter is not supported in VB.NET."
},
{
"code": null,
"e": 26026,
"s": 26018,
"text": "Syntax:"
},
{
"code": null,
"e": 26077,
"s": 26026,
"text": "int Count<TSource>(Func<TSource, bool> predicate);"
},
{
"code": null,
"e": 26148,
"s": 26077,
"text": "Note: This method with predicate parameter is not supported in VB.NET."
},
{
"code": null,
"e": 26159,
"s": 26148,
"text": "Example 1:"
},
{
"code": "// C# program to find total number of// elements present in the given arrayusing System;using System.Linq; class GFG { // Main Method static public void Main() { // Data source int[] sequence = {6, 455, 50, 56, 102, 89, 9, 100, 67, 29}; // Display the sequence Console.WriteLine(\"The sequence is: \"); foreach(int s in sequence) { Console.WriteLine(s); } // Finding the total number of elements // present in the given sequence // Using Count function int result = sequence.Count(); Console.WriteLine(\"Total number of Elements: {0}\", result); }}",
"e": 26847,
"s": 26159,
"text": null
},
{
"code": null,
"e": 26926,
"s": 26847,
"text": "The sequence is: \n6\n455\n50\n56\n102\n89\n9\n100\n67\n29\nTotal number of Elements: 10\n"
},
{
"code": null,
"e": 26937,
"s": 26926,
"text": "Example 2:"
},
{
"code": "// C# program to count the total// number of the employeesusing System;using System.Linq;using System.Collections.Generic; // Employee detailspublic class Employee { public int emp_id { get; set; } public string emp_name { get; set; } public string emp_gender { get; set; } public string emp_hire_date { get; set; } public int emp_salary { get; set; }} class GFG { // Main method static public void Main() { List<Employee> emp = new List<Employee>() { new Employee() { emp_id = 209, emp_name = \"Anjita\", emp_gender = \"Female\", emp_hire_date = \"12/3/2017\", emp_salary = 20000 }, new Employee() { emp_id = 210, emp_name = \"Soniya\", emp_gender = \"Female\", emp_hire_date = \"22/4/2018\", emp_salary = 30000 }, new Employee() { emp_id = 211, emp_name = \"Rohit\", emp_gender = \"Male\", emp_hire_date = \"3/5/2016\", emp_salary = 40000 }, new Employee() { emp_id = 212, emp_name = \"Supriya\", emp_gender = \"Female\", emp_hire_date = \"4/8/2017\", emp_salary = 40000 }, new Employee() { emp_id = 213, emp_name = \"Anil\", emp_gender = \"Male\", emp_hire_date = \"12/1/2016\", emp_salary = 40000 }, new Employee() { emp_id = 214, emp_name = \"Anju\", emp_gender = \"Female\", emp_hire_date = \"17/6/2015\", emp_salary = 50000 }, }; // Count the total number of employees // Using Count () method var res = (from e in emp select e.emp_id) .Count(); Console.WriteLine(\"Total number of Employees: {0}\", res); }}",
"e": 28631,
"s": 26937,
"text": null
},
{
"code": null,
"e": 28661,
"s": 28631,
"text": "Total number of Employees: 6\n"
},
{
"code": null,
"e": 28673,
"s": 28661,
"text": "CSharp LINQ"
},
{
"code": null,
"e": 28676,
"s": 28673,
"text": "C#"
},
{
"code": null,
"e": 28774,
"s": 28676,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28783,
"s": 28774,
"text": "Comments"
},
{
"code": null,
"e": 28796,
"s": 28783,
"text": "Old Comments"
},
{
"code": null,
"e": 28836,
"s": 28796,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 28859,
"s": 28836,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 28887,
"s": 28859,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 28909,
"s": 28887,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 28926,
"s": 28909,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 28966,
"s": 28926,
"text": "Convert String to Character Array in C#"
},
{
"code": null,
"e": 28999,
"s": 28966,
"text": "Linked List Implementation in C#"
},
{
"code": null,
"e": 29042,
"s": 28999,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 29058,
"s": 29042,
"text": "C# | List Class"
}
] |
JSP - The taglib Directive
|
The JavaServer Pages API allow you to define custom JSP tags that look like HTML or XML tags and a tag library is a set of user-defined tags that implement custom behavior.
The taglib directive declares that your JSP page uses a set of custom tags, identifies the location of the library, and provides means for identifying the custom tags in your JSP page.
The taglib directive follows the syntax given below −
<%@ taglib uri = "uri" prefix = "prefixOfTag" >
Where, the uri attribute value resolves to a location the container understands and the prefix attribute informs a container what bits of markup are custom actions.
You can write the XML equivalent of the above syntax as follows −
<jsp:directive.taglib uri = "uri" prefix = "prefixOfTag" />
When you use a custom tag, it is typically of the form <prefix:tagname>. The prefix is the same as the prefix you specify in the taglib directive, and the tagname is the name of a tag implemented in the tag library.
For example, suppose the custlib tag library contains a tag called hello. If you wanted to use the hello tag with a prefix of mytag, your tag would be <mytag:hello> and it will be used in your JSP file as follows −
<%@ taglib uri = "http://www.example.com/custlib" prefix = "mytag" %>
<html>
<body>
<mytag:hello/>
</body>
</html>
We can call another piece of code using <mytag:hello>. We will see how to develop our custom tags and how to use them in JSP - Custom Tags tutorial.
108 Lectures
11 hours
Chaand Sheikh
517 Lectures
57 hours
Chaand Sheikh
41 Lectures
4.5 hours
Karthikeya T
42 Lectures
5.5 hours
TELCOMA Global
15 Lectures
3 hours
TELCOMA Global
44 Lectures
15 hours
Uplatz
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2412,
"s": 2239,
"text": "The JavaServer Pages API allow you to define custom JSP tags that look like HTML or XML tags and a tag library is a set of user-defined tags that implement custom behavior."
},
{
"code": null,
"e": 2597,
"s": 2412,
"text": "The taglib directive declares that your JSP page uses a set of custom tags, identifies the location of the library, and provides means for identifying the custom tags in your JSP page."
},
{
"code": null,
"e": 2651,
"s": 2597,
"text": "The taglib directive follows the syntax given below −"
},
{
"code": null,
"e": 2700,
"s": 2651,
"text": "<%@ taglib uri = \"uri\" prefix = \"prefixOfTag\" >\n"
},
{
"code": null,
"e": 2865,
"s": 2700,
"text": "Where, the uri attribute value resolves to a location the container understands and the prefix attribute informs a container what bits of markup are custom actions."
},
{
"code": null,
"e": 2931,
"s": 2865,
"text": "You can write the XML equivalent of the above syntax as follows −"
},
{
"code": null,
"e": 2992,
"s": 2931,
"text": "<jsp:directive.taglib uri = \"uri\" prefix = \"prefixOfTag\" />\n"
},
{
"code": null,
"e": 3208,
"s": 2992,
"text": "When you use a custom tag, it is typically of the form <prefix:tagname>. The prefix is the same as the prefix you specify in the taglib directive, and the tagname is the name of a tag implemented in the tag library."
},
{
"code": null,
"e": 3423,
"s": 3208,
"text": "For example, suppose the custlib tag library contains a tag called hello. If you wanted to use the hello tag with a prefix of mytag, your tag would be <mytag:hello> and it will be used in your JSP file as follows −"
},
{
"code": null,
"e": 3551,
"s": 3423,
"text": "<%@ taglib uri = \"http://www.example.com/custlib\" prefix = \"mytag\" %>\n\n<html>\n <body>\n <mytag:hello/>\n </body>\n</html>"
},
{
"code": null,
"e": 3700,
"s": 3551,
"text": "We can call another piece of code using <mytag:hello>. We will see how to develop our custom tags and how to use them in JSP - Custom Tags tutorial."
},
{
"code": null,
"e": 3735,
"s": 3700,
"text": "\n 108 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3750,
"s": 3735,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 3785,
"s": 3750,
"text": "\n 517 Lectures \n 57 hours \n"
},
{
"code": null,
"e": 3800,
"s": 3785,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 3835,
"s": 3800,
"text": "\n 41 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3849,
"s": 3835,
"text": " Karthikeya T"
},
{
"code": null,
"e": 3884,
"s": 3849,
"text": "\n 42 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3900,
"s": 3884,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 3933,
"s": 3900,
"text": "\n 15 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3949,
"s": 3933,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 3983,
"s": 3949,
"text": "\n 44 Lectures \n 15 hours \n"
},
{
"code": null,
"e": 3991,
"s": 3983,
"text": " Uplatz"
},
{
"code": null,
"e": 3998,
"s": 3991,
"text": " Print"
},
{
"code": null,
"e": 4009,
"s": 3998,
"text": " Add Notes"
}
] |
Find length of Loop | Practice | GeeksforGeeks
|
Given a linked list of size N. The task is to complete the function countNodesinLoop() that checks whether a given Linked List contains a loop or not and if the loop is present then return the count of nodes in a loop or else return 0. C is the position of the node to which the last node is connected. If it is 0 then no loop.
Example 1:
Input:
N = 10
value[]={25,14,19,33,10,21,39,90,58,45}
C = 4
Output: 7
Explanation: The loop is 45->33. So
length of loop is 33->10->21->39->
90->58->45 = 7. The number 33 is
connected to the last node to form the
loop because according to the input the
4th node from the beginning(1 based
index) will be connected to the last
node for the loop.
Example 2:
Input:
N = 2
value[] = {1,0}
C = 1
Output: 2
Explanation: The length of the loop
is 2.
Your Task:
The task is to complete the function countNodesinLoop() which contains the only argument as reference to head of linked list and return the lenght of the loop ( 0 if there is no loop).
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
Constraints:
1 <= N <= 500
0 <= C <= N-1
0
awektoppo5 days ago
int countNodesinLoop(struct Node *head){ // Floyd Loop finding method with counting loop elements
Node *slow=head; Node *fast = NULL; if(head->next) fast = head->next; int cnt=0; bool start=false; while(fast){ if(slow == fast){ if(start) break; start = !start; } if(start) cnt++; if(slow->next) slow = slow->next; else break; if(fast->next) fast=fast->next; else break; if(fast->next) fast=fast->next; else break; } return cnt; }
0
tthakare732 weeks ago
//Java Solution TC -> 1.55
//hint -> tortoise and hare algorithm
class Solution{
static int findcycleStart(Node root){
Node fast = root, slow = root;
boolean loop = false;
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
if(slow == fast) {
loop = true;
break;
}
}
if(!loop) return 0;
int count = 1;
slow = slow.next;
while(fast != slow){
slow = slow.next;
count++;
}
return count;
}
static int countNodesinLoop(Node head){
if(head == null) return 0;
return findcycleStart(head);
}
}
0
hharshit81183 weeks ago
T(N) : O(N)
int countNodesinLoop(struct Node *head){ if(head == NULL){ return 0; } bool isloop = false; int len = 0; Node *slow = head, *fast = head; while(fast && fast->next){ slow = slow->next; fast = fast->next->next; if(slow == fast){ isloop = true; break; } } if(isloop){ slow = head; while(slow != fast){ slow = slow->next; fast = fast->next; } do{ len++; fast = fast->next; }while(fast != slow); } return len;}
0
roysidharth5823 weeks ago
static int countNodesinLoop(Node head)
{
Node fast=head;
Node slow=head;
while(fast!=null && fast.next!=null){
slow=slow.next;
fast=fast.next.next;
if(slow==fast){
int c=1;
slow=slow.next;
while(slow!=fast){
c++;
slow=slow.next;
}
return c;
}
} return 0;
}
0
jpragati053 weeks ago
JAVA SOLUTION USING HASHSET
class Solution
{
//Function to find the length of a loop in the linked list.
static int count(Node head){
int res=1;
Node temp=head;
while(temp.next!=head){
res++;
temp=temp.next;
}
return res;
}
static int countNodesinLoop(Node head)
{
//Add your code here.
Set<Node>hs=new HashSet<>();
while(head!=null){
if(hs.contains(head))
return count(head);
hs.add(head);
head=head.next;
}
return 0;
}
}
0
amiransarimy4 weeks ago
Python Solutions
def countNodesinLoop(head):
count = 0
fast, slow = head, head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if fast == slow:
count += 1
slow = slow.next
while fast != slow:
count += 1
slow = slow.next
return count
return 0
0
rmn51241 month ago
int countNodesinLoop(struct Node *head)
{
Node*slow=head,*fast=head;
while(fast and fast->next){
slow=slow->next;
fast=fast->next->next;
if(slow==fast){ // loop detected
int c=1;
slow=slow->next;
while(fast!=slow){ //check the length
c++;
slow=slow->next;
}
return c;
}
}
return 0;
}
0
roopsaisurampudi1 month ago
static int countNodesinLoop(Node head)
{
//Add your code here.
Node temp = head;
Node slow = head;
Node fast = head;
Node intersection = null;
while(fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (fast == slow) {
intersection = slow;
break;
}
}
if (fast == null || fast.next == null) return 0;
Node start = intersection.next;
int len = 1;
while(intersection != start) {
len++;
start = start.next;
}
return len;
}
0
sgupta0781 month ago
C++ solution
int countNodesinLoop(struct Node *head)
{
// Code here
Node* start=NULL;
Node* slow = head;
Node* fast = head;
// find the loop start
while(slow!=NULL && fast!=NULL && fast->next!=NULL){
slow=slow->next;
fast=fast->next->next;
if(slow==fast){
start=slow;
break;
}
}
// count nodes between loop
Node* check=start;
int count=0;
while(start!=NULL){
count++;
start=start->next;
if(start==check){
break;
}
}
return count;
}
0
pritamtech19981 month ago
int count(Node *t1, Node *t2){ int len = 0; while((t2 = t2->next) and t1 != t2 and (len = len+1)); return len+1;}
int countNodesinLoop(struct Node *head){ Node *t1 = head, *t2 = head; while(t1 and t2 and t1->next and t2->next and t2->next->next and (t1 = t1->next) and (t2 = t2->next->next)){ if(t1 == t2) return count(t1, t2); } return 0;}
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": 566,
"s": 238,
"text": "Given a linked list of size N. The task is to complete the function countNodesinLoop() that checks whether a given Linked List contains a loop or not and if the loop is present then return the count of nodes in a loop or else return 0. C is the position of the node to which the last node is connected. If it is 0 then no loop."
},
{
"code": null,
"e": 579,
"s": 568,
"text": "Example 1:"
},
{
"code": null,
"e": 925,
"s": 579,
"text": "Input:\nN = 10\nvalue[]={25,14,19,33,10,21,39,90,58,45}\nC = 4\nOutput: 7\nExplanation: The loop is 45->33. So\nlength of loop is 33->10->21->39->\n90->58->45 = 7. The number 33 is\nconnected to the last node to form the\nloop because according to the input the\n4th node from the beginning(1 based\nindex) will be connected to the last\nnode for the loop.\n"
},
{
"code": null,
"e": 936,
"s": 925,
"text": "Example 2:"
},
{
"code": null,
"e": 1023,
"s": 936,
"text": "Input:\nN = 2\nvalue[] = {1,0}\nC = 1\nOutput: 2\nExplanation: The length of the loop\nis 2."
},
{
"code": null,
"e": 1219,
"s": 1023,
"text": "Your Task:\nThe task is to complete the function countNodesinLoop() which contains the only argument as reference to head of linked list and return the lenght of the loop ( 0 if there is no loop)."
},
{
"code": null,
"e": 1281,
"s": 1219,
"text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1322,
"s": 1281,
"text": "Constraints:\n1 <= N <= 500\n0 <= C <= N-1"
},
{
"code": null,
"e": 1324,
"s": 1322,
"text": "0"
},
{
"code": null,
"e": 1344,
"s": 1324,
"text": "awektoppo5 days ago"
},
{
"code": null,
"e": 1444,
"s": 1344,
"text": "int countNodesinLoop(struct Node *head){ // Floyd Loop finding method with counting loop elements"
},
{
"code": null,
"e": 1886,
"s": 1444,
"text": " Node *slow=head; Node *fast = NULL; if(head->next) fast = head->next; int cnt=0; bool start=false; while(fast){ if(slow == fast){ if(start) break; start = !start; } if(start) cnt++; if(slow->next) slow = slow->next; else break; if(fast->next) fast=fast->next; else break; if(fast->next) fast=fast->next; else break; } return cnt; }"
},
{
"code": null,
"e": 1888,
"s": 1886,
"text": "0"
},
{
"code": null,
"e": 1910,
"s": 1888,
"text": "tthakare732 weeks ago"
},
{
"code": null,
"e": 2645,
"s": 1910,
"text": "//Java Solution TC -> 1.55\n//hint -> tortoise and hare algorithm\nclass Solution{\n static int findcycleStart(Node root){\n Node fast = root, slow = root;\n boolean loop = false;\n while(fast != null && fast.next != null){\n slow = slow.next;\n fast = fast.next.next;\n if(slow == fast) {\n loop = true;\n break;\n }\n }\n if(!loop) return 0;\n int count = 1;\n slow = slow.next;\n while(fast != slow){\n slow = slow.next;\n count++;\n }\n return count;\n }\n static int countNodesinLoop(Node head){\n if(head == null) return 0;\n return findcycleStart(head);\n }\n}\n"
},
{
"code": null,
"e": 2647,
"s": 2645,
"text": "0"
},
{
"code": null,
"e": 2671,
"s": 2647,
"text": "hharshit81183 weeks ago"
},
{
"code": null,
"e": 2683,
"s": 2671,
"text": "T(N) : O(N)"
},
{
"code": null,
"e": 3225,
"s": 2683,
"text": "int countNodesinLoop(struct Node *head){ if(head == NULL){ return 0; } bool isloop = false; int len = 0; Node *slow = head, *fast = head; while(fast && fast->next){ slow = slow->next; fast = fast->next->next; if(slow == fast){ isloop = true; break; } } if(isloop){ slow = head; while(slow != fast){ slow = slow->next; fast = fast->next; } do{ len++; fast = fast->next; }while(fast != slow); } return len;}"
},
{
"code": null,
"e": 3227,
"s": 3225,
"text": "0"
},
{
"code": null,
"e": 3253,
"s": 3227,
"text": "roysidharth5823 weeks ago"
},
{
"code": null,
"e": 3725,
"s": 3253,
"text": "static int countNodesinLoop(Node head)\n {\n Node fast=head;\n Node slow=head;\n while(fast!=null && fast.next!=null){\n slow=slow.next;\n fast=fast.next.next;\n \n \n if(slow==fast){\n int c=1;\n slow=slow.next;\n while(slow!=fast){\n c++;\n slow=slow.next;\n }\n return c;\n }\n } return 0;\n }"
},
{
"code": null,
"e": 3727,
"s": 3725,
"text": "0"
},
{
"code": null,
"e": 3749,
"s": 3727,
"text": "jpragati053 weeks ago"
},
{
"code": null,
"e": 4348,
"s": 3749,
"text": "JAVA SOLUTION USING HASHSET\nclass Solution\n{\n //Function to find the length of a loop in the linked list.\n static int count(Node head){\n int res=1;\n Node temp=head;\n while(temp.next!=head){\n res++;\n temp=temp.next;\n }\n return res;\n }\n static int countNodesinLoop(Node head)\n {\n //Add your code here.\n Set<Node>hs=new HashSet<>();\n while(head!=null){\n if(hs.contains(head))\n return count(head);\n hs.add(head);\n head=head.next;\n }\n return 0;\n }\n}"
},
{
"code": null,
"e": 4350,
"s": 4348,
"text": "0"
},
{
"code": null,
"e": 4374,
"s": 4350,
"text": "amiransarimy4 weeks ago"
},
{
"code": null,
"e": 4391,
"s": 4374,
"text": "Python Solutions"
},
{
"code": null,
"e": 4774,
"s": 4393,
"text": "def countNodesinLoop(head):\n count = 0\n fast, slow = head, head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n \n if fast == slow:\n count += 1\n slow = slow.next\n \n while fast != slow:\n count += 1\n slow = slow.next\n \n return count\n return 0"
},
{
"code": null,
"e": 4776,
"s": 4774,
"text": "0"
},
{
"code": null,
"e": 4795,
"s": 4776,
"text": "rmn51241 month ago"
},
{
"code": null,
"e": 5283,
"s": 4795,
"text": "int countNodesinLoop(struct Node *head)\n{\n Node*slow=head,*fast=head;\n\n while(fast and fast->next){\n slow=slow->next;\n fast=fast->next->next;\n if(slow==fast){ // loop detected\n int c=1;\n slow=slow->next;\n while(fast!=slow){ //check the length\n c++;\n slow=slow->next;\n }\n return c;\n }\n }\n return 0;\n }\n"
},
{
"code": null,
"e": 5285,
"s": 5283,
"text": "0"
},
{
"code": null,
"e": 5313,
"s": 5285,
"text": "roopsaisurampudi1 month ago"
},
{
"code": null,
"e": 5976,
"s": 5313,
"text": "static int countNodesinLoop(Node head)\n {\n //Add your code here.\n Node temp = head;\n Node slow = head;\n Node fast = head;\n Node intersection = null;\n while(fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n if (fast == slow) {\n intersection = slow;\n break;\n }\n }\n if (fast == null || fast.next == null) return 0;\n Node start = intersection.next;\n int len = 1;\n while(intersection != start) {\n len++;\n start = start.next;\n }\n return len;\n }"
},
{
"code": null,
"e": 5978,
"s": 5976,
"text": "0"
},
{
"code": null,
"e": 5999,
"s": 5978,
"text": "sgupta0781 month ago"
},
{
"code": null,
"e": 6012,
"s": 5999,
"text": "C++ solution"
},
{
"code": null,
"e": 6613,
"s": 6012,
"text": "int countNodesinLoop(struct Node *head)\n{\n // Code here\n \n \n Node* start=NULL;\n Node* slow = head;\n Node* fast = head;\n \n \n // find the loop start\n while(slow!=NULL && fast!=NULL && fast->next!=NULL){\n slow=slow->next;\n fast=fast->next->next;\n if(slow==fast){\n start=slow;\n break;\n }\n }\n \n // count nodes between loop\n Node* check=start;\n int count=0;\n while(start!=NULL){\n count++;\n start=start->next;\n if(start==check){\n break;\n }\n }\n return count;\n \n}"
},
{
"code": null,
"e": 6615,
"s": 6613,
"text": "0"
},
{
"code": null,
"e": 6641,
"s": 6615,
"text": "pritamtech19981 month ago"
},
{
"code": null,
"e": 6761,
"s": 6641,
"text": "int count(Node *t1, Node *t2){ int len = 0; while((t2 = t2->next) and t1 != t2 and (len = len+1)); return len+1;}"
},
{
"code": null,
"e": 7012,
"s": 6761,
"text": "int countNodesinLoop(struct Node *head){ Node *t1 = head, *t2 = head; while(t1 and t2 and t1->next and t2->next and t2->next->next and (t1 = t1->next) and (t2 = t2->next->next)){ if(t1 == t2) return count(t1, t2); } return 0;}"
},
{
"code": null,
"e": 7158,
"s": 7012,
"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": 7194,
"s": 7158,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 7204,
"s": 7194,
"text": "\nProblem\n"
},
{
"code": null,
"e": 7214,
"s": 7204,
"text": "\nContest\n"
},
{
"code": null,
"e": 7277,
"s": 7214,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 7425,
"s": 7277,
"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": 7633,
"s": 7425,
"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": 7739,
"s": 7633,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
How to communicate JSON data between Python and Node.js ? - GeeksforGeeks
|
11 Feb, 2022
The following article covers how to communicate JSON data between Python and Node.js. Suppose we are working with the Node.js application, and we want to make use of a specific library that is only available in python or vice versa. We should be able to share the results from one language to another and to achieve it, we will use the JSON as it is language independent.
Approach:
Set up a server for each language and share data using JSON using the good old GET and POST request.Call a python background process from Node.js or vice versa and listen to the stdout stream of the process in both instances.
Set up a server for each language and share data using JSON using the good old GET and POST request.
Call a python background process from Node.js or vice versa and listen to the stdout stream of the process in both instances.
Project Structure: All the files used below are present in the same directory as shown below.
File Structure
1. Using Servers: This is similar to the approach of using a third-party API service wherein we make a GET request to the remote server to get the data and a POST request to send the data. The only difference is we will be running the servers locally (This would also work on the remote servers with the required URL).
Node.js to Python: When we are working in node.js and want to process some data in python.
In the following example, we will set up a server for Python and make requests from node.js. We are using Flask micro framework as this is the simplest way to set up a server in Python and to make requests in Node.js we will need a request package.
Module Installation:
Install the flask module for the Python using the following command:pip install flask
pip install flask
Install the request module for the NodeJS using the following command:npm install request-promise
npm install request-promise
Example: Calculate the sum of an array containing integers and return the result back to Node.js
pyserver.py
from flask import Flask, requestimport json # Setup flask serverapp = Flask(__name__) # Setup url route which will calculate# total sum of array.@app.route('/arraysum', methods = ['POST']) def sum_of_array(): data = request.get_json() print(data) # Data variable contains the # data from the node server ls = data['array'] result = sum(ls) # calculate the sum # Return data in json format return json.dumps({"result":result}) if __name__ == "__main__": app.run(port=5000)
Run the server using the following command.
python pyserver.py
This will start the server at http://127.0.0.1:5000/. Now we make a POST request from Node.js to http://127.0.0.1:5000/arraysum
talk.js
var request = require('request-promise'); async function arraysum() { // This variable contains the data // you want to send var data = { array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] } var options = { method: 'POST', // http:flaskserverurl:port/route uri: 'http://127.0.0.1:5000/arraysum', body: data, // Automatically stringifies // the body to JSON json: true }; var sendrequest = await request(options) // The parsedBody contains the data // sent back from the Flask server .then(function (parsedBody) { console.log(parsedBody); // You can do something with // returned data let result; result = parsedBody['result']; console.log("Sum of Array from Python: ", result); }) .catch(function (err) { console.log(err); });} arraysum();
Run this script by the following command.
node talk.js
Output:
{ result: 55 }
Sum of Array from Python: 55
Python to Node.js: When we are working in python and want to process some data in Node.js.
Here we will reverse the above process and use express to fire up the server in node.js and request package in python.
Module Installation:
Install the request module for the Python using the following command:pip install requests
pip install requests
Install the express and body-parser module for the NodeJS using the following command:npm install express
npm install body-parser
npm install express
npm install body-parser
nodeserver.js
var express = require('express');var bodyParser = require('body-parser'); var app = express(); app.use(bodyParser.json());app.use(bodyParser.urlencoded({ extended: false })); app.post("/arraysum", (req, res) => { // Retrieve array form post body var array = req.body.array; console.log(array); // Calculate sum var sum = 0; for (var i = 0; i < array.length; i++) { if (isNaN(array[i])) { continue; } sum += array[i]; } console.log(sum); // Return json response res.json({ result: sum });}); // Server listening to PORT 3000app.listen(3000);
Run the server using the following command.
node nodeserver.js
This starts the server at http://127.0.0.1:3000/. Now we make a POST request from Python to 127.0.0.1:3000/arraysum
talk.py
import requests # Sample arrayarray = [1,2,3,4,5,6,7,8,9,10] # Data that we will send in post request.data = {'array':array} # The POST request to our node serverres = requests.post('http://127.0.0.1:3000/arraysum', json=data) # Convert response data to jsonreturned_data = res.json() print(returned_data)result = returned_data['result'] print("Sum of Array from Node.js:", result)
Run this script by the following command.
python talk.py
Output:
{'result': 55}
Sum of Array from Node.js: 55
2. Using background processes: In the following example, we will communicate by spawning a Python process from Node.js and vice versa and listen to the stdout stream.
Node.js to Python: Calling the python process from node.js. It involves the following steps:
Calling python process and pass JSON data as a command-line argument.Read that data in python, process it, and output it to stdout stream in JSON format.Again from node.js read the output stream and process the JSON data.
Calling python process and pass JSON data as a command-line argument.
Read that data in python, process it, and output it to stdout stream in JSON format.
Again from node.js read the output stream and process the JSON data.
arraysum.py
import sys, json # Function to calculate the sum of arraydef arraysum(arr): return sum(arr) # Get the command line arguments# and parse it to jsondata = json.loads(sys.argv[1]) # Get the required field from# the dataarray = data['array'] # Calculate the resultresult = arraysum(array) # Print the data in stringified# json format so that we can# easily parse it in Node.jsnewdata = {'sum':result}print(json.dumps(newdata))
Now python will process the sum of the array and print it to stdout as shown in the below code.
caller.js
const spawn = require('child_process').spawn; // Initialise the dataconst data = { array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]} // We need to stringify the data as // python cannot directly read JSON// as command line argument.let stringifiedData = JSON.stringify(data); // Call the python process and pass the// data as command line argument.const py = spawn('python', ['arraysum.py', stringifiedData]); resultString = ''; // As the stdout data stream is chunked,// we need to concat all the chunks.py.stdout.on('data', function (stdData) { resultString += stdData.toString();}); py.stdout.on('end', function () { // Parse the string as JSON when stdout // data stream ends let resultData = JSON.parse(resultString); let sum = resultData['sum']; console.log('Sum of array from Python process =', sum);});
Run this script by the following command:
node caller.js
Output:
Sum of array from Python process = 55
Python to Node.js: Calling node.js process from python. The steps essentially remain the same as mentioned above with python and node.js interchanging their roles.
arraysum.js
// Function to calculate sum of arrayfunction arraysum(arr) { let sum = 0; for (var i = 0; i < arr.length; i++) { if (isNaN(arr[i])) { continue; } sum += arr[i]; } return sum;} // Get the command line arguments and// parse it to jsonvar data = JSON.parse(process.argv[2]); // Get the required field form the data.array = data['array']; // Calculate the result.var sum = arraysum(array); // Print the data in stringified json// format so that we can easily parse// it in Pythonconst newData = { sum }console.log(JSON.stringify(newData));
Now run this Node.js process from python.
Filename: caller.py
Python3
from subprocess import Popen, PIPEimport json # Initialise the dataarray = [1,2,3,4,5,6,7,8,9,10]data = {'array':array} # Stringify the data.stingified_data = json.dumps(data) # Call the node process and pass the# data as command line argumentprocess = Popen(['node', 'arraysum.js', stingified_data], stdout=PIPE) # This line essentially waits for the # node process to complete and then# read stdout datastdout = process.communicate()[0] # The stdout is a bytes string, you can# convert it to another encoding but# json.loads() supports bytes string# so we aren't converting # Parse the data into jsonresult_data = json.loads(stdout)array_sum = result_data['sum']print('Sum of array from Node.js process =',array_sum)
Run this script by the following command.
python caller.py
Output:
Sum of array from Node.js process = 55
anikaseth98
kpshah
JSON
NodeJS-Questions
Picked
Python-json
Node.js
Python
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Node.js fs.writeFile() Method
Express.js express.Router() Function
Difference between promise and async await in Node.js
How to read and write Excel file in Node.js ?
Express.js res.render() Function
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
|
[
{
"code": null,
"e": 24628,
"s": 24600,
"text": "\n11 Feb, 2022"
},
{
"code": null,
"e": 25000,
"s": 24628,
"text": "The following article covers how to communicate JSON data between Python and Node.js. Suppose we are working with the Node.js application, and we want to make use of a specific library that is only available in python or vice versa. We should be able to share the results from one language to another and to achieve it, we will use the JSON as it is language independent."
},
{
"code": null,
"e": 25010,
"s": 25000,
"text": "Approach:"
},
{
"code": null,
"e": 25236,
"s": 25010,
"text": "Set up a server for each language and share data using JSON using the good old GET and POST request.Call a python background process from Node.js or vice versa and listen to the stdout stream of the process in both instances."
},
{
"code": null,
"e": 25337,
"s": 25236,
"text": "Set up a server for each language and share data using JSON using the good old GET and POST request."
},
{
"code": null,
"e": 25463,
"s": 25337,
"text": "Call a python background process from Node.js or vice versa and listen to the stdout stream of the process in both instances."
},
{
"code": null,
"e": 25557,
"s": 25463,
"text": "Project Structure: All the files used below are present in the same directory as shown below."
},
{
"code": null,
"e": 25572,
"s": 25557,
"text": "File Structure"
},
{
"code": null,
"e": 25891,
"s": 25572,
"text": "1. Using Servers: This is similar to the approach of using a third-party API service wherein we make a GET request to the remote server to get the data and a POST request to send the data. The only difference is we will be running the servers locally (This would also work on the remote servers with the required URL)."
},
{
"code": null,
"e": 25984,
"s": 25893,
"text": "Node.js to Python: When we are working in node.js and want to process some data in python."
},
{
"code": null,
"e": 26233,
"s": 25984,
"text": "In the following example, we will set up a server for Python and make requests from node.js. We are using Flask micro framework as this is the simplest way to set up a server in Python and to make requests in Node.js we will need a request package."
},
{
"code": null,
"e": 26254,
"s": 26233,
"text": "Module Installation:"
},
{
"code": null,
"e": 26340,
"s": 26254,
"text": "Install the flask module for the Python using the following command:pip install flask"
},
{
"code": null,
"e": 26358,
"s": 26340,
"text": "pip install flask"
},
{
"code": null,
"e": 26456,
"s": 26358,
"text": "Install the request module for the NodeJS using the following command:npm install request-promise"
},
{
"code": null,
"e": 26484,
"s": 26456,
"text": "npm install request-promise"
},
{
"code": null,
"e": 26581,
"s": 26484,
"text": "Example: Calculate the sum of an array containing integers and return the result back to Node.js"
},
{
"code": null,
"e": 26593,
"s": 26581,
"text": "pyserver.py"
},
{
"code": "from flask import Flask, requestimport json # Setup flask serverapp = Flask(__name__) # Setup url route which will calculate# total sum of array.@app.route('/arraysum', methods = ['POST']) def sum_of_array(): data = request.get_json() print(data) # Data variable contains the # data from the node server ls = data['array'] result = sum(ls) # calculate the sum # Return data in json format return json.dumps({\"result\":result}) if __name__ == \"__main__\": app.run(port=5000)",
"e": 27109,
"s": 26593,
"text": null
},
{
"code": null,
"e": 27153,
"s": 27109,
"text": "Run the server using the following command."
},
{
"code": null,
"e": 27172,
"s": 27153,
"text": "python pyserver.py"
},
{
"code": null,
"e": 27300,
"s": 27172,
"text": "This will start the server at http://127.0.0.1:5000/. Now we make a POST request from Node.js to http://127.0.0.1:5000/arraysum"
},
{
"code": null,
"e": 27308,
"s": 27300,
"text": "talk.js"
},
{
"code": "var request = require('request-promise'); async function arraysum() { // This variable contains the data // you want to send var data = { array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] } var options = { method: 'POST', // http:flaskserverurl:port/route uri: 'http://127.0.0.1:5000/arraysum', body: data, // Automatically stringifies // the body to JSON json: true }; var sendrequest = await request(options) // The parsedBody contains the data // sent back from the Flask server .then(function (parsedBody) { console.log(parsedBody); // You can do something with // returned data let result; result = parsedBody['result']; console.log(\"Sum of Array from Python: \", result); }) .catch(function (err) { console.log(err); });} arraysum();",
"e": 28263,
"s": 27308,
"text": null
},
{
"code": null,
"e": 28307,
"s": 28265,
"text": "Run this script by the following command."
},
{
"code": null,
"e": 28320,
"s": 28307,
"text": "node talk.js"
},
{
"code": null,
"e": 28328,
"s": 28320,
"text": "Output:"
},
{
"code": null,
"e": 28373,
"s": 28328,
"text": "{ result: 55 }\nSum of Array from Python: 55"
},
{
"code": null,
"e": 28464,
"s": 28373,
"text": "Python to Node.js: When we are working in python and want to process some data in Node.js."
},
{
"code": null,
"e": 28584,
"s": 28464,
"text": "Here we will reverse the above process and use express to fire up the server in node.js and request package in python. "
},
{
"code": null,
"e": 28605,
"s": 28584,
"text": "Module Installation:"
},
{
"code": null,
"e": 28696,
"s": 28605,
"text": "Install the request module for the Python using the following command:pip install requests"
},
{
"code": null,
"e": 28717,
"s": 28696,
"text": "pip install requests"
},
{
"code": null,
"e": 28847,
"s": 28717,
"text": "Install the express and body-parser module for the NodeJS using the following command:npm install express\nnpm install body-parser"
},
{
"code": null,
"e": 28891,
"s": 28847,
"text": "npm install express\nnpm install body-parser"
},
{
"code": null,
"e": 28905,
"s": 28891,
"text": "nodeserver.js"
},
{
"code": "var express = require('express');var bodyParser = require('body-parser'); var app = express(); app.use(bodyParser.json());app.use(bodyParser.urlencoded({ extended: false })); app.post(\"/arraysum\", (req, res) => { // Retrieve array form post body var array = req.body.array; console.log(array); // Calculate sum var sum = 0; for (var i = 0; i < array.length; i++) { if (isNaN(array[i])) { continue; } sum += array[i]; } console.log(sum); // Return json response res.json({ result: sum });}); // Server listening to PORT 3000app.listen(3000);",
"e": 29520,
"s": 28905,
"text": null
},
{
"code": null,
"e": 29564,
"s": 29520,
"text": "Run the server using the following command."
},
{
"code": null,
"e": 29583,
"s": 29564,
"text": "node nodeserver.js"
},
{
"code": null,
"e": 29700,
"s": 29583,
"text": "This starts the server at http://127.0.0.1:3000/. Now we make a POST request from Python to 127.0.0.1:3000/arraysum "
},
{
"code": null,
"e": 29708,
"s": 29700,
"text": "talk.py"
},
{
"code": "import requests # Sample arrayarray = [1,2,3,4,5,6,7,8,9,10] # Data that we will send in post request.data = {'array':array} # The POST request to our node serverres = requests.post('http://127.0.0.1:3000/arraysum', json=data) # Convert response data to jsonreturned_data = res.json() print(returned_data)result = returned_data['result'] print(\"Sum of Array from Node.js:\", result)",
"e": 30097,
"s": 29708,
"text": null
},
{
"code": null,
"e": 30139,
"s": 30097,
"text": "Run this script by the following command."
},
{
"code": null,
"e": 30155,
"s": 30139,
"text": "python talk.py "
},
{
"code": null,
"e": 30165,
"s": 30157,
"text": "Output:"
},
{
"code": null,
"e": 30210,
"s": 30165,
"text": "{'result': 55}\nSum of Array from Node.js: 55"
},
{
"code": null,
"e": 30377,
"s": 30210,
"text": "2. Using background processes: In the following example, we will communicate by spawning a Python process from Node.js and vice versa and listen to the stdout stream."
},
{
"code": null,
"e": 30470,
"s": 30377,
"text": "Node.js to Python: Calling the python process from node.js. It involves the following steps:"
},
{
"code": null,
"e": 30692,
"s": 30470,
"text": "Calling python process and pass JSON data as a command-line argument.Read that data in python, process it, and output it to stdout stream in JSON format.Again from node.js read the output stream and process the JSON data."
},
{
"code": null,
"e": 30762,
"s": 30692,
"text": "Calling python process and pass JSON data as a command-line argument."
},
{
"code": null,
"e": 30847,
"s": 30762,
"text": "Read that data in python, process it, and output it to stdout stream in JSON format."
},
{
"code": null,
"e": 30916,
"s": 30847,
"text": "Again from node.js read the output stream and process the JSON data."
},
{
"code": null,
"e": 30928,
"s": 30916,
"text": "arraysum.py"
},
{
"code": "import sys, json # Function to calculate the sum of arraydef arraysum(arr): return sum(arr) # Get the command line arguments# and parse it to jsondata = json.loads(sys.argv[1]) # Get the required field from# the dataarray = data['array'] # Calculate the resultresult = arraysum(array) # Print the data in stringified# json format so that we can# easily parse it in Node.jsnewdata = {'sum':result}print(json.dumps(newdata))",
"e": 31359,
"s": 30928,
"text": null
},
{
"code": null,
"e": 31455,
"s": 31359,
"text": "Now python will process the sum of the array and print it to stdout as shown in the below code."
},
{
"code": null,
"e": 31465,
"s": 31455,
"text": "caller.js"
},
{
"code": "const spawn = require('child_process').spawn; // Initialise the dataconst data = { array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]} // We need to stringify the data as // python cannot directly read JSON// as command line argument.let stringifiedData = JSON.stringify(data); // Call the python process and pass the// data as command line argument.const py = spawn('python', ['arraysum.py', stringifiedData]); resultString = ''; // As the stdout data stream is chunked,// we need to concat all the chunks.py.stdout.on('data', function (stdData) { resultString += stdData.toString();}); py.stdout.on('end', function () { // Parse the string as JSON when stdout // data stream ends let resultData = JSON.parse(resultString); let sum = resultData['sum']; console.log('Sum of array from Python process =', sum);});",
"e": 32283,
"s": 31465,
"text": null
},
{
"code": null,
"e": 32325,
"s": 32283,
"text": "Run this script by the following command:"
},
{
"code": null,
"e": 32340,
"s": 32325,
"text": "node caller.js"
},
{
"code": null,
"e": 32348,
"s": 32340,
"text": "Output:"
},
{
"code": null,
"e": 32386,
"s": 32348,
"text": "Sum of array from Python process = 55"
},
{
"code": null,
"e": 32550,
"s": 32386,
"text": "Python to Node.js: Calling node.js process from python. The steps essentially remain the same as mentioned above with python and node.js interchanging their roles."
},
{
"code": null,
"e": 32562,
"s": 32550,
"text": "arraysum.js"
},
{
"code": "// Function to calculate sum of arrayfunction arraysum(arr) { let sum = 0; for (var i = 0; i < arr.length; i++) { if (isNaN(arr[i])) { continue; } sum += arr[i]; } return sum;} // Get the command line arguments and// parse it to jsonvar data = JSON.parse(process.argv[2]); // Get the required field form the data.array = data['array']; // Calculate the result.var sum = arraysum(array); // Print the data in stringified json// format so that we can easily parse// it in Pythonconst newData = { sum }console.log(JSON.stringify(newData));",
"e": 33121,
"s": 32562,
"text": null
},
{
"code": null,
"e": 33163,
"s": 33121,
"text": "Now run this Node.js process from python."
},
{
"code": null,
"e": 33183,
"s": 33163,
"text": "Filename: caller.py"
},
{
"code": null,
"e": 33191,
"s": 33183,
"text": "Python3"
},
{
"code": "from subprocess import Popen, PIPEimport json # Initialise the dataarray = [1,2,3,4,5,6,7,8,9,10]data = {'array':array} # Stringify the data.stingified_data = json.dumps(data) # Call the node process and pass the# data as command line argumentprocess = Popen(['node', 'arraysum.js', stingified_data], stdout=PIPE) # This line essentially waits for the # node process to complete and then# read stdout datastdout = process.communicate()[0] # The stdout is a bytes string, you can# convert it to another encoding but# json.loads() supports bytes string# so we aren't converting # Parse the data into jsonresult_data = json.loads(stdout)array_sum = result_data['sum']print('Sum of array from Node.js process =',array_sum)",
"e": 33924,
"s": 33191,
"text": null
},
{
"code": null,
"e": 33966,
"s": 33924,
"text": "Run this script by the following command."
},
{
"code": null,
"e": 33983,
"s": 33966,
"text": "python caller.py"
},
{
"code": null,
"e": 33991,
"s": 33983,
"text": "Output:"
},
{
"code": null,
"e": 34030,
"s": 33991,
"text": "Sum of array from Node.js process = 55"
},
{
"code": null,
"e": 34042,
"s": 34030,
"text": "anikaseth98"
},
{
"code": null,
"e": 34049,
"s": 34042,
"text": "kpshah"
},
{
"code": null,
"e": 34054,
"s": 34049,
"text": "JSON"
},
{
"code": null,
"e": 34071,
"s": 34054,
"text": "NodeJS-Questions"
},
{
"code": null,
"e": 34078,
"s": 34071,
"text": "Picked"
},
{
"code": null,
"e": 34090,
"s": 34078,
"text": "Python-json"
},
{
"code": null,
"e": 34098,
"s": 34090,
"text": "Node.js"
},
{
"code": null,
"e": 34105,
"s": 34098,
"text": "Python"
},
{
"code": null,
"e": 34122,
"s": 34105,
"text": "Web Technologies"
},
{
"code": null,
"e": 34220,
"s": 34122,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34229,
"s": 34220,
"text": "Comments"
},
{
"code": null,
"e": 34242,
"s": 34229,
"text": "Old Comments"
},
{
"code": null,
"e": 34272,
"s": 34242,
"text": "Node.js fs.writeFile() Method"
},
{
"code": null,
"e": 34309,
"s": 34272,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 34363,
"s": 34309,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 34409,
"s": 34363,
"text": "How to read and write Excel file in Node.js ?"
},
{
"code": null,
"e": 34442,
"s": 34409,
"text": "Express.js res.render() Function"
},
{
"code": null,
"e": 34470,
"s": 34442,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 34520,
"s": 34470,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 34564,
"s": 34520,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 34582,
"s": 34564,
"text": "Python Dictionary"
}
] |
DOM - NamedNodeMap Object Method - item ()
|
The method item () returns the indexth item in the map. If index is greater than or equal to the number of nodes in this map, this returns null.
Following is the syntax for the usage of the item() method.
nodemapObject.item(index)
index
It specifies the position of the item into the map. It is of type unsigned long.
This method returns the indexth item in the map.
node.xml contents are as below −
<Company>
<Employee category = "Technical">
<FirstName>Tanmay</FirstName>
<LastName>Patil</LastName>
<ContactNo>1234567890</ContactNo>
<Email>tanmaypatil@xyz.com</Email>
</Employee>
<Employee category = "Non-Technical">
<FirstName>Taniya</FirstName>
<LastName>Mishra</LastName>
<ContactNo>1234667898</ContactNo>
<Email>taniyamishra@xyz.com</Email>
</Employee>
<Employee category = "Management">
<FirstName>Tanisha</FirstName>
<LastName>Sharma</LastName>
<ContactNo>1234562350</ContactNo>
<Email>tanishasharma@xyz.com</Email>
</Employee>
</Company>
Following example demonstrates the usage of the item() method −
<!DOCTYPE html>
<html>
<body>
<script>
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","/dom/node.xml",false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
x = xmlDoc.getElementsByTagName('Employee');
item_name = x.item(0).attributes.getNamedItem("category");
document.write("Get the specified item value : ")
document.write( item_name.value );
</script>
</body>
</html>
Save this file as namednodemapmethod_item.htm on the server path (this file and node_methods.xml should be on the same path in your server). We will get the output as shown below −
Get the specified item value : Technical
41 Lectures
5 hours
Abhishek And Pukhraj
33 Lectures
3.5 hours
Abhishek And Pukhraj
15 Lectures
1 hours
Zach Miller
15 Lectures
4 hours
Prof. Paul Cline, Ed.D
13 Lectures
4 hours
Prof. Paul Cline, Ed.D
17 Lectures
2 hours
Laurence Svekis
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2433,
"s": 2288,
"text": "The method item () returns the indexth item in the map. If index is greater than or equal to the number of nodes in this map, this returns null."
},
{
"code": null,
"e": 2493,
"s": 2433,
"text": "Following is the syntax for the usage of the item() method."
},
{
"code": null,
"e": 2520,
"s": 2493,
"text": "nodemapObject.item(index)\n"
},
{
"code": null,
"e": 2526,
"s": 2520,
"text": "index"
},
{
"code": null,
"e": 2607,
"s": 2526,
"text": "It specifies the position of the item into the map. It is of type unsigned long."
},
{
"code": null,
"e": 2656,
"s": 2607,
"text": "This method returns the indexth item in the map."
},
{
"code": null,
"e": 2689,
"s": 2656,
"text": "node.xml contents are as below −"
},
{
"code": null,
"e": 3335,
"s": 2689,
"text": "<Company>\n <Employee category = \"Technical\">\n <FirstName>Tanmay</FirstName>\n <LastName>Patil</LastName>\n <ContactNo>1234567890</ContactNo>\n <Email>tanmaypatil@xyz.com</Email>\n </Employee>\n \n <Employee category = \"Non-Technical\">\n <FirstName>Taniya</FirstName>\n <LastName>Mishra</LastName>\n <ContactNo>1234667898</ContactNo>\n <Email>taniyamishra@xyz.com</Email>\n </Employee>\n \n <Employee category = \"Management\">\n <FirstName>Tanisha</FirstName>\n <LastName>Sharma</LastName>\n <ContactNo>1234562350</ContactNo>\n <Email>tanishasharma@xyz.com</Email>\n </Employee>\n</Company>"
},
{
"code": null,
"e": 3399,
"s": 3335,
"text": "Following example demonstrates the usage of the item() method −"
},
{
"code": null,
"e": 4075,
"s": 3399,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <script>\n if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari\n xmlhttp = new XMLHttpRequest();\n }\n else {// code for IE6, IE5\n xmlhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n xmlhttp.open(\"GET\",\"/dom/node.xml\",false);\n xmlhttp.send();\n xmlDoc = xmlhttp.responseXML;\n\n x = xmlDoc.getElementsByTagName('Employee');\n\n\n item_name = x.item(0).attributes.getNamedItem(\"category\");\n document.write(\"Get the specified item value : \")\n document.write( item_name.value );\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 4256,
"s": 4075,
"text": "Save this file as namednodemapmethod_item.htm on the server path (this file and node_methods.xml should be on the same path in your server). We will get the output as shown below −"
},
{
"code": null,
"e": 4298,
"s": 4256,
"text": "Get the specified item value : Technical\n"
},
{
"code": null,
"e": 4331,
"s": 4298,
"text": "\n 41 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 4353,
"s": 4331,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 4388,
"s": 4353,
"text": "\n 33 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4410,
"s": 4388,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 4443,
"s": 4410,
"text": "\n 15 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4456,
"s": 4443,
"text": " Zach Miller"
},
{
"code": null,
"e": 4489,
"s": 4456,
"text": "\n 15 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4513,
"s": 4489,
"text": " Prof. Paul Cline, Ed.D"
},
{
"code": null,
"e": 4546,
"s": 4513,
"text": "\n 13 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4570,
"s": 4546,
"text": " Prof. Paul Cline, Ed.D"
},
{
"code": null,
"e": 4603,
"s": 4570,
"text": "\n 17 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4620,
"s": 4603,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 4627,
"s": 4620,
"text": " Print"
},
{
"code": null,
"e": 4638,
"s": 4627,
"text": " Add Notes"
}
] |
Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue) in C++
|
In this tutorial, we will be discussing a program to convert a binary tree to a threaded binary tree using a queue data structure.
For this, we will be provided with a binary tree. Our task is to convert that particular binary tree into a threaded binary tree by adding additional routes for quicker inorder traversal with the help of a queue data structure.
Live Demo
#include <iostream>
#include <queue>
using namespace std;
//node structure for threaded tree
struct Node {
int key;
Node *left, *right;
bool isThreaded;
};
//putting the inorder pattern into a queue
void convert_queue(Node* root, std::queue<Node*>* q){
if (root == NULL)
return;
if (root->left)
convert_queue(root->left, q);
q->push(root);
if (root->right)
convert_queue(root->right, q);
}
//traversing the queue and making threaded tree
void create_threadedtree(Node* root, std::queue<Node*>* q){
if (root == NULL)
return;
if (root->left)
create_threadedtree(root->left, q);
q->pop();
if (root->right)
create_threadedtree(root->right, q);
//if right pointer in NUll, point it to
//inorder successor
else {
root->right = q->front();
root->isThreaded = true;
}
}
//finally taking the tree and converting it into threaded
void createThreaded(Node* root){
std::queue<Node*> q;
convert_queue(root, &q);
create_threadedtree(root, &q);
}
Node* leftMost(Node* root){
while (root != NULL && root->left != NULL)
root = root->left;
return root;
}
//performing inorder traversal of threaded tree
void inOrder(Node* root){
if (root == NULL)
return;
Node* cur = leftMost(root);
while (cur != NULL) {
cout << cur->key << " ";
//if threaded node, move to inorder successor
if (cur->isThreaded)
cur = cur->right;
else
cur = leftMost(cur->right);
}
}
Node* newNode(int key){
Node* temp = new Node;
temp->left = temp->right = NULL;
temp->key = key;
return temp;
}
int main(){
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
createThreaded(root);
cout << "Traversing threaded tree :\n";
inOrder(root);
return 0;
}
Traversing threaded tree :
4 2 5 1 6 3 7
|
[
{
"code": null,
"e": 1193,
"s": 1062,
"text": "In this tutorial, we will be discussing a program to convert a binary tree to a threaded binary tree using a queue data structure."
},
{
"code": null,
"e": 1421,
"s": 1193,
"text": "For this, we will be provided with a binary tree. Our task is to convert that particular binary tree into a threaded binary tree by adding additional routes for quicker inorder traversal with the help of a queue data structure."
},
{
"code": null,
"e": 1432,
"s": 1421,
"text": " Live Demo"
},
{
"code": null,
"e": 3465,
"s": 1432,
"text": "#include <iostream>\n#include <queue>\nusing namespace std;\n//node structure for threaded tree\nstruct Node {\n int key;\n Node *left, *right;\n bool isThreaded;\n};\n//putting the inorder pattern into a queue\nvoid convert_queue(Node* root, std::queue<Node*>* q){\n if (root == NULL)\n return;\n if (root->left)\n convert_queue(root->left, q);\n q->push(root);\n if (root->right)\n convert_queue(root->right, q);\n}\n//traversing the queue and making threaded tree\nvoid create_threadedtree(Node* root, std::queue<Node*>* q){\n if (root == NULL)\n return;\n if (root->left)\n create_threadedtree(root->left, q);\n q->pop();\n if (root->right)\n create_threadedtree(root->right, q);\n //if right pointer in NUll, point it to\n //inorder successor\n else {\n root->right = q->front();\n root->isThreaded = true;\n }\n}\n//finally taking the tree and converting it into threaded\nvoid createThreaded(Node* root){\n std::queue<Node*> q;\n convert_queue(root, &q);\n create_threadedtree(root, &q);\n}\nNode* leftMost(Node* root){\n while (root != NULL && root->left != NULL)\n root = root->left;\n return root;\n }\n //performing inorder traversal of threaded tree\n void inOrder(Node* root){\n if (root == NULL)\n return;\n Node* cur = leftMost(root);\n while (cur != NULL) {\n cout << cur->key << \" \";\n //if threaded node, move to inorder successor\n if (cur->isThreaded)\n cur = cur->right;\n else\n cur = leftMost(cur->right);\n }\n }\n Node* newNode(int key){\n Node* temp = new Node;\n temp->left = temp->right = NULL;\n temp->key = key;\n return temp;\n}\nint main(){\n Node* root = newNode(1);\n root->left = newNode(2);\n root->right = newNode(3);\n root->left->left = newNode(4);\n root->left->right = newNode(5);\n root->right->left = newNode(6);\n root->right->right = newNode(7);\n createThreaded(root);\n cout << \"Traversing threaded tree :\\n\";\n inOrder(root);\n return 0;\n}"
},
{
"code": null,
"e": 3506,
"s": 3465,
"text": "Traversing threaded tree :\n4 2 5 1 6 3 7"
}
] |
Program for Identity Matrix in C
|
Given a square matrix M[r][c] where ‘r’ is some number of rows and ‘c’ are columns such that r = c, we have to check that ‘M’ is identity matrix or not.
Identity matrix is also known as Unit matrix of size nxn square matrix where diagonal elements will only have integer value one and non diagonal elements will only have integer value as 0
Like in the given Example below −
I1=[1],I2=[1001],I3=[100010001],In=[100...0010...0001...0..............000...1]
Input: m[3][3] = { {1, 0, 0},
{0, 1, 0},
{0, 0, 1}}
Output: yes
Input: m[3][3] == { {3, 0, 1},
{6, 2, 0},
{7, 5, 3} }
Output: no
Start
Step 1 -> declare function for finding identity matrix
int identity(int num)
declare int row, col
Loop For row = 0 and row < num and row++
Loop For col = 0 and col < num and col++
IF (row = col)
Print 1
Else
Print 0
End
End
Step 2 -> In main()
Declare int size = 4
Call identity(size)
Stop
#include<stdio.h>
int identity(int num){
int row, col;
for (row = 0; row < num; row++){
for (col = 0; col < num; col++){
if (row == col)
printf("%d ", 1);
else
printf("%d ", 0);
}
printf("\n");
}
return 0;
}
int main(){
int size = 4;
identity(size);
return 0;
}
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
|
[
{
"code": null,
"e": 1215,
"s": 1062,
"text": "Given a square matrix M[r][c] where ‘r’ is some number of rows and ‘c’ are columns such that r = c, we have to check that ‘M’ is identity matrix or not."
},
{
"code": null,
"e": 1403,
"s": 1215,
"text": "Identity matrix is also known as Unit matrix of size nxn square matrix where diagonal elements will only have integer value one and non diagonal elements will only have integer value as 0"
},
{
"code": null,
"e": 1437,
"s": 1403,
"text": "Like in the given Example below −"
},
{
"code": null,
"e": 1517,
"s": 1437,
"text": "I1=[1],I2=[1001],I3=[100010001],In=[100...0010...0001...0..............000...1]"
},
{
"code": null,
"e": 1658,
"s": 1517,
"text": "Input: m[3][3] = { {1, 0, 0},\n {0, 1, 0},\n {0, 0, 1}}\nOutput: yes\nInput: m[3][3] == { {3, 0, 1},\n {6, 2, 0},\n {7, 5, 3} }\nOutput: no"
},
{
"code": null,
"e": 2047,
"s": 1658,
"text": "Start\nStep 1 -> declare function for finding identity matrix\n int identity(int num)\n declare int row, col\n Loop For row = 0 and row < num and row++\n Loop For col = 0 and col < num and col++\n IF (row = col)\n Print 1\n Else\n Print 0\n End\n End\nStep 2 -> In main()\n Declare int size = 4\n Call identity(size)\nStop"
},
{
"code": null,
"e": 2390,
"s": 2047,
"text": "#include<stdio.h>\nint identity(int num){\n int row, col;\n for (row = 0; row < num; row++){\n for (col = 0; col < num; col++){\n if (row == col)\n printf(\"%d \", 1);\n else\n printf(\"%d \", 0);\n }\n printf(\"\\n\");\n }\n return 0;\n}\nint main(){\n int size = 4;\n identity(size);\n return 0;\n}"
},
{
"code": null,
"e": 2422,
"s": 2390,
"text": "1 0 0 0\n0 1 0 0\n0 0 1 0\n0 0 0 1"
}
] |
Array getInt() Method in Java - GeeksforGeeks
|
23 Jul, 2020
The java.lang.reflect.Array.getInt() is an inbuilt method in Java and is used to return an element at the given index from the specified Array as a int.
Syntax
Array.getInt(Object []array, int index)
Parameters: This method accepts two mandatory parameters:
array: The object array whose index is to be returned.
index: The particular index of the given array. The element at ‘index’ in the given array is returned.
Return Value: This method returns the element of the array as int.
Exceptions: This method throws following exceptions:
NullPointerException – when the array is null.
IllegalArgumentException – when the given object array is not an Array.
ArrayIndexOutOfBoundsException – if the given index is not in the range of the size of the array.
Note: Typecast isn’t necessary as the return type is int.
Below programs illustrate the get() method of Array class:
Program 1:
import java.lang.reflect.Array; public class GfG { // main method public static void main(String[] args) { // Declaring and defining an int array int a[] = { 1, 2, 3, 4, 5 }; // Traversing the array for (int i = 0; i < 5; i++) { // Array.getInt method int x = Array.getInt(a, i); // Printing the values System.out.print(x + " "); } }}
1 2 3 4 5
Program 2: To demonstrate ArrayIndexOutOfBoundsException
import java.lang.reflect.Array; public class GfG { // main method public static void main(String[] args) { // Declaring and defining an int array int a[] = { 1, 2, 3, 4, 5 }; try { // invalid index int x = Array.getInt(a, 6); System.out.println(x); } catch (Exception e) { // throws Exception System.out.println("Exception : " + e); } }}
Exception : java.lang.ArrayIndexOutOfBoundsException
Program 3: To demonstrate NullPointerException
import java.lang.reflect.Array; public class GfG { // main method public static void main(String[] args) { // Declaring an int array int a[]; // array to null a = null; try { // null Object array int x = Array.getInt(a, 6); System.out.println(x); } catch (Exception e) { // throws Exception System.out.println("Exception : " + e); } }}
Exception : java.lang.NullPointerException
Program 4: To demonstrate IllegalArgumentException
import java.lang.reflect.Array; public class GfG { // main method public static void main(String[] args) { // int (Not an array) int y = 0; try { // illegalArgument int x = Array.getInt(y, 6); System.out.println(x); } catch (Exception e) { // Throws exception System.out.println("Exception : " + e); } }}
Exception : java.lang.IllegalArgumentException: Argument is not an array
nidhi_biet
Java - util package
Java-Arrays
Java-Collections
Java-Functions
java-lang-reflect-package
java-reflection-array
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
ArrayList in Java
How to iterate any Map in Java
Multidimensional Arrays in Java
Stack Class in Java
Stream In Java
Singleton Class in Java
|
[
{
"code": null,
"e": 24930,
"s": 24902,
"text": "\n23 Jul, 2020"
},
{
"code": null,
"e": 25083,
"s": 24930,
"text": "The java.lang.reflect.Array.getInt() is an inbuilt method in Java and is used to return an element at the given index from the specified Array as a int."
},
{
"code": null,
"e": 25090,
"s": 25083,
"text": "Syntax"
},
{
"code": null,
"e": 25131,
"s": 25090,
"text": "Array.getInt(Object []array, int index)\n"
},
{
"code": null,
"e": 25189,
"s": 25131,
"text": "Parameters: This method accepts two mandatory parameters:"
},
{
"code": null,
"e": 25244,
"s": 25189,
"text": "array: The object array whose index is to be returned."
},
{
"code": null,
"e": 25347,
"s": 25244,
"text": "index: The particular index of the given array. The element at ‘index’ in the given array is returned."
},
{
"code": null,
"e": 25414,
"s": 25347,
"text": "Return Value: This method returns the element of the array as int."
},
{
"code": null,
"e": 25467,
"s": 25414,
"text": "Exceptions: This method throws following exceptions:"
},
{
"code": null,
"e": 25514,
"s": 25467,
"text": "NullPointerException – when the array is null."
},
{
"code": null,
"e": 25586,
"s": 25514,
"text": "IllegalArgumentException – when the given object array is not an Array."
},
{
"code": null,
"e": 25684,
"s": 25586,
"text": "ArrayIndexOutOfBoundsException – if the given index is not in the range of the size of the array."
},
{
"code": null,
"e": 25742,
"s": 25684,
"text": "Note: Typecast isn’t necessary as the return type is int."
},
{
"code": null,
"e": 25801,
"s": 25742,
"text": "Below programs illustrate the get() method of Array class:"
},
{
"code": null,
"e": 25812,
"s": 25801,
"text": "Program 1:"
},
{
"code": "import java.lang.reflect.Array; public class GfG { // main method public static void main(String[] args) { // Declaring and defining an int array int a[] = { 1, 2, 3, 4, 5 }; // Traversing the array for (int i = 0; i < 5; i++) { // Array.getInt method int x = Array.getInt(a, i); // Printing the values System.out.print(x + \" \"); } }}",
"e": 26245,
"s": 25812,
"text": null
},
{
"code": null,
"e": 26256,
"s": 26245,
"text": "1 2 3 4 5\n"
},
{
"code": null,
"e": 26313,
"s": 26256,
"text": "Program 2: To demonstrate ArrayIndexOutOfBoundsException"
},
{
"code": "import java.lang.reflect.Array; public class GfG { // main method public static void main(String[] args) { // Declaring and defining an int array int a[] = { 1, 2, 3, 4, 5 }; try { // invalid index int x = Array.getInt(a, 6); System.out.println(x); } catch (Exception e) { // throws Exception System.out.println(\"Exception : \" + e); } }}",
"e": 26765,
"s": 26313,
"text": null
},
{
"code": null,
"e": 26819,
"s": 26765,
"text": "Exception : java.lang.ArrayIndexOutOfBoundsException\n"
},
{
"code": null,
"e": 26866,
"s": 26819,
"text": "Program 3: To demonstrate NullPointerException"
},
{
"code": "import java.lang.reflect.Array; public class GfG { // main method public static void main(String[] args) { // Declaring an int array int a[]; // array to null a = null; try { // null Object array int x = Array.getInt(a, 6); System.out.println(x); } catch (Exception e) { // throws Exception System.out.println(\"Exception : \" + e); } }}",
"e": 27332,
"s": 26866,
"text": null
},
{
"code": null,
"e": 27376,
"s": 27332,
"text": "Exception : java.lang.NullPointerException\n"
},
{
"code": null,
"e": 27427,
"s": 27376,
"text": "Program 4: To demonstrate IllegalArgumentException"
},
{
"code": "import java.lang.reflect.Array; public class GfG { // main method public static void main(String[] args) { // int (Not an array) int y = 0; try { // illegalArgument int x = Array.getInt(y, 6); System.out.println(x); } catch (Exception e) { // Throws exception System.out.println(\"Exception : \" + e); } }}",
"e": 27846,
"s": 27427,
"text": null
},
{
"code": null,
"e": 27920,
"s": 27846,
"text": "Exception : java.lang.IllegalArgumentException: Argument is not an array\n"
},
{
"code": null,
"e": 27931,
"s": 27920,
"text": "nidhi_biet"
},
{
"code": null,
"e": 27951,
"s": 27931,
"text": "Java - util package"
},
{
"code": null,
"e": 27963,
"s": 27951,
"text": "Java-Arrays"
},
{
"code": null,
"e": 27980,
"s": 27963,
"text": "Java-Collections"
},
{
"code": null,
"e": 27995,
"s": 27980,
"text": "Java-Functions"
},
{
"code": null,
"e": 28021,
"s": 27995,
"text": "java-lang-reflect-package"
},
{
"code": null,
"e": 28043,
"s": 28021,
"text": "java-reflection-array"
},
{
"code": null,
"e": 28048,
"s": 28043,
"text": "Java"
},
{
"code": null,
"e": 28053,
"s": 28048,
"text": "Java"
},
{
"code": null,
"e": 28070,
"s": 28053,
"text": "Java-Collections"
},
{
"code": null,
"e": 28168,
"s": 28070,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28200,
"s": 28168,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 28251,
"s": 28200,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 28281,
"s": 28251,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 28300,
"s": 28281,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 28318,
"s": 28300,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 28349,
"s": 28318,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 28381,
"s": 28349,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 28401,
"s": 28381,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 28416,
"s": 28401,
"text": "Stream In Java"
}
] |
How to use Line chart graph in android?
|
This example demonstrate about How to use Line chart graph in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Open build.gradle(module level) and add library dependency.
apply plugin: 'com.android.application'
android {
packagingOptions {
exclude 'META-INF/proguard/androidx-annotations.pro'
}
packagingOptions {
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/LICENSE'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/license.txt'
exclude 'META-INF/NOTICE'
exclude 'META-INF/NOTICE.txt'
exclude 'META-INF/notice.txt'
exclude 'META-INF/ASL2.0'
}
compileSdkVersion 28
defaultConfig {
applicationId "com.example.andy.myapplication"
minSdkVersion 15
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0-alpha'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
Step 3 − Open build.gradle(application level) and add library dependency.
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.2.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
maven { url 'https://jitpack.io' }
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
Step 4 − 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">
<com.github.mikephil.charting.charts.LineChart
android:id = "@+id/lineChart"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent" />
</android.support.constraint.ConstraintLayout>
In the above code, we have taken Line Chart view to show Line chart
Step 4 − Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
LineChart lineChart;
LineData lineData;
LineDataSet lineDataSet;
ArrayList lineEntries;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lineChart = findViewById(R.id.lineChart);
getEntries();
lineDataSet = new LineDataSet(lineEntries, "");
lineData = new LineData(lineDataSet);
lineChart.setData(lineData);
lineDataSet.setColors(ColorTemplate.JOYFUL_COLORS);
lineDataSet.setValueTextColor(Color.BLACK);
lineDataSet.setValueTextSize(18f);
}
private void getEntries() {
lineEntries = new ArrayList<>();
lineEntries.add(new Entry(2f, 0));
lineEntries.add(new Entry(4f, 1));
lineEntries.add(new Entry(6f, 1));
lineEntries.add(new Entry(8f, 3));
lineEntries.add(new Entry(7f, 4));
lineEntries.add(new Entry(3f, 3));
}
}
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 is showing Line chart as per our data set values.
Click here to download the project code
|
[
{
"code": null,
"e": 1133,
"s": 1062,
"text": "This example demonstrate about How to use Line chart graph in android."
},
{
"code": null,
"e": 1262,
"s": 1133,
"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": 1331,
"s": 1262,
"text": "Step 2 − Open build.gradle(module level) and add library dependency."
},
{
"code": null,
"e": 2692,
"s": 1331,
"text": "apply plugin: 'com.android.application'\nandroid {\n packagingOptions {\n exclude 'META-INF/proguard/androidx-annotations.pro'\n }\n packagingOptions {\n exclude 'META-INF/DEPENDENCIES'\n exclude 'META-INF/LICENSE'\n exclude 'META-INF/LICENSE.txt'\n exclude 'META-INF/license.txt'\n exclude 'META-INF/NOTICE'\n exclude 'META-INF/NOTICE.txt'\n exclude 'META-INF/notice.txt'\n exclude 'META-INF/ASL2.0'\n }\n compileSdkVersion 28\n defaultConfig {\n applicationId \"com.example.andy.myapplication\"\n minSdkVersion 15\n targetSdkVersion 28\n versionCode 1\n versionName \"1.0\"\n testInstrumentationRunner \"android.support.test.runner.AndroidJUnitRunner\"\n }\n buildTypes {\n release {\n minifyEnabled false\n proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\n }\n }\n}\ndependencies {\n implementation fileTree(dir: 'libs', include: ['*.jar'])\n implementation 'com.android.support:appcompat-v7:28.0.0'\n implementation 'com.android.support.constraint:constraint-layout:1.1.3'\n implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0-alpha'\n testImplementation 'junit:junit:4.12'\n androidTestImplementation 'com.android.support.test:runner:1.0.2'\n androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'\n}"
},
{
"code": null,
"e": 2766,
"s": 2692,
"text": "Step 3 − Open build.gradle(application level) and add library dependency."
},
{
"code": null,
"e": 3314,
"s": 2766,
"text": "// Top-level build file where you can add configuration options common to all sub-projects/modules.\nbuildscript {\n repositories {\n google()\n jcenter()\n }\n dependencies {\n classpath 'com.android.tools.build:gradle:3.2.1'\n // NOTE: Do not place your application dependencies here; they belong\n // in the individual module build.gradle files\n }\n}\nallprojects {\n repositories {\n google()\n jcenter()\n maven { url 'https://jitpack.io' }\n }\n}\ntask clean(type: Delete) {\n delete rootProject.buildDir\n}"
},
{
"code": null,
"e": 3379,
"s": 3314,
"text": "Step 4 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 3979,
"s": 3379,
"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 <com.github.mikephil.charting.charts.LineChart\n android:id = \"@+id/lineChart\"\n android:layout_width = \"fill_parent\"\n android:layout_height = \"fill_parent\" />\n</android.support.constraint.ConstraintLayout>"
},
{
"code": null,
"e": 4047,
"s": 3979,
"text": "In the above code, we have taken Line Chart view to show Line chart"
},
{
"code": null,
"e": 4104,
"s": 4047,
"text": "Step 4 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 5531,
"s": 4104,
"text": "package com.example.andy.myapplication;\nimport android.graphics.Color;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport com.github.mikephil.charting.charts.LineChart;\nimport com.github.mikephil.charting.data.Entry;\nimport com.github.mikephil.charting.data.LineData;\nimport com.github.mikephil.charting.data.LineDataSet;\nimport com.github.mikephil.charting.utils.ColorTemplate;\nimport java.util.ArrayList;\npublic class MainActivity extends AppCompatActivity {\n LineChart lineChart;\n LineData lineData;\n LineDataSet lineDataSet;\n ArrayList lineEntries;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n lineChart = findViewById(R.id.lineChart);\n getEntries();\n lineDataSet = new LineDataSet(lineEntries, \"\");\n lineData = new LineData(lineDataSet);\n lineChart.setData(lineData);\n lineDataSet.setColors(ColorTemplate.JOYFUL_COLORS);\n lineDataSet.setValueTextColor(Color.BLACK);\n lineDataSet.setValueTextSize(18f);\n }\n private void getEntries() {\n lineEntries = new ArrayList<>();\n lineEntries.add(new Entry(2f, 0));\n lineEntries.add(new Entry(4f, 1));\n lineEntries.add(new Entry(6f, 1));\n lineEntries.add(new Entry(8f, 3));\n lineEntries.add(new Entry(7f, 4));\n lineEntries.add(new Entry(3f, 3));\n }\n}"
},
{
"code": null,
"e": 5878,
"s": 5531,
"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": 5952,
"s": 5878,
"text": "In the above result, it is showing Line chart as per our data set values."
},
{
"code": null,
"e": 5992,
"s": 5952,
"text": "Click here to download the project code"
}
] |
Step-by-Step Guide to Creating R and Python Libraries (in JupyterLab) | by Sean McClure | Towards Data Science
|
R and Python are the bread and butter of today’s machine learning languages. R provides powerful statistics and quick visualizations, while Python offers an intuitive syntax, abundant support, and is the choice interface to today’s major AI frameworks.
In this article we’ll look at the steps involved in creating libraries in R and Python. This is a skill every machine learning practitioner should have in their toolbox. Libraries help us organize our code and share it with others, offering packaged functionality to the data community.
NOTE: In this article I use the terms “library” and “package” interchangeably. While some people differentiate these words I don’t find this distinction useful, and rarely see it done in practice. We can think of a library (or package) as a directory of scripts containing functions. Those functions are grouped together to help engineers and scientists solve challenges.
Building today’s software doesn’t happen without extensive use of libraries. Libraries dramatically cut down the time and effort required for a team to bring work to production. By leveraging the open source community engineers and scientists can move their unique contribution towards a larger audience, and effectively improve the quality of their code. Companies of all sizes use these libraries to sit their work on top of existing functionality, making product development more productive and focused.
But creating libraries isn’t just for production software. Libraries are critical to rapidly prototyping ideas, helping teams validate hypotheses and craft experimental software quickly. While popular libraries enjoy massive community support and a set of best practices, smaller projects can be converted into libraries overnight.
By learning to create lighter-weight libraries we develop an ongoing habit of maintaining code and sharing our work. Our own development is sped up dramatically, and we anchor our coding efforts around a tangible unit of work we can improve over time.
In this article we will focus on creating libraries in R and Python as well as hosting them on, and installing from, GitHub. This means we won’t look at popular hosting sites like CRAN for R and PyPI for Python. These are extra steps that are beyond the scope of this article.
Focusing only on GitHub helps encourage practitioners to develop and share libraries more frequently. CRAN and PyPI have a number of criteria that must be met (and they change frequently), which can slow down the process of releasing our work. Rest assured, it is just as easy for others to install our libraries from GitHub. Also, the steps for CRAN and PyPI can always be added later should you feel your library would benefit from a hosting site.
We will build both R and Python libraries using the same environment (JupyterLab), with the same high-level steps for both languages. This should help you build a working knowledge of the core steps required to package your code as a library.
Let’s get started.
We will be creating a library called datapeek in both R and Python. The datapeek library is a simple package offering a few useful functions for handling raw data. These functions are:
encode_and_bind
remove_features
apply_function_to_column
get_closest_string
We will look at these functions later. For now we need to setup an R and Python environment to create datapeek, along with a few libraries to support packaging our code. We will be using JupyterLab inside a Docker container, along with a “docker stack” that comes with the pieces we need.
The Docker Stack we will use is called the jupyter/datascience-notebook. This image contains both R and Python environments, along with many of the packages typically used in machine learning.
Since these run inside Docker you must have Docker installed on your machine. So install Docker if you don’t already have it, and once installed, run the following in terminal to pull the datascience-notebook:
docker pull jupyter/datascience-notebook
This will pull the most recent image hosted on Docker Hub.
NOTE: Anytime you pull a project from Docker Hub you get the latest build. If some time passes since your last pull, pull again to update your image.
Immediately after running the above command you should see the following:
Once everything has been pulled we can confirm our new image exists by running the following:
docker images
... showing something similar to the following:
Now that we have our Docker stack let’s setup JupyterLab.
We will create our libraries inside a JupyterLab environment. JupyterLab is a web-based user interface for programming. With JupyterLab we have a lightweight IDE in the browser, making it convenient for building quick applications. JupyterLab provides everything we need to create libraries in R and Python, including:
A terminal environment for running shell commands and downloading/installing libraries;
An R and Python console for working interactively with these languages;
A simple text editor for creating files with various extensions;
Jupyter Notebooks for prototyping ML work.
The datascience-notebook we just pulled contains an installation of JupyterLab so we don’t need to install this separately. Before running our Docker image we need to mount a volume to ensure our work is saved outside the container.
First, create a folder called datapeek on your desktop (or anywhere you wish) and change into that directory. We need to run our Docker container with JupyterLab, so our full command should look as follows:
docker run -it -v `pwd`:/home/jovyan/work -p 8888:8888 jupyter/datascience-notebook start.sh jupyter lab
You can learn more about Docker commands here. Importantly, the above command exposes our environment on port 8888, meaning we can access our container through the browser.
After running the above command you should see the following output at the end:
This tells us to copy and paste the provided URL into our browser. Open your browser and add the link in the address bar and hit enter (your token will be different):
localhost:8888/?token=11e5027e9f7cacebac465d79c9548978b03aaf53131ce5fd
This will automatically open JupyterLab in your browser as a new tab:
We are now ready to start building libraries.
We begin this article with R, then look at Python.
R is one of the “big 2” languages of machine learning. At the time of this writing it has well-over 10,000 libraries. Going to Available CRAN Packages By Date of Publication and running...
document.getElementsByTagName('tr').length
...in the browser console gives me 13858. Minus the header and final row this gives 13856 packages. Needless to say R is not in need of variety. With strong community support and a concise (if not intuitive) language, R sits comfortably at the top of statistical languages worth learning.
The most well-known treatise on creating R packages is Hadley Wickam’s book R Packages. Its contents are available for free online. For a deeper dive on topic I recommend looking there.
We will use Hadley’s devtools package to abstract away the tedious tasks involved in creating packages. devtools is already installed in our Docker Stacks environment. We also require the roxygen2 package, which helps us document our functions. Since this doesn’t come pre-installed with our image let’s install that now.
NOTE: From now on we’ll use the terminal in JupyterLab in order to conveniently keep our work within the browser.
Open terminal inside JupyterLab’s Launcher:
NOTE: If you’d like to change your JupyterLab to dark theme, click on Settings at the top, JupyterLab Theme, then JupyterLab Dark:
Inside the console type R, then....
install.packages("roxygen2")library(roxygen2)
With the necessary packages installed we’re ready to tackle each step.
We need to create a directory for our package. We can do this in one line of code, using the devtools create function. In terminal run:
devtools::create("datapeek")
This automatically creates the bare bone files and directories needed to define our R package. In JupyterLab you will see a set of new folders and files created on the left side.
NOTE: You will also see your new directory structure created on your desktop (or wherever you chose to create it) since we mounted a volume to our container during setup.
If we inspect our package in JupyterLab we now see:
datapeek├── R├── datapeek.Rproj├── DESCRIPTION├── NAMESPACE
The R folder will eventually contain our R code. The my_package.Rproj file is specific to the RStudio IDE so we can ignore that. The DESCRIPTION folder holds our package’s metadata (a detailed discussion can be found here). Finally, NAMSPACE is a file that ensures our library plays nicely with others, and is more of a CRAN requirement.
We must follow these rules when naming an R package:
must be unique on CRAN (you can check all current R libraries here);
can only consist of letters, numbers and periods;
cannot contain an underscore or hyphen;
must start with a letter;
cannot end in a period;
You can read more about naming packages here. Our package name “datapeek” passes the above criteria. Let’s head over to CRAN and do a Command+F search for “datapeek” to ensure it’s not already taken:
...looks like we’re good.
The job of the DESCRIPTION file is to store important metadata about our package. These data include others packages required to run our library, our license, and our contact information. Technically, the definition of a package in R is any directory containing a DESCRIPTION file, so always ensure this is present.
Click on the DESCRIPTION file in JupyterLab’s directory listing. You will see the basic details created automatically when we ran devtools::create(“datapeek”) :
Let’s add our specific details so our package contains the necessary metadata. Simply edit this file inside JupyterLab. Here are the details I am adding:
Package: datapeek
Title: Provides useful functions for working with raw data.
Version: 0.0.0.1
Authors@R: person(“Sean”, “McClure”, email=”sean.mcclure@example.com”, role=c('aut','cre'))
Description: The datapeek package helps users transform raw data for machine learning development.
Depends: R (≥ 3.5.1)
License: MIT
Encoding: UTF-8
LazyData: true
Of course you should fill out these parts with your own details. You can read more about the definitions of each of these in Hadley’s chapter on metadata. As a brief overview...the package, title, and version parts are self-explanatory, just be sure to keep title to one line. Authors@R must adhere to the format you see above, since it contains executable R code. Note the role argument, which allows us to list the main contributors of our library. The usual ones are:
aut: author
cre: creator or maintainer
ctb: contributors
cph: copyright holder
There are many more options, with the full list found here.
You can add multiple authors by listing them as a vector:
Authors@R: as.person(c( "Sean McClure <sean.mcclure@example.com> [aut, cre]", "Rick Deckard <rick.deckard@example.com> [aut]", "Rachael Tyrell <rachel.tyrell@example.com> [ctb]"))
NOTE: If you do plan on hosting your library on CRAN be sure your email address is correct, as CRAN will use this to contact you.
The description can be multiple lines, limited to 1 paragraph. We use depends to specify the minimum version of R our package depends on. You should use an R version equal or greater than the one you used to build your library. Most people today set their License to MIT, which permits anyone to “use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software” as long as your copyright is included. You can learn more about the MIT license here. Encoding ensures our library can be opened, read and saved using modern parsers, and LazyData refers to how data in our package are loaded. Since we set ours to true it means our data won’t occupy memory until they are used.
Our library wouldn’t do much without functions. Let’s add the 4 functions mentioned in the beginning of this article. The following GIST shows our datapeek functions in R:
We have to add our functions to the R folder, since this is where R looks for any functions inside a library.
datapeek├── R├── datapeek.Rproj├── DESCRIPTION├── NAMESPACE
Since our library only contains 4 functions we will place all of them into a single file called utilities.R, with this file residing inside the R folder.
Go into the directory in JupyterLab and open the R folder. Click on Text File in the Launcher and paste in our 4 R functions. Right-click the file and rename it to utilities.R.
It isn’t enough to simply place R functions in our file. Each function must be exported to expose them to users of our library. This is accomplished by adding the @export tag above each function.
The export syntax comes from Roxygen, and ensures our function gets added to the NAMESPACE. Let’s add the @export tag to our first function:
Do this for the remaining functions as well.
NOTE: In larger libraries we would only export functions that need to be usable outside our package. This helps reduce the chances of a conflict with another library.
It is important to document our functions. Documenting functions provides information for users, such that when they type ?datapeek they get details about our package. Documenting also supports working with vignettes, which are a long-form type of documentation. You can read more about documenting functions here.
There are 2 sub-steps we will take:
add the document annotations
run devtools::document()
— Add the Document Annotations
Documentation is added above our function, directly above our #’ @export line. Here’s the example with our first function:
We space out the lines for readability, adding a title, description, and any parameters used by the function. Let’s do this for our remaining functions:
— Run devtools::document()
With documentation added to our functions we then run the following in terminal, just outside the root directory:
devtools::document()
NOTE: Make sure you’re one level outside the datapeek directory.
You may get the error:
Error: ‘roxygen2’ >= 5.0.0 must be installed for this functionality.
In this case open terminal in JupyterLab and install roxygen2. You should also install data.table and mltools, since our first function uses these:
install.packages('roxygen2')install.packages('data.table')install.packages('mltools')
Run the devtools::document() again. You should see the following:
This will generate .Rd files inside a new man folder. You’ll notice an .Rd file is created for each function in our package.
If you look at your DESCRIPTION file it will now show a new line at the bottom:
This will also generate a NAMESPACE file:
We can see our 4 functions have been exposed. Let’s now move onto ensuring dependencies are specified inside our library.
It is common for our functions to require functions found in other libraries. There are 2 things we must do to ensure external functionality is made available to our library’s functions:
Use double colons inside our functions to specify which library we are relying on;Add imports to our DESCRIPTION file.
Use double colons inside our functions to specify which library we are relying on;
Add imports to our DESCRIPTION file.
You’ll notice in the above GIST we simply listed our libraries at the top. While this works well in stand-alone R scripts it isn’t the way to use dependencies in an R package. When creating R packages we must use the “double-colon approach” to ensure the correct function is read. This is related to how “top-level code” (code that isn’t an object like a function) in an R package is only executed when the package is built, not when it’s loaded.
For example:
library(mltools)do_something_cool_with_mltools <- function() { auc_roc(preds, actuals)}
...won’t work because auc_roc will not be available (running library(datapeek) doesn’t re-execute library(mltools)). This will work:
do_something_cool_with_mltools <- function() { mltools::auc_roc(preds, actuals)}
The only function in our datapeek package requiring additional packages is our first one:
Notice each time we call an external function we preface it with the external library and double colons.
We must also list external dependencies in our DESCRIPTION file, so they are handled correctly. Let’s add our imports to the DESCRIPTION file:
Be sure to have the imported libraries comma-separated. Notice we didn’t specify any versions for our external dependencies. If we need to specify versions we can use parentheses after the package name:
Imports: data.table (>= 1.12.0)
Since our encode_and_bind function isn’t taking advantage of any bleeding-edge updates we will leave it without any version specified.
Sometimes it makes sense to include data inside our library. Package data can allow our user’s to practice with our library’s functions, and also helps with testing, since machine learning packages will always contain functions that ingest and transform data. The 4 options for adding external data to an R package are:
binary dataparsed dataraw dataserialized data
binary data
parsed data
raw data
serialized data
You can learn more about these different approaches here. For this article we will stick with the most common approach, which is to add external data to an R folder.
Let’s add the Iris dataset to our library in order to provide users a quick way to test our functions. The data must be in the .rda format, created using R’s save() function, and have the same name as the file. We can ensure these criteria are satisfied by using devtools’ use_data function:
x <- read.csv("http://bit.ly/2HuTS0Z")devtools::use_data(x, iris)
Above, I read in the Iris dataset from its URL and pass the data frame to devtools::use_data().
In JupyterLab we see a new data folder has been created, along with our iris.rda dataset:
datapeek├── data └── iris.rda├── man├── R├── datapeek.Rproj├── DESCRIPTION├── NAMESPACE
We will use our added dataset to run tests in the following section.
Testing is an important part of software development. Testing helps ensure our code works as expected, and makes debugging our code a much faster and more effective process. Learn more about testing R packages here.
A common challenge in testing is knowing what we should test. Testing every function in a large library is cumbersome and not always needed, while not enough testing can make it harder to find and correct bugs when they arise.
I like the following quote from Martin Fowler regarding when to test:
“Whenever you are tempted to type something into a print statement or a debugger expression, write it as a test instead.” — Martin Fowler
If you prototype applications regularly you’ll find yourself writing to the console frequently to see if a piece of code returns what you expect. In data science, writing interactive code is even more common, since machine learning work is highly experimental. On one hand this provides ample opportunity to think about which tests to write. On the other hand, the non-deterministic nature of machine learning code means testing certain aspect of ML can be less than straightforward. As a general rule, look for obvious deterministic pieces of your code that should return the same output every time.
The interactive testing we do in data science is manual, but what we are looking for in our packages is automated testing. Automated testing means we run a suite of pre-defined tests to ensure our package works end-to-end.
While there are many kinds of tests in software, here we are taking about “unit tests.” Thinking in terms of unit tests forces us to break up our code into more modular components, which is good practice in software design.
NOTE: If you are used to testing in languages like Python, notice that R is more functional in nature (i.e., methods belong to functions not classes), so there will be some differences.
There are 2 sub-steps we will take for testing our R library:
6A: Creating the tests/testthat folder;
6B: Writing tests.
— 6A: Creating the tests/testthat folder
Just as R expects our R scripts and data to be in specific folders it also expects the same for our tests. To create the tests folder, we run the following in JupyterLab’s R console:
devtools::use_testthat()
You may get the following error:
Error: ‘testthat’ >= 1.0.2 must be installed for this functionality.
If so, use the same approach above for installing roxygen2 in Jupyter’s terminal.
install.packages('testthat')
Running devtools::use_testthat() will produce the following output:
* Adding testthat to Suggests* Creating `tests/testthat`.* Creating `tests/testthat.R` from template.
There will now be a new tests folder in our main directory:
datapeek├── data├── man├── R├── tests └── testthat.R├── datapeek.Rproj├── DESCRIPTION├── NAMESPACE
The above command also created a file called testthat.R inside the tests folder. This runs all your tests when R CMD check runs (we’ll look at that shortly). You’ll also notice testthat has been added under Suggests in our DESCRIPTION file:
— 6B: Writing Tests
testthat is the most popular unit testing package for R, used by at least 2,600 CRAN package, not to mention libraries on Github. You can check out the latest news regarding testthat on the Tidyverse page here. Also check out its documentation.
There are 3 levels to testing we need to consider:
expectation (assertion): the expected result of a computation;
test: groups together multiple expectations from a single function, or related functionality from across multiple functions;
file: groups together multiple related tests. Files are given a human readable name with context().
Assertions are the functions included in the testing library we choose. We use assertions to check whether our own functions return the expected output. Assertions come in many flavors, depending on what is being checked. In the following section I will cover the main tests used in R programming, showing each one failing so you can understand how it works.
Equality Assertions
expect_equal()
expect_identical()
expect_equivalent
# test for equalitya <- 10expect_equal(a, 14)> Error: `a` not equal to 14.# test for identical expect_identical(42, 2)> Error: 42 not identical to 2.# test for equivalence expect_equivalent(10, 12)> Error: 10 not equivalent to 12.
There are subtle differences between the examples above. For example, expect_equal is used to check for equality within a numerical tolerance, while expect_identical tests for exact equivalence. Here are examples:
expect_equal(10, 10 + 1e-7) # trueexpect_identical(10, 10 + 1e-7) # false
As you write more tests you’ll understand when to use each one. Of course always refer to the documentation referenced above when in doubt.
Testing for String Matches
expect_match()
# test for string matchingexpect_match("Machine Learning is Fun", "But also rewarding.")> Error: "Machine Learning is Fun" does not match "But also rewarding.".
Testing for Length
expect_length
# test for length vec <- 1:10expect_length(vec, 12)> Error: `vec` has length 10, not length 12.
Testing for Comparison
expect_lt
expect_gt
# test for less thana <- 11expect_lt(a, 10)> Error: `a` is not strictly less than 10. Difference: 1# test for greater thana <- 11expect_gt(a, 12)> Error: `a` is not strictly more than 12. Difference: -1
Testing for Logic
expect_true
expect_false
# test for truth expect_true(5 == 2)> Error: 5 == 2 isn't true.# test for false expect_false(2 == 2)> Error: 2 == 2 isn't false.
Testing for Outputs
expect_output
expect_message
# testing for outputs expect_output(str(mtcars), "31 obs")> Error: `str\(mtcars\)` does not match "31 obs".# test for warning f <-function(x) { if(x < 0) { message("*x* is already negative") }}expect_message(f(1))> Error: `f(1)` did not produce any messages.
There are many more included in the testthat library. If you are new to testing, start writing a few simple ones to get used to the process. With time you’ll build an intuition around what to test and when.
A test is a group of assertions. We write tests in testthat as follows:
test_that("this functionality does what it should", { // group of assertions here})
We can see we have both a description (the test name) and the code (containing the assertions). The description completes the sentence, “test that ....”
Above, we are saying “test that this functionality does what it should.”
The assertions are the outputs we wish to test. For example:
test_that("trigonometric functions match identities", { expect_equal(sin(pi / 4), 1 / sqrt(2)) expect_equal(cos(pi / 4), 1 / sqrt(10)) expect_equal(tan(pi / 4), 1) })> Error: Test failed: 'trigonometric functions match identities'
NOTE: It is worth considering the balance between cohesion and coupling with our test files. As stated in Hadley’s book, “the two extremes are clearly bad (all tests in one file, one file per test). You need to find a happy medium that works for you. A good starting place is to have one file of tests for each complicated function.”
The last thing we do in testing is create files. As stated above, a“file” in testing is a group of tests covering a related set of functionality. Our test file must live inside thetests/testthat/ directory. Here is an example test file for the stringr package on GitHub:
The file is called test-case.R (starts with “test”) and lives inside the tests/testthat/ directory. The context at the top simply allows us to provide a simple description of the file’s contents. This appears in the console when we run our tests.
Let’s create our test file, which will contain tests and assertions related to our 4 functions. As usual, we use JupyterLab’s Text File in Launcher to create and rename a new file:
Now let’s add our tests:
For the first function I am going to make sure a data frame with the correct number of features is returned:
Notice how we called our encode_and_bind function, then simply checked the equality between the dimensions and the expected output. We run our automated tests at any point to ensure our test file runs and we get the expected output. Running devtools::test() in the console runs our tests:
We get a smiley face too!
Since our second function removes a specified feature I will use the same test as above, checking for the dimensions of the returned frame. Our third function applies a specified function to a chosen column, so I will write a test that checks the result of given specified function. Finally, our fourth function returns the closest matching string, so I will simply check the returned string for the expected result.
Here is our full test file:
NOTE: Notice the relative path to the data in the test file.
As we did above, we run our tests using the following command:
devtools::test()
This will run all tests in any test files we placed inside the testthat directory. Let’s check the result:
We had 5 assertions across 4 unit tests, placed in one test file. Looks like we’re good. If any of our tests failed we would see this in the above printout, at which point we would look to correct the issue.
This has traditionally been done using “Vignettes” in R. You can learn about creating R vignettes for your R package here. Personally, I find this a dated approach to documentation. I prefer to use things like Sphinx or Julep. Documentation should be easily shared, searchable and hosted.
Click on the question mark at julepcode.com to learn how to use Julep.
I created and hosted some simple documentation for our R datapeek library, which you can find here.
Of course we will also have the library on GitHub, which I cover below.
As I mentioned in the introduction we should be creating libraries on a regular basis, so others can benefit from and extend our work. The best way to do this is through GitHub, which is the standard way to distribute and collaborate on open source software projects.
In case you’re new to GitHub here’s a quick tutorial to get you started so we can push our datapeek project to a remote repo.
Sign up/in to GitHub and create a new repository.
...which will provide us with the usual screen:
With our remote repo setup we can initialize our local repo on our machine, and send our first commit.
Open Terminal in JupyterLab and change into the datapeek directory:
Initialize the local repo:
git init
Add the remote origin (your link will be different):
git remote add origin https://github.com/sean-mcclure/datapeek.git
Now run git add . to add all modified and new (untracked) files in the current directory and all subdirectories to the staging area:
git add .
Don’t forget the “dot” in the above command. Now we can commit our changes, which adds any new code to our local repo.
But, since we are working inside a Docker container the username and email associated with our local repo cannot be autodetected. We can set these by running the following in terminal:
git config --global user.email {emailaddress}git config --global user.name {name}
Use the email address and username you use to sign into GitHub.
Now we can commit:
git commit -m 'initial commit'
With our new code committed we can do our push, which transfers the last commit(s) to our remote repo:
git push origin master
NOTE: Since we are in Docker you’ll likely get asked again for authentication. Simply add your GitHub username and password when prompted. Then run the above command again.
Some readers will notice we didn’t place a .gitignore file in our directory. It is usually fine to push all files inside smaller R libraries. For larger libraries, or libraries containing large datasets, you can use the site gitignore.io to see what common gitignore files look like. Here is a common R .gitignore file for R:
To recap, git add adds all modified and new (untracked) files in the current directory to the staging area. Commit adds any changes to our local repo, and push transfers the last commit(s) to our remote repo. While git add might seem superfluous, the reason it exists is because sometimes we want to only commit certain files, this we can stage files selectively. Above, we staged all files by using the “dot” after git add.
You may also notice we didn’t include a README file. You should indeed include this, however for the sake of brevity I have left this step out.
Now, anyone can use our library. 👍 Let’s see how.
As mentioned in the introduction I will not be discussing CRAN in this article. Sticking with GitHub make it easier to share our code frequently, and we can always add CRAN criteria later.
To install a library from GitHub, users can simply run the following command on their local machine:
devtools::install_github("yourusername/mypackage")
As such, we can simply instruct others wishing to use datapeek to run the following command on their local machine:
devtools::install_github("sean-mcclure/datapeek")
This is something we would include in a README file and/or any other documentation we create. This will install our package like any other package we get from CRAN:
Users then load the library as usual and they’re good to go:
library(datapeek)
I recommend trying the above commands in a new R environment to confirm the installation and loading of your new library works as expected.
Creating Python libraries follows the same high-level steps we saw previously for R. We require a basic directory structure with proper naming conventions, functions with descriptions, imports, specified dependencies, added datasets, documentation, and the ability to share and allow others to install our library.
We will use JupyterLab to build our Python library, just as we did for R.
In the beginning of this article I discussed the difference between a “library” and a “package”, and how I prefer to use these terms interchangeably. The same holds for Python libraries. “Modules” are another term, and in Python simply refer to any file containing Python code. Python libraries obviously contain modules as scripts.
I stated in the introduction that we will host and install our libraries on and from GitHub. This encourages rapid creation and sharing of libraries without getting bogged down by publishing criteria on popular package hosting sites for R and Python.
The most popular hosting site for Python is the Python Package Index (PyPI). This is a place for finding, installing and publishing python libraries. Whenever you run pip install <package_name> (or easy_intall) you are fetching a package from PyPI.
While we won’t cover hosting our package on PyPI it’s still a good idea to see if our library name is unique. This will minimize confusion with other popular Python libraries and improve the odds our library name is distinctive, should we decide to someday host it on PyPI.
First, we should follow a few naming conventions for Python libraries.
Use all lowercase;
Make the name unique on PyPI (search for name on PyPI)
No hyphens (you can use underscore to separate words)
Our library name is datapeek, so the first and third criteria are met; let’s check PyPI for uniqueness:
All good. 👍
We’re now ready to move through each step required to create a Python library.
JupyterLab should be up-and-running as per the instructions in the setup section of this article.
Use JupyterLab’s New Folder and Text File options to create the following directory structure and files:
datapeek├── datapeek └── __init__.py └── utilities.py├── setup.py
NOTE: Bold names are folders and light names are files. We will refer to the inner datapeek folder as the “module directory” and the outer datapeek directory as the “root directory.”
The following video shows me creating our datapeek directory in JupyterLab:
There will be files we do not want to commit to source control. These are files that are created by the Python build system. As such, let’s also add the following .gitignore file to our package framework:
NOTE: At the time of this writing JupyterLab lacks a front-end setting to toggle hidden files in the browser. As such, we will simply name our file gitignore (no preceding dot); we will change it to a hidden file later prior to pushing to GitHub.
Add your gitignore file as a simple text file to the root directory:
datapeek├── datapeek └── __init__.py └── utilities.py├── setup.py├── gitignore
Just as we did for R, we should add metadata about our new library. We do this using Setuptools. Setuptools is a Python library designed to facilitate packaging Python projects.
Open setup.py and add the following details for our library:
Of course you should change the authoring to your own. We will add more details to this file later. The keywords are fairly self-explanatory. url is the URL of our project on GitHub, which we will add later; unless you’ve already created your python repo, in which case add the URL now. We talked about licensing in the R section. zip_safe simply means our package can be run safely as a zip file which will usually be the case. You can learn more about what can be added to the setup.py file here.
Our library obviously requires functions to be useful. For larger libraries we would organize our modules so as to balance cohesion/coupling, but since our library is small we will simply keep all functions inside a single file.
We will add the same functions we did for R, this time written in Python:
Add these functions to the utilities.py module, inside datapeek’s module directory.
Our library will often require other packages as dependencies. Our user’s Python environment will need to be aware of these when installing our library (so these other packages can also be installed). Setuptools provides the install_requires keyword to list any packages our library depends on.
Our datapeek library depends on the fuzzywuzzy package for fuzzy string matching, and the pandas package for high-performance manipulation of data structures. To specify our dependencies, add the following to your setup.py file:
install_requires=[ 'fuzzywuzzy', 'pandas']
Your setup.py file should currently look as follows:
We can confirm all is in order by running the following in a JupyterLab terminal session:
python setup.py develop
NOTE: Run this in datapeek’s root directory.
After running the command you should see something like this:
...with an ending that reads:
Finished processing dependencies for datapeek==0.1
If one or more of our dependencies is not available on PyPI, but is available on GitHub (e.g. a bleeding-edge machine learning package is only available on Github...or it’s another one of our team’s libraries hosted only on GitHub), we can use dependency_links inside our setup call:
setup( ... dependency_links=['http://github.com/user/repo/tarball/master#egg=package-1.0'], ...)
If you want to add additional metadata, such as status, licensing, language version, etc. we can use classifiers like this:
setup( ... classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', 'Topic :: Text Processing :: Linguistic', ], ...)
To learn more about the different classifiers that can be added to our setup.py file see here.
Just as we did above in R we can add data to our Python library. In Python these are called Non-Code Files and can include things like images, data, documentation, etc.
We add data to our library’s module directory, so that any code that requires those data can use a relative path from the consuming module’s __file__ variable.
Let’s add the Iris dataset to our library in order to provide users a quick way to test our functions. First, use the New Folder button in JupyterLab to create a new folder called data inside the module directory:
datapeek├── datapeek └── __init__.py └── utilities.py └── data├── setup.py├── gitignore
...then make a new Text File inside the data folder called iris.csv, and paste the data from here into the new file.
If you close and open the new csv file it will render inside JupyterLab as a proper table:
We specify Non-Code Files using a MANIFEST.in file. Create another Text File called MANIFEST.in placing it inside your root folder:
datapeek├── datapeek └── __init__.py └── utilities.py └── data├── MANIFEST.in├── setup.py├── gitignore
...and add this line to the file:
include datapeek/data/iris.csv
NOTE: The MANIFEST.in is often not needed, but included in this tutorial for completeness. See here for more discussion.
We also need to include the following line in setup.py:
include_package_data=True
Our setup.py file should now look like this:
As with our R library we should add tests so others can extend our library and ensure their own functions do not conflict with existing code. Add a test folder to our library’s module directory:
datapeek├── datapeek └── __init__.py └── utilities.py └── data └── tests├── MANIFEST.in├── setup.py├── gitignore
Our test folder should have its own __init__.py file as well as the test file itself. Create those now using JupyterLab’s Text File option:
datapeek├── datapeek └── __init__.py └── utilities.py └── data └── tests └──__init__.py └──datapeek_tests.py├── MANIFEST.in├── setup.py├── gitignore
Our datapeek directory structure is now set to house test functions, which we will write now.
Writing tests in Python is similar to doing so in R. Assertions are used to check the expected outputs produced by our library’s functions. We can use these “unit tests” to check a variety of expected outputs depending on what might be expected to fail. For example, we might want to ensure a data frame is returned, or perhaps the correct number of columns after some known transformation.
I will add a simple test for each of our 4 functions. Feel free to add your own tests. Think about what should be checked, and keep in mind Martin Fowler’s quote shown in the R section of this article.
We will use unittest, a popular unit testing framework in Python.
Add unit tests to the datapeek_tests.py file, ensuring the unittest and datapeek libraries are imported:
To run these tests we can use Nose, which extends unittest to make testing easier. Install nose using a terminal session in JupyterLab:
$ pip install nose
We also need to add the following lines to setup.py:
setup( ... test_suite='nose.collector', tests_require=['nose'],)
Our setup.py should now look like this:
Run the following from the root directory to run our tests:
python setup.py test
Setuptools will take care of installing nose if required and running the test suite. After running the above, you should see the following:
All our tests have passed!
If any test should fail, the unittest framework will show which functions did not pass. At this point, check to ensure you are calling the function correctly and that the output is indeed what you expected. It can also be good practice to purposely write tests to fail first, then write your functions until they pass.
As I mentioned in the R section, I use Julep to rapidly create sharable and searchable documentation. This avoids writing cryptic annotations and provides the ability to immediately host our documentation. Of course this doesn’t come with the IDE hooks that other documentation does, but for rapidly communicating it works.
You can find the documentation I create for this library here.
The standard approach for sharing python libraries is through PyPI. Just as we didn’t cover CRAN with R, we will not cover hosting our library on PyPI. While the requirements are fewer than those associated with CRAN there are still a number of steps that must be taken to successfully host on PyPI. The steps required to host on sites other than GitHub can always be added later.
We covered the steps for adding a project to GitHub in the R section. The same steps apply here.
I mentioned above the need to rename our gitignore file to make it a hidden file. You can do that by running the following in terminal:
mv gitignore .gitignore
You’ll notice this file is no longer visible in our JupyterLab directory (it eventually disappears). Since JupyterLab still lacks a front-end setting to toggle hidden files simply run the following in terminal at anytime to see hidden files:
ls -a
We can make it visible again should we need to view/edit the file in JupyterLab, by running:
mv .gitignore gitignore
Here is a quick recap on pushing our library to GitHub (change git URL to your own):
Create a new repo on GitHub called datapeek_py
Initialize your library’s directory using git init
Configure your local repo with your GitGub email and username (if using Docker) using:
git config --global user.email {emailaddress}git config --global user.name {name}
Add your new remote origin using git remote add origin https://github.com/sean-mcclure/datapeek_py.git
Stage your library using git add .
Commit all files using git commit -m ‘initial commit’
Push your library to the remote repo using git push origin master (authenticate when prompted)
Now, anyone can use our python library. 👍 Let’s see how.
While we usually install Python libraries using the following command:
pip install <package_name>
... this requires hosting our library on PyPI, which as explained above is beyond the scope of this article. Instead we will learn how to install our Python libraries from GitHub, as we did for R. This approach still requires the pip install command but uses the GitHub URL instead of the package name.
With our library hosted on GitHub, we simply use pip install git+ followed by the URL provided on our GitHub repo (available by clicking the Clone or Download button on the GitHub website):
pip install git+https://github.com/sean-mcclure/datapeek_py
Now, we can import our library into our Python environment. For a single function:
from datapeek.utilities import encode_and_bind
...and for all functions:
from datapeek.utilities import *
Let’s do a quick check in a new Python environment to ensure our functions are available. Spinning up a new Docker container, I run the following:
Fetch a dataset:
iris = pd.read_csv('https://raw.githubusercontent.com/uiuc-cse/data-fa14/gh-pages/data/iris.csv')
Check functions:
encode_and_bind(iris, 'species')
remove_features(iris, ['petal_length', 'petal_width'])
apply_function_to_column(iris, ['sepal_length'], 'times_4', 'x*4')
get_closest_string(['hey there','we we are','howdy doody'], 'doody')
Success!
In this article we looked at how to create both R and Python libraries using JupyterLab running inside a Docker container. Docker allowed us to leverage Docker Stacks such that our environment was easily controlled and common packages available. This also made it easy to use the same high-level interface to create libraries through the browser for 2 different languages. All files were written to our local machine since we mounted a volume inside Docker.
Creating libraries is a critical skill for any machine learning practitioner, and something I encourage others to do regularly. Libraries help isolate our work inside useful abstractions, improves reproducibility, makes our work shareable, and is the first step towards designing better software. Using a lightweight approach ensures we can prototype and share quickly, with the option to add more detailed practices and publishing criteria later as needed.
As always, please ask questions in the comments section should you run into issues. Happy coding.
If you enjoyed this article you might also enjoy:
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
R Packages by Hadley Wickham
Testing by Hadley Wickham
Python Packaging by Scott Torborg
Jupyter Data Science Notebook
Docker — Orientation and Setup
JupyterLab Documentation
Available CRAN Packages By Date of Publication
Documenting Functions in R
Julep
gitignore.io
The Python Package Index
Setuptools Documentation
Iris Dataset on GitHub
Unit Tests — Wikipedia Article
unitest — A Unit Testing Framework
Nose — Nicer Testing for Python
Test-Driven Development — Article on Wikipedia
Docker Run Reference
|
[
{
"code": null,
"e": 425,
"s": 172,
"text": "R and Python are the bread and butter of today’s machine learning languages. R provides powerful statistics and quick visualizations, while Python offers an intuitive syntax, abundant support, and is the choice interface to today’s major AI frameworks."
},
{
"code": null,
"e": 712,
"s": 425,
"text": "In this article we’ll look at the steps involved in creating libraries in R and Python. This is a skill every machine learning practitioner should have in their toolbox. Libraries help us organize our code and share it with others, offering packaged functionality to the data community."
},
{
"code": null,
"e": 1084,
"s": 712,
"text": "NOTE: In this article I use the terms “library” and “package” interchangeably. While some people differentiate these words I don’t find this distinction useful, and rarely see it done in practice. We can think of a library (or package) as a directory of scripts containing functions. Those functions are grouped together to help engineers and scientists solve challenges."
},
{
"code": null,
"e": 1591,
"s": 1084,
"text": "Building today’s software doesn’t happen without extensive use of libraries. Libraries dramatically cut down the time and effort required for a team to bring work to production. By leveraging the open source community engineers and scientists can move their unique contribution towards a larger audience, and effectively improve the quality of their code. Companies of all sizes use these libraries to sit their work on top of existing functionality, making product development more productive and focused."
},
{
"code": null,
"e": 1923,
"s": 1591,
"text": "But creating libraries isn’t just for production software. Libraries are critical to rapidly prototyping ideas, helping teams validate hypotheses and craft experimental software quickly. While popular libraries enjoy massive community support and a set of best practices, smaller projects can be converted into libraries overnight."
},
{
"code": null,
"e": 2175,
"s": 1923,
"text": "By learning to create lighter-weight libraries we develop an ongoing habit of maintaining code and sharing our work. Our own development is sped up dramatically, and we anchor our coding efforts around a tangible unit of work we can improve over time."
},
{
"code": null,
"e": 2452,
"s": 2175,
"text": "In this article we will focus on creating libraries in R and Python as well as hosting them on, and installing from, GitHub. This means we won’t look at popular hosting sites like CRAN for R and PyPI for Python. These are extra steps that are beyond the scope of this article."
},
{
"code": null,
"e": 2902,
"s": 2452,
"text": "Focusing only on GitHub helps encourage practitioners to develop and share libraries more frequently. CRAN and PyPI have a number of criteria that must be met (and they change frequently), which can slow down the process of releasing our work. Rest assured, it is just as easy for others to install our libraries from GitHub. Also, the steps for CRAN and PyPI can always be added later should you feel your library would benefit from a hosting site."
},
{
"code": null,
"e": 3145,
"s": 2902,
"text": "We will build both R and Python libraries using the same environment (JupyterLab), with the same high-level steps for both languages. This should help you build a working knowledge of the core steps required to package your code as a library."
},
{
"code": null,
"e": 3164,
"s": 3145,
"text": "Let’s get started."
},
{
"code": null,
"e": 3349,
"s": 3164,
"text": "We will be creating a library called datapeek in both R and Python. The datapeek library is a simple package offering a few useful functions for handling raw data. These functions are:"
},
{
"code": null,
"e": 3365,
"s": 3349,
"text": "encode_and_bind"
},
{
"code": null,
"e": 3381,
"s": 3365,
"text": "remove_features"
},
{
"code": null,
"e": 3406,
"s": 3381,
"text": "apply_function_to_column"
},
{
"code": null,
"e": 3425,
"s": 3406,
"text": "get_closest_string"
},
{
"code": null,
"e": 3714,
"s": 3425,
"text": "We will look at these functions later. For now we need to setup an R and Python environment to create datapeek, along with a few libraries to support packaging our code. We will be using JupyterLab inside a Docker container, along with a “docker stack” that comes with the pieces we need."
},
{
"code": null,
"e": 3907,
"s": 3714,
"text": "The Docker Stack we will use is called the jupyter/datascience-notebook. This image contains both R and Python environments, along with many of the packages typically used in machine learning."
},
{
"code": null,
"e": 4117,
"s": 3907,
"text": "Since these run inside Docker you must have Docker installed on your machine. So install Docker if you don’t already have it, and once installed, run the following in terminal to pull the datascience-notebook:"
},
{
"code": null,
"e": 4158,
"s": 4117,
"text": "docker pull jupyter/datascience-notebook"
},
{
"code": null,
"e": 4217,
"s": 4158,
"text": "This will pull the most recent image hosted on Docker Hub."
},
{
"code": null,
"e": 4367,
"s": 4217,
"text": "NOTE: Anytime you pull a project from Docker Hub you get the latest build. If some time passes since your last pull, pull again to update your image."
},
{
"code": null,
"e": 4441,
"s": 4367,
"text": "Immediately after running the above command you should see the following:"
},
{
"code": null,
"e": 4535,
"s": 4441,
"text": "Once everything has been pulled we can confirm our new image exists by running the following:"
},
{
"code": null,
"e": 4549,
"s": 4535,
"text": "docker images"
},
{
"code": null,
"e": 4597,
"s": 4549,
"text": "... showing something similar to the following:"
},
{
"code": null,
"e": 4655,
"s": 4597,
"text": "Now that we have our Docker stack let’s setup JupyterLab."
},
{
"code": null,
"e": 4974,
"s": 4655,
"text": "We will create our libraries inside a JupyterLab environment. JupyterLab is a web-based user interface for programming. With JupyterLab we have a lightweight IDE in the browser, making it convenient for building quick applications. JupyterLab provides everything we need to create libraries in R and Python, including:"
},
{
"code": null,
"e": 5062,
"s": 4974,
"text": "A terminal environment for running shell commands and downloading/installing libraries;"
},
{
"code": null,
"e": 5134,
"s": 5062,
"text": "An R and Python console for working interactively with these languages;"
},
{
"code": null,
"e": 5199,
"s": 5134,
"text": "A simple text editor for creating files with various extensions;"
},
{
"code": null,
"e": 5242,
"s": 5199,
"text": "Jupyter Notebooks for prototyping ML work."
},
{
"code": null,
"e": 5475,
"s": 5242,
"text": "The datascience-notebook we just pulled contains an installation of JupyterLab so we don’t need to install this separately. Before running our Docker image we need to mount a volume to ensure our work is saved outside the container."
},
{
"code": null,
"e": 5682,
"s": 5475,
"text": "First, create a folder called datapeek on your desktop (or anywhere you wish) and change into that directory. We need to run our Docker container with JupyterLab, so our full command should look as follows:"
},
{
"code": null,
"e": 5787,
"s": 5682,
"text": "docker run -it -v `pwd`:/home/jovyan/work -p 8888:8888 jupyter/datascience-notebook start.sh jupyter lab"
},
{
"code": null,
"e": 5960,
"s": 5787,
"text": "You can learn more about Docker commands here. Importantly, the above command exposes our environment on port 8888, meaning we can access our container through the browser."
},
{
"code": null,
"e": 6040,
"s": 5960,
"text": "After running the above command you should see the following output at the end:"
},
{
"code": null,
"e": 6207,
"s": 6040,
"text": "This tells us to copy and paste the provided URL into our browser. Open your browser and add the link in the address bar and hit enter (your token will be different):"
},
{
"code": null,
"e": 6278,
"s": 6207,
"text": "localhost:8888/?token=11e5027e9f7cacebac465d79c9548978b03aaf53131ce5fd"
},
{
"code": null,
"e": 6348,
"s": 6278,
"text": "This will automatically open JupyterLab in your browser as a new tab:"
},
{
"code": null,
"e": 6394,
"s": 6348,
"text": "We are now ready to start building libraries."
},
{
"code": null,
"e": 6445,
"s": 6394,
"text": "We begin this article with R, then look at Python."
},
{
"code": null,
"e": 6634,
"s": 6445,
"text": "R is one of the “big 2” languages of machine learning. At the time of this writing it has well-over 10,000 libraries. Going to Available CRAN Packages By Date of Publication and running..."
},
{
"code": null,
"e": 6677,
"s": 6634,
"text": "document.getElementsByTagName('tr').length"
},
{
"code": null,
"e": 6966,
"s": 6677,
"text": "...in the browser console gives me 13858. Minus the header and final row this gives 13856 packages. Needless to say R is not in need of variety. With strong community support and a concise (if not intuitive) language, R sits comfortably at the top of statistical languages worth learning."
},
{
"code": null,
"e": 7152,
"s": 6966,
"text": "The most well-known treatise on creating R packages is Hadley Wickam’s book R Packages. Its contents are available for free online. For a deeper dive on topic I recommend looking there."
},
{
"code": null,
"e": 7474,
"s": 7152,
"text": "We will use Hadley’s devtools package to abstract away the tedious tasks involved in creating packages. devtools is already installed in our Docker Stacks environment. We also require the roxygen2 package, which helps us document our functions. Since this doesn’t come pre-installed with our image let’s install that now."
},
{
"code": null,
"e": 7588,
"s": 7474,
"text": "NOTE: From now on we’ll use the terminal in JupyterLab in order to conveniently keep our work within the browser."
},
{
"code": null,
"e": 7632,
"s": 7588,
"text": "Open terminal inside JupyterLab’s Launcher:"
},
{
"code": null,
"e": 7763,
"s": 7632,
"text": "NOTE: If you’d like to change your JupyterLab to dark theme, click on Settings at the top, JupyterLab Theme, then JupyterLab Dark:"
},
{
"code": null,
"e": 7799,
"s": 7763,
"text": "Inside the console type R, then...."
},
{
"code": null,
"e": 7845,
"s": 7799,
"text": "install.packages(\"roxygen2\")library(roxygen2)"
},
{
"code": null,
"e": 7916,
"s": 7845,
"text": "With the necessary packages installed we’re ready to tackle each step."
},
{
"code": null,
"e": 8052,
"s": 7916,
"text": "We need to create a directory for our package. We can do this in one line of code, using the devtools create function. In terminal run:"
},
{
"code": null,
"e": 8081,
"s": 8052,
"text": "devtools::create(\"datapeek\")"
},
{
"code": null,
"e": 8260,
"s": 8081,
"text": "This automatically creates the bare bone files and directories needed to define our R package. In JupyterLab you will see a set of new folders and files created on the left side."
},
{
"code": null,
"e": 8431,
"s": 8260,
"text": "NOTE: You will also see your new directory structure created on your desktop (or wherever you chose to create it) since we mounted a volume to our container during setup."
},
{
"code": null,
"e": 8483,
"s": 8431,
"text": "If we inspect our package in JupyterLab we now see:"
},
{
"code": null,
"e": 8543,
"s": 8483,
"text": "datapeek├── R├── datapeek.Rproj├── DESCRIPTION├── NAMESPACE"
},
{
"code": null,
"e": 8881,
"s": 8543,
"text": "The R folder will eventually contain our R code. The my_package.Rproj file is specific to the RStudio IDE so we can ignore that. The DESCRIPTION folder holds our package’s metadata (a detailed discussion can be found here). Finally, NAMSPACE is a file that ensures our library plays nicely with others, and is more of a CRAN requirement."
},
{
"code": null,
"e": 8934,
"s": 8881,
"text": "We must follow these rules when naming an R package:"
},
{
"code": null,
"e": 9003,
"s": 8934,
"text": "must be unique on CRAN (you can check all current R libraries here);"
},
{
"code": null,
"e": 9053,
"s": 9003,
"text": "can only consist of letters, numbers and periods;"
},
{
"code": null,
"e": 9093,
"s": 9053,
"text": "cannot contain an underscore or hyphen;"
},
{
"code": null,
"e": 9119,
"s": 9093,
"text": "must start with a letter;"
},
{
"code": null,
"e": 9143,
"s": 9119,
"text": "cannot end in a period;"
},
{
"code": null,
"e": 9343,
"s": 9143,
"text": "You can read more about naming packages here. Our package name “datapeek” passes the above criteria. Let’s head over to CRAN and do a Command+F search for “datapeek” to ensure it’s not already taken:"
},
{
"code": null,
"e": 9369,
"s": 9343,
"text": "...looks like we’re good."
},
{
"code": null,
"e": 9685,
"s": 9369,
"text": "The job of the DESCRIPTION file is to store important metadata about our package. These data include others packages required to run our library, our license, and our contact information. Technically, the definition of a package in R is any directory containing a DESCRIPTION file, so always ensure this is present."
},
{
"code": null,
"e": 9846,
"s": 9685,
"text": "Click on the DESCRIPTION file in JupyterLab’s directory listing. You will see the basic details created automatically when we ran devtools::create(“datapeek”) :"
},
{
"code": null,
"e": 10000,
"s": 9846,
"text": "Let’s add our specific details so our package contains the necessary metadata. Simply edit this file inside JupyterLab. Here are the details I am adding:"
},
{
"code": null,
"e": 10018,
"s": 10000,
"text": "Package: datapeek"
},
{
"code": null,
"e": 10078,
"s": 10018,
"text": "Title: Provides useful functions for working with raw data."
},
{
"code": null,
"e": 10095,
"s": 10078,
"text": "Version: 0.0.0.1"
},
{
"code": null,
"e": 10187,
"s": 10095,
"text": "Authors@R: person(“Sean”, “McClure”, email=”sean.mcclure@example.com”, role=c('aut','cre'))"
},
{
"code": null,
"e": 10286,
"s": 10187,
"text": "Description: The datapeek package helps users transform raw data for machine learning development."
},
{
"code": null,
"e": 10307,
"s": 10286,
"text": "Depends: R (≥ 3.5.1)"
},
{
"code": null,
"e": 10320,
"s": 10307,
"text": "License: MIT"
},
{
"code": null,
"e": 10336,
"s": 10320,
"text": "Encoding: UTF-8"
},
{
"code": null,
"e": 10351,
"s": 10336,
"text": "LazyData: true"
},
{
"code": null,
"e": 10822,
"s": 10351,
"text": "Of course you should fill out these parts with your own details. You can read more about the definitions of each of these in Hadley’s chapter on metadata. As a brief overview...the package, title, and version parts are self-explanatory, just be sure to keep title to one line. Authors@R must adhere to the format you see above, since it contains executable R code. Note the role argument, which allows us to list the main contributors of our library. The usual ones are:"
},
{
"code": null,
"e": 10834,
"s": 10822,
"text": "aut: author"
},
{
"code": null,
"e": 10861,
"s": 10834,
"text": "cre: creator or maintainer"
},
{
"code": null,
"e": 10879,
"s": 10861,
"text": "ctb: contributors"
},
{
"code": null,
"e": 10901,
"s": 10879,
"text": "cph: copyright holder"
},
{
"code": null,
"e": 10961,
"s": 10901,
"text": "There are many more options, with the full list found here."
},
{
"code": null,
"e": 11019,
"s": 10961,
"text": "You can add multiple authors by listing them as a vector:"
},
{
"code": null,
"e": 11209,
"s": 11019,
"text": "Authors@R: as.person(c( \"Sean McClure <sean.mcclure@example.com> [aut, cre]\", \"Rick Deckard <rick.deckard@example.com> [aut]\", \"Rachael Tyrell <rachel.tyrell@example.com> [ctb]\"))"
},
{
"code": null,
"e": 11339,
"s": 11209,
"text": "NOTE: If you do plan on hosting your library on CRAN be sure your email address is correct, as CRAN will use this to contact you."
},
{
"code": null,
"e": 12042,
"s": 11339,
"text": "The description can be multiple lines, limited to 1 paragraph. We use depends to specify the minimum version of R our package depends on. You should use an R version equal or greater than the one you used to build your library. Most people today set their License to MIT, which permits anyone to “use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software” as long as your copyright is included. You can learn more about the MIT license here. Encoding ensures our library can be opened, read and saved using modern parsers, and LazyData refers to how data in our package are loaded. Since we set ours to true it means our data won’t occupy memory until they are used."
},
{
"code": null,
"e": 12214,
"s": 12042,
"text": "Our library wouldn’t do much without functions. Let’s add the 4 functions mentioned in the beginning of this article. The following GIST shows our datapeek functions in R:"
},
{
"code": null,
"e": 12324,
"s": 12214,
"text": "We have to add our functions to the R folder, since this is where R looks for any functions inside a library."
},
{
"code": null,
"e": 12384,
"s": 12324,
"text": "datapeek├── R├── datapeek.Rproj├── DESCRIPTION├── NAMESPACE"
},
{
"code": null,
"e": 12538,
"s": 12384,
"text": "Since our library only contains 4 functions we will place all of them into a single file called utilities.R, with this file residing inside the R folder."
},
{
"code": null,
"e": 12715,
"s": 12538,
"text": "Go into the directory in JupyterLab and open the R folder. Click on Text File in the Launcher and paste in our 4 R functions. Right-click the file and rename it to utilities.R."
},
{
"code": null,
"e": 12911,
"s": 12715,
"text": "It isn’t enough to simply place R functions in our file. Each function must be exported to expose them to users of our library. This is accomplished by adding the @export tag above each function."
},
{
"code": null,
"e": 13052,
"s": 12911,
"text": "The export syntax comes from Roxygen, and ensures our function gets added to the NAMESPACE. Let’s add the @export tag to our first function:"
},
{
"code": null,
"e": 13097,
"s": 13052,
"text": "Do this for the remaining functions as well."
},
{
"code": null,
"e": 13264,
"s": 13097,
"text": "NOTE: In larger libraries we would only export functions that need to be usable outside our package. This helps reduce the chances of a conflict with another library."
},
{
"code": null,
"e": 13579,
"s": 13264,
"text": "It is important to document our functions. Documenting functions provides information for users, such that when they type ?datapeek they get details about our package. Documenting also supports working with vignettes, which are a long-form type of documentation. You can read more about documenting functions here."
},
{
"code": null,
"e": 13615,
"s": 13579,
"text": "There are 2 sub-steps we will take:"
},
{
"code": null,
"e": 13644,
"s": 13615,
"text": "add the document annotations"
},
{
"code": null,
"e": 13669,
"s": 13644,
"text": "run devtools::document()"
},
{
"code": null,
"e": 13700,
"s": 13669,
"text": "— Add the Document Annotations"
},
{
"code": null,
"e": 13823,
"s": 13700,
"text": "Documentation is added above our function, directly above our #’ @export line. Here’s the example with our first function:"
},
{
"code": null,
"e": 13976,
"s": 13823,
"text": "We space out the lines for readability, adding a title, description, and any parameters used by the function. Let’s do this for our remaining functions:"
},
{
"code": null,
"e": 14003,
"s": 13976,
"text": "— Run devtools::document()"
},
{
"code": null,
"e": 14117,
"s": 14003,
"text": "With documentation added to our functions we then run the following in terminal, just outside the root directory:"
},
{
"code": null,
"e": 14138,
"s": 14117,
"text": "devtools::document()"
},
{
"code": null,
"e": 14203,
"s": 14138,
"text": "NOTE: Make sure you’re one level outside the datapeek directory."
},
{
"code": null,
"e": 14226,
"s": 14203,
"text": "You may get the error:"
},
{
"code": null,
"e": 14295,
"s": 14226,
"text": "Error: ‘roxygen2’ >= 5.0.0 must be installed for this functionality."
},
{
"code": null,
"e": 14443,
"s": 14295,
"text": "In this case open terminal in JupyterLab and install roxygen2. You should also install data.table and mltools, since our first function uses these:"
},
{
"code": null,
"e": 14529,
"s": 14443,
"text": "install.packages('roxygen2')install.packages('data.table')install.packages('mltools')"
},
{
"code": null,
"e": 14595,
"s": 14529,
"text": "Run the devtools::document() again. You should see the following:"
},
{
"code": null,
"e": 14720,
"s": 14595,
"text": "This will generate .Rd files inside a new man folder. You’ll notice an .Rd file is created for each function in our package."
},
{
"code": null,
"e": 14800,
"s": 14720,
"text": "If you look at your DESCRIPTION file it will now show a new line at the bottom:"
},
{
"code": null,
"e": 14842,
"s": 14800,
"text": "This will also generate a NAMESPACE file:"
},
{
"code": null,
"e": 14964,
"s": 14842,
"text": "We can see our 4 functions have been exposed. Let’s now move onto ensuring dependencies are specified inside our library."
},
{
"code": null,
"e": 15151,
"s": 14964,
"text": "It is common for our functions to require functions found in other libraries. There are 2 things we must do to ensure external functionality is made available to our library’s functions:"
},
{
"code": null,
"e": 15270,
"s": 15151,
"text": "Use double colons inside our functions to specify which library we are relying on;Add imports to our DESCRIPTION file."
},
{
"code": null,
"e": 15353,
"s": 15270,
"text": "Use double colons inside our functions to specify which library we are relying on;"
},
{
"code": null,
"e": 15390,
"s": 15353,
"text": "Add imports to our DESCRIPTION file."
},
{
"code": null,
"e": 15837,
"s": 15390,
"text": "You’ll notice in the above GIST we simply listed our libraries at the top. While this works well in stand-alone R scripts it isn’t the way to use dependencies in an R package. When creating R packages we must use the “double-colon approach” to ensure the correct function is read. This is related to how “top-level code” (code that isn’t an object like a function) in an R package is only executed when the package is built, not when it’s loaded."
},
{
"code": null,
"e": 15850,
"s": 15837,
"text": "For example:"
},
{
"code": null,
"e": 15941,
"s": 15850,
"text": "library(mltools)do_something_cool_with_mltools <- function() { auc_roc(preds, actuals)}"
},
{
"code": null,
"e": 16074,
"s": 15941,
"text": "...won’t work because auc_roc will not be available (running library(datapeek) doesn’t re-execute library(mltools)). This will work:"
},
{
"code": null,
"e": 16158,
"s": 16074,
"text": "do_something_cool_with_mltools <- function() { mltools::auc_roc(preds, actuals)}"
},
{
"code": null,
"e": 16248,
"s": 16158,
"text": "The only function in our datapeek package requiring additional packages is our first one:"
},
{
"code": null,
"e": 16353,
"s": 16248,
"text": "Notice each time we call an external function we preface it with the external library and double colons."
},
{
"code": null,
"e": 16496,
"s": 16353,
"text": "We must also list external dependencies in our DESCRIPTION file, so they are handled correctly. Let’s add our imports to the DESCRIPTION file:"
},
{
"code": null,
"e": 16699,
"s": 16496,
"text": "Be sure to have the imported libraries comma-separated. Notice we didn’t specify any versions for our external dependencies. If we need to specify versions we can use parentheses after the package name:"
},
{
"code": null,
"e": 16734,
"s": 16699,
"text": "Imports: data.table (>= 1.12.0)"
},
{
"code": null,
"e": 16869,
"s": 16734,
"text": "Since our encode_and_bind function isn’t taking advantage of any bleeding-edge updates we will leave it without any version specified."
},
{
"code": null,
"e": 17189,
"s": 16869,
"text": "Sometimes it makes sense to include data inside our library. Package data can allow our user’s to practice with our library’s functions, and also helps with testing, since machine learning packages will always contain functions that ingest and transform data. The 4 options for adding external data to an R package are:"
},
{
"code": null,
"e": 17235,
"s": 17189,
"text": "binary dataparsed dataraw dataserialized data"
},
{
"code": null,
"e": 17247,
"s": 17235,
"text": "binary data"
},
{
"code": null,
"e": 17259,
"s": 17247,
"text": "parsed data"
},
{
"code": null,
"e": 17268,
"s": 17259,
"text": "raw data"
},
{
"code": null,
"e": 17284,
"s": 17268,
"text": "serialized data"
},
{
"code": null,
"e": 17450,
"s": 17284,
"text": "You can learn more about these different approaches here. For this article we will stick with the most common approach, which is to add external data to an R folder."
},
{
"code": null,
"e": 17742,
"s": 17450,
"text": "Let’s add the Iris dataset to our library in order to provide users a quick way to test our functions. The data must be in the .rda format, created using R’s save() function, and have the same name as the file. We can ensure these criteria are satisfied by using devtools’ use_data function:"
},
{
"code": null,
"e": 17808,
"s": 17742,
"text": "x <- read.csv(\"http://bit.ly/2HuTS0Z\")devtools::use_data(x, iris)"
},
{
"code": null,
"e": 17904,
"s": 17808,
"text": "Above, I read in the Iris dataset from its URL and pass the data frame to devtools::use_data()."
},
{
"code": null,
"e": 17994,
"s": 17904,
"text": "In JupyterLab we see a new data folder has been created, along with our iris.rda dataset:"
},
{
"code": null,
"e": 18085,
"s": 17994,
"text": "datapeek├── data └── iris.rda├── man├── R├── datapeek.Rproj├── DESCRIPTION├── NAMESPACE"
},
{
"code": null,
"e": 18154,
"s": 18085,
"text": "We will use our added dataset to run tests in the following section."
},
{
"code": null,
"e": 18370,
"s": 18154,
"text": "Testing is an important part of software development. Testing helps ensure our code works as expected, and makes debugging our code a much faster and more effective process. Learn more about testing R packages here."
},
{
"code": null,
"e": 18597,
"s": 18370,
"text": "A common challenge in testing is knowing what we should test. Testing every function in a large library is cumbersome and not always needed, while not enough testing can make it harder to find and correct bugs when they arise."
},
{
"code": null,
"e": 18667,
"s": 18597,
"text": "I like the following quote from Martin Fowler regarding when to test:"
},
{
"code": null,
"e": 18805,
"s": 18667,
"text": "“Whenever you are tempted to type something into a print statement or a debugger expression, write it as a test instead.” — Martin Fowler"
},
{
"code": null,
"e": 19406,
"s": 18805,
"text": "If you prototype applications regularly you’ll find yourself writing to the console frequently to see if a piece of code returns what you expect. In data science, writing interactive code is even more common, since machine learning work is highly experimental. On one hand this provides ample opportunity to think about which tests to write. On the other hand, the non-deterministic nature of machine learning code means testing certain aspect of ML can be less than straightforward. As a general rule, look for obvious deterministic pieces of your code that should return the same output every time."
},
{
"code": null,
"e": 19629,
"s": 19406,
"text": "The interactive testing we do in data science is manual, but what we are looking for in our packages is automated testing. Automated testing means we run a suite of pre-defined tests to ensure our package works end-to-end."
},
{
"code": null,
"e": 19853,
"s": 19629,
"text": "While there are many kinds of tests in software, here we are taking about “unit tests.” Thinking in terms of unit tests forces us to break up our code into more modular components, which is good practice in software design."
},
{
"code": null,
"e": 20039,
"s": 19853,
"text": "NOTE: If you are used to testing in languages like Python, notice that R is more functional in nature (i.e., methods belong to functions not classes), so there will be some differences."
},
{
"code": null,
"e": 20101,
"s": 20039,
"text": "There are 2 sub-steps we will take for testing our R library:"
},
{
"code": null,
"e": 20141,
"s": 20101,
"text": "6A: Creating the tests/testthat folder;"
},
{
"code": null,
"e": 20160,
"s": 20141,
"text": "6B: Writing tests."
},
{
"code": null,
"e": 20201,
"s": 20160,
"text": "— 6A: Creating the tests/testthat folder"
},
{
"code": null,
"e": 20384,
"s": 20201,
"text": "Just as R expects our R scripts and data to be in specific folders it also expects the same for our tests. To create the tests folder, we run the following in JupyterLab’s R console:"
},
{
"code": null,
"e": 20409,
"s": 20384,
"text": "devtools::use_testthat()"
},
{
"code": null,
"e": 20442,
"s": 20409,
"text": "You may get the following error:"
},
{
"code": null,
"e": 20511,
"s": 20442,
"text": "Error: ‘testthat’ >= 1.0.2 must be installed for this functionality."
},
{
"code": null,
"e": 20593,
"s": 20511,
"text": "If so, use the same approach above for installing roxygen2 in Jupyter’s terminal."
},
{
"code": null,
"e": 20622,
"s": 20593,
"text": "install.packages('testthat')"
},
{
"code": null,
"e": 20690,
"s": 20622,
"text": "Running devtools::use_testthat() will produce the following output:"
},
{
"code": null,
"e": 20792,
"s": 20690,
"text": "* Adding testthat to Suggests* Creating `tests/testthat`.* Creating `tests/testthat.R` from template."
},
{
"code": null,
"e": 20852,
"s": 20792,
"text": "There will now be a new tests folder in our main directory:"
},
{
"code": null,
"e": 20954,
"s": 20852,
"text": "datapeek├── data├── man├── R├── tests └── testthat.R├── datapeek.Rproj├── DESCRIPTION├── NAMESPACE"
},
{
"code": null,
"e": 21195,
"s": 20954,
"text": "The above command also created a file called testthat.R inside the tests folder. This runs all your tests when R CMD check runs (we’ll look at that shortly). You’ll also notice testthat has been added under Suggests in our DESCRIPTION file:"
},
{
"code": null,
"e": 21215,
"s": 21195,
"text": "— 6B: Writing Tests"
},
{
"code": null,
"e": 21460,
"s": 21215,
"text": "testthat is the most popular unit testing package for R, used by at least 2,600 CRAN package, not to mention libraries on Github. You can check out the latest news regarding testthat on the Tidyverse page here. Also check out its documentation."
},
{
"code": null,
"e": 21511,
"s": 21460,
"text": "There are 3 levels to testing we need to consider:"
},
{
"code": null,
"e": 21574,
"s": 21511,
"text": "expectation (assertion): the expected result of a computation;"
},
{
"code": null,
"e": 21699,
"s": 21574,
"text": "test: groups together multiple expectations from a single function, or related functionality from across multiple functions;"
},
{
"code": null,
"e": 21799,
"s": 21699,
"text": "file: groups together multiple related tests. Files are given a human readable name with context()."
},
{
"code": null,
"e": 22158,
"s": 21799,
"text": "Assertions are the functions included in the testing library we choose. We use assertions to check whether our own functions return the expected output. Assertions come in many flavors, depending on what is being checked. In the following section I will cover the main tests used in R programming, showing each one failing so you can understand how it works."
},
{
"code": null,
"e": 22178,
"s": 22158,
"text": "Equality Assertions"
},
{
"code": null,
"e": 22193,
"s": 22178,
"text": "expect_equal()"
},
{
"code": null,
"e": 22212,
"s": 22193,
"text": "expect_identical()"
},
{
"code": null,
"e": 22230,
"s": 22212,
"text": "expect_equivalent"
},
{
"code": null,
"e": 22461,
"s": 22230,
"text": "# test for equalitya <- 10expect_equal(a, 14)> Error: `a` not equal to 14.# test for identical expect_identical(42, 2)> Error: 42 not identical to 2.# test for equivalence expect_equivalent(10, 12)> Error: 10 not equivalent to 12."
},
{
"code": null,
"e": 22675,
"s": 22461,
"text": "There are subtle differences between the examples above. For example, expect_equal is used to check for equality within a numerical tolerance, while expect_identical tests for exact equivalence. Here are examples:"
},
{
"code": null,
"e": 22749,
"s": 22675,
"text": "expect_equal(10, 10 + 1e-7) # trueexpect_identical(10, 10 + 1e-7) # false"
},
{
"code": null,
"e": 22889,
"s": 22749,
"text": "As you write more tests you’ll understand when to use each one. Of course always refer to the documentation referenced above when in doubt."
},
{
"code": null,
"e": 22916,
"s": 22889,
"text": "Testing for String Matches"
},
{
"code": null,
"e": 22931,
"s": 22916,
"text": "expect_match()"
},
{
"code": null,
"e": 23092,
"s": 22931,
"text": "# test for string matchingexpect_match(\"Machine Learning is Fun\", \"But also rewarding.\")> Error: \"Machine Learning is Fun\" does not match \"But also rewarding.\"."
},
{
"code": null,
"e": 23111,
"s": 23092,
"text": "Testing for Length"
},
{
"code": null,
"e": 23125,
"s": 23111,
"text": "expect_length"
},
{
"code": null,
"e": 23221,
"s": 23125,
"text": "# test for length vec <- 1:10expect_length(vec, 12)> Error: `vec` has length 10, not length 12."
},
{
"code": null,
"e": 23244,
"s": 23221,
"text": "Testing for Comparison"
},
{
"code": null,
"e": 23254,
"s": 23244,
"text": "expect_lt"
},
{
"code": null,
"e": 23264,
"s": 23254,
"text": "expect_gt"
},
{
"code": null,
"e": 23467,
"s": 23264,
"text": "# test for less thana <- 11expect_lt(a, 10)> Error: `a` is not strictly less than 10. Difference: 1# test for greater thana <- 11expect_gt(a, 12)> Error: `a` is not strictly more than 12. Difference: -1"
},
{
"code": null,
"e": 23485,
"s": 23467,
"text": "Testing for Logic"
},
{
"code": null,
"e": 23497,
"s": 23485,
"text": "expect_true"
},
{
"code": null,
"e": 23510,
"s": 23497,
"text": "expect_false"
},
{
"code": null,
"e": 23639,
"s": 23510,
"text": "# test for truth expect_true(5 == 2)> Error: 5 == 2 isn't true.# test for false expect_false(2 == 2)> Error: 2 == 2 isn't false."
},
{
"code": null,
"e": 23659,
"s": 23639,
"text": "Testing for Outputs"
},
{
"code": null,
"e": 23673,
"s": 23659,
"text": "expect_output"
},
{
"code": null,
"e": 23688,
"s": 23673,
"text": "expect_message"
},
{
"code": null,
"e": 23952,
"s": 23688,
"text": "# testing for outputs expect_output(str(mtcars), \"31 obs\")> Error: `str\\(mtcars\\)` does not match \"31 obs\".# test for warning f <-function(x) { if(x < 0) { message(\"*x* is already negative\") }}expect_message(f(1))> Error: `f(1)` did not produce any messages."
},
{
"code": null,
"e": 24159,
"s": 23952,
"text": "There are many more included in the testthat library. If you are new to testing, start writing a few simple ones to get used to the process. With time you’ll build an intuition around what to test and when."
},
{
"code": null,
"e": 24231,
"s": 24159,
"text": "A test is a group of assertions. We write tests in testthat as follows:"
},
{
"code": null,
"e": 24318,
"s": 24231,
"text": "test_that(\"this functionality does what it should\", { // group of assertions here})"
},
{
"code": null,
"e": 24471,
"s": 24318,
"text": "We can see we have both a description (the test name) and the code (containing the assertions). The description completes the sentence, “test that ....”"
},
{
"code": null,
"e": 24544,
"s": 24471,
"text": "Above, we are saying “test that this functionality does what it should.”"
},
{
"code": null,
"e": 24605,
"s": 24544,
"text": "The assertions are the outputs we wish to test. For example:"
},
{
"code": null,
"e": 24854,
"s": 24605,
"text": "test_that(\"trigonometric functions match identities\", { expect_equal(sin(pi / 4), 1 / sqrt(2)) expect_equal(cos(pi / 4), 1 / sqrt(10)) expect_equal(tan(pi / 4), 1) })> Error: Test failed: 'trigonometric functions match identities'"
},
{
"code": null,
"e": 25188,
"s": 24854,
"text": "NOTE: It is worth considering the balance between cohesion and coupling with our test files. As stated in Hadley’s book, “the two extremes are clearly bad (all tests in one file, one file per test). You need to find a happy medium that works for you. A good starting place is to have one file of tests for each complicated function.”"
},
{
"code": null,
"e": 25459,
"s": 25188,
"text": "The last thing we do in testing is create files. As stated above, a“file” in testing is a group of tests covering a related set of functionality. Our test file must live inside thetests/testthat/ directory. Here is an example test file for the stringr package on GitHub:"
},
{
"code": null,
"e": 25706,
"s": 25459,
"text": "The file is called test-case.R (starts with “test”) and lives inside the tests/testthat/ directory. The context at the top simply allows us to provide a simple description of the file’s contents. This appears in the console when we run our tests."
},
{
"code": null,
"e": 25887,
"s": 25706,
"text": "Let’s create our test file, which will contain tests and assertions related to our 4 functions. As usual, we use JupyterLab’s Text File in Launcher to create and rename a new file:"
},
{
"code": null,
"e": 25912,
"s": 25887,
"text": "Now let’s add our tests:"
},
{
"code": null,
"e": 26021,
"s": 25912,
"text": "For the first function I am going to make sure a data frame with the correct number of features is returned:"
},
{
"code": null,
"e": 26310,
"s": 26021,
"text": "Notice how we called our encode_and_bind function, then simply checked the equality between the dimensions and the expected output. We run our automated tests at any point to ensure our test file runs and we get the expected output. Running devtools::test() in the console runs our tests:"
},
{
"code": null,
"e": 26336,
"s": 26310,
"text": "We get a smiley face too!"
},
{
"code": null,
"e": 26753,
"s": 26336,
"text": "Since our second function removes a specified feature I will use the same test as above, checking for the dimensions of the returned frame. Our third function applies a specified function to a chosen column, so I will write a test that checks the result of given specified function. Finally, our fourth function returns the closest matching string, so I will simply check the returned string for the expected result."
},
{
"code": null,
"e": 26781,
"s": 26753,
"text": "Here is our full test file:"
},
{
"code": null,
"e": 26842,
"s": 26781,
"text": "NOTE: Notice the relative path to the data in the test file."
},
{
"code": null,
"e": 26905,
"s": 26842,
"text": "As we did above, we run our tests using the following command:"
},
{
"code": null,
"e": 26922,
"s": 26905,
"text": "devtools::test()"
},
{
"code": null,
"e": 27029,
"s": 26922,
"text": "This will run all tests in any test files we placed inside the testthat directory. Let’s check the result:"
},
{
"code": null,
"e": 27237,
"s": 27029,
"text": "We had 5 assertions across 4 unit tests, placed in one test file. Looks like we’re good. If any of our tests failed we would see this in the above printout, at which point we would look to correct the issue."
},
{
"code": null,
"e": 27526,
"s": 27237,
"text": "This has traditionally been done using “Vignettes” in R. You can learn about creating R vignettes for your R package here. Personally, I find this a dated approach to documentation. I prefer to use things like Sphinx or Julep. Documentation should be easily shared, searchable and hosted."
},
{
"code": null,
"e": 27597,
"s": 27526,
"text": "Click on the question mark at julepcode.com to learn how to use Julep."
},
{
"code": null,
"e": 27697,
"s": 27597,
"text": "I created and hosted some simple documentation for our R datapeek library, which you can find here."
},
{
"code": null,
"e": 27769,
"s": 27697,
"text": "Of course we will also have the library on GitHub, which I cover below."
},
{
"code": null,
"e": 28037,
"s": 27769,
"text": "As I mentioned in the introduction we should be creating libraries on a regular basis, so others can benefit from and extend our work. The best way to do this is through GitHub, which is the standard way to distribute and collaborate on open source software projects."
},
{
"code": null,
"e": 28163,
"s": 28037,
"text": "In case you’re new to GitHub here’s a quick tutorial to get you started so we can push our datapeek project to a remote repo."
},
{
"code": null,
"e": 28213,
"s": 28163,
"text": "Sign up/in to GitHub and create a new repository."
},
{
"code": null,
"e": 28261,
"s": 28213,
"text": "...which will provide us with the usual screen:"
},
{
"code": null,
"e": 28364,
"s": 28261,
"text": "With our remote repo setup we can initialize our local repo on our machine, and send our first commit."
},
{
"code": null,
"e": 28432,
"s": 28364,
"text": "Open Terminal in JupyterLab and change into the datapeek directory:"
},
{
"code": null,
"e": 28459,
"s": 28432,
"text": "Initialize the local repo:"
},
{
"code": null,
"e": 28468,
"s": 28459,
"text": "git init"
},
{
"code": null,
"e": 28521,
"s": 28468,
"text": "Add the remote origin (your link will be different):"
},
{
"code": null,
"e": 28588,
"s": 28521,
"text": "git remote add origin https://github.com/sean-mcclure/datapeek.git"
},
{
"code": null,
"e": 28721,
"s": 28588,
"text": "Now run git add . to add all modified and new (untracked) files in the current directory and all subdirectories to the staging area:"
},
{
"code": null,
"e": 28731,
"s": 28721,
"text": "git add ."
},
{
"code": null,
"e": 28850,
"s": 28731,
"text": "Don’t forget the “dot” in the above command. Now we can commit our changes, which adds any new code to our local repo."
},
{
"code": null,
"e": 29035,
"s": 28850,
"text": "But, since we are working inside a Docker container the username and email associated with our local repo cannot be autodetected. We can set these by running the following in terminal:"
},
{
"code": null,
"e": 29117,
"s": 29035,
"text": "git config --global user.email {emailaddress}git config --global user.name {name}"
},
{
"code": null,
"e": 29181,
"s": 29117,
"text": "Use the email address and username you use to sign into GitHub."
},
{
"code": null,
"e": 29200,
"s": 29181,
"text": "Now we can commit:"
},
{
"code": null,
"e": 29231,
"s": 29200,
"text": "git commit -m 'initial commit'"
},
{
"code": null,
"e": 29334,
"s": 29231,
"text": "With our new code committed we can do our push, which transfers the last commit(s) to our remote repo:"
},
{
"code": null,
"e": 29357,
"s": 29334,
"text": "git push origin master"
},
{
"code": null,
"e": 29530,
"s": 29357,
"text": "NOTE: Since we are in Docker you’ll likely get asked again for authentication. Simply add your GitHub username and password when prompted. Then run the above command again."
},
{
"code": null,
"e": 29856,
"s": 29530,
"text": "Some readers will notice we didn’t place a .gitignore file in our directory. It is usually fine to push all files inside smaller R libraries. For larger libraries, or libraries containing large datasets, you can use the site gitignore.io to see what common gitignore files look like. Here is a common R .gitignore file for R:"
},
{
"code": null,
"e": 30281,
"s": 29856,
"text": "To recap, git add adds all modified and new (untracked) files in the current directory to the staging area. Commit adds any changes to our local repo, and push transfers the last commit(s) to our remote repo. While git add might seem superfluous, the reason it exists is because sometimes we want to only commit certain files, this we can stage files selectively. Above, we staged all files by using the “dot” after git add."
},
{
"code": null,
"e": 30425,
"s": 30281,
"text": "You may also notice we didn’t include a README file. You should indeed include this, however for the sake of brevity I have left this step out."
},
{
"code": null,
"e": 30475,
"s": 30425,
"text": "Now, anyone can use our library. 👍 Let’s see how."
},
{
"code": null,
"e": 30664,
"s": 30475,
"text": "As mentioned in the introduction I will not be discussing CRAN in this article. Sticking with GitHub make it easier to share our code frequently, and we can always add CRAN criteria later."
},
{
"code": null,
"e": 30765,
"s": 30664,
"text": "To install a library from GitHub, users can simply run the following command on their local machine:"
},
{
"code": null,
"e": 30816,
"s": 30765,
"text": "devtools::install_github(\"yourusername/mypackage\")"
},
{
"code": null,
"e": 30932,
"s": 30816,
"text": "As such, we can simply instruct others wishing to use datapeek to run the following command on their local machine:"
},
{
"code": null,
"e": 30982,
"s": 30932,
"text": "devtools::install_github(\"sean-mcclure/datapeek\")"
},
{
"code": null,
"e": 31147,
"s": 30982,
"text": "This is something we would include in a README file and/or any other documentation we create. This will install our package like any other package we get from CRAN:"
},
{
"code": null,
"e": 31208,
"s": 31147,
"text": "Users then load the library as usual and they’re good to go:"
},
{
"code": null,
"e": 31226,
"s": 31208,
"text": "library(datapeek)"
},
{
"code": null,
"e": 31366,
"s": 31226,
"text": "I recommend trying the above commands in a new R environment to confirm the installation and loading of your new library works as expected."
},
{
"code": null,
"e": 31681,
"s": 31366,
"text": "Creating Python libraries follows the same high-level steps we saw previously for R. We require a basic directory structure with proper naming conventions, functions with descriptions, imports, specified dependencies, added datasets, documentation, and the ability to share and allow others to install our library."
},
{
"code": null,
"e": 31755,
"s": 31681,
"text": "We will use JupyterLab to build our Python library, just as we did for R."
},
{
"code": null,
"e": 32088,
"s": 31755,
"text": "In the beginning of this article I discussed the difference between a “library” and a “package”, and how I prefer to use these terms interchangeably. The same holds for Python libraries. “Modules” are another term, and in Python simply refer to any file containing Python code. Python libraries obviously contain modules as scripts."
},
{
"code": null,
"e": 32339,
"s": 32088,
"text": "I stated in the introduction that we will host and install our libraries on and from GitHub. This encourages rapid creation and sharing of libraries without getting bogged down by publishing criteria on popular package hosting sites for R and Python."
},
{
"code": null,
"e": 32588,
"s": 32339,
"text": "The most popular hosting site for Python is the Python Package Index (PyPI). This is a place for finding, installing and publishing python libraries. Whenever you run pip install <package_name> (or easy_intall) you are fetching a package from PyPI."
},
{
"code": null,
"e": 32862,
"s": 32588,
"text": "While we won’t cover hosting our package on PyPI it’s still a good idea to see if our library name is unique. This will minimize confusion with other popular Python libraries and improve the odds our library name is distinctive, should we decide to someday host it on PyPI."
},
{
"code": null,
"e": 32933,
"s": 32862,
"text": "First, we should follow a few naming conventions for Python libraries."
},
{
"code": null,
"e": 32952,
"s": 32933,
"text": "Use all lowercase;"
},
{
"code": null,
"e": 33007,
"s": 32952,
"text": "Make the name unique on PyPI (search for name on PyPI)"
},
{
"code": null,
"e": 33061,
"s": 33007,
"text": "No hyphens (you can use underscore to separate words)"
},
{
"code": null,
"e": 33165,
"s": 33061,
"text": "Our library name is datapeek, so the first and third criteria are met; let’s check PyPI for uniqueness:"
},
{
"code": null,
"e": 33177,
"s": 33165,
"text": "All good. 👍"
},
{
"code": null,
"e": 33256,
"s": 33177,
"text": "We’re now ready to move through each step required to create a Python library."
},
{
"code": null,
"e": 33354,
"s": 33256,
"text": "JupyterLab should be up-and-running as per the instructions in the setup section of this article."
},
{
"code": null,
"e": 33459,
"s": 33354,
"text": "Use JupyterLab’s New Folder and Text File options to create the following directory structure and files:"
},
{
"code": null,
"e": 33531,
"s": 33459,
"text": "datapeek├── datapeek └── __init__.py └── utilities.py├── setup.py"
},
{
"code": null,
"e": 33714,
"s": 33531,
"text": "NOTE: Bold names are folders and light names are files. We will refer to the inner datapeek folder as the “module directory” and the outer datapeek directory as the “root directory.”"
},
{
"code": null,
"e": 33790,
"s": 33714,
"text": "The following video shows me creating our datapeek directory in JupyterLab:"
},
{
"code": null,
"e": 33995,
"s": 33790,
"text": "There will be files we do not want to commit to source control. These are files that are created by the Python build system. As such, let’s also add the following .gitignore file to our package framework:"
},
{
"code": null,
"e": 34242,
"s": 33995,
"text": "NOTE: At the time of this writing JupyterLab lacks a front-end setting to toggle hidden files in the browser. As such, we will simply name our file gitignore (no preceding dot); we will change it to a hidden file later prior to pushing to GitHub."
},
{
"code": null,
"e": 34311,
"s": 34242,
"text": "Add your gitignore file as a simple text file to the root directory:"
},
{
"code": null,
"e": 34396,
"s": 34311,
"text": "datapeek├── datapeek └── __init__.py └── utilities.py├── setup.py├── gitignore"
},
{
"code": null,
"e": 34574,
"s": 34396,
"text": "Just as we did for R, we should add metadata about our new library. We do this using Setuptools. Setuptools is a Python library designed to facilitate packaging Python projects."
},
{
"code": null,
"e": 34635,
"s": 34574,
"text": "Open setup.py and add the following details for our library:"
},
{
"code": null,
"e": 35134,
"s": 34635,
"text": "Of course you should change the authoring to your own. We will add more details to this file later. The keywords are fairly self-explanatory. url is the URL of our project on GitHub, which we will add later; unless you’ve already created your python repo, in which case add the URL now. We talked about licensing in the R section. zip_safe simply means our package can be run safely as a zip file which will usually be the case. You can learn more about what can be added to the setup.py file here."
},
{
"code": null,
"e": 35363,
"s": 35134,
"text": "Our library obviously requires functions to be useful. For larger libraries we would organize our modules so as to balance cohesion/coupling, but since our library is small we will simply keep all functions inside a single file."
},
{
"code": null,
"e": 35437,
"s": 35363,
"text": "We will add the same functions we did for R, this time written in Python:"
},
{
"code": null,
"e": 35521,
"s": 35437,
"text": "Add these functions to the utilities.py module, inside datapeek’s module directory."
},
{
"code": null,
"e": 35816,
"s": 35521,
"text": "Our library will often require other packages as dependencies. Our user’s Python environment will need to be aware of these when installing our library (so these other packages can also be installed). Setuptools provides the install_requires keyword to list any packages our library depends on."
},
{
"code": null,
"e": 36045,
"s": 35816,
"text": "Our datapeek library depends on the fuzzywuzzy package for fuzzy string matching, and the pandas package for high-performance manipulation of data structures. To specify our dependencies, add the following to your setup.py file:"
},
{
"code": null,
"e": 36094,
"s": 36045,
"text": "install_requires=[ 'fuzzywuzzy', 'pandas']"
},
{
"code": null,
"e": 36147,
"s": 36094,
"text": "Your setup.py file should currently look as follows:"
},
{
"code": null,
"e": 36237,
"s": 36147,
"text": "We can confirm all is in order by running the following in a JupyterLab terminal session:"
},
{
"code": null,
"e": 36261,
"s": 36237,
"text": "python setup.py develop"
},
{
"code": null,
"e": 36306,
"s": 36261,
"text": "NOTE: Run this in datapeek’s root directory."
},
{
"code": null,
"e": 36368,
"s": 36306,
"text": "After running the command you should see something like this:"
},
{
"code": null,
"e": 36398,
"s": 36368,
"text": "...with an ending that reads:"
},
{
"code": null,
"e": 36449,
"s": 36398,
"text": "Finished processing dependencies for datapeek==0.1"
},
{
"code": null,
"e": 36733,
"s": 36449,
"text": "If one or more of our dependencies is not available on PyPI, but is available on GitHub (e.g. a bleeding-edge machine learning package is only available on Github...or it’s another one of our team’s libraries hosted only on GitHub), we can use dependency_links inside our setup call:"
},
{
"code": null,
"e": 36839,
"s": 36733,
"text": "setup( ... dependency_links=['http://github.com/user/repo/tarball/master#egg=package-1.0'], ...)"
},
{
"code": null,
"e": 36963,
"s": 36839,
"text": "If you want to add additional metadata, such as status, licensing, language version, etc. we can use classifiers like this:"
},
{
"code": null,
"e": 37198,
"s": 36963,
"text": "setup( ... classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', 'Topic :: Text Processing :: Linguistic', ], ...)"
},
{
"code": null,
"e": 37293,
"s": 37198,
"text": "To learn more about the different classifiers that can be added to our setup.py file see here."
},
{
"code": null,
"e": 37462,
"s": 37293,
"text": "Just as we did above in R we can add data to our Python library. In Python these are called Non-Code Files and can include things like images, data, documentation, etc."
},
{
"code": null,
"e": 37622,
"s": 37462,
"text": "We add data to our library’s module directory, so that any code that requires those data can use a relative path from the consuming module’s __file__ variable."
},
{
"code": null,
"e": 37836,
"s": 37622,
"text": "Let’s add the Iris dataset to our library in order to provide users a quick way to test our functions. First, use the New Folder button in JupyterLab to create a new folder called data inside the module directory:"
},
{
"code": null,
"e": 37933,
"s": 37836,
"text": "datapeek├── datapeek └── __init__.py └── utilities.py └── data├── setup.py├── gitignore"
},
{
"code": null,
"e": 38050,
"s": 37933,
"text": "...then make a new Text File inside the data folder called iris.csv, and paste the data from here into the new file."
},
{
"code": null,
"e": 38141,
"s": 38050,
"text": "If you close and open the new csv file it will render inside JupyterLab as a proper table:"
},
{
"code": null,
"e": 38273,
"s": 38141,
"text": "We specify Non-Code Files using a MANIFEST.in file. Create another Text File called MANIFEST.in placing it inside your root folder:"
},
{
"code": null,
"e": 38385,
"s": 38273,
"text": "datapeek├── datapeek └── __init__.py └── utilities.py └── data├── MANIFEST.in├── setup.py├── gitignore"
},
{
"code": null,
"e": 38419,
"s": 38385,
"text": "...and add this line to the file:"
},
{
"code": null,
"e": 38450,
"s": 38419,
"text": "include datapeek/data/iris.csv"
},
{
"code": null,
"e": 38571,
"s": 38450,
"text": "NOTE: The MANIFEST.in is often not needed, but included in this tutorial for completeness. See here for more discussion."
},
{
"code": null,
"e": 38627,
"s": 38571,
"text": "We also need to include the following line in setup.py:"
},
{
"code": null,
"e": 38653,
"s": 38627,
"text": "include_package_data=True"
},
{
"code": null,
"e": 38698,
"s": 38653,
"text": "Our setup.py file should now look like this:"
},
{
"code": null,
"e": 38893,
"s": 38698,
"text": "As with our R library we should add tests so others can extend our library and ensure their own functions do not conflict with existing code. Add a test folder to our library’s module directory:"
},
{
"code": null,
"e": 39018,
"s": 38893,
"text": "datapeek├── datapeek └── __init__.py └── utilities.py └── data └── tests├── MANIFEST.in├── setup.py├── gitignore"
},
{
"code": null,
"e": 39158,
"s": 39018,
"text": "Our test folder should have its own __init__.py file as well as the test file itself. Create those now using JupyterLab’s Text File option:"
},
{
"code": null,
"e": 39333,
"s": 39158,
"text": "datapeek├── datapeek └── __init__.py └── utilities.py └── data └── tests └──__init__.py └──datapeek_tests.py├── MANIFEST.in├── setup.py├── gitignore"
},
{
"code": null,
"e": 39427,
"s": 39333,
"text": "Our datapeek directory structure is now set to house test functions, which we will write now."
},
{
"code": null,
"e": 39818,
"s": 39427,
"text": "Writing tests in Python is similar to doing so in R. Assertions are used to check the expected outputs produced by our library’s functions. We can use these “unit tests” to check a variety of expected outputs depending on what might be expected to fail. For example, we might want to ensure a data frame is returned, or perhaps the correct number of columns after some known transformation."
},
{
"code": null,
"e": 40020,
"s": 39818,
"text": "I will add a simple test for each of our 4 functions. Feel free to add your own tests. Think about what should be checked, and keep in mind Martin Fowler’s quote shown in the R section of this article."
},
{
"code": null,
"e": 40086,
"s": 40020,
"text": "We will use unittest, a popular unit testing framework in Python."
},
{
"code": null,
"e": 40191,
"s": 40086,
"text": "Add unit tests to the datapeek_tests.py file, ensuring the unittest and datapeek libraries are imported:"
},
{
"code": null,
"e": 40327,
"s": 40191,
"text": "To run these tests we can use Nose, which extends unittest to make testing easier. Install nose using a terminal session in JupyterLab:"
},
{
"code": null,
"e": 40346,
"s": 40327,
"text": "$ pip install nose"
},
{
"code": null,
"e": 40399,
"s": 40346,
"text": "We also need to add the following lines to setup.py:"
},
{
"code": null,
"e": 40473,
"s": 40399,
"text": "setup( ... test_suite='nose.collector', tests_require=['nose'],)"
},
{
"code": null,
"e": 40513,
"s": 40473,
"text": "Our setup.py should now look like this:"
},
{
"code": null,
"e": 40573,
"s": 40513,
"text": "Run the following from the root directory to run our tests:"
},
{
"code": null,
"e": 40594,
"s": 40573,
"text": "python setup.py test"
},
{
"code": null,
"e": 40734,
"s": 40594,
"text": "Setuptools will take care of installing nose if required and running the test suite. After running the above, you should see the following:"
},
{
"code": null,
"e": 40761,
"s": 40734,
"text": "All our tests have passed!"
},
{
"code": null,
"e": 41080,
"s": 40761,
"text": "If any test should fail, the unittest framework will show which functions did not pass. At this point, check to ensure you are calling the function correctly and that the output is indeed what you expected. It can also be good practice to purposely write tests to fail first, then write your functions until they pass."
},
{
"code": null,
"e": 41404,
"s": 41080,
"text": "As I mentioned in the R section, I use Julep to rapidly create sharable and searchable documentation. This avoids writing cryptic annotations and provides the ability to immediately host our documentation. Of course this doesn’t come with the IDE hooks that other documentation does, but for rapidly communicating it works."
},
{
"code": null,
"e": 41467,
"s": 41404,
"text": "You can find the documentation I create for this library here."
},
{
"code": null,
"e": 41848,
"s": 41467,
"text": "The standard approach for sharing python libraries is through PyPI. Just as we didn’t cover CRAN with R, we will not cover hosting our library on PyPI. While the requirements are fewer than those associated with CRAN there are still a number of steps that must be taken to successfully host on PyPI. The steps required to host on sites other than GitHub can always be added later."
},
{
"code": null,
"e": 41945,
"s": 41848,
"text": "We covered the steps for adding a project to GitHub in the R section. The same steps apply here."
},
{
"code": null,
"e": 42081,
"s": 41945,
"text": "I mentioned above the need to rename our gitignore file to make it a hidden file. You can do that by running the following in terminal:"
},
{
"code": null,
"e": 42105,
"s": 42081,
"text": "mv gitignore .gitignore"
},
{
"code": null,
"e": 42347,
"s": 42105,
"text": "You’ll notice this file is no longer visible in our JupyterLab directory (it eventually disappears). Since JupyterLab still lacks a front-end setting to toggle hidden files simply run the following in terminal at anytime to see hidden files:"
},
{
"code": null,
"e": 42354,
"s": 42347,
"text": "ls -a "
},
{
"code": null,
"e": 42447,
"s": 42354,
"text": "We can make it visible again should we need to view/edit the file in JupyterLab, by running:"
},
{
"code": null,
"e": 42471,
"s": 42447,
"text": "mv .gitignore gitignore"
},
{
"code": null,
"e": 42556,
"s": 42471,
"text": "Here is a quick recap on pushing our library to GitHub (change git URL to your own):"
},
{
"code": null,
"e": 42603,
"s": 42556,
"text": "Create a new repo on GitHub called datapeek_py"
},
{
"code": null,
"e": 42654,
"s": 42603,
"text": "Initialize your library’s directory using git init"
},
{
"code": null,
"e": 42741,
"s": 42654,
"text": "Configure your local repo with your GitGub email and username (if using Docker) using:"
},
{
"code": null,
"e": 42823,
"s": 42741,
"text": "git config --global user.email {emailaddress}git config --global user.name {name}"
},
{
"code": null,
"e": 42926,
"s": 42823,
"text": "Add your new remote origin using git remote add origin https://github.com/sean-mcclure/datapeek_py.git"
},
{
"code": null,
"e": 42961,
"s": 42926,
"text": "Stage your library using git add ."
},
{
"code": null,
"e": 43015,
"s": 42961,
"text": "Commit all files using git commit -m ‘initial commit’"
},
{
"code": null,
"e": 43110,
"s": 43015,
"text": "Push your library to the remote repo using git push origin master (authenticate when prompted)"
},
{
"code": null,
"e": 43167,
"s": 43110,
"text": "Now, anyone can use our python library. 👍 Let’s see how."
},
{
"code": null,
"e": 43238,
"s": 43167,
"text": "While we usually install Python libraries using the following command:"
},
{
"code": null,
"e": 43265,
"s": 43238,
"text": "pip install <package_name>"
},
{
"code": null,
"e": 43568,
"s": 43265,
"text": "... this requires hosting our library on PyPI, which as explained above is beyond the scope of this article. Instead we will learn how to install our Python libraries from GitHub, as we did for R. This approach still requires the pip install command but uses the GitHub URL instead of the package name."
},
{
"code": null,
"e": 43758,
"s": 43568,
"text": "With our library hosted on GitHub, we simply use pip install git+ followed by the URL provided on our GitHub repo (available by clicking the Clone or Download button on the GitHub website):"
},
{
"code": null,
"e": 43818,
"s": 43758,
"text": "pip install git+https://github.com/sean-mcclure/datapeek_py"
},
{
"code": null,
"e": 43901,
"s": 43818,
"text": "Now, we can import our library into our Python environment. For a single function:"
},
{
"code": null,
"e": 43948,
"s": 43901,
"text": "from datapeek.utilities import encode_and_bind"
},
{
"code": null,
"e": 43974,
"s": 43948,
"text": "...and for all functions:"
},
{
"code": null,
"e": 44007,
"s": 43974,
"text": "from datapeek.utilities import *"
},
{
"code": null,
"e": 44154,
"s": 44007,
"text": "Let’s do a quick check in a new Python environment to ensure our functions are available. Spinning up a new Docker container, I run the following:"
},
{
"code": null,
"e": 44171,
"s": 44154,
"text": "Fetch a dataset:"
},
{
"code": null,
"e": 44269,
"s": 44171,
"text": "iris = pd.read_csv('https://raw.githubusercontent.com/uiuc-cse/data-fa14/gh-pages/data/iris.csv')"
},
{
"code": null,
"e": 44286,
"s": 44269,
"text": "Check functions:"
},
{
"code": null,
"e": 44319,
"s": 44286,
"text": "encode_and_bind(iris, 'species')"
},
{
"code": null,
"e": 44374,
"s": 44319,
"text": "remove_features(iris, ['petal_length', 'petal_width'])"
},
{
"code": null,
"e": 44441,
"s": 44374,
"text": "apply_function_to_column(iris, ['sepal_length'], 'times_4', 'x*4')"
},
{
"code": null,
"e": 44510,
"s": 44441,
"text": "get_closest_string(['hey there','we we are','howdy doody'], 'doody')"
},
{
"code": null,
"e": 44519,
"s": 44510,
"text": "Success!"
},
{
"code": null,
"e": 44977,
"s": 44519,
"text": "In this article we looked at how to create both R and Python libraries using JupyterLab running inside a Docker container. Docker allowed us to leverage Docker Stacks such that our environment was easily controlled and common packages available. This also made it easy to use the same high-level interface to create libraries through the browser for 2 different languages. All files were written to our local machine since we mounted a volume inside Docker."
},
{
"code": null,
"e": 45435,
"s": 44977,
"text": "Creating libraries is a critical skill for any machine learning practitioner, and something I encourage others to do regularly. Libraries help isolate our work inside useful abstractions, improves reproducibility, makes our work shareable, and is the first step towards designing better software. Using a lightweight approach ensures we can prototype and share quickly, with the option to add more detailed practices and publishing criteria later as needed."
},
{
"code": null,
"e": 45533,
"s": 45435,
"text": "As always, please ask questions in the comments section should you run into issues. Happy coding."
},
{
"code": null,
"e": 45583,
"s": 45533,
"text": "If you enjoyed this article you might also enjoy:"
},
{
"code": null,
"e": 45606,
"s": 45583,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 45629,
"s": 45606,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 45652,
"s": 45629,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 45681,
"s": 45652,
"text": "R Packages by Hadley Wickham"
},
{
"code": null,
"e": 45707,
"s": 45681,
"text": "Testing by Hadley Wickham"
},
{
"code": null,
"e": 45741,
"s": 45707,
"text": "Python Packaging by Scott Torborg"
},
{
"code": null,
"e": 45771,
"s": 45741,
"text": "Jupyter Data Science Notebook"
},
{
"code": null,
"e": 45802,
"s": 45771,
"text": "Docker — Orientation and Setup"
},
{
"code": null,
"e": 45827,
"s": 45802,
"text": "JupyterLab Documentation"
},
{
"code": null,
"e": 45874,
"s": 45827,
"text": "Available CRAN Packages By Date of Publication"
},
{
"code": null,
"e": 45901,
"s": 45874,
"text": "Documenting Functions in R"
},
{
"code": null,
"e": 45907,
"s": 45901,
"text": "Julep"
},
{
"code": null,
"e": 45920,
"s": 45907,
"text": "gitignore.io"
},
{
"code": null,
"e": 45945,
"s": 45920,
"text": "The Python Package Index"
},
{
"code": null,
"e": 45970,
"s": 45945,
"text": "Setuptools Documentation"
},
{
"code": null,
"e": 45993,
"s": 45970,
"text": "Iris Dataset on GitHub"
},
{
"code": null,
"e": 46024,
"s": 45993,
"text": "Unit Tests — Wikipedia Article"
},
{
"code": null,
"e": 46059,
"s": 46024,
"text": "unitest — A Unit Testing Framework"
},
{
"code": null,
"e": 46091,
"s": 46059,
"text": "Nose — Nicer Testing for Python"
},
{
"code": null,
"e": 46138,
"s": 46091,
"text": "Test-Driven Development — Article on Wikipedia"
}
] |
Scala - break Statement
|
As such there is no built-in break statement available in Scala but if you are running Scala version 2.8, then there is a way to use break statement. When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop.
The following is the syntax for break statement.
// import following package
import scala.util.control._
// create a Breaks object as follows
val loop = new Breaks;
// Keep the loop inside breakable as follows
loop.breakable {
// Loop will go here
for(...){
....
// Break will go here
loop.break;
}
}
Try the following example program to understand break statement.
import scala.util.control._
object Demo {
def main(args: Array[String]) {
var a = 0;
val numList = List(1,2,3,4,5,6,7,8,9,10);
val loop = new Breaks;
loop.breakable {
for( a <- numList){
println( "Value of a: " + a );
if( a == 4 ){
loop.break;
}
}
}
println( "After the loop" );
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
Value of a: 1
Value of a: 2
Value of a: 3
Value of a: 4
After the loop
Existing break has an issue while using for nested loops. Just in case to use break for nested loops, follow this method. This is an example program for breaking nested loops.
import scala.util.control._
object Demo {
def main(args: Array[String]) {
var a = 0;
var b = 0;
val numList1 = List(1,2,3,4,5);
val numList2 = List(11,12,13);
val outer = new Breaks;
val inner = new Breaks;
outer.breakable {
for( a <- numList1){
println( "Value of a: " + a );
inner.breakable {
for( b <- numList2){
println( "Value of b: " + b );
if( b == 12 ){
inner.break;
}
}
} // inner breakable
}
} // outer breakable.
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
Value of a: 1
Value of b: 11
Value of b: 12
Value of a: 2
Value of b: 11
Value of b: 12
Value of a: 3
Value of b: 11
Value of b: 12
Value of a: 4
Value of b: 11
Value of b: 12
Value of a: 5
Value of b: 11
Value of b: 12
82 Lectures
7 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
52 Lectures
1.5 hours
Bigdata Engineer
76 Lectures
5.5 hours
Bigdata Engineer
69 Lectures
7.5 hours
Bigdata Engineer
46 Lectures
4.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2308,
"s": 1998,
"text": "As such there is no built-in break statement available in Scala but if you are running Scala version 2.8, then there is a way to use break statement. When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop."
},
{
"code": null,
"e": 2357,
"s": 2308,
"text": "The following is the syntax for break statement."
},
{
"code": null,
"e": 2646,
"s": 2357,
"text": "// import following package\nimport scala.util.control._\n\n// create a Breaks object as follows\nval loop = new Breaks;\n\n// Keep the loop inside breakable as follows\nloop.breakable {\n // Loop will go here\n for(...){\n ....\n \n // Break will go here\n loop.break;\n }\n}\n"
},
{
"code": null,
"e": 2711,
"s": 2646,
"text": "Try the following example program to understand break statement."
},
{
"code": null,
"e": 3127,
"s": 2711,
"text": "import scala.util.control._\n\nobject Demo {\n def main(args: Array[String]) {\n var a = 0;\n val numList = List(1,2,3,4,5,6,7,8,9,10);\n\n val loop = new Breaks;\n \n loop.breakable {\n for( a <- numList){\n println( \"Value of a: \" + a );\n \n if( a == 4 ){\n loop.break;\n }\n }\n }\n println( \"After the loop\" );\n }\n}"
},
{
"code": null,
"e": 3234,
"s": 3127,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 3268,
"s": 3234,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 3340,
"s": 3268,
"text": "Value of a: 1\nValue of a: 2\nValue of a: 3\nValue of a: 4\nAfter the loop\n"
},
{
"code": null,
"e": 3516,
"s": 3340,
"text": "Existing break has an issue while using for nested loops. Just in case to use break for nested loops, follow this method. This is an example program for breaking nested loops."
},
{
"code": null,
"e": 4192,
"s": 3516,
"text": "import scala.util.control._\n\nobject Demo {\n def main(args: Array[String]) {\n var a = 0;\n var b = 0;\n val numList1 = List(1,2,3,4,5);\n val numList2 = List(11,12,13);\n\n val outer = new Breaks;\n val inner = new Breaks;\n\n outer.breakable {\n for( a <- numList1){\n println( \"Value of a: \" + a );\n \n inner.breakable {\n for( b <- numList2){\n println( \"Value of b: \" + b );\n \n if( b == 12 ){\n inner.break;\n }\n }\n } // inner breakable\n }\n } // outer breakable.\n }\n}"
},
{
"code": null,
"e": 4299,
"s": 4192,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 4333,
"s": 4299,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 4554,
"s": 4333,
"text": "Value of a: 1\nValue of b: 11\nValue of b: 12\nValue of a: 2\nValue of b: 11\nValue of b: 12\nValue of a: 3\nValue of b: 11\nValue of b: 12\nValue of a: 4\nValue of b: 11\nValue of b: 12\nValue of a: 5\nValue of b: 11\nValue of b: 12\n"
},
{
"code": null,
"e": 4587,
"s": 4554,
"text": "\n 82 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 4606,
"s": 4587,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4641,
"s": 4606,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4662,
"s": 4641,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 4697,
"s": 4662,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4715,
"s": 4697,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 4750,
"s": 4715,
"text": "\n 76 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 4768,
"s": 4750,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 4803,
"s": 4768,
"text": "\n 69 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 4821,
"s": 4803,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 4856,
"s": 4821,
"text": "\n 46 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4879,
"s": 4856,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 4886,
"s": 4879,
"text": " Print"
},
{
"code": null,
"e": 4897,
"s": 4886,
"text": " Add Notes"
}
] |
C# | Getting the index of the specified key in a SortedList object - GeeksforGeeks
|
01 Feb, 2019
SortedList.IndexOfKey(Object) Method is used to get the zero-based index of the specified key in a SortedList object.
Syntax:
public virtual int IndexOfKey (object key);
Here, key is the Key which is to be located in the SortedList object.
Return Value: This method returns the zero-based index of type System.Int32 of the key parameter if the key is found in the SortedList object otherwise it returns -1.
Exceptions:
ArgumentNullException: If the key is null.
InvalidOperationException: If the comparer throws an exception.
Below programs illustrate the use of above-discussed method:
Example 1:
// C# code to get the zero-based index// of the specified key in a SortedList// objectusing System;using System.Collections; class Geeks { // Main Method public static void Main(String[] args) { // Creating a SortedList of integers SortedList mylist = new SortedList(); // Adding elements to SortedList mylist.Add("First", "Ram"); mylist.Add("Second", "Shyam"); mylist.Add("Third", "Mohit"); mylist.Add("Fourth", "Rohit"); mylist.Add("Fifth", "Manish"); // printing the keys and values of mylist Console.WriteLine("Index \t\t Keys \t\tValues"); for (int i = 0; i < mylist.Count; i++) { Console.WriteLine("[{0}]\t\t{1}\t\t{2}", i, mylist.GetKey(i), mylist.GetByIndex(i)); } Console.Write("\nThe index of key 'Third' is: "); // getting the index of key "Third" Console.Write(mylist.IndexOfKey("Third")); // getting the index of key which is // not present in mylist so it will // return -1 Console.Write("\nThe index of key 'Sixth' is: "); Console.Write(mylist.IndexOfKey("Sixth")); }}
Output:
Index Keys Values
[0] Fifth Manish
[1] First Ram
[2] Fourth Rohit
[3] Second Shyam
[4] Third Mohit
The index of key 'Third' is: 4
The index of key 'Sixth' is: -1
Example 2: To demonstrate the case where ArgumentNullException can occur
// C# code to get the zero-based index// of the specified key in a SortedList// objectusing System;using System.Collections; class Geeks { // Main Method public static void Main(String[] args) { // Creating a SortedList of integers SortedList mylist = new SortedList(); // Adding elements to SortedList mylist.Add("1", "C++"); mylist.Add("2", "Java"); mylist.Add("3", "DSA"); mylist.Add("4", "Python"); mylist.Add("5", "C#"); // printing the keys and values of mylist Console.WriteLine("Index \t\t Keys \t\tValues"); for (int i = 0; i < mylist.Count; i++) { Console.WriteLine("[{0}]\t\t{1}\t\t{2}", i, mylist.GetKey(i), mylist.GetByIndex(i)); } Console.Write("\nThe index of key 'null' is: "); // getting the index of key "null" // it will give ArgumentNullException Console.Write(mylist.IndexOfKey(null)); }}
Runtime Error:
Unhandled Exception:System.ArgumentNullException: Key cannot be null.Parameter name: key
Note:
The index sequence is based on the sort sequence. When an element is added, it is inserted into SortedList in the correct sort order, and the indexing adjusts accordingly. When an element is removed, the indexing also adjusts accordingly. So, the index of a specific key/value pair may change.
This method uses a binary search algorithm so, this method is an O(log n) operation, where n is the Count.
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.sortedlist.indexofkey?view=netframework-4.7.2
CSharp-Collections-Namespace
CSharp-Collections-SortedList
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
C# | Inheritance
C# | List Class
Partial Classes in C#
Convert String to Character Array in C#
Lambda Expressions in C#
Linked List Implementation in C#
|
[
{
"code": null,
"e": 24302,
"s": 24274,
"text": "\n01 Feb, 2019"
},
{
"code": null,
"e": 24420,
"s": 24302,
"text": "SortedList.IndexOfKey(Object) Method is used to get the zero-based index of the specified key in a SortedList object."
},
{
"code": null,
"e": 24428,
"s": 24420,
"text": "Syntax:"
},
{
"code": null,
"e": 24472,
"s": 24428,
"text": "public virtual int IndexOfKey (object key);"
},
{
"code": null,
"e": 24542,
"s": 24472,
"text": "Here, key is the Key which is to be located in the SortedList object."
},
{
"code": null,
"e": 24709,
"s": 24542,
"text": "Return Value: This method returns the zero-based index of type System.Int32 of the key parameter if the key is found in the SortedList object otherwise it returns -1."
},
{
"code": null,
"e": 24721,
"s": 24709,
"text": "Exceptions:"
},
{
"code": null,
"e": 24764,
"s": 24721,
"text": "ArgumentNullException: If the key is null."
},
{
"code": null,
"e": 24828,
"s": 24764,
"text": "InvalidOperationException: If the comparer throws an exception."
},
{
"code": null,
"e": 24889,
"s": 24828,
"text": "Below programs illustrate the use of above-discussed method:"
},
{
"code": null,
"e": 24900,
"s": 24889,
"text": "Example 1:"
},
{
"code": "// C# code to get the zero-based index// of the specified key in a SortedList// objectusing System;using System.Collections; class Geeks { // Main Method public static void Main(String[] args) { // Creating a SortedList of integers SortedList mylist = new SortedList(); // Adding elements to SortedList mylist.Add(\"First\", \"Ram\"); mylist.Add(\"Second\", \"Shyam\"); mylist.Add(\"Third\", \"Mohit\"); mylist.Add(\"Fourth\", \"Rohit\"); mylist.Add(\"Fifth\", \"Manish\"); // printing the keys and values of mylist Console.WriteLine(\"Index \\t\\t Keys \\t\\tValues\"); for (int i = 0; i < mylist.Count; i++) { Console.WriteLine(\"[{0}]\\t\\t{1}\\t\\t{2}\", i, mylist.GetKey(i), mylist.GetByIndex(i)); } Console.Write(\"\\nThe index of key 'Third' is: \"); // getting the index of key \"Third\" Console.Write(mylist.IndexOfKey(\"Third\")); // getting the index of key which is // not present in mylist so it will // return -1 Console.Write(\"\\nThe index of key 'Sixth' is: \"); Console.Write(mylist.IndexOfKey(\"Sixth\")); }}",
"e": 26115,
"s": 24900,
"text": null
},
{
"code": null,
"e": 26123,
"s": 26115,
"text": "Output:"
},
{
"code": null,
"e": 26374,
"s": 26123,
"text": "Index Keys Values\n[0] Fifth Manish\n[1] First Ram\n[2] Fourth Rohit\n[3] Second Shyam\n[4] Third Mohit\n\nThe index of key 'Third' is: 4\nThe index of key 'Sixth' is: -1\n"
},
{
"code": null,
"e": 26447,
"s": 26374,
"text": "Example 2: To demonstrate the case where ArgumentNullException can occur"
},
{
"code": "// C# code to get the zero-based index// of the specified key in a SortedList// objectusing System;using System.Collections; class Geeks { // Main Method public static void Main(String[] args) { // Creating a SortedList of integers SortedList mylist = new SortedList(); // Adding elements to SortedList mylist.Add(\"1\", \"C++\"); mylist.Add(\"2\", \"Java\"); mylist.Add(\"3\", \"DSA\"); mylist.Add(\"4\", \"Python\"); mylist.Add(\"5\", \"C#\"); // printing the keys and values of mylist Console.WriteLine(\"Index \\t\\t Keys \\t\\tValues\"); for (int i = 0; i < mylist.Count; i++) { Console.WriteLine(\"[{0}]\\t\\t{1}\\t\\t{2}\", i, mylist.GetKey(i), mylist.GetByIndex(i)); } Console.Write(\"\\nThe index of key 'null' is: \"); // getting the index of key \"null\" // it will give ArgumentNullException Console.Write(mylist.IndexOfKey(null)); }}",
"e": 27453,
"s": 26447,
"text": null
},
{
"code": null,
"e": 27468,
"s": 27453,
"text": "Runtime Error:"
},
{
"code": null,
"e": 27557,
"s": 27468,
"text": "Unhandled Exception:System.ArgumentNullException: Key cannot be null.Parameter name: key"
},
{
"code": null,
"e": 27563,
"s": 27557,
"text": "Note:"
},
{
"code": null,
"e": 27857,
"s": 27563,
"text": "The index sequence is based on the sort sequence. When an element is added, it is inserted into SortedList in the correct sort order, and the indexing adjusts accordingly. When an element is removed, the indexing also adjusts accordingly. So, the index of a specific key/value pair may change."
},
{
"code": null,
"e": 27964,
"s": 27857,
"text": "This method uses a binary search algorithm so, this method is an O(log n) operation, where n is the Count."
},
{
"code": null,
"e": 27975,
"s": 27964,
"text": "Reference:"
},
{
"code": null,
"e": 28084,
"s": 27975,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.sortedlist.indexofkey?view=netframework-4.7.2"
},
{
"code": null,
"e": 28113,
"s": 28084,
"text": "CSharp-Collections-Namespace"
},
{
"code": null,
"e": 28143,
"s": 28113,
"text": "CSharp-Collections-SortedList"
},
{
"code": null,
"e": 28157,
"s": 28143,
"text": "CSharp-method"
},
{
"code": null,
"e": 28160,
"s": 28157,
"text": "C#"
},
{
"code": null,
"e": 28258,
"s": 28160,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28281,
"s": 28258,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 28309,
"s": 28281,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 28349,
"s": 28309,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 28392,
"s": 28349,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 28409,
"s": 28392,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 28425,
"s": 28409,
"text": "C# | List Class"
},
{
"code": null,
"e": 28447,
"s": 28425,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 28487,
"s": 28447,
"text": "Convert String to Character Array in C#"
},
{
"code": null,
"e": 28512,
"s": 28487,
"text": "Lambda Expressions in C#"
}
] |
Locating child nodes of WebElements in selenium.
|
We can locate child nodes of web elements with Selenium webdriver. First of all we need to identify the parent element with help of any of the locators like id, class, name, xpath or css. Then we have to identify the children with the findElements(By.xpath()) method.
We can identify the child nodes from the parent, by localizing it with the parent and then passing ( ./child::*) as a parameter to the findElements(By.xpath())
Syntax−
parent.findElements(By.xpath("./child::*"))
Let us identify the text of the child nodes of ul node in below html code−
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class ChildNodes{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
// identify element
WebElement t=driver.findElement(By.xpath("//ul[@class='toc chapters']"));
//identify child nodes with ./child::* expression in xpath
List<WebElement> c = t.findElements(By.xpath("./child::*"));
// iterate child nodes
for ( WebElement i : c ) {
//getText() to get text for child nodes
System.out.println(i.getText());}
driver.close();
}
}
|
[
{
"code": null,
"e": 1330,
"s": 1062,
"text": "We can locate child nodes of web elements with Selenium webdriver. First of all we need to identify the parent element with help of any of the locators like id, class, name, xpath or css. Then we have to identify the children with the findElements(By.xpath()) method."
},
{
"code": null,
"e": 1490,
"s": 1330,
"text": "We can identify the child nodes from the parent, by localizing it with the parent and then passing ( ./child::*) as a parameter to the findElements(By.xpath())"
},
{
"code": null,
"e": 1498,
"s": 1490,
"text": "Syntax−"
},
{
"code": null,
"e": 1542,
"s": 1498,
"text": "parent.findElements(By.xpath(\"./child::*\"))"
},
{
"code": null,
"e": 1617,
"s": 1542,
"text": "Let us identify the text of the child nodes of ul node in below html code−"
},
{
"code": null,
"e": 2588,
"s": 1617,
"text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\n\npublic class ChildNodes{\n public static void main(String[] args) {\nSystem.setProperty(\"webdriver.chrome.driver\",\"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n driver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\");\n // identify element\n WebElement t=driver.findElement(By.xpath(\"//ul[@class='toc chapters']\"));\n //identify child nodes with ./child::* expression in xpath\n List<WebElement> c = t.findElements(By.xpath(\"./child::*\"));\n // iterate child nodes\n for ( WebElement i : c ) {\n //getText() to get text for child nodes\n System.out.println(i.getText());}\n driver.close();\n }\n}"
}
] |
Here is the reason why SQLAlchemy is so popular | by Ange Uwase | Towards Data Science
|
There are two ways you can connect a python application to a relational database: a low-level approach and a high-level one. The low-level approach involves installing and setting up the relational database management system on your local machine, and writing actual SQL commands to carry out database operations. The alternative approach is to use an object relational mapper (ORM for short). An ORM is a database abstraction layer that sits as an intermediary between you and the database engine. It allows you to define regular Python objects and methods and translates them into low-level SQL database instructions for you. SQLAlchemy is the ORM of choice for working with relational databases in python.
The reason why SQLAlchemy is so popular is because it is very simple to implement, helps you develop your code quicker and doesn’t require knowledge of SQL to get started. This is why almost all the programming tutorials and courses online teach the high-level approach. Most practicing software engineers also seem to prefer to use SQLAlchemy too.
This article is a tutorial on how to connect a simple flask application to a postgresql database without using SQLAlchemy. Yes, you read that correctly, so here me out: once you understand how to work with a database the low-level approach, you will not only have a much greater appreciation for SQLAlchemy, but also actually understand what is happening behind the scenes when you use it!
Our investigation will involve building a web app that takes in user input via a form and stores it in a postgresql database. Let’s get started!
Create a project directory, navigate to it in terminal and then create a virtual environment for the project. Once you have activated the virtual environment, install flask and psycopg2. psycopg2 is the most popular PostgreSQL adaptor for python. It allows you to access a postgresql database on your local machine directly from your python code. Make sure to write all the python packages you installed in the virtual environment to a requirements.txt file.
$ py -3 -m venv venv$ venv/Scripts/activate$ pip install flask$ pip install psycopg2$ pip freeze > requirements.txt
You can also go ahead and create an empty python script called app.py , a folder called templates and a blank html document called index.html inside the templates folder in your project directory. The structure of your project folder should look as follows:
|- app.py|- requirements.txt|- templates -index.html|- env
You will need to install postgres on your local machine. You can download the right version for your operating system from https://www.postgresql.org/download/.
Once installation has completed, run the SQL Shell for postgres (psql) and enter into the database server. If you installed postgres with its default settings, you will be able to leave all the fields blank (just press enter each time so that the selector moves to the next field) and only have to enter the password you chose. You will know that you are in the database server when the SQL Shell terminal gets prepended with the database name (which by default should be the default postgresql database,postgres=#).
You can use the default “postgres” database as your project’s database if you want, but I prefer to create my own. To create a database on the server, run the command shown below in the SQL shell. This command instructs the server to create a database named python_app. Make sure to not forget the semicolon at the end of the command otherwhise the command wont execute.
postgres=# CREATE DATABASE python_app;
The server will respond with a confirmation message that it created a database. To view all the databases on the server run the command shown below. You should see python_app listed as one of the databases stored on the server.
postgres=#\l
That is all that we will be doing in the SQL Shell. The rest of the database operations (creating tables and adding entries, etc) will be carried out in our python application.
In your app.py file, import the psycopg2 module. You also want to import the Error object from psycopg2 so that you can handle any database errors directly in your python code.
The psycopg2 module exposes a connect() method that takes in as arguments key-value pairs of the parameters you use to log into a postgres database server in the SQL Shell: host, database, port, user, password. The output of the connect() method is a connection object which allows you to create a connection to a postgres database. Once a connection has been established you need some way of telling the database what SQL commands to execute. That’s where cursor objects comes in. The connection object exposes a cursor() method that can be used to create a cursor object whose job is to execute any SQL commands you want the database to carry out.
The workflow for connecting to a postgres database in python code is as follows:
Create a connection objectUse the connection object to create a cursor objectUse the cursor object to execute SQL commandsClose the cursor object and database connection
Create a connection object
Use the connection object to create a cursor object
Use the cursor object to execute SQL commands
Close the cursor object and database connection
Since this workflow involves connections to external systems, a good practice would be to is to implement this workflow in a try-catch-finally block so that you can handle any exceptions that arise either due to connectivity issues or bugs in your code.
Executing SQL commands on the database is a two-step process: you first pass a query string to the cursor object via its execute() method. You then have to commit the SQL command to the database using the connection object’s commit() method to get the change to reflect on the database. You can think of `cursor.execute()` as `git add x` and `connection.commit()` as `git push`.
I find it easier to first define the query string as a variable and then pass it into the execute method as an argument, but you can just go ahead and write the full query as an argument if that’s what you prefer.
The code for creating a users table in the database is shown below. To tell the databse to create a table you use the command keywords “CREATE TABLE” followed by the name of the table, and then in paranthesis the names of the columns that make up the table. Each column has keywords that define its expected data type and constraints.
If your code runs successfully, the python_app database on the postgres server should now contain a users table. To confirm this, you can open up the SQL shell and access the python_app database and then run the \dt command to view all the tables in that database. If you want to see all the columns you defined and their contraints you can run the \d users command. Also, if for some reason you want to delete the table from the database you can run the DROP TABLE users; command. Lastly, if you find yourself in the default postgres database you can easily switch to the python_app database by running the \c python_app`command.
Begin by instantiating a flask application object. Next, define a route and view function that will handle requests for ‘/’, the url for the webform. This view function should render the form when it recieves a GET request and process the form when it recieves a POST request when the user submits the form. The processing part has been left blank for now as we will define it in the next step.
your app.py file code should look as follows:
Your index.html file should contain the following code:
Running the command $ python app.py in terminal opens up the flask development server in debug mode. Accessing the url `http://127.0.0.1:5000/` in your browser should bring up the registration form.
We now have a form that renders in the browser and allows a user to submit input to a server, but nothing happens after the user presses the submit button. Let’s change that.
First define a function called “add_new_user” that takes in a tuple of the user data (name, email, hashed password) and writes it to the database.
Then modify the view function so that when a “POST” request is recieved it calls the “add_new_user” function so that the data can be saved to the database.
When you fill out the registration form and press submit, that information should be written to the postgres database on your local machine! To confirm this, open up the SQL shell and access the python_app database. To view the data in a given database table you need to run a query. Since we want to view all the data stored in the users table, we will run SELECT * FROM users;.
You should see the details you entered in the form captured as a new entry in the users table.
For your convinience the full app.py code is shown below:
This is what the same application would look like using SQLAlchemy:
And there you have it. A simple flask application that connects directly with a postgres database to store user information. As you can see, it is quite a tedious process you have to go through to write to a database using this method. Although very doable, it isnt really very pythonic.
SQLAlchemy allows you to continue writing code in the manner that you are used to even when working with databases. You define a class which represents a particular entity type and directly maps to a table in the database. All the class attributes you define are mapped to the columns in the table, and then any instance of the class is stored in the database as a new entry in the table. Using SQLAlchemy results in simpler, cleaner code that is quicker to write up. Now you know why SQLAlchemy is the defacto way of working with databases in python!
|
[
{
"code": null,
"e": 880,
"s": 171,
"text": "There are two ways you can connect a python application to a relational database: a low-level approach and a high-level one. The low-level approach involves installing and setting up the relational database management system on your local machine, and writing actual SQL commands to carry out database operations. The alternative approach is to use an object relational mapper (ORM for short). An ORM is a database abstraction layer that sits as an intermediary between you and the database engine. It allows you to define regular Python objects and methods and translates them into low-level SQL database instructions for you. SQLAlchemy is the ORM of choice for working with relational databases in python."
},
{
"code": null,
"e": 1229,
"s": 880,
"text": "The reason why SQLAlchemy is so popular is because it is very simple to implement, helps you develop your code quicker and doesn’t require knowledge of SQL to get started. This is why almost all the programming tutorials and courses online teach the high-level approach. Most practicing software engineers also seem to prefer to use SQLAlchemy too."
},
{
"code": null,
"e": 1619,
"s": 1229,
"text": "This article is a tutorial on how to connect a simple flask application to a postgresql database without using SQLAlchemy. Yes, you read that correctly, so here me out: once you understand how to work with a database the low-level approach, you will not only have a much greater appreciation for SQLAlchemy, but also actually understand what is happening behind the scenes when you use it!"
},
{
"code": null,
"e": 1764,
"s": 1619,
"text": "Our investigation will involve building a web app that takes in user input via a form and stores it in a postgresql database. Let’s get started!"
},
{
"code": null,
"e": 2223,
"s": 1764,
"text": "Create a project directory, navigate to it in terminal and then create a virtual environment for the project. Once you have activated the virtual environment, install flask and psycopg2. psycopg2 is the most popular PostgreSQL adaptor for python. It allows you to access a postgresql database on your local machine directly from your python code. Make sure to write all the python packages you installed in the virtual environment to a requirements.txt file."
},
{
"code": null,
"e": 2339,
"s": 2223,
"text": "$ py -3 -m venv venv$ venv/Scripts/activate$ pip install flask$ pip install psycopg2$ pip freeze > requirements.txt"
},
{
"code": null,
"e": 2597,
"s": 2339,
"text": "You can also go ahead and create an empty python script called app.py , a folder called templates and a blank html document called index.html inside the templates folder in your project directory. The structure of your project folder should look as follows:"
},
{
"code": null,
"e": 2658,
"s": 2597,
"text": "|- app.py|- requirements.txt|- templates -index.html|- env"
},
{
"code": null,
"e": 2819,
"s": 2658,
"text": "You will need to install postgres on your local machine. You can download the right version for your operating system from https://www.postgresql.org/download/."
},
{
"code": null,
"e": 3336,
"s": 2819,
"text": "Once installation has completed, run the SQL Shell for postgres (psql) and enter into the database server. If you installed postgres with its default settings, you will be able to leave all the fields blank (just press enter each time so that the selector moves to the next field) and only have to enter the password you chose. You will know that you are in the database server when the SQL Shell terminal gets prepended with the database name (which by default should be the default postgresql database,postgres=#)."
},
{
"code": null,
"e": 3707,
"s": 3336,
"text": "You can use the default “postgres” database as your project’s database if you want, but I prefer to create my own. To create a database on the server, run the command shown below in the SQL shell. This command instructs the server to create a database named python_app. Make sure to not forget the semicolon at the end of the command otherwhise the command wont execute."
},
{
"code": null,
"e": 3746,
"s": 3707,
"text": "postgres=# CREATE DATABASE python_app;"
},
{
"code": null,
"e": 3974,
"s": 3746,
"text": "The server will respond with a confirmation message that it created a database. To view all the databases on the server run the command shown below. You should see python_app listed as one of the databases stored on the server."
},
{
"code": null,
"e": 3987,
"s": 3974,
"text": "postgres=#\\l"
},
{
"code": null,
"e": 4164,
"s": 3987,
"text": "That is all that we will be doing in the SQL Shell. The rest of the database operations (creating tables and adding entries, etc) will be carried out in our python application."
},
{
"code": null,
"e": 4341,
"s": 4164,
"text": "In your app.py file, import the psycopg2 module. You also want to import the Error object from psycopg2 so that you can handle any database errors directly in your python code."
},
{
"code": null,
"e": 4991,
"s": 4341,
"text": "The psycopg2 module exposes a connect() method that takes in as arguments key-value pairs of the parameters you use to log into a postgres database server in the SQL Shell: host, database, port, user, password. The output of the connect() method is a connection object which allows you to create a connection to a postgres database. Once a connection has been established you need some way of telling the database what SQL commands to execute. That’s where cursor objects comes in. The connection object exposes a cursor() method that can be used to create a cursor object whose job is to execute any SQL commands you want the database to carry out."
},
{
"code": null,
"e": 5072,
"s": 4991,
"text": "The workflow for connecting to a postgres database in python code is as follows:"
},
{
"code": null,
"e": 5242,
"s": 5072,
"text": "Create a connection objectUse the connection object to create a cursor objectUse the cursor object to execute SQL commandsClose the cursor object and database connection"
},
{
"code": null,
"e": 5269,
"s": 5242,
"text": "Create a connection object"
},
{
"code": null,
"e": 5321,
"s": 5269,
"text": "Use the connection object to create a cursor object"
},
{
"code": null,
"e": 5367,
"s": 5321,
"text": "Use the cursor object to execute SQL commands"
},
{
"code": null,
"e": 5415,
"s": 5367,
"text": "Close the cursor object and database connection"
},
{
"code": null,
"e": 5669,
"s": 5415,
"text": "Since this workflow involves connections to external systems, a good practice would be to is to implement this workflow in a try-catch-finally block so that you can handle any exceptions that arise either due to connectivity issues or bugs in your code."
},
{
"code": null,
"e": 6048,
"s": 5669,
"text": "Executing SQL commands on the database is a two-step process: you first pass a query string to the cursor object via its execute() method. You then have to commit the SQL command to the database using the connection object’s commit() method to get the change to reflect on the database. You can think of `cursor.execute()` as `git add x` and `connection.commit()` as `git push`."
},
{
"code": null,
"e": 6262,
"s": 6048,
"text": "I find it easier to first define the query string as a variable and then pass it into the execute method as an argument, but you can just go ahead and write the full query as an argument if that’s what you prefer."
},
{
"code": null,
"e": 6597,
"s": 6262,
"text": "The code for creating a users table in the database is shown below. To tell the databse to create a table you use the command keywords “CREATE TABLE” followed by the name of the table, and then in paranthesis the names of the columns that make up the table. Each column has keywords that define its expected data type and constraints."
},
{
"code": null,
"e": 7228,
"s": 6597,
"text": "If your code runs successfully, the python_app database on the postgres server should now contain a users table. To confirm this, you can open up the SQL shell and access the python_app database and then run the \\dt command to view all the tables in that database. If you want to see all the columns you defined and their contraints you can run the \\d users command. Also, if for some reason you want to delete the table from the database you can run the DROP TABLE users; command. Lastly, if you find yourself in the default postgres database you can easily switch to the python_app database by running the \\c python_app`command."
},
{
"code": null,
"e": 7623,
"s": 7228,
"text": "Begin by instantiating a flask application object. Next, define a route and view function that will handle requests for ‘/’, the url for the webform. This view function should render the form when it recieves a GET request and process the form when it recieves a POST request when the user submits the form. The processing part has been left blank for now as we will define it in the next step."
},
{
"code": null,
"e": 7669,
"s": 7623,
"text": "your app.py file code should look as follows:"
},
{
"code": null,
"e": 7725,
"s": 7669,
"text": "Your index.html file should contain the following code:"
},
{
"code": null,
"e": 7924,
"s": 7725,
"text": "Running the command $ python app.py in terminal opens up the flask development server in debug mode. Accessing the url `http://127.0.0.1:5000/` in your browser should bring up the registration form."
},
{
"code": null,
"e": 8099,
"s": 7924,
"text": "We now have a form that renders in the browser and allows a user to submit input to a server, but nothing happens after the user presses the submit button. Let’s change that."
},
{
"code": null,
"e": 8246,
"s": 8099,
"text": "First define a function called “add_new_user” that takes in a tuple of the user data (name, email, hashed password) and writes it to the database."
},
{
"code": null,
"e": 8402,
"s": 8246,
"text": "Then modify the view function so that when a “POST” request is recieved it calls the “add_new_user” function so that the data can be saved to the database."
},
{
"code": null,
"e": 8782,
"s": 8402,
"text": "When you fill out the registration form and press submit, that information should be written to the postgres database on your local machine! To confirm this, open up the SQL shell and access the python_app database. To view the data in a given database table you need to run a query. Since we want to view all the data stored in the users table, we will run SELECT * FROM users;."
},
{
"code": null,
"e": 8877,
"s": 8782,
"text": "You should see the details you entered in the form captured as a new entry in the users table."
},
{
"code": null,
"e": 8935,
"s": 8877,
"text": "For your convinience the full app.py code is shown below:"
},
{
"code": null,
"e": 9003,
"s": 8935,
"text": "This is what the same application would look like using SQLAlchemy:"
},
{
"code": null,
"e": 9291,
"s": 9003,
"text": "And there you have it. A simple flask application that connects directly with a postgres database to store user information. As you can see, it is quite a tedious process you have to go through to write to a database using this method. Although very doable, it isnt really very pythonic."
}
] |
Defanging an IP Address in Python
|
Suppose we have a valid IPv4 IP address. We have to return the Defanged version of the IP address. A Defanged IP address is basically replace every period “.” by “[.]” So if the IP address is “192.168.4.1”, the output will be “192[.]168[.]4[.]1”
To solve this, we will follow these steps −
We will split the string using dot, then put each element separated by “[.]”
Let us see the following implementation to get better understanding −
Live Demo
class Solution(object):
def defangIPaddr(self, address):
address = address.split(".")
return "[.]".join(address)
ob1 = Solution()
print(ob1.defangIPaddr("192.168.4.1"))
"192.168.4.1"
"192[.]168[.]4[.]1"
|
[
{
"code": null,
"e": 1308,
"s": 1062,
"text": "Suppose we have a valid IPv4 IP address. We have to return the Defanged version of the IP address. A Defanged IP address is basically replace every period “.” by “[.]” So if the IP address is “192.168.4.1”, the output will be “192[.]168[.]4[.]1”"
},
{
"code": null,
"e": 1352,
"s": 1308,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1429,
"s": 1352,
"text": "We will split the string using dot, then put each element separated by “[.]”"
},
{
"code": null,
"e": 1499,
"s": 1429,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 1510,
"s": 1499,
"text": " Live Demo"
},
{
"code": null,
"e": 1694,
"s": 1510,
"text": "class Solution(object):\n def defangIPaddr(self, address):\n address = address.split(\".\")\n return \"[.]\".join(address)\nob1 = Solution()\nprint(ob1.defangIPaddr(\"192.168.4.1\"))"
},
{
"code": null,
"e": 1708,
"s": 1694,
"text": "\"192.168.4.1\""
},
{
"code": null,
"e": 1728,
"s": 1708,
"text": "\"192[.]168[.]4[.]1\""
}
] |
Subsetting in R Programming - GeeksforGeeks
|
08 Nov, 2021
In R Programming Language, subsetting allows the user to access elements from an object. It takes out a portion from the object based on the condition provided. There are 4 ways of subsetting in R programming. Each of the methods depends on the usability of the user and the type of object. For example, if there is a dataframe with many columns such as states, country, and population and suppose the user wants to extract states from it, then subsetting is used to do this operation. In this article, let us discuss the implementation of different types of subsetting in R programming.
Using the ‘[ ]’ operator, elements of vectors and observations from data frames can be accessed. To neglect some indexes, ‘-‘ is used to access all other indexes of vector or data frame.
Example 1:
In this example, let us create a vector and perform subsetting using the [ ] operator.
R
# Create vectorx <- 1:15 # Print vectorcat("Original vector: ", x, "\n") # Subsetting vectorcat("First 5 values of vector: ", x[1:5], "\n") cat("Without values present at index 1, 2 and 3: ", x[-c(1, 2, 3)], "\n")
Output:
Original vector: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
First 5 values of vector: 1 2 3 4 5
Without values present at index 1, 2 and 3: 4 5 6 7 8 9 10 11 12 13 14 15
Example 2:
In this example, let us use mtcars data frame present in R base package for subsetting.
R
# Datasetcat("Original dataset: \n")print(mtcars) # Subsetting data framecat("HP values of all cars:\n")print(mtcars['hp']) # First 10 carscat("Without mpg and cyl column:\n")print(mtcars[1:10, -c(1, 2)])
Output:
Original dataset:
mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4
Datsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1
Hornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1
Hornet Sportabout 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2
Valiant 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1
Duster 360 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4
Merc 240D 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2
Merc 230 22.8 4 140.8 95 3.92 3.150 22.90 1 0 4 2
Merc 280 19.2 6 167.6 123 3.92 3.440 18.30 1 0 4 4
Merc 280C 17.8 6 167.6 123 3.92 3.440 18.90 1 0 4 4
Merc 450SE 16.4 8 275.8 180 3.07 4.070 17.40 0 0 3 3
Merc 450SL 17.3 8 275.8 180 3.07 3.730 17.60 0 0 3 3
Merc 450SLC 15.2 8 275.8 180 3.07 3.780 18.00 0 0 3 3
Cadillac Fleetwood 10.4 8 472.0 205 2.93 5.250 17.98 0 0 3 4
Lincoln Continental 10.4 8 460.0 215 3.00 5.424 17.82 0 0 3 4
Chrysler Imperial 14.7 8 440.0 230 3.23 5.345 17.42 0 0 3 4
Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1
Honda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2
Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1
Toyota Corona 21.5 4 120.1 97 3.70 2.465 20.01 1 0 3 1
Dodge Challenger 15.5 8 318.0 150 2.76 3.520 16.87 0 0 3 2
AMC Javelin 15.2 8 304.0 150 3.15 3.435 17.30 0 0 3 2
Camaro Z28 13.3 8 350.0 245 3.73 3.840 15.41 0 0 3 4
Pontiac Firebird 19.2 8 400.0 175 3.08 3.845 17.05 0 0 3 2
Fiat X1-9 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1
Porsche 914-2 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2
Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2
Ford Pantera L 15.8 8 351.0 264 4.22 3.170 14.50 0 1 5 4
Ferrari Dino 19.7 6 145.0 175 3.62 2.770 15.50 0 1 5 6
Maserati Bora 15.0 8 301.0 335 3.54 3.570 14.60 0 1 5 8
Volvo 142E 21.4 4 121.0 109 4.11 2.780 18.60 1 1 4 2
HP values of all cars:
hp
Mazda RX4 110
Mazda RX4 Wag 110
Datsun 710 93
Hornet 4 Drive 110
Hornet Sportabout 175
Valiant 105
Duster 360 245
Merc 240D 62
Merc 230 95
Merc 280 123
Merc 280C 123
Merc 450SE 180
Merc 450SL 180
Merc 450SLC 180
Cadillac Fleetwood 205
Lincoln Continental 215
Chrysler Imperial 230
Fiat 128 66
Honda Civic 52
Toyota Corolla 65
Toyota Corona 97
Dodge Challenger 150
AMC Javelin 150
Camaro Z28 245
Pontiac Firebird 175
Fiat X1-9 66
Porsche 914-2 91
Lotus Europa 113
Ford Pantera L 264
Ferrari Dino 175
Maserati Bora 335
Volvo 142E 109
Without mpg and cyl column:
disp hp drat wt qsec vs am gear carb
Mazda RX4 160.0 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 160.0 110 3.90 2.875 17.02 0 1 4 4
Datsun 710 108.0 93 3.85 2.320 18.61 1 1 4 1
Hornet 4 Drive 258.0 110 3.08 3.215 19.44 1 0 3 1
Hornet Sportabout 360.0 175 3.15 3.440 17.02 0 0 3 2
Valiant 225.0 105 2.76 3.460 20.22 1 0 3 1
Duster 360 360.0 245 3.21 3.570 15.84 0 0 3 4
Merc 240D 146.7 62 3.69 3.190 20.00 1 0 4 2
Merc 230 140.8 95 3.92 3.150 22.90 1 0 4 2
Merc 280 167.6 123 3.92 3.440 18.30 1 0 4 4
[[ ]] operator is used for subsetting of list-objects. This operator is the same as [ ] operator but the only difference is that [[ ]] selects only one element whereas [ ] operator can select more than 1 element in a single command.
Example 1: In this example, let us create a list and select the elements using [[]] operator.
R
# Create listls <- list(a = 1, b = 2, c = 10, d = 20) # Print listcat("Original List: \n")print(ls) # Select first element of listcat("First element of list: ", ls[[1]], "\n")
Output:
Original List:
$a
[1] 1
$b
[1] 2
$c
[1] 10
$d
[1] 20
First element of list: 1
Example 2: In this example, let us create a list and recursively select elements using c() function.
R
# Create listz <- list(a = list(x = 1, y = "GFG"), b = 1:10) # Print listcat("Original list:\n")print(z) # Print GFG using c() functioncat("Using c() function:\n")print(z[[c(1, 2)]]) # Print GFG using only [[]] operatorcat("Using [[]] operator:\n")print(z[[1]][[2]])
Output:
Original list:
$a
$a$x
[1] 1
$a$y
[1] "GFG"
$b
[1] 1 2 3 4 5 6 7 8 9 10
Using c() function:
[1] "GFG"
Using [[]] operator:
[1] "GFG"
$ operator can be used for lists and data frames in R. Unlike [ ] operator, it selects only a single observation at a time. It can be used to access an element in named list or a column in data frame. $ operator is only applicable for recursive objects or list-like objects.
Example 1: In this example, let us create a named list and access the elements using $ operator
R
# Create listls <- list(a = 1, b = 2, c = "Hello", d = "GFG") # Print listcat("Original list:\n")print(ls) # Print "GFG" using $ operatorcat("Using $ operator:\n")print(ls$d)
Output:
Original list:
$a
[1] 1
$b
[1] 2
$c
[1] "Hello"
$d
[1] "GFG"
Using $ operator:
[1] "GFG"
Example 2: In this example, let us use the mtcars dataframe and select a particular column using $ operator.
R
# Datasetcat("Original data frame:\n")print(mtcars) # Access hp columncat("Using $ operator:\n")print(mtcars$hp)
Output:
Original data frame:
mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4
Datsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1
Hornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1
Hornet Sportabout 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2
Valiant 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1
Duster 360 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4
Merc 240D 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2
Merc 230 22.8 4 140.8 95 3.92 3.150 22.90 1 0 4 2
Merc 280 19.2 6 167.6 123 3.92 3.440 18.30 1 0 4 4
Merc 280C 17.8 6 167.6 123 3.92 3.440 18.90 1 0 4 4
Merc 450SE 16.4 8 275.8 180 3.07 4.070 17.40 0 0 3 3
Merc 450SL 17.3 8 275.8 180 3.07 3.730 17.60 0 0 3 3
Merc 450SLC 15.2 8 275.8 180 3.07 3.780 18.00 0 0 3 3
Cadillac Fleetwood 10.4 8 472.0 205 2.93 5.250 17.98 0 0 3 4
Lincoln Continental 10.4 8 460.0 215 3.00 5.424 17.82 0 0 3 4
Chrysler Imperial 14.7 8 440.0 230 3.23 5.345 17.42 0 0 3 4
Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1
Honda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2
Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1
Toyota Corona 21.5 4 120.1 97 3.70 2.465 20.01 1 0 3 1
Dodge Challenger 15.5 8 318.0 150 2.76 3.520 16.87 0 0 3 2
AMC Javelin 15.2 8 304.0 150 3.15 3.435 17.30 0 0 3 2
Camaro Z28 13.3 8 350.0 245 3.73 3.840 15.41 0 0 3 4
Pontiac Firebird 19.2 8 400.0 175 3.08 3.845 17.05 0 0 3 2
Fiat X1-9 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1
Porsche 914-2 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2
Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2
Ford Pantera L 15.8 8 351.0 264 4.22 3.170 14.50 0 1 5 4
Ferrari Dino 19.7 6 145.0 175 3.62 2.770 15.50 0 1 5 6
Maserati Bora 15.0 8 301.0 335 3.54 3.570 14.60 0 1 5 8
Volvo 142E 21.4 4 121.0 109 4.11 2.780 18.60 1 1 4 2
Using $ operator:
[1] 110 110 93 110 175 105 245 62 95 123 123 180 180 180 205 215 230 66 52
[20] 65 97 150 150 245 175 66 91 113 264 175 335 109
subset() function in R programming is used to create a subset of vectors, matrices, or data frames based on the conditions provided in the parameters.
Syntax: subset(x, subset, select)
Parameters:
x: indicates the object
subset: indicates the logical expression on the basis of which subsetting has to be done
select: indicates columns to select
Example 1: In this example, let us use airquality data frame present in R base package and select Month where Temp < 65.
R
# Subsettingairq <- subset(airquality, Temp < 65, select = c(Month)) # Print subsetprint(airq)
Output:
Month
4 5
5 5
8 5
9 5
15 5
16 5
18 5
20 5
21 5
23 5
24 5
25 5
26 5
27 5
144 9
148 9
Example 2: In this example, let us use mtcars data frame present in R base package and selects the car with 5 gears and hp > 200.
R
# Subsettingmtc <- subset(mtcars, gear == 5 & hp > 200, select = c(gear, hp)) # Print subsetprint(mtc)
Output:
gear hp
Ford Pantera L 5 264
Maserati Bora 5 335
kumar_satyam
R-DataFrame
R-Objects
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
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 import an Excel File into R ?
How to filter R dataframe by multiple conditions?
Replace Specific Characters in String in R
Time Series Analysis in R
R - if statement
|
[
{
"code": null,
"e": 25242,
"s": 25214,
"text": "\n08 Nov, 2021"
},
{
"code": null,
"e": 25830,
"s": 25242,
"text": "In R Programming Language, subsetting allows the user to access elements from an object. It takes out a portion from the object based on the condition provided. There are 4 ways of subsetting in R programming. Each of the methods depends on the usability of the user and the type of object. For example, if there is a dataframe with many columns such as states, country, and population and suppose the user wants to extract states from it, then subsetting is used to do this operation. In this article, let us discuss the implementation of different types of subsetting in R programming."
},
{
"code": null,
"e": 26018,
"s": 25830,
"text": "Using the ‘[ ]’ operator, elements of vectors and observations from data frames can be accessed. To neglect some indexes, ‘-‘ is used to access all other indexes of vector or data frame. "
},
{
"code": null,
"e": 26031,
"s": 26018,
"text": "Example 1: "
},
{
"code": null,
"e": 26119,
"s": 26031,
"text": "In this example, let us create a vector and perform subsetting using the [ ] operator. "
},
{
"code": null,
"e": 26121,
"s": 26119,
"text": "R"
},
{
"code": "# Create vectorx <- 1:15 # Print vectorcat(\"Original vector: \", x, \"\\n\") # Subsetting vectorcat(\"First 5 values of vector: \", x[1:5], \"\\n\") cat(\"Without values present at index 1, 2 and 3: \", x[-c(1, 2, 3)], \"\\n\")",
"e": 26364,
"s": 26121,
"text": null
},
{
"code": null,
"e": 26373,
"s": 26364,
"text": "Output: "
},
{
"code": null,
"e": 26540,
"s": 26373,
"text": "Original vector: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 \nFirst 5 values of vector: 1 2 3 4 5\nWithout values present at index 1, 2 and 3: 4 5 6 7 8 9 10 11 12 13 14 15"
},
{
"code": null,
"e": 26552,
"s": 26540,
"text": "Example 2: "
},
{
"code": null,
"e": 26641,
"s": 26552,
"text": "In this example, let us use mtcars data frame present in R base package for subsetting. "
},
{
"code": null,
"e": 26643,
"s": 26641,
"text": "R"
},
{
"code": "# Datasetcat(\"Original dataset: \\n\")print(mtcars) # Subsetting data framecat(\"HP values of all cars:\\n\")print(mtcars['hp']) # First 10 carscat(\"Without mpg and cyl column:\\n\")print(mtcars[1:10, -c(1, 2)])",
"e": 26848,
"s": 26643,
"text": null
},
{
"code": null,
"e": 26857,
"s": 26848,
"text": "Output: "
},
{
"code": null,
"e": 30767,
"s": 26857,
"text": "Original dataset:\n mpg cyl disp hp drat wt qsec vs am gear carb\nMazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4\nMazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4\nDatsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1\nHornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1\nHornet Sportabout 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2\nValiant 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1\nDuster 360 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4\nMerc 240D 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2\nMerc 230 22.8 4 140.8 95 3.92 3.150 22.90 1 0 4 2\nMerc 280 19.2 6 167.6 123 3.92 3.440 18.30 1 0 4 4\nMerc 280C 17.8 6 167.6 123 3.92 3.440 18.90 1 0 4 4\nMerc 450SE 16.4 8 275.8 180 3.07 4.070 17.40 0 0 3 3\nMerc 450SL 17.3 8 275.8 180 3.07 3.730 17.60 0 0 3 3\nMerc 450SLC 15.2 8 275.8 180 3.07 3.780 18.00 0 0 3 3\nCadillac Fleetwood 10.4 8 472.0 205 2.93 5.250 17.98 0 0 3 4\nLincoln Continental 10.4 8 460.0 215 3.00 5.424 17.82 0 0 3 4\nChrysler Imperial 14.7 8 440.0 230 3.23 5.345 17.42 0 0 3 4\nFiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1\nHonda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2\nToyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1\nToyota Corona 21.5 4 120.1 97 3.70 2.465 20.01 1 0 3 1\nDodge Challenger 15.5 8 318.0 150 2.76 3.520 16.87 0 0 3 2\nAMC Javelin 15.2 8 304.0 150 3.15 3.435 17.30 0 0 3 2\nCamaro Z28 13.3 8 350.0 245 3.73 3.840 15.41 0 0 3 4\nPontiac Firebird 19.2 8 400.0 175 3.08 3.845 17.05 0 0 3 2\nFiat X1-9 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1\nPorsche 914-2 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2\nLotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2\nFord Pantera L 15.8 8 351.0 264 4.22 3.170 14.50 0 1 5 4\nFerrari Dino 19.7 6 145.0 175 3.62 2.770 15.50 0 1 5 6\nMaserati Bora 15.0 8 301.0 335 3.54 3.570 14.60 0 1 5 8\nVolvo 142E 21.4 4 121.0 109 4.11 2.780 18.60 1 1 4 2\n\nHP values of all cars:\n hp\nMazda RX4 110\nMazda RX4 Wag 110\nDatsun 710 93\nHornet 4 Drive 110\nHornet Sportabout 175\nValiant 105\nDuster 360 245\nMerc 240D 62\nMerc 230 95\nMerc 280 123\nMerc 280C 123\nMerc 450SE 180\nMerc 450SL 180\nMerc 450SLC 180\nCadillac Fleetwood 205\nLincoln Continental 215\nChrysler Imperial 230\nFiat 128 66\nHonda Civic 52\nToyota Corolla 65\nToyota Corona 97\nDodge Challenger 150\nAMC Javelin 150\nCamaro Z28 245\nPontiac Firebird 175\nFiat X1-9 66\nPorsche 914-2 91\nLotus Europa 113\nFord Pantera L 264\nFerrari Dino 175\nMaserati Bora 335\nVolvo 142E 109\n\nWithout mpg and cyl column:\n disp hp drat wt qsec vs am gear carb\nMazda RX4 160.0 110 3.90 2.620 16.46 0 1 4 4\nMazda RX4 Wag 160.0 110 3.90 2.875 17.02 0 1 4 4\nDatsun 710 108.0 93 3.85 2.320 18.61 1 1 4 1\nHornet 4 Drive 258.0 110 3.08 3.215 19.44 1 0 3 1\nHornet Sportabout 360.0 175 3.15 3.440 17.02 0 0 3 2\nValiant 225.0 105 2.76 3.460 20.22 1 0 3 1\nDuster 360 360.0 245 3.21 3.570 15.84 0 0 3 4\nMerc 240D 146.7 62 3.69 3.190 20.00 1 0 4 2\nMerc 230 140.8 95 3.92 3.150 22.90 1 0 4 2\nMerc 280 167.6 123 3.92 3.440 18.30 1 0 4 4"
},
{
"code": null,
"e": 31001,
"s": 30767,
"text": "[[ ]] operator is used for subsetting of list-objects. This operator is the same as [ ] operator but the only difference is that [[ ]] selects only one element whereas [ ] operator can select more than 1 element in a single command. "
},
{
"code": null,
"e": 31096,
"s": 31001,
"text": "Example 1: In this example, let us create a list and select the elements using [[]] operator. "
},
{
"code": null,
"e": 31098,
"s": 31096,
"text": "R"
},
{
"code": "# Create listls <- list(a = 1, b = 2, c = 10, d = 20) # Print listcat(\"Original List: \\n\")print(ls) # Select first element of listcat(\"First element of list: \", ls[[1]], \"\\n\")",
"e": 31274,
"s": 31098,
"text": null
},
{
"code": null,
"e": 31283,
"s": 31274,
"text": "Output: "
},
{
"code": null,
"e": 31367,
"s": 31283,
"text": "Original List:\n$a\n[1] 1\n\n$b\n[1] 2\n\n$c\n[1] 10\n\n$d\n[1] 20\n\nFirst element of list: 1 "
},
{
"code": null,
"e": 31469,
"s": 31367,
"text": "Example 2: In this example, let us create a list and recursively select elements using c() function. "
},
{
"code": null,
"e": 31471,
"s": 31469,
"text": "R"
},
{
"code": "# Create listz <- list(a = list(x = 1, y = \"GFG\"), b = 1:10) # Print listcat(\"Original list:\\n\")print(z) # Print GFG using c() functioncat(\"Using c() function:\\n\")print(z[[c(1, 2)]]) # Print GFG using only [[]] operatorcat(\"Using [[]] operator:\\n\")print(z[[1]][[2]])",
"e": 31738,
"s": 31471,
"text": null
},
{
"code": null,
"e": 31747,
"s": 31738,
"text": "Output: "
},
{
"code": null,
"e": 31895,
"s": 31747,
"text": "Original list:\n$a\n$a$x\n[1] 1\n\n$a$y\n[1] \"GFG\"\n\n\n$b\n [1] 1 2 3 4 5 6 7 8 9 10\n\nUsing c() function:\n[1] \"GFG\"\n\nUsing [[]] operator:\n[1] \"GFG\""
},
{
"code": null,
"e": 32171,
"s": 31895,
"text": "$ operator can be used for lists and data frames in R. Unlike [ ] operator, it selects only a single observation at a time. It can be used to access an element in named list or a column in data frame. $ operator is only applicable for recursive objects or list-like objects. "
},
{
"code": null,
"e": 32268,
"s": 32171,
"text": "Example 1: In this example, let us create a named list and access the elements using $ operator "
},
{
"code": null,
"e": 32270,
"s": 32268,
"text": "R"
},
{
"code": "# Create listls <- list(a = 1, b = 2, c = \"Hello\", d = \"GFG\") # Print listcat(\"Original list:\\n\")print(ls) # Print \"GFG\" using $ operatorcat(\"Using $ operator:\\n\")print(ls$d)",
"e": 32445,
"s": 32270,
"text": null
},
{
"code": null,
"e": 32454,
"s": 32445,
"text": "Output: "
},
{
"code": null,
"e": 32547,
"s": 32454,
"text": "Original list:\n$a\n[1] 1\n\n$b\n[1] 2\n\n$c\n[1] \"Hello\"\n\n$d\n[1] \"GFG\"\n\nUsing $ operator:\n[1] \"GFG\""
},
{
"code": null,
"e": 32657,
"s": 32547,
"text": "Example 2: In this example, let us use the mtcars dataframe and select a particular column using $ operator. "
},
{
"code": null,
"e": 32659,
"s": 32657,
"text": "R"
},
{
"code": "# Datasetcat(\"Original data frame:\\n\")print(mtcars) # Access hp columncat(\"Using $ operator:\\n\")print(mtcars$hp)",
"e": 32772,
"s": 32659,
"text": null
},
{
"code": null,
"e": 32781,
"s": 32772,
"text": "Output: "
},
{
"code": null,
"e": 35334,
"s": 32781,
"text": "Original data frame:\n mpg cyl disp hp drat wt qsec vs am gear carb\nMazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4\nMazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4\nDatsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1\nHornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1\nHornet Sportabout 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2\nValiant 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1\nDuster 360 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4\nMerc 240D 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2\nMerc 230 22.8 4 140.8 95 3.92 3.150 22.90 1 0 4 2\nMerc 280 19.2 6 167.6 123 3.92 3.440 18.30 1 0 4 4\nMerc 280C 17.8 6 167.6 123 3.92 3.440 18.90 1 0 4 4\nMerc 450SE 16.4 8 275.8 180 3.07 4.070 17.40 0 0 3 3\nMerc 450SL 17.3 8 275.8 180 3.07 3.730 17.60 0 0 3 3\nMerc 450SLC 15.2 8 275.8 180 3.07 3.780 18.00 0 0 3 3\nCadillac Fleetwood 10.4 8 472.0 205 2.93 5.250 17.98 0 0 3 4\nLincoln Continental 10.4 8 460.0 215 3.00 5.424 17.82 0 0 3 4\nChrysler Imperial 14.7 8 440.0 230 3.23 5.345 17.42 0 0 3 4\nFiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1\nHonda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2\nToyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1\nToyota Corona 21.5 4 120.1 97 3.70 2.465 20.01 1 0 3 1\nDodge Challenger 15.5 8 318.0 150 2.76 3.520 16.87 0 0 3 2\nAMC Javelin 15.2 8 304.0 150 3.15 3.435 17.30 0 0 3 2\nCamaro Z28 13.3 8 350.0 245 3.73 3.840 15.41 0 0 3 4\nPontiac Firebird 19.2 8 400.0 175 3.08 3.845 17.05 0 0 3 2\nFiat X1-9 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1\nPorsche 914-2 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2\nLotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2\nFord Pantera L 15.8 8 351.0 264 4.22 3.170 14.50 0 1 5 4\nFerrari Dino 19.7 6 145.0 175 3.62 2.770 15.50 0 1 5 6\nMaserati Bora 15.0 8 301.0 335 3.54 3.570 14.60 0 1 5 8\nVolvo 142E 21.4 4 121.0 109 4.11 2.780 18.60 1 1 4 2\n\nUsing $ operator:\n[1] 110 110 93 110 175 105 245 62 95 123 123 180 180 180 205 215 230 66 52\n[20] 65 97 150 150 245 175 66 91 113 264 175 335 109"
},
{
"code": null,
"e": 35486,
"s": 35334,
"text": "subset() function in R programming is used to create a subset of vectors, matrices, or data frames based on the conditions provided in the parameters. "
},
{
"code": null,
"e": 35520,
"s": 35486,
"text": "Syntax: subset(x, subset, select)"
},
{
"code": null,
"e": 35533,
"s": 35520,
"text": "Parameters: "
},
{
"code": null,
"e": 35557,
"s": 35533,
"text": "x: indicates the object"
},
{
"code": null,
"e": 35646,
"s": 35557,
"text": "subset: indicates the logical expression on the basis of which subsetting has to be done"
},
{
"code": null,
"e": 35682,
"s": 35646,
"text": "select: indicates columns to select"
},
{
"code": null,
"e": 35804,
"s": 35682,
"text": "Example 1: In this example, let us use airquality data frame present in R base package and select Month where Temp < 65. "
},
{
"code": null,
"e": 35806,
"s": 35804,
"text": "R"
},
{
"code": "# Subsettingairq <- subset(airquality, Temp < 65, select = c(Month)) # Print subsetprint(airq)",
"e": 35918,
"s": 35806,
"text": null
},
{
"code": null,
"e": 35927,
"s": 35918,
"text": "Output: "
},
{
"code": null,
"e": 36097,
"s": 35927,
"text": " Month\n4 5\n5 5\n8 5\n9 5\n15 5\n16 5\n18 5\n20 5\n21 5\n23 5\n24 5\n25 5\n26 5\n27 5\n144 9\n148 9"
},
{
"code": null,
"e": 36228,
"s": 36097,
"text": "Example 2: In this example, let us use mtcars data frame present in R base package and selects the car with 5 gears and hp > 200. "
},
{
"code": null,
"e": 36230,
"s": 36228,
"text": "R"
},
{
"code": "# Subsettingmtc <- subset(mtcars, gear == 5 & hp > 200, select = c(gear, hp)) # Print subsetprint(mtc)",
"e": 36354,
"s": 36230,
"text": null
},
{
"code": null,
"e": 36363,
"s": 36354,
"text": "Output: "
},
{
"code": null,
"e": 36435,
"s": 36363,
"text": " gear hp\nFord Pantera L 5 264\nMaserati Bora 5 335"
},
{
"code": null,
"e": 36448,
"s": 36435,
"text": "kumar_satyam"
},
{
"code": null,
"e": 36460,
"s": 36448,
"text": "R-DataFrame"
},
{
"code": null,
"e": 36470,
"s": 36460,
"text": "R-Objects"
},
{
"code": null,
"e": 36481,
"s": 36470,
"text": "R Language"
},
{
"code": null,
"e": 36579,
"s": 36481,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36631,
"s": 36579,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 36669,
"s": 36631,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 36704,
"s": 36669,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 36762,
"s": 36704,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 36811,
"s": 36762,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 36848,
"s": 36811,
"text": "How to import an Excel File into R ?"
},
{
"code": null,
"e": 36898,
"s": 36848,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 36941,
"s": 36898,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 36967,
"s": 36941,
"text": "Time Series Analysis in R"
}
] |
Perl stat Function
|
This function returns a 13-element array giving the status info for a file, specified by either FILEHANDLE, EXPR, or $_. The list of values returned is shown below in Table. If used in a scalar context, returns 0 on failure, 1 on success.
Note that support for some of these elements is system dependent. Check the documentation for a complete list.
Element Description
0 Device number of file system
1 Inode number
2 File mode (type and permissions)
3 Number of (hard) links to the file
4 Numeric user ID of file.s owner
5 Numeric group ID of file.s owner
6 The device identifier (special files only)
7 File size, in bytes
8 Last access time since the epoch
9 Last modify time since the epoch
10 Inode change time (not creation time!) since the epoch
11 Preferred block size for file system I/O
12 Actual number of blocks allocated
Following is the simple syntax for this function −
stat FILEHANDLE
stat EXPR
stat
This function returns ARRAY, ($device, $inode, $mode, $nlink, $uid, $gid, $rdev, $size, $atime, $mtime, $ctime, $blksize, $blocks)
Following is the example code showing its basic usage −
#!/usr/bin/perl -w
($device, $inode, $mode, $nlink, $uid, $gid, $rdev, $size, $atime, $mtime,
$ctime, $blksize, $blocks) = stat("/etc/passwd");
print("stat() $device, $inode, $ctime\n");
When above code is executed, it produces the following result −
stat() 2065, 5374250, 1508051555
46 Lectures
4.5 hours
Devi Killada
11 Lectures
1.5 hours
Harshit Srivastava
30 Lectures
6 hours
TELCOMA Global
24 Lectures
2 hours
Mohammad Nauman
68 Lectures
7 hours
Stone River ELearning
58 Lectures
6.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2459,
"s": 2220,
"text": "This function returns a 13-element array giving the status info for a file, specified by either FILEHANDLE, EXPR, or $_. The list of values returned is shown below in Table. If used in a scalar context, returns 0 on failure, 1 on success."
},
{
"code": null,
"e": 2570,
"s": 2459,
"text": "Note that support for some of these elements is system dependent. Check the documentation for a complete list."
},
{
"code": null,
"e": 3066,
"s": 2570,
"text": "Element Description\n0 \tDevice number of file system\n1 \tInode number\n2 \tFile mode (type and permissions)\n3 \tNumber of (hard) links to the file\n4 \tNumeric user ID of file.s owner\n5 \tNumeric group ID of file.s owner\n6 \tThe device identifier (special files only)\n7 \tFile size, in bytes\n8 \tLast access time since the epoch\n9 \tLast modify time since the epoch\n10 \tInode change time (not creation time!) since the epoch\n11 \tPreferred block size for file system I/O\n12\tActual number of blocks allocated\n"
},
{
"code": null,
"e": 3117,
"s": 3066,
"text": "Following is the simple syntax for this function −"
},
{
"code": null,
"e": 3151,
"s": 3117,
"text": "stat FILEHANDLE\n\nstat EXPR\n\nstat\n"
},
{
"code": null,
"e": 3282,
"s": 3151,
"text": "This function returns ARRAY, ($device, $inode, $mode, $nlink, $uid, $gid, $rdev, $size, $atime, $mtime, $ctime, $blksize, $blocks)"
},
{
"code": null,
"e": 3338,
"s": 3282,
"text": "Following is the example code showing its basic usage −"
},
{
"code": null,
"e": 3530,
"s": 3338,
"text": "#!/usr/bin/perl -w\n\n($device, $inode, $mode, $nlink, $uid, $gid, $rdev, $size, $atime, $mtime,\n $ctime, $blksize, $blocks) = stat(\"/etc/passwd\");\n\nprint(\"stat() $device, $inode, $ctime\\n\");"
},
{
"code": null,
"e": 3594,
"s": 3530,
"text": "When above code is executed, it produces the following result −"
},
{
"code": null,
"e": 3628,
"s": 3594,
"text": "stat() 2065, 5374250, 1508051555\n"
},
{
"code": null,
"e": 3663,
"s": 3628,
"text": "\n 46 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3677,
"s": 3663,
"text": " Devi Killada"
},
{
"code": null,
"e": 3712,
"s": 3677,
"text": "\n 11 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3732,
"s": 3712,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 3765,
"s": 3732,
"text": "\n 30 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3781,
"s": 3765,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 3814,
"s": 3781,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3831,
"s": 3814,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 3864,
"s": 3831,
"text": "\n 68 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3887,
"s": 3864,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 3922,
"s": 3887,
"text": "\n 58 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3945,
"s": 3922,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 3952,
"s": 3945,
"text": " Print"
},
{
"code": null,
"e": 3963,
"s": 3952,
"text": " Add Notes"
}
] |
How to Build a Bitcoin Tracker Android App? - GeeksforGeeks
|
09 Feb, 2021
In this article, we will be building a Bitcoin Tracker App Project using Java and XML in Android. The application will display the current rates of Bitcoin in different countries using Bitcoin API. There are many free APIs available and for this project, we will be using API by Coinlayer. The API will return a JSON that we will parse according to our needs. There will be a single activity in this app. A sample GIF is given below to get an idea about what we are going to do in this article.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Before going to the coding section first you have to do some pre-task
Permission: Add internet permission in the AndroidManifest.xml file
<uses-permission android:name=”android.permission.INTERNET”/>
Change the style to NoActionBar in the themes.xml file:
<style name=”AppTheme” parent=”Theme.AppCompat.NoActionBar”>
Get the API key: You need to create a free account on Coinlayer and get an API key for this project.
Add dependency:
We need to add this dependency in the app gradle file to make HTTP requests
implementation ‘com.loopj.android:android-async-http:1.4.9’
Add Currency list in string.xml:
We need to add the list of all currencies in the strings.xml. From here we will display it in the activity to the users. Add the below code in the strings.xml file.
XML
<resources> <string name="app_name">Am I Rich?</string> <string name="label_default_text">304.74</string> <string name="label_error_text">Error</string> <string name="base">Base Currency</string> <string name="imageview_desc">Bitcoin Logo</string> <string-array name="currency_array"> <item>AUD</item> <item>BRL</item> <item>CAD</item> <item>CNY</item> <item>EUR</item> <item>GBP</item> <item>HKD</item> <item>JPY</item> <item>PLN</item> <item>RUB</item> <item>SEK</item> <item>USD</item> <item>ZAR</item> </string-array> </resources>
Step 3: Working with the activity_main.xml file
The XML codes are used to build the structure of the activity as well as its styling part. It contains an ImageView at the very top of the activity to display the logo of the app. Then it contains a TextView to display the bitcoin rate in the center of the activity. At last, we have a Spinner at the bottom of the activity to display the list of currencies from which the user can choose. This is a single activity application. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/bkgndColour" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context="com.example.bitcointracker.MainActivity"> <TextView android:id="@+id/priceLabel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:text="@string/label_default_text" android:textColor="@color/fontColour" android:textSize="45sp" android:textStyle="bold" /> <ImageView android:id="@+id/logoImage" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:contentDescription="@string/imageview_desc" android:src="@drawable/bitcoin_image" /> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@+id/priceLabel" android:gravity="center_vertical|center_horizontal" android:orientation="horizontal"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:text="@string/base" android:textAppearance="?android:attr/textAppearanceLarge" android:textSize="30sp" android:textStyle="bold" /> <Spinner android:id="@+id/currency_spinner" android:layout_width="wrap_content" android:layout_height="wrap_content" android:dropDownSelector="@color/fontColour" android:gravity="center_horizontal" android:spinnerMode="dropdown" /> </LinearLayout> </RelativeLayout>
Step 4: Create new layout resource files
For the spinner to display the list we also need to create a spinner item’s XML layout as well as its item’s layout for the adapter. Add the below codes in app> res > layout > spinner_dropdown_item.xml.
XML
<?xml version="1.0" encoding="utf-8"?><CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/text1" style="?android:attr/spinnerDropDownItemStyle" android:layout_width="match_parent" android:layout_height="?android:attr/listPreferredItemHeight" android:background="@drawable/color_selector" android:ellipsize="marquee" android:paddingLeft="10dp" android:paddingRight="10dp" android:singleLine="true" android:text="@string/label_error_text" android:textColor="@color/black" android:textSize="30sp" />
spinner_item.xml file:
XML
<?xml version="1.0" encoding="utf-8"?><TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="start" android:padding="10dip" android:text="@string/label_error_text" android:textColor="@color/black" android:textSize="30sp" android:textStyle="bold" />
Step 5: Working with the MainActivity.java file
In the java file, we will create a function that will make HTTP requests from the URL. The URL will be consisting of the API key the base URL and the target currency code. First, we will create an adapter for the list of all the currencies and set it to the Spinner view in the main activity. Then we will call the function onItemSelectedListener and get the selected currency code. We will add this code to the URL along with its other parts. Then we will call the function that makes HTTP requests to get a JSON. We will parse the JSON object to get the required rate of the bitcoin of the selected currency. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.AdapterView;import android.widget.AdapterView.OnItemSelectedListener;import android.widget.ArrayAdapter;import android.widget.Spinner;import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import com.loopj.android.http.AsyncHttpClient;import com.loopj.android.http.JsonHttpResponseHandler; import org.json.JSONException;import org.json.JSONObject; import java.io.IOException; import cz.msebera.android.httpclient.Header; public class MainActivity extends AppCompatActivity { // Constants: // TODO: Create the base URL private final String BASE_URL = "http://api.coinlayer.com/live?access_key="; // Member Variables: TextView mPriceTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mPriceTextView = (TextView) findViewById(R.id.priceLabel); Spinner spinner = (Spinner) findViewById(R.id.currency_spinner); // Create an ArrayAdapter using the String array and a spinner layout final ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.currency_array, R.layout.spinner_item); // Specify the layout to use when the list of choices appears adapter.setDropDownViewResource(R.layout.spinner_dropdown_item); // Apply the adapter to the spinner spinner.setAdapter(adapter); // TODO: Set an OnItemSelected listener on the spinner spinner.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { String publicKey = "cd9ebbd0c5c20340b9d638e409f41fb1"; String finalUrl = BASE_URL + publicKey + "&TARGET=" + adapterView.getItemAtPosition(i) + "&symbols=BTC"; Log.d("Clima", "Request fail! Status code: " + finalUrl); try { letsDoSomeNetworking(finalUrl); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); } // TODO: complete the letsDoSomeNetworking() method private void letsDoSomeNetworking(String url) throws IOException, JSONException { AsyncHttpClient client = new AsyncHttpClient(); client.get(url, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { // called when response HTTP status is "200 OK" Log.d("Clima", "JSON: " + response.toString()); try { JSONObject price = response.getJSONObject("rates"); String object = price.getString("BTC"); mPriceTextView.setText(object); } catch (JSONException E) { E.printStackTrace(); } } @Override public void onFailure(int statusCode, Header[] headers, Throwable e, JSONObject response) { // called when response HTTP status is "4XX" (eg. 401, 403, 404) Log.d("Clima", "Request fail! Status code: " + statusCode); Log.d("Clima", "Fail response: " + response); Log.e("ERROR", e.toString()); } }); }}
GitHub Link: https://github.com/namanjha007/BitcoinTracker
android
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
Android Listview in Java with Example
Retrofit with Kotlin Coroutine in Android
How to Change the Background Color After Clicking the Button in Android?
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Reverse a string in Java
|
[
{
"code": null,
"e": 25142,
"s": 25114,
"text": "\n09 Feb, 2021"
},
{
"code": null,
"e": 25638,
"s": 25142,
"text": "In this article, we will be building a Bitcoin Tracker App Project using Java and XML in Android. The application will display the current rates of Bitcoin in different countries using Bitcoin API. There are many free APIs available and for this project, we will be using API by Coinlayer. The API will return a JSON that we will parse according to our needs. There will be a single activity in this app. A sample GIF is given below to get an idea about what we are going to do in this article. "
},
{
"code": null,
"e": 25667,
"s": 25638,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 25829,
"s": 25667,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 25907,
"s": 25829,
"text": "Step 2: Before going to the coding section first you have to do some pre-task"
},
{
"code": null,
"e": 25975,
"s": 25907,
"text": "Permission: Add internet permission in the AndroidManifest.xml file"
},
{
"code": null,
"e": 26037,
"s": 25975,
"text": "<uses-permission android:name=”android.permission.INTERNET”/>"
},
{
"code": null,
"e": 26094,
"s": 26037,
"text": "Change the style to NoActionBar in the themes.xml file: "
},
{
"code": null,
"e": 26155,
"s": 26094,
"text": "<style name=”AppTheme” parent=”Theme.AppCompat.NoActionBar”>"
},
{
"code": null,
"e": 26256,
"s": 26155,
"text": "Get the API key: You need to create a free account on Coinlayer and get an API key for this project."
},
{
"code": null,
"e": 26273,
"s": 26256,
"text": "Add dependency: "
},
{
"code": null,
"e": 26349,
"s": 26273,
"text": "We need to add this dependency in the app gradle file to make HTTP requests"
},
{
"code": null,
"e": 26409,
"s": 26349,
"text": "implementation ‘com.loopj.android:android-async-http:1.4.9’"
},
{
"code": null,
"e": 26442,
"s": 26409,
"text": "Add Currency list in string.xml:"
},
{
"code": null,
"e": 26607,
"s": 26442,
"text": "We need to add the list of all currencies in the strings.xml. From here we will display it in the activity to the users. Add the below code in the strings.xml file."
},
{
"code": null,
"e": 26611,
"s": 26607,
"text": "XML"
},
{
"code": "<resources> <string name=\"app_name\">Am I Rich?</string> <string name=\"label_default_text\">304.74</string> <string name=\"label_error_text\">Error</string> <string name=\"base\">Base Currency</string> <string name=\"imageview_desc\">Bitcoin Logo</string> <string-array name=\"currency_array\"> <item>AUD</item> <item>BRL</item> <item>CAD</item> <item>CNY</item> <item>EUR</item> <item>GBP</item> <item>HKD</item> <item>JPY</item> <item>PLN</item> <item>RUB</item> <item>SEK</item> <item>USD</item> <item>ZAR</item> </string-array> </resources>",
"e": 27265,
"s": 26611,
"text": null
},
{
"code": null,
"e": 27313,
"s": 27265,
"text": "Step 3: Working with the activity_main.xml file"
},
{
"code": null,
"e": 27792,
"s": 27313,
"text": "The XML codes are used to build the structure of the activity as well as its styling part. It contains an ImageView at the very top of the activity to display the logo of the app. Then it contains a TextView to display the bitcoin rate in the center of the activity. At last, we have a Spinner at the bottom of the activity to display the list of currencies from which the user can choose. This is a single activity application. Below is the code for the activity_main.xml file."
},
{
"code": null,
"e": 27796,
"s": 27792,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"@color/bkgndColour\" android:paddingLeft=\"@dimen/activity_horizontal_margin\" android:paddingTop=\"@dimen/activity_vertical_margin\" android:paddingRight=\"@dimen/activity_horizontal_margin\" android:paddingBottom=\"@dimen/activity_vertical_margin\" tools:context=\"com.example.bitcointracker.MainActivity\"> <TextView android:id=\"@+id/priceLabel\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerHorizontal=\"true\" android:layout_centerVertical=\"true\" android:text=\"@string/label_default_text\" android:textColor=\"@color/fontColour\" android:textSize=\"45sp\" android:textStyle=\"bold\" /> <ImageView android:id=\"@+id/logoImage\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignParentTop=\"true\" android:layout_centerHorizontal=\"true\" android:contentDescription=\"@string/imageview_desc\" android:src=\"@drawable/bitcoin_image\" /> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_below=\"@+id/priceLabel\" android:gravity=\"center_vertical|center_horizontal\" android:orientation=\"horizontal\"> <TextView android:id=\"@+id/textView\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center_vertical\" android:layout_marginLeft=\"10dp\" android:layout_marginRight=\"10dp\" android:text=\"@string/base\" android:textAppearance=\"?android:attr/textAppearanceLarge\" android:textSize=\"30sp\" android:textStyle=\"bold\" /> <Spinner android:id=\"@+id/currency_spinner\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:dropDownSelector=\"@color/fontColour\" android:gravity=\"center_horizontal\" android:spinnerMode=\"dropdown\" /> </LinearLayout> </RelativeLayout>",
"e": 30185,
"s": 27796,
"text": null
},
{
"code": null,
"e": 30226,
"s": 30185,
"text": "Step 4: Create new layout resource files"
},
{
"code": null,
"e": 30429,
"s": 30226,
"text": "For the spinner to display the list we also need to create a spinner item’s XML layout as well as its item’s layout for the adapter. Add the below codes in app> res > layout > spinner_dropdown_item.xml."
},
{
"code": null,
"e": 30433,
"s": 30429,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><CheckedTextView xmlns:android=\"http://schemas.android.com/apk/res/android\" android:id=\"@android:id/text1\" style=\"?android:attr/spinnerDropDownItemStyle\" android:layout_width=\"match_parent\" android:layout_height=\"?android:attr/listPreferredItemHeight\" android:background=\"@drawable/color_selector\" android:ellipsize=\"marquee\" android:paddingLeft=\"10dp\" android:paddingRight=\"10dp\" android:singleLine=\"true\" android:text=\"@string/label_error_text\" android:textColor=\"@color/black\" android:textSize=\"30sp\" />",
"e": 31018,
"s": 30433,
"text": null
},
{
"code": null,
"e": 31041,
"s": 31018,
"text": "spinner_item.xml file:"
},
{
"code": null,
"e": 31045,
"s": 31041,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><TextView xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:gravity=\"start\" android:padding=\"10dip\" android:text=\"@string/label_error_text\" android:textColor=\"@color/black\" android:textSize=\"30sp\" android:textStyle=\"bold\" />",
"e": 31426,
"s": 31045,
"text": null
},
{
"code": null,
"e": 31474,
"s": 31426,
"text": "Step 5: Working with the MainActivity.java file"
},
{
"code": null,
"e": 32209,
"s": 31474,
"text": "In the java file, we will create a function that will make HTTP requests from the URL. The URL will be consisting of the API key the base URL and the target currency code. First, we will create an adapter for the list of all the currencies and set it to the Spinner view in the main activity. Then we will call the function onItemSelectedListener and get the selected currency code. We will add this code to the URL along with its other parts. Then we will call the function that makes HTTP requests to get a JSON. We will parse the JSON object to get the required rate of the bitcoin of the selected currency. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 32214,
"s": 32209,
"text": "Java"
},
{
"code": "import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.AdapterView;import android.widget.AdapterView.OnItemSelectedListener;import android.widget.ArrayAdapter;import android.widget.Spinner;import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import com.loopj.android.http.AsyncHttpClient;import com.loopj.android.http.JsonHttpResponseHandler; import org.json.JSONException;import org.json.JSONObject; import java.io.IOException; import cz.msebera.android.httpclient.Header; public class MainActivity extends AppCompatActivity { // Constants: // TODO: Create the base URL private final String BASE_URL = \"http://api.coinlayer.com/live?access_key=\"; // Member Variables: TextView mPriceTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mPriceTextView = (TextView) findViewById(R.id.priceLabel); Spinner spinner = (Spinner) findViewById(R.id.currency_spinner); // Create an ArrayAdapter using the String array and a spinner layout final ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.currency_array, R.layout.spinner_item); // Specify the layout to use when the list of choices appears adapter.setDropDownViewResource(R.layout.spinner_dropdown_item); // Apply the adapter to the spinner spinner.setAdapter(adapter); // TODO: Set an OnItemSelected listener on the spinner spinner.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { String publicKey = \"cd9ebbd0c5c20340b9d638e409f41fb1\"; String finalUrl = BASE_URL + publicKey + \"&TARGET=\" + adapterView.getItemAtPosition(i) + \"&symbols=BTC\"; Log.d(\"Clima\", \"Request fail! Status code: \" + finalUrl); try { letsDoSomeNetworking(finalUrl); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); } // TODO: complete the letsDoSomeNetworking() method private void letsDoSomeNetworking(String url) throws IOException, JSONException { AsyncHttpClient client = new AsyncHttpClient(); client.get(url, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { // called when response HTTP status is \"200 OK\" Log.d(\"Clima\", \"JSON: \" + response.toString()); try { JSONObject price = response.getJSONObject(\"rates\"); String object = price.getString(\"BTC\"); mPriceTextView.setText(object); } catch (JSONException E) { E.printStackTrace(); } } @Override public void onFailure(int statusCode, Header[] headers, Throwable e, JSONObject response) { // called when response HTTP status is \"4XX\" (eg. 401, 403, 404) Log.d(\"Clima\", \"Request fail! Status code: \" + statusCode); Log.d(\"Clima\", \"Fail response: \" + response); Log.e(\"ERROR\", e.toString()); } }); }}",
"e": 35883,
"s": 32214,
"text": null
},
{
"code": null,
"e": 35942,
"s": 35883,
"text": "GitHub Link: https://github.com/namanjha007/BitcoinTracker"
},
{
"code": null,
"e": 35950,
"s": 35942,
"text": "android"
},
{
"code": null,
"e": 35974,
"s": 35950,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 35982,
"s": 35974,
"text": "Android"
},
{
"code": null,
"e": 35987,
"s": 35982,
"text": "Java"
},
{
"code": null,
"e": 36006,
"s": 35987,
"text": "Technical Scripter"
},
{
"code": null,
"e": 36011,
"s": 36006,
"text": "Java"
},
{
"code": null,
"e": 36019,
"s": 36011,
"text": "Android"
},
{
"code": null,
"e": 36117,
"s": 36019,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36156,
"s": 36117,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 36206,
"s": 36156,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 36244,
"s": 36206,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 36286,
"s": 36244,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 36359,
"s": 36286,
"text": "How to Change the Background Color After Clicking the Button in Android?"
},
{
"code": null,
"e": 36374,
"s": 36359,
"text": "Arrays in Java"
},
{
"code": null,
"e": 36418,
"s": 36374,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 36440,
"s": 36418,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 36476,
"s": 36440,
"text": "Arrays.sort() in Java with examples"
}
] |
Encapsulation in Java - GeeksforGeeks
|
24 Mar, 2022
Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that binds together code and the data it manipulates. Another way to think about encapsulation is, it is a protective shield that prevents the data from being accessed by the code outside this shield.
Technically in encapsulation, the variables or data of a class is hidden from any other class and can be accessed only through any member function of its own class in which it is declared.
As in encapsulation, the data in a class is hidden from other classes using the data hiding concept which is achieved by making the members or methods of a class private, and the class is exposed to the end-user or the world without providing any details behind implementation using the abstraction concept, so it is also known as a combination of data-hiding and abstraction.
Encapsulation can be achieved by Declaring all the variables in the class as private and writing public methods in the class to set and get the values of variables
It is more defined with setter and getter method.
The program to access variables of the class EncapsulateDemo is shown below:
Java
// Java program to demonstrate encapsulationclass Encapsulate { // private variables declared // these can only be accessed by // public methods of class private String geekName; private int geekRoll; private int geekAge; // get method for age to access // private variable geekAge public int getAge() { return geekAge; } // get method for name to access // private variable geekName public String getName() { return geekName; } // get method for roll to access // private variable geekRoll public int getRoll() { return geekRoll; } // set method for age to access // private variable geekage public void setAge(int newAge) { geekAge = newAge; } // set method for name to access // private variable geekName public void setName(String newName) { geekName = newName; } // set method for roll to access // private variable geekRoll public void setRoll(int newRoll) { geekRoll = newRoll; }} public class TestEncapsulation { public static void main(String[] args) { Encapsulate obj = new Encapsulate(); // setting values of the variables obj.setName("Harsh"); obj.setAge(19); obj.setRoll(51); // Displaying values of the variables System.out.println("Geek's name: " + obj.getName()); System.out.println("Geek's age: " + obj.getAge()); System.out.println("Geek's roll: " + obj.getRoll()); // Direct access of geekRoll is not possible // due to encapsulation // System.out.println("Geek's roll: " + // obj.geekName); }}
Geek's name: Harsh
Geek's age: 19
Geek's roll: 51
In the above program, the class Encapsulate is encapsulated as the variables are declared as private. The get methods like getAge() , getName() , getRoll() are set as public, these methods are used to access these variables. The setter methods like setName(), setAge(), setRoll() are also declared as public and are used to set the values of the variables.
Advantages of Encapsulation:
Data Hiding: The user will have no idea about the inner implementation of the class. It will not be visible to the user how the class is storing values in the variables. The user will only know that we are passing the values to a setter method and variables are getting initialized with that value.
Increased Flexibility: We can make the variables of the class read-only or write-only depending on our requirement. If we wish to make the variables read-only then we have to omit the setter methods like setName(), setAge(), etc. from the above program or if we wish to make the variables as write-only then we have to omit the get methods like getName(), getAge(), etc. from the above program
Reusability: Encapsulation also improves the re-usability and is easy to change with new requirements.
Testing code is easy: Encapsulated code is easy to test for unit testing.
This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
sai003
CHANDRASEKHARVARMA
anshikabhatnagar
rithwiksv3700
phanitanshi12
Java-Object Oriented
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Split() String method in Java with examples
Arrays.sort() in Java with examples
Reverse a string in Java
Initialize an ArrayList in Java
How to iterate any Map in Java
Singleton Class in Java
Different ways of Reading a text file in Java
Stream In Java
Initializing a List in Java
How to add an element to an Array in Java?
|
[
{
"code": null,
"e": 28950,
"s": 28922,
"text": "\n24 Mar, 2022"
},
{
"code": null,
"e": 29246,
"s": 28950,
"text": "Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that binds together code and the data it manipulates. Another way to think about encapsulation is, it is a protective shield that prevents the data from being accessed by the code outside this shield. "
},
{
"code": null,
"e": 29435,
"s": 29246,
"text": "Technically in encapsulation, the variables or data of a class is hidden from any other class and can be accessed only through any member function of its own class in which it is declared."
},
{
"code": null,
"e": 29812,
"s": 29435,
"text": "As in encapsulation, the data in a class is hidden from other classes using the data hiding concept which is achieved by making the members or methods of a class private, and the class is exposed to the end-user or the world without providing any details behind implementation using the abstraction concept, so it is also known as a combination of data-hiding and abstraction."
},
{
"code": null,
"e": 29976,
"s": 29812,
"text": "Encapsulation can be achieved by Declaring all the variables in the class as private and writing public methods in the class to set and get the values of variables"
},
{
"code": null,
"e": 30026,
"s": 29976,
"text": "It is more defined with setter and getter method."
},
{
"code": null,
"e": 30105,
"s": 30026,
"text": "The program to access variables of the class EncapsulateDemo is shown below: "
},
{
"code": null,
"e": 30110,
"s": 30105,
"text": "Java"
},
{
"code": "// Java program to demonstrate encapsulationclass Encapsulate { // private variables declared // these can only be accessed by // public methods of class private String geekName; private int geekRoll; private int geekAge; // get method for age to access // private variable geekAge public int getAge() { return geekAge; } // get method for name to access // private variable geekName public String getName() { return geekName; } // get method for roll to access // private variable geekRoll public int getRoll() { return geekRoll; } // set method for age to access // private variable geekage public void setAge(int newAge) { geekAge = newAge; } // set method for name to access // private variable geekName public void setName(String newName) { geekName = newName; } // set method for roll to access // private variable geekRoll public void setRoll(int newRoll) { geekRoll = newRoll; }} public class TestEncapsulation { public static void main(String[] args) { Encapsulate obj = new Encapsulate(); // setting values of the variables obj.setName(\"Harsh\"); obj.setAge(19); obj.setRoll(51); // Displaying values of the variables System.out.println(\"Geek's name: \" + obj.getName()); System.out.println(\"Geek's age: \" + obj.getAge()); System.out.println(\"Geek's roll: \" + obj.getRoll()); // Direct access of geekRoll is not possible // due to encapsulation // System.out.println(\"Geek's roll: \" + // obj.geekName); }}",
"e": 31718,
"s": 30110,
"text": null
},
{
"code": null,
"e": 31768,
"s": 31718,
"text": "Geek's name: Harsh\nGeek's age: 19\nGeek's roll: 51"
},
{
"code": null,
"e": 32125,
"s": 31768,
"text": "In the above program, the class Encapsulate is encapsulated as the variables are declared as private. The get methods like getAge() , getName() , getRoll() are set as public, these methods are used to access these variables. The setter methods like setName(), setAge(), setRoll() are also declared as public and are used to set the values of the variables."
},
{
"code": null,
"e": 32156,
"s": 32125,
"text": "Advantages of Encapsulation: "
},
{
"code": null,
"e": 32455,
"s": 32156,
"text": "Data Hiding: The user will have no idea about the inner implementation of the class. It will not be visible to the user how the class is storing values in the variables. The user will only know that we are passing the values to a setter method and variables are getting initialized with that value."
},
{
"code": null,
"e": 32849,
"s": 32455,
"text": "Increased Flexibility: We can make the variables of the class read-only or write-only depending on our requirement. If we wish to make the variables read-only then we have to omit the setter methods like setName(), setAge(), etc. from the above program or if we wish to make the variables as write-only then we have to omit the get methods like getName(), getAge(), etc. from the above program"
},
{
"code": null,
"e": 32952,
"s": 32849,
"text": "Reusability: Encapsulation also improves the re-usability and is easy to change with new requirements."
},
{
"code": null,
"e": 33026,
"s": 32952,
"text": "Testing code is easy: Encapsulated code is easy to test for unit testing."
},
{
"code": null,
"e": 33448,
"s": 33026,
"text": "This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 33455,
"s": 33448,
"text": "sai003"
},
{
"code": null,
"e": 33474,
"s": 33455,
"text": "CHANDRASEKHARVARMA"
},
{
"code": null,
"e": 33491,
"s": 33474,
"text": "anshikabhatnagar"
},
{
"code": null,
"e": 33505,
"s": 33491,
"text": "rithwiksv3700"
},
{
"code": null,
"e": 33519,
"s": 33505,
"text": "phanitanshi12"
},
{
"code": null,
"e": 33540,
"s": 33519,
"text": "Java-Object Oriented"
},
{
"code": null,
"e": 33545,
"s": 33540,
"text": "Java"
},
{
"code": null,
"e": 33550,
"s": 33545,
"text": "Java"
},
{
"code": null,
"e": 33648,
"s": 33550,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33657,
"s": 33648,
"text": "Comments"
},
{
"code": null,
"e": 33670,
"s": 33657,
"text": "Old Comments"
},
{
"code": null,
"e": 33714,
"s": 33670,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 33750,
"s": 33714,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 33775,
"s": 33750,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 33807,
"s": 33775,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 33838,
"s": 33807,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 33862,
"s": 33838,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 33908,
"s": 33862,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 33923,
"s": 33908,
"text": "Stream In Java"
},
{
"code": null,
"e": 33951,
"s": 33923,
"text": "Initializing a List in Java"
}
] |
Tk - Geometry Manager
|
The geometry manager is used to manage the geometry of the window and other frames. We can use it to handle the position and size of the window and frames. The layout widgets are used for this purpose.
The syntax for positioning and sizing window is shown below −
wm geometry . wxh+/-x+/-y
Here, w refers to width and h refers to height. It is followed by a '+' or '-' sign with number next referring to the x position on screen. Similarly the following '+' or '-' sign with number refers to the y position on screen
A simple example is shown below for the above Statement −.
#!/usr/bin/wish
wm geometry . 300x200+100+100
When we run the above program, we will get the following output −
The syntax for grid geometry is shown below −
grid gridName -column number -row number -columnspan number -rowspan number
The column, row, columnspan, or rowspan helps in providing the grid geometry.
A simple example is shown below for the above statement −
#!/usr/bin/wish
frame .myFrame1 -background red -height 100 -width 100
frame .myFrame2 -background blue -height 100 -width 50
grid .myFrame1 -columnspan 10 -rowspan 10 -sticky w
grid .myFrame2 -column 10 -row 2
When we run the above program, we will get the following output −
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2403,
"s": 2201,
"text": "The geometry manager is used to manage the geometry of the window and other frames. We can use it to handle the position and size of the window and frames. The layout widgets are used for this purpose."
},
{
"code": null,
"e": 2465,
"s": 2403,
"text": "The syntax for positioning and sizing window is shown below −"
},
{
"code": null,
"e": 2492,
"s": 2465,
"text": "wm geometry . wxh+/-x+/-y\n"
},
{
"code": null,
"e": 2719,
"s": 2492,
"text": "Here, w refers to width and h refers to height. It is followed by a '+' or '-' sign with number next referring to the x position on screen. Similarly the following '+' or '-' sign with number refers to the y position on screen"
},
{
"code": null,
"e": 2778,
"s": 2719,
"text": "A simple example is shown below for the above Statement −."
},
{
"code": null,
"e": 2825,
"s": 2778,
"text": "#!/usr/bin/wish\n\nwm geometry . 300x200+100+100"
},
{
"code": null,
"e": 2891,
"s": 2825,
"text": "When we run the above program, we will get the following output −"
},
{
"code": null,
"e": 2937,
"s": 2891,
"text": "The syntax for grid geometry is shown below −"
},
{
"code": null,
"e": 3014,
"s": 2937,
"text": "grid gridName -column number -row number -columnspan number -rowspan number\n"
},
{
"code": null,
"e": 3092,
"s": 3014,
"text": "The column, row, columnspan, or rowspan helps in providing the grid geometry."
},
{
"code": null,
"e": 3150,
"s": 3092,
"text": "A simple example is shown below for the above statement −"
},
{
"code": null,
"e": 3363,
"s": 3150,
"text": "#!/usr/bin/wish\n\nframe .myFrame1 -background red -height 100 -width 100\nframe .myFrame2 -background blue -height 100 -width 50\ngrid .myFrame1 -columnspan 10 -rowspan 10 -sticky w\ngrid .myFrame2 -column 10 -row 2"
},
{
"code": null,
"e": 3429,
"s": 3363,
"text": "When we run the above program, we will get the following output −"
},
{
"code": null,
"e": 3436,
"s": 3429,
"text": " Print"
},
{
"code": null,
"e": 3447,
"s": 3436,
"text": " Add Notes"
}
] |
Find sum of fields inside array in MongoDB?
|
To find sum of fields inside array, use $sum. Let us create a collection with documents −
> db.demo96.insertOne(
... {
...
... "Name" : "Chris",
... "Details" : [
... {
... Marks:67
... },
... {
... Marks:33
... },
... {
... Marks:50
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e2d6aadb8903cdd865577ad")
}
Display all documents from a collection with the help of find() method −
> db.demo96.find();
This will produce the following output −
{
"_id" : ObjectId("5e2d6aadb8903cdd865577ad"), "Name" : "Chris", "Details" : [
{ "Marks" : 67 }, { "Marks" : 33 }, { "Marks" : 50 }
]
}
Following is the query to find sum of fields inside array in MongoDB −
> db.demo96.aggregate([
... { "$project": {
... "Name": 1,
... "TotalMarks": {
... "$sum": "$Details.Marks"
... }
... }}
... ]);
This will produce the following output −
{ "_id" : ObjectId("5e2d6aadb8903cdd865577ad"), "Name" : "Chris", "TotalMarks" : 150 }
|
[
{
"code": null,
"e": 1152,
"s": 1062,
"text": "To find sum of fields inside array, use $sum. Let us create a collection with documents −"
},
{
"code": null,
"e": 1478,
"s": 1152,
"text": "> db.demo96.insertOne(\n... {\n...\n... \"Name\" : \"Chris\",\n... \"Details\" : [\n... {\n... Marks:67\n... },\n... {\n... Marks:33\n... },\n... {\n... Marks:50\n... }\n... ]\n... }\n... );\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e2d6aadb8903cdd865577ad\")\n}"
},
{
"code": null,
"e": 1551,
"s": 1478,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1571,
"s": 1551,
"text": "> db.demo96.find();"
},
{
"code": null,
"e": 1612,
"s": 1571,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1762,
"s": 1612,
"text": "{\n \"_id\" : ObjectId(\"5e2d6aadb8903cdd865577ad\"), \"Name\" : \"Chris\", \"Details\" : [\n { \"Marks\" : 67 }, { \"Marks\" : 33 }, { \"Marks\" : 50 }\n ] \n}"
},
{
"code": null,
"e": 1833,
"s": 1762,
"text": "Following is the query to find sum of fields inside array in MongoDB −"
},
{
"code": null,
"e": 1983,
"s": 1833,
"text": "> db.demo96.aggregate([\n... { \"$project\": {\n... \"Name\": 1,\n... \"TotalMarks\": {\n... \"$sum\": \"$Details.Marks\"\n... }\n... }}\n... ]);"
},
{
"code": null,
"e": 2024,
"s": 1983,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2111,
"s": 2024,
"text": "{ \"_id\" : ObjectId(\"5e2d6aadb8903cdd865577ad\"), \"Name\" : \"Chris\", \"TotalMarks\" : 150 }"
}
] |
Groovy - concat()
|
Concatenates the specified String to the end of this String.
String concat(String str)
str - the String that is concatenated to the end of this String.
This methods returns a string that represents the concatenation of this object's characters followed by the string argument's characters.
Following is an example of the usage of this method −
class Example {
static void main(String[] args) {
String s = "Hello ";
s = s.concat("World");
System.out.println(s);
}
}
When we run the above program, we will get the following result −
|
[
{
"code": null,
"e": 2433,
"s": 2372,
"text": "Concatenates the specified String to the end of this String."
},
{
"code": null,
"e": 2460,
"s": 2433,
"text": "String concat(String str)\n"
},
{
"code": null,
"e": 2525,
"s": 2460,
"text": "str - the String that is concatenated to the end of this String."
},
{
"code": null,
"e": 2663,
"s": 2525,
"text": "This methods returns a string that represents the concatenation of this object's characters followed by the string argument's characters."
},
{
"code": null,
"e": 2717,
"s": 2663,
"text": "Following is an example of the usage of this method −"
},
{
"code": null,
"e": 2863,
"s": 2717,
"text": "class Example {\n static void main(String[] args) {\n String s = \"Hello \";\n s = s.concat(\"World\");\n System.out.println(s);\n } \n}"
}
] |
Priority Queue using doubly linked list in C++
|
We are given with the data and the priority as an integer value and the task is to create a doubly linked list as per the priority given and display the result.
Queue is a FIFO data structure in which the element which is inserted first is the first one to get removed. A Priority Queue is a type of queue in which elements can be inserted or deleted depending upon the priority. It can be implemented using queue, stack or linked list data structure. Priority queue is implemented by following these rules −
Data or element with the highest priority will get executed before the data or element with the lowest priority.
If two elements have the same priority than they will be executed in the sequence they are added in the list.
A node of a doubly linked list for implementing priority queue will contain three parts −
Data − It will store the integer value.
Next Address − It will store the address of a next node
Previous Address − It will store the address of a previous node
Priority − It will store the priority which is an integer value. It can range from 0-10 where 0 represents the highest priority and 10 represents the lowest priority.
Input -
Output-
Start
Step 1-> Declare a struct Node
Declare info, priority
Declare struct Node *prev, *next
Step 2-> In function push(Node** fr, Node** rr, int n, int p)
Set Node* news = (Node*)malloc(sizeof(Node))
Set news->info = n
Set news->priority = p
If *fr == NULL then,
Set *fr = news
Set *rr = news
Set news->next = NULL
Else If p <= (*fr)->priority then,
Set news->next = *fr
Set (*fr)->prev = news->next
Set *fr = news
Else If p > (*rr)->priority then,
Set news->next = NULL
Set (*rr)->next = news
Set news->prev = (*rr)->next
Set *rr = news
Else
Set Node* start = (*fr)->next
Loop While start->priority > p
Set start = start->next
Set (start->prev)->next = news
Set news->next = start->prev
Set news->prev = (start->prev)->next
Set start->prev = news->next
Step 3-> In function int peek(Node *fr)
Return fr->info
Step 4-> In function bool isEmpty(Node *fr)
Return (fr == NULL)
Step 5-> In function int pop(Node** fr, Node** rr)
Set Node* temp = *fr
Set res = temp->info
Set (*fr) = (*fr)->next
free(temp)
If *fr == NULL then,
*rr = NULL
Return res
Step 6-> In function int main()
Declare and assign Node *front = NULL, *rear = NULL
Call function push(&front, &rear, 4, 3)
Call function push(&front, &rear, 3, 2)
Call function push(&front, &rear, 5, 2)
Call function push(&front, &rear, 5, 7)
Call function push(&front, &rear, 2, 6)
Call function push(&front, &rear, 1, 4)
Print the results obtained from calling the function pop(&front, &rear)
Print the results obtained from calling the function peek(front)
Stop
Live Demo
#include <bits/stdc++.h>
using namespace std;
//doubly linked list node
struct Node {
int info;
int priority;
struct Node *prev, *next;
};
//inserting a new Node
void push(Node** fr, Node** rr, int n, int p) {
Node* news = (Node*)malloc(sizeof(Node));
news->info = n;
news->priority = p;
// if the linked list is empty
if (*fr == NULL) {
*fr = news;
*rr = news;
news->next = NULL;
} else {
// If p is less than or equal front
// node's priority, then insert the node
// at front.
if (p <= (*fr)->priority) {
news->next = *fr;
(*fr)->prev = news->next;
*fr = news;
} else if (p > (*rr)->priority) {
news->next = NULL;
(*rr)->next = news;
news->prev = (*rr)->next;
*rr = news;
} else {
// Finding the position where we need to
// insert the new node.
Node* start = (*fr)->next;
while (start->priority > p)
start = start->next;
(start->prev)->next = news;
news->next = start->prev;
news->prev = (start->prev)->next;
start->prev = news->next;
}
}
}
//the last value
int peek(Node *fr) {
return fr->info;
}
bool isEmpty(Node *fr) {
return (fr == NULL);
}
int pop(Node** fr, Node** rr) {
Node* temp = *fr;
int res = temp->info;
(*fr) = (*fr)->next;
free(temp);
if (*fr == NULL)
*rr = NULL;
return res;
}
// main function
int main() {
Node *front = NULL, *rear = NULL;
push(&front, &rear, 4, 3);
push(&front, &rear, 3, 2);
push(&front, &rear, 5, 2);
push(&front, &rear, 5, 7);
push(&front, &rear, 2, 6);
push(&front, &rear, 1, 4);
printf("%d\n", pop(&front, &rear));
printf("%d\n", peek(front));
return 0;
}
5
3
|
[
{
"code": null,
"e": 1348,
"s": 1187,
"text": "We are given with the data and the priority as an integer value and the task is to create a doubly linked list as per the priority given and display the result."
},
{
"code": null,
"e": 1696,
"s": 1348,
"text": "Queue is a FIFO data structure in which the element which is inserted first is the first one to get removed. A Priority Queue is a type of queue in which elements can be inserted or deleted depending upon the priority. It can be implemented using queue, stack or linked list data structure. Priority queue is implemented by following these rules −"
},
{
"code": null,
"e": 1809,
"s": 1696,
"text": "Data or element with the highest priority will get executed before the data or element with the lowest priority."
},
{
"code": null,
"e": 1919,
"s": 1809,
"text": "If two elements have the same priority than they will be executed in the sequence they are added in the list."
},
{
"code": null,
"e": 2009,
"s": 1919,
"text": "A node of a doubly linked list for implementing priority queue will contain three parts −"
},
{
"code": null,
"e": 2049,
"s": 2009,
"text": "Data − It will store the integer value."
},
{
"code": null,
"e": 2105,
"s": 2049,
"text": "Next Address − It will store the address of a next node"
},
{
"code": null,
"e": 2169,
"s": 2105,
"text": "Previous Address − It will store the address of a previous node"
},
{
"code": null,
"e": 2336,
"s": 2169,
"text": "Priority − It will store the priority which is an integer value. It can range from 0-10 where 0 represents the highest priority and 10 represents the lowest priority."
},
{
"code": null,
"e": 2344,
"s": 2336,
"text": "Input -"
},
{
"code": null,
"e": 2355,
"s": 2346,
"text": "Output- "
},
{
"code": null,
"e": 4049,
"s": 2355,
"text": "Start\nStep 1-> Declare a struct Node\n Declare info, priority\n Declare struct Node *prev, *next\nStep 2-> In function push(Node** fr, Node** rr, int n, int p)\n Set Node* news = (Node*)malloc(sizeof(Node))\n Set news->info = n\n Set news->priority = p\n If *fr == NULL then,\n Set *fr = news\n Set *rr = news\n Set news->next = NULL\n Else If p <= (*fr)->priority then,\n Set news->next = *fr\n Set (*fr)->prev = news->next\n Set *fr = news\n Else If p > (*rr)->priority then,\n Set news->next = NULL\n Set (*rr)->next = news\n Set news->prev = (*rr)->next\n Set *rr = news\n Else\n Set Node* start = (*fr)->next\n Loop While start->priority > p\n Set start = start->next\n Set (start->prev)->next = news\n Set news->next = start->prev\n Set news->prev = (start->prev)->next\n Set start->prev = news->next\nStep 3-> In function int peek(Node *fr)\n Return fr->info\nStep 4-> In function bool isEmpty(Node *fr)\n Return (fr == NULL)\nStep 5-> In function int pop(Node** fr, Node** rr)\n Set Node* temp = *fr\n Set res = temp->info\n Set (*fr) = (*fr)->next\n free(temp)\n If *fr == NULL then,\n *rr = NULL\n Return res\nStep 6-> In function int main()\n Declare and assign Node *front = NULL, *rear = NULL\n Call function push(&front, &rear, 4, 3)\n Call function push(&front, &rear, 3, 2)\n Call function push(&front, &rear, 5, 2)\n Call function push(&front, &rear, 5, 7)\n Call function push(&front, &rear, 2, 6)\n Call function push(&front, &rear, 1, 4)\n Print the results obtained from calling the function pop(&front, &rear)\n Print the results obtained from calling the function peek(front)\nStop"
},
{
"code": null,
"e": 4060,
"s": 4049,
"text": " Live Demo"
},
{
"code": null,
"e": 5852,
"s": 4060,
"text": "#include <bits/stdc++.h>\nusing namespace std;\n//doubly linked list node\nstruct Node {\n int info;\n int priority;\n struct Node *prev, *next;\n};\n//inserting a new Node\nvoid push(Node** fr, Node** rr, int n, int p) {\n Node* news = (Node*)malloc(sizeof(Node));\n news->info = n;\n news->priority = p;\n // if the linked list is empty\n if (*fr == NULL) {\n *fr = news;\n *rr = news;\n news->next = NULL;\n } else {\n // If p is less than or equal front\n // node's priority, then insert the node\n // at front.\n if (p <= (*fr)->priority) {\n news->next = *fr;\n (*fr)->prev = news->next;\n *fr = news;\n } else if (p > (*rr)->priority) {\n news->next = NULL;\n (*rr)->next = news;\n news->prev = (*rr)->next;\n *rr = news;\n } else {\n // Finding the position where we need to\n // insert the new node.\n Node* start = (*fr)->next;\n while (start->priority > p)\n start = start->next;\n (start->prev)->next = news;\n news->next = start->prev;\n news->prev = (start->prev)->next;\n start->prev = news->next;\n }\n }\n}\n//the last value\nint peek(Node *fr) {\n return fr->info;\n}\nbool isEmpty(Node *fr) {\n return (fr == NULL);\n}\nint pop(Node** fr, Node** rr) {\n Node* temp = *fr;\n int res = temp->info;\n (*fr) = (*fr)->next;\n free(temp);\n if (*fr == NULL)\n *rr = NULL;\n return res;\n}\n// main function\nint main() {\n Node *front = NULL, *rear = NULL;\n push(&front, &rear, 4, 3);\n push(&front, &rear, 3, 2);\n push(&front, &rear, 5, 2);\n push(&front, &rear, 5, 7);\n push(&front, &rear, 2, 6);\n push(&front, &rear, 1, 4);\n printf(\"%d\\n\", pop(&front, &rear));\n printf(\"%d\\n\", peek(front));\n return 0;\n}"
},
{
"code": null,
"e": 5856,
"s": 5852,
"text": "5\n3"
}
] |
Python | os.fsdecode() method
|
25 Jun, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.
os.fsdecode() method in Python is used to decode the specified filename from the filesystem encoding with ‘surrogateescape‘ error handler, or ‘strict‘ on Windows;
Syntax: os.fsdecode(filename)
Parameter:filename: A path-like object representing an encoded file. A path-like object is either a str or bytes object representing a path.
Return Type: This method returns a string which represents the decoded filename.
Code: use of os.fsdecode() method
# Python program to explain os.fsdecode() method # importing os module import os # Filename encoded to the filesystem encoding# with 'surrogateescape' error handler# or 'strict' error handlerfilename = b"/home / user / F\xc3\x8e\xe2\x95\x9a\xc3\x88.txt" # Decode the above filename# form the filesystem encoding # with 'surrogateescape' error handler,# or 'strict' (On Windows)decode = os.fsdecode(filename) # Print the decoded filenameprint("Decoded filename:", decode) # To encode a filename to the filesystem # encoding with 'surrogateescape' error handler# or 'strict' error handler os.encode() method# can be used
Encoded filename: b'/home/user/F\xc3\x8e\xe2\x95\x9a\xc3\x88.txt'
Decoded filename: /home/user/FÎ?È.txt
Reference: https://docs.python.org/3/library/os.html#os.fsdecode
python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Jun, 2019"
},
{
"code": null,
"e": 247,
"s": 28,
"text": "OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality."
},
{
"code": null,
"e": 410,
"s": 247,
"text": "os.fsdecode() method in Python is used to decode the specified filename from the filesystem encoding with ‘surrogateescape‘ error handler, or ‘strict‘ on Windows;"
},
{
"code": null,
"e": 440,
"s": 410,
"text": "Syntax: os.fsdecode(filename)"
},
{
"code": null,
"e": 581,
"s": 440,
"text": "Parameter:filename: A path-like object representing an encoded file. A path-like object is either a str or bytes object representing a path."
},
{
"code": null,
"e": 662,
"s": 581,
"text": "Return Type: This method returns a string which represents the decoded filename."
},
{
"code": null,
"e": 696,
"s": 662,
"text": "Code: use of os.fsdecode() method"
},
{
"code": "# Python program to explain os.fsdecode() method # importing os module import os # Filename encoded to the filesystem encoding# with 'surrogateescape' error handler# or 'strict' error handlerfilename = b\"/home / user / F\\xc3\\x8e\\xe2\\x95\\x9a\\xc3\\x88.txt\" # Decode the above filename# form the filesystem encoding # with 'surrogateescape' error handler,# or 'strict' (On Windows)decode = os.fsdecode(filename) # Print the decoded filenameprint(\"Decoded filename:\", decode) # To encode a filename to the filesystem # encoding with 'surrogateescape' error handler# or 'strict' error handler os.encode() method# can be used",
"e": 1325,
"s": 696,
"text": null
},
{
"code": null,
"e": 1432,
"s": 1325,
"text": "Encoded filename: b'/home/user/F\\xc3\\x8e\\xe2\\x95\\x9a\\xc3\\x88.txt'\nDecoded filename: /home/user/FÎ?È.txt\n"
},
{
"code": null,
"e": 1497,
"s": 1432,
"text": "Reference: https://docs.python.org/3/library/os.html#os.fsdecode"
},
{
"code": null,
"e": 1514,
"s": 1497,
"text": "python-os-module"
},
{
"code": null,
"e": 1521,
"s": 1514,
"text": "Python"
},
{
"code": null,
"e": 1619,
"s": 1521,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1651,
"s": 1619,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1678,
"s": 1651,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1699,
"s": 1678,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1730,
"s": 1699,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1786,
"s": 1730,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1809,
"s": 1786,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1851,
"s": 1809,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1893,
"s": 1851,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1932,
"s": 1893,
"text": "Python | datetime.timedelta() function"
}
] |
PostgreSQL – Describe Table
|
08 Feb, 2021
In PostgreSQL, there is no DESCRIBE statement as in MySQL. But users can query the information on columns of a table in a couple of ways. In this article we will look into them.
The information on various columns of a table can be achieved any of the below commands:
Syntax: \d or \d+
Example:
In this example, we will describe the table city of the sample database, ie, dvdrental:
First log into the PostgreSQL server using the pSQL shell:
Now shift to the dvdrental database using the below command:
\c dvdrental
Now use the below command to describe the city table:
\d city;
This will result in the below:
The below command can also be used for the same purpose:
\d+ city
Output:
The information_schema.columns catalog contains the information on columns of all tables. To get information on columns of a table, you query the information_schema.columns catalog.
Syntax:
SELECT
table_name,
column_name,
data_type
FROM
information_schema.columns
WHERE
table_name = 'table_name';
Example:
Use the below statement to get information on the film table of the dvdrental database:
SELECT
table_name,
column_name,
data_type
FROM
information_schema.columns
WHERE
table_name = 'film';
Output:
postgreSQL-managing-table
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - REPLACE Function
PostgreSQL - DROP INDEX
PostgreSQL - INSERT
PostgreSQL - ROW_NUMBER Function
PostgreSQL - TIME Data Type
PostgreSQL - CREATE SCHEMA
PostgreSQL - SELECT
PostgreSQL - EXISTS Operator
PostgreSQL - LEFT JOIN
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Feb, 2021"
},
{
"code": null,
"e": 206,
"s": 28,
"text": "In PostgreSQL, there is no DESCRIBE statement as in MySQL. But users can query the information on columns of a table in a couple of ways. In this article we will look into them."
},
{
"code": null,
"e": 295,
"s": 206,
"text": "The information on various columns of a table can be achieved any of the below commands:"
},
{
"code": null,
"e": 314,
"s": 295,
"text": "Syntax: \\d or \\d+\n"
},
{
"code": null,
"e": 323,
"s": 314,
"text": "Example:"
},
{
"code": null,
"e": 411,
"s": 323,
"text": "In this example, we will describe the table city of the sample database, ie, dvdrental:"
},
{
"code": null,
"e": 470,
"s": 411,
"text": "First log into the PostgreSQL server using the pSQL shell:"
},
{
"code": null,
"e": 531,
"s": 470,
"text": "Now shift to the dvdrental database using the below command:"
},
{
"code": null,
"e": 545,
"s": 531,
"text": "\\c dvdrental\n"
},
{
"code": null,
"e": 599,
"s": 545,
"text": "Now use the below command to describe the city table:"
},
{
"code": null,
"e": 609,
"s": 599,
"text": "\\d city;\n"
},
{
"code": null,
"e": 640,
"s": 609,
"text": "This will result in the below:"
},
{
"code": null,
"e": 697,
"s": 640,
"text": "The below command can also be used for the same purpose:"
},
{
"code": null,
"e": 707,
"s": 697,
"text": "\\d+ city\n"
},
{
"code": null,
"e": 715,
"s": 707,
"text": "Output:"
},
{
"code": null,
"e": 897,
"s": 715,
"text": "The information_schema.columns catalog contains the information on columns of all tables. To get information on columns of a table, you query the information_schema.columns catalog."
},
{
"code": null,
"e": 1034,
"s": 897,
"text": "Syntax:\nSELECT \n table_name, \n column_name, \n data_type \nFROM \n information_schema.columns\nWHERE \n table_name = 'table_name';\n"
},
{
"code": null,
"e": 1043,
"s": 1034,
"text": "Example:"
},
{
"code": null,
"e": 1131,
"s": 1043,
"text": "Use the below statement to get information on the film table of the dvdrental database:"
},
{
"code": null,
"e": 1254,
"s": 1131,
"text": "SELECT \n table_name, \n column_name, \n data_type \nFROM \n information_schema.columns\nWHERE \n table_name = 'film';\n"
},
{
"code": null,
"e": 1262,
"s": 1254,
"text": "Output:"
},
{
"code": null,
"e": 1288,
"s": 1262,
"text": "postgreSQL-managing-table"
},
{
"code": null,
"e": 1299,
"s": 1288,
"text": "PostgreSQL"
},
{
"code": null,
"e": 1397,
"s": 1299,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1435,
"s": 1397,
"text": "PostgreSQL - LIMIT with OFFSET clause"
},
{
"code": null,
"e": 1465,
"s": 1435,
"text": "PostgreSQL - REPLACE Function"
},
{
"code": null,
"e": 1489,
"s": 1465,
"text": "PostgreSQL - DROP INDEX"
},
{
"code": null,
"e": 1509,
"s": 1489,
"text": "PostgreSQL - INSERT"
},
{
"code": null,
"e": 1542,
"s": 1509,
"text": "PostgreSQL - ROW_NUMBER Function"
},
{
"code": null,
"e": 1570,
"s": 1542,
"text": "PostgreSQL - TIME Data Type"
},
{
"code": null,
"e": 1597,
"s": 1570,
"text": "PostgreSQL - CREATE SCHEMA"
},
{
"code": null,
"e": 1617,
"s": 1597,
"text": "PostgreSQL - SELECT"
},
{
"code": null,
"e": 1646,
"s": 1617,
"text": "PostgreSQL - EXISTS Operator"
}
] |
CREATE and DROP INDEX Statement in SQL
|
31 Aug, 2020
1. CREATE INDEX Statement :The CREATE INDEX statement will create indexes in tables. Indexes are used for data procurement from the databases faster. The users cannot see the indexes, they are running in the background of queries, used to speed up searches/queries.
Syntax :Create an index on a table :
CREATE INDEX indexname
ON tablename (columnname1, columnname2, ...);
Create a unique index on a table –
CREATE UNIQUE INDEX indexname
ON tablename (columnname1, columnname2, ...);
Example –Below SQL statement would create an index named “idx_name” on the “LastName” column in the “GeeksTab” table –
CREATE INDEX idx_name
ON GeeksTab (LastName);
To create an index on multiple columns –
CREATE INDEX idx_pname
ON GeeksTab (LastName, FirstName);
2. DROP INDEX Statement :The DROP INDEX statement could be used to remove an index from any table.
Syntax :
DROP INDEX tablename.indexname;
Example –
DROP INDEX GeeksTab.idx_pname;
DBMS-SQL
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Relational Model in DBMS
Introduction of Relational Algebra in DBMS
Types of Functional dependencies in DBMS
Difference between Where and Having Clause in SQL
MySQL | Regular expressions (Regexp)
SQL | DDL, DQL, DML, DCL and TCL Commands
How to find Nth highest salary from a table
SQL | ALTER (RENAME)
Window functions in SQL
SQL | DDL, DML, TCL and DCL
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 Aug, 2020"
},
{
"code": null,
"e": 294,
"s": 28,
"text": "1. CREATE INDEX Statement :The CREATE INDEX statement will create indexes in tables. Indexes are used for data procurement from the databases faster. The users cannot see the indexes, they are running in the background of queries, used to speed up searches/queries."
},
{
"code": null,
"e": 331,
"s": 294,
"text": "Syntax :Create an index on a table :"
},
{
"code": null,
"e": 400,
"s": 331,
"text": "CREATE INDEX indexname\nON tablename (columnname1, columnname2, ...);"
},
{
"code": null,
"e": 435,
"s": 400,
"text": "Create a unique index on a table –"
},
{
"code": null,
"e": 511,
"s": 435,
"text": "CREATE UNIQUE INDEX indexname\nON tablename (columnname1, columnname2, ...);"
},
{
"code": null,
"e": 630,
"s": 511,
"text": "Example –Below SQL statement would create an index named “idx_name” on the “LastName” column in the “GeeksTab” table –"
},
{
"code": null,
"e": 676,
"s": 630,
"text": "CREATE INDEX idx_name\nON GeeksTab (LastName);"
},
{
"code": null,
"e": 717,
"s": 676,
"text": "To create an index on multiple columns –"
},
{
"code": null,
"e": 775,
"s": 717,
"text": "CREATE INDEX idx_pname\nON GeeksTab (LastName, FirstName);"
},
{
"code": null,
"e": 874,
"s": 775,
"text": "2. DROP INDEX Statement :The DROP INDEX statement could be used to remove an index from any table."
},
{
"code": null,
"e": 883,
"s": 874,
"text": "Syntax :"
},
{
"code": null,
"e": 915,
"s": 883,
"text": "DROP INDEX tablename.indexname;"
},
{
"code": null,
"e": 925,
"s": 915,
"text": "Example –"
},
{
"code": null,
"e": 956,
"s": 925,
"text": "DROP INDEX GeeksTab.idx_pname;"
},
{
"code": null,
"e": 965,
"s": 956,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 970,
"s": 965,
"text": "DBMS"
},
{
"code": null,
"e": 974,
"s": 970,
"text": "SQL"
},
{
"code": null,
"e": 979,
"s": 974,
"text": "DBMS"
},
{
"code": null,
"e": 983,
"s": 979,
"text": "SQL"
},
{
"code": null,
"e": 1081,
"s": 983,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1106,
"s": 1081,
"text": "Relational Model in DBMS"
},
{
"code": null,
"e": 1149,
"s": 1106,
"text": "Introduction of Relational Algebra in DBMS"
},
{
"code": null,
"e": 1190,
"s": 1149,
"text": "Types of Functional dependencies in DBMS"
},
{
"code": null,
"e": 1240,
"s": 1190,
"text": "Difference between Where and Having Clause in SQL"
},
{
"code": null,
"e": 1277,
"s": 1240,
"text": "MySQL | Regular expressions (Regexp)"
},
{
"code": null,
"e": 1319,
"s": 1277,
"text": "SQL | DDL, DQL, DML, DCL and TCL Commands"
},
{
"code": null,
"e": 1363,
"s": 1319,
"text": "How to find Nth highest salary from a table"
},
{
"code": null,
"e": 1384,
"s": 1363,
"text": "SQL | ALTER (RENAME)"
},
{
"code": null,
"e": 1408,
"s": 1384,
"text": "Window functions in SQL"
}
] |
Hyperlink Induced Topic Search (HITS) Algorithm using Networxx Module | Python
|
22 Feb, 2021
Hyperlink Induced Topic Search (HITS) Algorithm is a Link Analysis Algorithm that rates webpages, developed by Jon Kleinberg. This algorithm is used to the web link-structures to discover and rank the webpages relevant for a particular search. HITS uses hubs and authorities to define a recursive relationship between webpages. Before understanding the HITS Algorithm, we first need to know about Hubs and Authorities.
Given a query to a Search Engine, the set of highly relevant web pages are called Roots. They are potential Authorities.
Pages that are not very relevant but point to pages in the Root are called Hubs. Thus, an Authority is a page that many hubs link to whereas a Hub is a page that links to many authorities.
Algorithm –
-> Let number of iterations be k. -> Each node is assigned a Hub score = 1 and an Authority score = 1.-> Repeat k times:
Hub update : Each node’s Hub score = (Authority score of each node it points to).
Authority update : Each node’s Authority score = (Hub score of each node pointing to it).
Normalize the scores by dividing each Hub score by square root of the sum of the squares of all Hub scores, and dividing each Authority score by square root of the sum of the squares of all Authority scores. (optional)
Now, let’s see how to implement this algorithm using Networxx Module. Let us consider the following Graph:
On running HITS Algorithm with (without Normalization),
Initially,
Hub Scores: Authority Scores:
A -> 1 A -> 1
B -> 1 B -> 1
C -> 1 C -> 1
D -> 1 D -> 1
E -> 1 E -> 1
F -> 1 F -> 1
G -> 1 G -> 1
H -> 1 H -> 1
After 1st iteration,
Hub Scores: Authority Scores:
A -> 1 A -> 3
B -> 2 B -> 2
C -> 1 C -> 4
D -> 2 D -> 2
E -> 4 E -> 1
F -> 1 F -> 1
G -> 2 G -> 0
H -> 1 H -> 1
After 2nd iteration,
Hub Scores: Authority Scores:
A -> 2 A -> 4
B -> 5 B -> 6
C -> 3 C -> 7
D -> 6 D -> 5
E -> 9 E -> 2
F -> 1 F -> 4
G -> 7 G -> 0
H -> 3 H -> 1
After 3rd iteration,
Hub Scores: Authority Scores:
A -> 5 A -> 13
B -> 9 B -> 15
C -> 4 C -> 27
D -> 13 D -> 11
E -> 22 E -> 5
F -> 1 F -> 9
G -> 11 G -> 0
H -> 4 H -> 3
The Python package Networkx has an in-built function for running the HITS Algorithm. This would be visualized with reference to the above Graph.
Python3
# importing modulesimport networkx as nximport matplotlib.pyplot as plt G = nx.DiGraph() G.add_edges_from([('A', 'D'), ('B', 'C'), ('B', 'E'), ('C', 'A'), ('D', 'C'), ('E', 'D'), ('E', 'B'), ('E', 'F'), ('E', 'C'), ('F', 'C'), ('F', 'H'), ('G', 'A'), ('G', 'C'), ('H', 'A')]) plt.figure(figsize =(10, 10))nx.draw_networkx(G, with_labels = True) hubs, authorities = nx.hits(G, max_iter = 50, normalized = True)# The in-built hits function returns two dictionaries keyed by nodes# containing hub scores and authority scores respectively. print("Hub Scores: ", hubs)print("Authority Scores: ", authorities)
Output:
Hub Scores: {'A': 0.04642540386472174, 'D': 0.133660375232863,
'B': 0.15763599440595596, 'C': 0.037389132480584515,
'E': 0.2588144594158868, 'F': 0.15763599440595596,
'H': 0.037389132480584515, 'G': 0.17104950771344754}
Authority Scores: {'A': 0.10864044085687284, 'D': 0.13489685393050574,
'B': 0.11437974045401585, 'C': 0.3883728005172019,
'E': 0.06966521189369385, 'F': 0.11437974045401585,
'H': 0.06966521189369385, 'G': 0.0}
sagarbhatiahar210
python-modules
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
Python | os.path.join() method
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Feb, 2021"
},
{
"code": null,
"e": 448,
"s": 28,
"text": "Hyperlink Induced Topic Search (HITS) Algorithm is a Link Analysis Algorithm that rates webpages, developed by Jon Kleinberg. This algorithm is used to the web link-structures to discover and rank the webpages relevant for a particular search. HITS uses hubs and authorities to define a recursive relationship between webpages. Before understanding the HITS Algorithm, we first need to know about Hubs and Authorities. "
},
{
"code": null,
"e": 569,
"s": 448,
"text": "Given a query to a Search Engine, the set of highly relevant web pages are called Roots. They are potential Authorities."
},
{
"code": null,
"e": 758,
"s": 569,
"text": "Pages that are not very relevant but point to pages in the Root are called Hubs. Thus, an Authority is a page that many hubs link to whereas a Hub is a page that links to many authorities."
},
{
"code": null,
"e": 772,
"s": 758,
"text": "Algorithm – "
},
{
"code": null,
"e": 895,
"s": 772,
"text": "-> Let number of iterations be k. -> Each node is assigned a Hub score = 1 and an Authority score = 1.-> Repeat k times: "
},
{
"code": null,
"e": 977,
"s": 895,
"text": "Hub update : Each node’s Hub score = (Authority score of each node it points to)."
},
{
"code": null,
"e": 1067,
"s": 977,
"text": "Authority update : Each node’s Authority score = (Hub score of each node pointing to it)."
},
{
"code": null,
"e": 1286,
"s": 1067,
"text": "Normalize the scores by dividing each Hub score by square root of the sum of the squares of all Hub scores, and dividing each Authority score by square root of the sum of the squares of all Authority scores. (optional)"
},
{
"code": null,
"e": 1395,
"s": 1286,
"text": "Now, let’s see how to implement this algorithm using Networxx Module. Let us consider the following Graph: "
},
{
"code": null,
"e": 1453,
"s": 1395,
"text": "On running HITS Algorithm with (without Normalization), "
},
{
"code": null,
"e": 2514,
"s": 1453,
"text": "Initially,\nHub Scores: Authority Scores:\nA -> 1 A -> 1\nB -> 1 B -> 1\nC -> 1 C -> 1\nD -> 1 D -> 1\nE -> 1 E -> 1\nF -> 1 F -> 1\nG -> 1 G -> 1\nH -> 1 H -> 1\n\nAfter 1st iteration,\nHub Scores: Authority Scores:\nA -> 1 A -> 3\nB -> 2 B -> 2\nC -> 1 C -> 4\nD -> 2 D -> 2\nE -> 4 E -> 1\nF -> 1 F -> 1\nG -> 2 G -> 0\nH -> 1 H -> 1\n\nAfter 2nd iteration,\nHub Scores: Authority Scores:\nA -> 2 A -> 4\nB -> 5 B -> 6\nC -> 3 C -> 7\nD -> 6 D -> 5\nE -> 9 E -> 2\nF -> 1 F -> 4\nG -> 7 G -> 0\nH -> 3 H -> 1\n\nAfter 3rd iteration,\nHub Scores: Authority Scores:\nA -> 5 A -> 13\nB -> 9 B -> 15\nC -> 4 C -> 27\nD -> 13 D -> 11\nE -> 22 E -> 5\nF -> 1 F -> 9\nG -> 11 G -> 0\nH -> 4 H -> 3"
},
{
"code": null,
"e": 2661,
"s": 2514,
"text": "The Python package Networkx has an in-built function for running the HITS Algorithm. This would be visualized with reference to the above Graph. "
},
{
"code": null,
"e": 2669,
"s": 2661,
"text": "Python3"
},
{
"code": "# importing modulesimport networkx as nximport matplotlib.pyplot as plt G = nx.DiGraph() G.add_edges_from([('A', 'D'), ('B', 'C'), ('B', 'E'), ('C', 'A'), ('D', 'C'), ('E', 'D'), ('E', 'B'), ('E', 'F'), ('E', 'C'), ('F', 'C'), ('F', 'H'), ('G', 'A'), ('G', 'C'), ('H', 'A')]) plt.figure(figsize =(10, 10))nx.draw_networkx(G, with_labels = True) hubs, authorities = nx.hits(G, max_iter = 50, normalized = True)# The in-built hits function returns two dictionaries keyed by nodes# containing hub scores and authority scores respectively. print(\"Hub Scores: \", hubs)print(\"Authority Scores: \", authorities)",
"e": 3324,
"s": 2669,
"text": null
},
{
"code": null,
"e": 3334,
"s": 3324,
"text": "Output: "
},
{
"code": null,
"e": 3873,
"s": 3336,
"text": "Hub Scores: {'A': 0.04642540386472174, 'D': 0.133660375232863,\n 'B': 0.15763599440595596, 'C': 0.037389132480584515, \n 'E': 0.2588144594158868, 'F': 0.15763599440595596,\n 'H': 0.037389132480584515, 'G': 0.17104950771344754}\n\nAuthority Scores: {'A': 0.10864044085687284, 'D': 0.13489685393050574, \n 'B': 0.11437974045401585, 'C': 0.3883728005172019,\n 'E': 0.06966521189369385, 'F': 0.11437974045401585,\n 'H': 0.06966521189369385, 'G': 0.0}"
},
{
"code": null,
"e": 3893,
"s": 3875,
"text": "sagarbhatiahar210"
},
{
"code": null,
"e": 3908,
"s": 3893,
"text": "python-modules"
},
{
"code": null,
"e": 3923,
"s": 3908,
"text": "python-utility"
},
{
"code": null,
"e": 3930,
"s": 3923,
"text": "Python"
},
{
"code": null,
"e": 4028,
"s": 3930,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4070,
"s": 4028,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 4092,
"s": 4070,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 4118,
"s": 4092,
"text": "Python String | replace()"
},
{
"code": null,
"e": 4150,
"s": 4118,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4179,
"s": 4150,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 4206,
"s": 4179,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4227,
"s": 4206,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 4263,
"s": 4227,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 4286,
"s": 4263,
"text": "Introduction To PYTHON"
}
] |
Java program to check whether a string is a Palindrome
|
22 Jun, 2022
A string is said to be a palindrome if it is the same if we start reading it from left to right or right to left. So let us consider a string “str”, now the task is just to find out with its reverse string is the same as it is.
Example:
Input : str = "abba"
Output: Yes
Input : str = "geeks"
Output: No
Naive Approach: By Reversing the given string and ComparingWe can check if the given string is a palindrome by comparing the original string with its reversed version. Below is the implementation of the above approach:
Java
/*package whatever //do not write package name here */ import java.io.*; class GFG { public static boolean isPalindrome(String str) { // Initializing an empty string to store the reverse // of the original str String rev = ""; // Initializing a new boolean variable for the // answer boolean ans = false; for (int i = str.length() - 1; i >= 0; i--) { rev = rev + str.charAt(i); } // Checking if both the strings are equal if (str.equals(rev)) { ans = true; } return ans; } public static void main(String[] args) { // Input string String str = "geeks"; // Convert the string to lowercase str = str.toLowerCase(); boolean A = isPalindrome(str); System.out.println(A); }}
false
In the above example, if we write ABba in place of abba, then also we should get the output as yes. So, we must change the case of the string to either lowercase or uppercase before we check it for a palindrome. If we do not do this, we will get unexpected results. This is because the compiler checks the characters based on their ASCII value and the ASCII value of A is not the same as a.
Approach: Our approach will be that we will first convert the string to lowercase. Then, we will take two pointers i pointing to the start of the string and j pointing to the end of the string. Keep incrementing i and decrementing j while i < j and at every step check whether the characters at these pointers are the same or not. If not then the string is not a palindrome else it is.
Example 1:
Java
// Java program to check whether a// string is a Palindrome// Using two pointing variables // Main classpublic class GFG { // Method // Returning true if string is palindrome static boolean isPalindrome(String str) { // Pointers pointing to the beginning // and the end of the string int i = 0, j = str.length() - 1; // While there are characters to compare while (i < j) { // If there is a mismatch if (str.charAt(i) != str.charAt(j)) return false; // Increment first pointer and // decrement the other i++; j--; } // Given string is a palindrome return true; } // Method 2 // main driver method public static void main(String[] args) { // Input string String str = "geeks"; //Convert the string to lowercase str = str.toLowerCase(); // passing bool function till holding true if (isPalindrome(str)) // It is a palindrome System.out.print("Yes"); else // Not a palindrome System.out.print("No"); }}
No
Example 2:
Java
// Java Program to check Whether the String is Palindrome// or Not // Main classclass GFG { // Method 1 // Returns true if string is a palindrome static boolean isPalindrome(String str) { // Pointers pointing to the beginning // and the end of the string int i = 0, j = str.length() - 1; // While there are characters to compare while (i < j) { // If there is a mismatch if (str.charAt(i) != str.charAt(j)) return false; // Increment first pointer and // decrement the other i++; j--; } // Given string is a palindrome return true; } // Main driver method public static void main(String[] args) { String str = "geeks"; String str2 = "RACEcar"; //Change strings to lowercase str = str.toLowerCase(); str2 = str2.toLowerCase(); // For string 1 System.out.print("String 1 :"); if (isPalindrome(str)) System.out.print("It is a palindrome"); else System.out.print("It is not a palindrome"); // new line for better readability System.out.println(); // For string 2 System.out.print("String 2 :"); if (isPalindrome(str2)) System.out.print("It is a palindrome"); else System.out.print("It is not a palindrome"); }}
String 1 :It is not a palindrome
String 2 :It is a palindrome
Recursive approach: The approach is very simple. Just like the two-pointer approach, we will check the first and the last value of the string but this time it will be through recursion.
We will take two pointers i pointing to the start of the string and j pointing to the end of the string. Keep incrementing i and decrementing j while i < j and at every step Check whether the characters at these pointers are the same or not. We are doing this through recursion – (i+1, j-1If all the characters are the same on the ith and jth index till i>=j condition satisfies, print true else false
We will take two pointers i pointing to the start of the string and j pointing to the end of the string.
Keep incrementing i and decrementing j while i < j and at every step
Check whether the characters at these pointers are the same or not. We are doing this through recursion – (i+1, j-1
If all the characters are the same on the ith and jth index till i>=j condition satisfies, print true else false
Below is the implementation of the above approach:
Java
//// Java program to check whether a// string is a Palindrome using recursion import java.io.*; class GFG { public static boolean isPalindrome(int i, int j, String A) { // comparing the two pointers if (i >= j) { return true; } // comparing the characters on those pointers if (A.charAt(i) != A.charAt(j)) { return false; } // checking everything again recursively return isPalindrome(i + 1, j - 1, A); } public static boolean isPalindrome(String A) { return isPalindrome(0, A.length() - 1, A); } public static void main(String[] args) { // Input string String A = "geeks"; // Convert the string to lowercase A = A.toLowerCase(); boolean str = isPalindrome(A); System.out.println(str); }}
false
nishantv
nitinagrawalup
solankimayank
saurabh1990aror
kk9826225
shikha19b131014
akd3257
Java-String-Programs
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Jun, 2022"
},
{
"code": null,
"e": 281,
"s": 52,
"text": "A string is said to be a palindrome if it is the same if we start reading it from left to right or right to left. So let us consider a string “str”, now the task is just to find out with its reverse string is the same as it is. "
},
{
"code": null,
"e": 290,
"s": 281,
"text": "Example:"
},
{
"code": null,
"e": 360,
"s": 290,
"text": "Input : str = \"abba\" \nOutput: Yes\n\nInput : str = \"geeks\"\nOutput: No "
},
{
"code": null,
"e": 579,
"s": 360,
"text": "Naive Approach: By Reversing the given string and ComparingWe can check if the given string is a palindrome by comparing the original string with its reversed version. Below is the implementation of the above approach:"
},
{
"code": null,
"e": 584,
"s": 579,
"text": "Java"
},
{
"code": "/*package whatever //do not write package name here */ import java.io.*; class GFG { public static boolean isPalindrome(String str) { // Initializing an empty string to store the reverse // of the original str String rev = \"\"; // Initializing a new boolean variable for the // answer boolean ans = false; for (int i = str.length() - 1; i >= 0; i--) { rev = rev + str.charAt(i); } // Checking if both the strings are equal if (str.equals(rev)) { ans = true; } return ans; } public static void main(String[] args) { // Input string String str = \"geeks\"; // Convert the string to lowercase str = str.toLowerCase(); boolean A = isPalindrome(str); System.out.println(A); }}",
"e": 1423,
"s": 584,
"text": null
},
{
"code": null,
"e": 1430,
"s": 1423,
"text": "false\n"
},
{
"code": null,
"e": 1823,
"s": 1430,
"text": "In the above example, if we write ABba in place of abba, then also we should get the output as yes. So, we must change the case of the string to either lowercase or uppercase before we check it for a palindrome. If we do not do this, we will get unexpected results. This is because the compiler checks the characters based on their ASCII value and the ASCII value of A is not the same as a. "
},
{
"code": null,
"e": 2209,
"s": 1823,
"text": "Approach: Our approach will be that we will first convert the string to lowercase. Then, we will take two pointers i pointing to the start of the string and j pointing to the end of the string. Keep incrementing i and decrementing j while i < j and at every step check whether the characters at these pointers are the same or not. If not then the string is not a palindrome else it is."
},
{
"code": null,
"e": 2220,
"s": 2209,
"text": "Example 1:"
},
{
"code": null,
"e": 2225,
"s": 2220,
"text": "Java"
},
{
"code": "// Java program to check whether a// string is a Palindrome// Using two pointing variables // Main classpublic class GFG { // Method // Returning true if string is palindrome static boolean isPalindrome(String str) { // Pointers pointing to the beginning // and the end of the string int i = 0, j = str.length() - 1; // While there are characters to compare while (i < j) { // If there is a mismatch if (str.charAt(i) != str.charAt(j)) return false; // Increment first pointer and // decrement the other i++; j--; } // Given string is a palindrome return true; } // Method 2 // main driver method public static void main(String[] args) { // Input string String str = \"geeks\"; //Convert the string to lowercase str = str.toLowerCase(); // passing bool function till holding true if (isPalindrome(str)) // It is a palindrome System.out.print(\"Yes\"); else // Not a palindrome System.out.print(\"No\"); }}",
"e": 3395,
"s": 2225,
"text": null
},
{
"code": null,
"e": 3398,
"s": 3395,
"text": "No"
},
{
"code": null,
"e": 3409,
"s": 3398,
"text": "Example 2:"
},
{
"code": null,
"e": 3414,
"s": 3409,
"text": "Java"
},
{
"code": "// Java Program to check Whether the String is Palindrome// or Not // Main classclass GFG { // Method 1 // Returns true if string is a palindrome static boolean isPalindrome(String str) { // Pointers pointing to the beginning // and the end of the string int i = 0, j = str.length() - 1; // While there are characters to compare while (i < j) { // If there is a mismatch if (str.charAt(i) != str.charAt(j)) return false; // Increment first pointer and // decrement the other i++; j--; } // Given string is a palindrome return true; } // Main driver method public static void main(String[] args) { String str = \"geeks\"; String str2 = \"RACEcar\"; //Change strings to lowercase str = str.toLowerCase(); str2 = str2.toLowerCase(); // For string 1 System.out.print(\"String 1 :\"); if (isPalindrome(str)) System.out.print(\"It is a palindrome\"); else System.out.print(\"It is not a palindrome\"); // new line for better readability System.out.println(); // For string 2 System.out.print(\"String 2 :\"); if (isPalindrome(str2)) System.out.print(\"It is a palindrome\"); else System.out.print(\"It is not a palindrome\"); }}",
"e": 4852,
"s": 3414,
"text": null
},
{
"code": null,
"e": 4914,
"s": 4852,
"text": "String 1 :It is not a palindrome\nString 2 :It is a palindrome"
},
{
"code": null,
"e": 5100,
"s": 4914,
"text": "Recursive approach: The approach is very simple. Just like the two-pointer approach, we will check the first and the last value of the string but this time it will be through recursion."
},
{
"code": null,
"e": 5502,
"s": 5100,
"text": "We will take two pointers i pointing to the start of the string and j pointing to the end of the string. Keep incrementing i and decrementing j while i < j and at every step Check whether the characters at these pointers are the same or not. We are doing this through recursion – (i+1, j-1If all the characters are the same on the ith and jth index till i>=j condition satisfies, print true else false"
},
{
"code": null,
"e": 5608,
"s": 5502,
"text": "We will take two pointers i pointing to the start of the string and j pointing to the end of the string. "
},
{
"code": null,
"e": 5678,
"s": 5608,
"text": "Keep incrementing i and decrementing j while i < j and at every step "
},
{
"code": null,
"e": 5794,
"s": 5678,
"text": "Check whether the characters at these pointers are the same or not. We are doing this through recursion – (i+1, j-1"
},
{
"code": null,
"e": 5907,
"s": 5794,
"text": "If all the characters are the same on the ith and jth index till i>=j condition satisfies, print true else false"
},
{
"code": null,
"e": 5958,
"s": 5907,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 5963,
"s": 5958,
"text": "Java"
},
{
"code": "//// Java program to check whether a// string is a Palindrome using recursion import java.io.*; class GFG { public static boolean isPalindrome(int i, int j, String A) { // comparing the two pointers if (i >= j) { return true; } // comparing the characters on those pointers if (A.charAt(i) != A.charAt(j)) { return false; } // checking everything again recursively return isPalindrome(i + 1, j - 1, A); } public static boolean isPalindrome(String A) { return isPalindrome(0, A.length() - 1, A); } public static void main(String[] args) { // Input string String A = \"geeks\"; // Convert the string to lowercase A = A.toLowerCase(); boolean str = isPalindrome(A); System.out.println(str); }}",
"e": 6849,
"s": 5963,
"text": null
},
{
"code": null,
"e": 6856,
"s": 6849,
"text": "false\n"
},
{
"code": null,
"e": 6865,
"s": 6856,
"text": "nishantv"
},
{
"code": null,
"e": 6880,
"s": 6865,
"text": "nitinagrawalup"
},
{
"code": null,
"e": 6894,
"s": 6880,
"text": "solankimayank"
},
{
"code": null,
"e": 6910,
"s": 6894,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 6920,
"s": 6910,
"text": "kk9826225"
},
{
"code": null,
"e": 6936,
"s": 6920,
"text": "shikha19b131014"
},
{
"code": null,
"e": 6944,
"s": 6936,
"text": "akd3257"
},
{
"code": null,
"e": 6965,
"s": 6944,
"text": "Java-String-Programs"
},
{
"code": null,
"e": 6970,
"s": 6965,
"text": "Java"
},
{
"code": null,
"e": 6975,
"s": 6970,
"text": "Java"
},
{
"code": null,
"e": 7073,
"s": 6975,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7124,
"s": 7073,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 7155,
"s": 7124,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 7174,
"s": 7155,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 7204,
"s": 7174,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 7219,
"s": 7204,
"text": "Stream In Java"
},
{
"code": null,
"e": 7237,
"s": 7219,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 7257,
"s": 7237,
"text": "Collections in Java"
},
{
"code": null,
"e": 7281,
"s": 7257,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 7313,
"s": 7281,
"text": "Multidimensional Arrays in Java"
}
] |
C++ Program to count Vowels in a string using Pointer
|
27 Sep, 2019
Pre-requisite: Pointers in C++
Given a string of lowercase english alphabets. The task is to count number of vowels present in a string using pointers
Examples:
Input : str = "geeks"
Output : 2
Input : str = "geeksforgeeks"
Output : 5
Approach:
Initialize the string using a character array.Create a character pointer and initialize it with the first element in array of character (string).Create a counter to count vowels.Iterate the loop till character pointer find ‘\0’ null character, and as soon as null character encounter, stop the loop.Check whether any vowel is present or not while iterating the pointer, if vowel found increment the count.Print the count.
Initialize the string using a character array.
Create a character pointer and initialize it with the first element in array of character (string).
Create a counter to count vowels.
Iterate the loop till character pointer find ‘\0’ null character, and as soon as null character encounter, stop the loop.
Check whether any vowel is present or not while iterating the pointer, if vowel found increment the count.
Print the count.
Below is the implementation of the above approach:
// CPP program to print count of// vowels using pointers #include <iostream> using namespace std; int vowelCount(char *sptr){ // Create a counter int count = 0; // Iterate the loop until null character encounter while ((*sptr) != '\0') { // Check whether character pointer finds any vowels if (*sptr == 'a' || *sptr == 'e' || *sptr == 'i' || *sptr == 'o' || *sptr == 'u') { // If vowel found increment the count count++; } // Increment the pointer to next location // of address sptr++; } return count;} // Driver Codeint main(){ // Initialize the string char str[] = "geeksforgeeks"; // Display the count cout << "Vowels in above string: " << vowelCount(str); return 0;}
Vowels in above string: 5
shubham_singh
cpp-pointer
cpp-string
C++
GATE
Technical Scripter
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
Substring in C++
unordered_map in C++ STL
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE-CS-2014-(Set-3) | Question 20
GATE | GATE CS 2008 | Question 40
GATE | GATE CS 2008 | Question 46
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n27 Sep, 2019"
},
{
"code": null,
"e": 83,
"s": 52,
"text": "Pre-requisite: Pointers in C++"
},
{
"code": null,
"e": 203,
"s": 83,
"text": "Given a string of lowercase english alphabets. The task is to count number of vowels present in a string using pointers"
},
{
"code": null,
"e": 213,
"s": 203,
"text": "Examples:"
},
{
"code": null,
"e": 290,
"s": 213,
"text": "Input : str = \"geeks\"\nOutput : 2\n\nInput : str = \"geeksforgeeks\"\nOutput : 5 \n"
},
{
"code": null,
"e": 300,
"s": 290,
"text": "Approach:"
},
{
"code": null,
"e": 722,
"s": 300,
"text": "Initialize the string using a character array.Create a character pointer and initialize it with the first element in array of character (string).Create a counter to count vowels.Iterate the loop till character pointer find ‘\\0’ null character, and as soon as null character encounter, stop the loop.Check whether any vowel is present or not while iterating the pointer, if vowel found increment the count.Print the count."
},
{
"code": null,
"e": 769,
"s": 722,
"text": "Initialize the string using a character array."
},
{
"code": null,
"e": 869,
"s": 769,
"text": "Create a character pointer and initialize it with the first element in array of character (string)."
},
{
"code": null,
"e": 903,
"s": 869,
"text": "Create a counter to count vowels."
},
{
"code": null,
"e": 1025,
"s": 903,
"text": "Iterate the loop till character pointer find ‘\\0’ null character, and as soon as null character encounter, stop the loop."
},
{
"code": null,
"e": 1132,
"s": 1025,
"text": "Check whether any vowel is present or not while iterating the pointer, if vowel found increment the count."
},
{
"code": null,
"e": 1149,
"s": 1132,
"text": "Print the count."
},
{
"code": null,
"e": 1200,
"s": 1149,
"text": "Below is the implementation of the above approach:"
},
{
"code": "// CPP program to print count of// vowels using pointers #include <iostream> using namespace std; int vowelCount(char *sptr){ // Create a counter int count = 0; // Iterate the loop until null character encounter while ((*sptr) != '\\0') { // Check whether character pointer finds any vowels if (*sptr == 'a' || *sptr == 'e' || *sptr == 'i' || *sptr == 'o' || *sptr == 'u') { // If vowel found increment the count count++; } // Increment the pointer to next location // of address sptr++; } return count;} // Driver Codeint main(){ // Initialize the string char str[] = \"geeksforgeeks\"; // Display the count cout << \"Vowels in above string: \" << vowelCount(str); return 0;}",
"e": 1998,
"s": 1200,
"text": null
},
{
"code": null,
"e": 2025,
"s": 1998,
"text": "Vowels in above string: 5\n"
},
{
"code": null,
"e": 2039,
"s": 2025,
"text": "shubham_singh"
},
{
"code": null,
"e": 2051,
"s": 2039,
"text": "cpp-pointer"
},
{
"code": null,
"e": 2062,
"s": 2051,
"text": "cpp-string"
},
{
"code": null,
"e": 2066,
"s": 2062,
"text": "C++"
},
{
"code": null,
"e": 2071,
"s": 2066,
"text": "GATE"
},
{
"code": null,
"e": 2090,
"s": 2071,
"text": "Technical Scripter"
},
{
"code": null,
"e": 2094,
"s": 2090,
"text": "CPP"
},
{
"code": null,
"e": 2192,
"s": 2094,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2219,
"s": 2192,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 2262,
"s": 2219,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 2296,
"s": 2262,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 2313,
"s": 2296,
"text": "Substring in C++"
},
{
"code": null,
"e": 2338,
"s": 2313,
"text": "unordered_map in C++ STL"
},
{
"code": null,
"e": 2380,
"s": 2338,
"text": "GATE | GATE-CS-2014-(Set-2) | Question 65"
},
{
"code": null,
"e": 2442,
"s": 2380,
"text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33"
},
{
"code": null,
"e": 2484,
"s": 2442,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 20"
},
{
"code": null,
"e": 2518,
"s": 2484,
"text": "GATE | GATE CS 2008 | Question 40"
}
] |
What is the use of constructor in Java?
|
A constructor is similar to method and it is invoked at the time creating an object of the class, it is generally used to initialize the instance variables of a class. The constructors have same name as their class and, have no return type.
There are two types of constructors parameterized constructors and no-arg constructors the main purpose of a constructor is to initialize the instance variables of a class.
In the following example we are trying to initialize the instance variables of a class using no-arg constructor.
Live Demo
public class Test {
int num;
String data;
Test(){
num = 100;
data = "sample";
}
public static void main(String args[]){
Test obj = new Test();
System.out.println(obj.num);
System.out.println(obj.data);
}
}
100
sample
In the following example we are trying to initialize the instance variables of a class using parameterized constructor.
Live Demo
import java.util.Scanner;
public class Test {
int num;
String data;
Test(int num, String data){
this.num = num;
this.data = data;
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string value: ");
String data = sc.nextLine();
System.out.println("Enter an integer value: ");
int num = sc.nextInt();
Test obj = new Test(num, data);
System.out.println(obj.num);
System.out.println(obj.data);
}
}
Enter a string value:
sample
Enter an integer value:
1023
1023
sample
|
[
{
"code": null,
"e": 1428,
"s": 1187,
"text": "A constructor is similar to method and it is invoked at the time creating an object of the class, it is generally used to initialize the instance variables of a class. The constructors have same name as their class and, have no return type."
},
{
"code": null,
"e": 1601,
"s": 1428,
"text": "There are two types of constructors parameterized constructors and no-arg constructors the main purpose of a constructor is to initialize the instance variables of a class."
},
{
"code": null,
"e": 1714,
"s": 1601,
"text": "In the following example we are trying to initialize the instance variables of a class using no-arg constructor."
},
{
"code": null,
"e": 1724,
"s": 1714,
"text": "Live Demo"
},
{
"code": null,
"e": 1978,
"s": 1724,
"text": "public class Test {\n int num;\n String data;\n Test(){\n num = 100;\n data = \"sample\";\n }\n public static void main(String args[]){\n Test obj = new Test();\n System.out.println(obj.num);\n System.out.println(obj.data);\n }\n}"
},
{
"code": null,
"e": 1989,
"s": 1978,
"text": "100\nsample"
},
{
"code": null,
"e": 2109,
"s": 1989,
"text": "In the following example we are trying to initialize the instance variables of a class using parameterized constructor."
},
{
"code": null,
"e": 2119,
"s": 2109,
"text": "Live Demo"
},
{
"code": null,
"e": 2654,
"s": 2119,
"text": "import java.util.Scanner;\npublic class Test {\n int num;\n String data;\n Test(int num, String data){\n this.num = num;\n this.data = data;\n }\n public static void main(String args[]){\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter a string value: \");\n String data = sc.nextLine();\n System.out.println(\"Enter an integer value: \");\n int num = sc.nextInt();\n \n Test obj = new Test(num, data);\n System.out.println(obj.num);\n System.out.println(obj.data);\n }\n}"
},
{
"code": null,
"e": 2724,
"s": 2654,
"text": "Enter a string value:\nsample\nEnter an integer value:\n1023\n1023\nsample"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.